DBA Data[Home] [Help]

PACKAGE BODY: APPS.CTO_UTILITY_PK

Source


1 package body CTO_UTILITY_PK as
2 /* $Header: CTOUTILB.pls 120.22.12020000.3 2013/03/29 10:57:53 abhissri ship $*/
3 
4 /*----------------------------------------------------------------------------+
5 | Copyright (c) 1993 Oracle Corporation    Belmont, California, USA
6 |                       All rights reserved.
7 |                       Oracle Manufacturing
8 |
9 |FILE NAME   : CTOUTILB.pls
10 |
11 |DESCRIPTION : Contains modules to :
12 |		1. Populate temporary tables bom_cto_order_lines and
13 |		bom_cto_src_orgs, used for intermediate CTO processing
14 |		2. Update these tables with the config_item_id
15 |		3. Copy sourcing rule assignments from model to config item
16 |
17 |HISTORY     : Created on 04-MAY-2000  by Sajani Sheth
18 |              Modified on 18-MAY-2000 by Sushant Sawant
19 |              Modified on 23-JUN-2000 by Sushant Sawant
20 |              Modified on 08-AUG-2000 by Sushant Sawant
21 |              Modified on 11-JAN-2001 by Sushant Sawant
22 |                                         removed multilevel profile query
23 |              Modified on 30-APR-2001 By Renga Kannan
24 |                                         FiXed the where condition in MRP_SOURCES_V query.
25 |                                         The where condition for the field source_type is added
26 |                                         with nvl function.
27 |
28 |
29 |              Modified on 14-MAY-2001 by Sushant Sawant
30 |                                         changes made to trunc to reflect
31 |                                         changes made to branch due to BUG
32 |                                         1728383 for performance.
33 |
34 |              Modified on 05-JUN-2001 by Sushant Sawant
35 |                                         changes made to derive perform_match value
36 |                                         through BOM:MATCH_CONFIG profile.
37 |              Modified on 15-JUN-2001 by Renga Kannan
38 |                                         Moved the get_model_sourcing_org code from
39 |                                         CTO_ATP_INTERFACE_PK to CTO_UTILITY_PK
40 |                                         This decision is taken by CTO team on
41 |                                         06/15/2001 to avoid the dependency
42 |                                         with CTOATPIB.pls for this procedure
43 |                                         This procedure is used in change order
44 |                                         package. We are expecting this procedure to
45 |                                         be used in future also.
46 |              Modified on 22-JUN-2001 by Shashi Bhaskaran : bugfix 1811007
47 |                                         Added a new function convert_uom for wt/vol
48 |                                         calculation.
49 |	       Modified on 18-JUL-2001 by Kundan Sarkar
50 |					  fixed bug 1876618 to improve performance
51 |	       Modified on 18-JUL-2001 by Shashi Bhaskaran : bugfix 1799874
52 |					  Added a new function get_source_document_id
53 |					  to know if it is a regular SO or internal SO.
54 |
55 |              Modified on 21-AUG-21001 by Renga Kannan
56 |
57 |                                          Get_model_sourcing_org and related procedures
58 |                                          are modified to handle BUY model type also. This
59 |                                          change is done as part of 'Procuring config' and
60 |                                          Auto create Req for ATO item project(Patch set G)
61 |                                          The changes made in the CTOATPIB.pls file is replicated
62 |                                          here .Look at the individual places for Further comments.
63 |                                          Get_all_item_orgs procedure is modified as part of this
64 |                                          Project
65 |              Modified on 24-AUG-2001 by Sushant Sawant: BUG #1957336
66 |                                         Added a new functionality for preconfigure bom.
67 
68 |              Modified on 02-NOV-2001 by Renga Kannan
69 |                                         Modified Generate_routing_attachment_text
70 |                                         Operation code was incorrect. One more join
71 |                                         is added to it. This bug was found during
72 |                                         Patch set G system testing.
73 |
74 |
75 |
76 |              Modified on 08-NOV-2001 by Renga Kannan
77 |                                         Modified the populate_src_orgs procedure
78 |                                         Added one more exception for invalid sourcing
79 |                                         When the item is not defined in the sourcing
80 |                                         org it will error out saying invalid sourcing
81 |
82 |
83 |              Modified on 13-NOV-2001 by Renga Kannan
84 |
85 |                                         The error message handling for this file is
86 |                                         changed completely. The FND_MESSAGE.SET_NAME
87 |                                         needs to be called twice in all the error handling
88 |                                         exception. And there should be one add for OE and
89 |                                         one add for FND. IN the exception block we need
90 |                                         to call the fnd_msg_pub.count_and_get and
91 |                                         oe_msg_pub.count_and_get.
92 |
93 |
94 |              Modified on 13-NOV-2001 By Renga Kannan
95 |
96 |
97 |                                         Modified the procedure Create_sourcing_rule
98 |                                         to have a filter condition to choose only
99 |                                         assignment_type 3 and 6.
100 |
101 |              Modified on 08-MAR-2002 By Sushant Sawant
102 |
103 |                                         BUG#2234858
104 |                                         Added new functionality for Drop Shipment
105 |                                         organization_type = 3 ,4 BUY
106 |                                         organization_type = 5 ,6 DROP SHIP
107 |              Modified on 27-MAR-2002 By Kiran Konada
108 |                                         removed the procedure GENERATE_ROUTING_ATTACH_TEXT
109 |                                         changed the signature and modified the logic of
110 |                                         GENERATE_BOM_ATTACH_TEXT to get bom from BCOL
111 |                                         above changes have been made as part of patchset-H
112 |                                         to be in sync with decisions made for cto-isp page
113 |
114 |              Modified on 12-APR-2002 By Sushant Sawant
115 |                                         Fixed BUG2310356
116 |                                         Drop Ship should respect buy sourcing rules.
117 |
118 |              Modified on 04-JUN-2002 BY Kiran Konada--bug fix 2327972
119 |                                         added a new procedure chk_all_rsv_details
120 |                                         This returns reservation details all types of
121 |                                         reservation for a given line_id in a table of records
122 |
123 |              Modified on 16-SEP-2002 By Sushant Sawant
124 |                                         Added New Function isModelMLMO copied from G branch
125 |                                         This function checks whether a model
126 |                                         is ML/MO.
127 |
128 |              Modified on 14-FEB-2003 By Kundan Sarkar
129 |                                         Bugfix 2804321 : Propagating customer bugfix 2774570
130 |                                         to main.
131 |
132 |              Modified on 14-MAR-2003 By Sushant Sawant
133 |                                         Decimal-Qty Support for Option Items.
134 |
135 |
136 |              Modified on 22-Aug-2003 By Kiran Konada
137 |                                         for enabling multiple soucres from DMF-J
138 |					  removed the error_code =66 in query sourcing org
139 |					  P_source_type will be 66 for multiple sources
140 |
141 |
142 |              Modified on 26-Mar-2004 By Sushant Sawant
143 |                                         Fixed Bug#3484511
144 |                                         all queries referencing oe_system_parameters_all
145 |                                         should be replaced with a function call to oe_sys_parameters.value
146 |
147 |
148 |             modified on 17-May-2004     Kiran Konada
149 |
150 |                                               inserted ship_from_org-id from BCOL into the
151 |                                               validation_org col on BCOL_GT
152 |                                               code has been changed in CTO_REUSE for
153 |                                               3555026 to look at validation_org, and so
154 |                                               validation-org cannot be null
155 |
156 |             on 07/09/2004 Kiran Konada
157 |                             --bugfix#3756670, added delte before insert in bcol_gt
158 |
159 |
160 |              Modified on 21-APR-2005 By Sushant Sawant
161 |                                         Fixed Bug#4044709
162 |                                         added validate_oe_data procedure to validate bcol/bcol_gt
163 |                                         data against OEL.
164 |
165 |
166 |			16-Jun-2005	Kiran Konada
167 |					changes for OPM and Ireq
168 |					chaneg comment : OPM
169 |					check_cto_can_create_supply_api
170 |					--two new parameters l_sourcing_org and l_message
171 |					--new logic to set x_can_create_supply for processorg
172 |					and make combination.
173 |					Hard dependency:
174 |					INV_GMI_RSV_BRANCH.Process_Branch
175 |
176 |
177 |
178 +-----------------------------------------------------------------------------*/
179 
180  G_PKG_NAME CONSTANT VARCHAR2(30) := 'CTO_UTILITY_PK';
181  --Bugfix 9148706: Indexing by LONG
182  --TYPE TAB_BCOL is TABLE of bom_cto_order_lines%rowtype index by binary_integer   ;
183  TYPE TAB_BCOL is TABLE of bom_cto_order_lines%rowtype index by LONG;
184  gMrpAssignmentSet        number ;
185 
186 
187   --
188   -- Forward Declarations
189   --
190   PG_DEBUG Number := NVL(FND_PROFILE.value('ONT_DEBUG_LEVEL'), 0);
191 
192   G_ERROR_SEQ Number := 1 ; /* This number will increment for each session and will help to provide unique item key for notification for model lines resulting in multiple error messages */
193 
194 PROCEDURE populate_plan_level ( p_t_bcol  in out NOCOPY TAB_BCOL ) ;
195   PROCEDURE populate_parent_ato (
196 				p_t_bcol  	in out 	NOCOPY TAB_BCOL ,
197   				p_bcol_line_id  in  	bom_cto_order_lines.line_id%type ) ;
198   PROCEDURE initialize_assignment_set( x_return_status out NOCOPY varchar2)  ;
199 
200 
201 
202 
203 
204 /*--------------------------------------------------------------------------+
205    This function identifies the model items for which configuration items need
206    to be created and populates the temporary table bom_cto_src_orgs with all the
207    organizations that each configuration item needs to be created in.
208 +-------------------------------------------------------------------------*/
209 
210 FUNCTION Populate_Src_Orgs(pTopAtoLineId in number,
211 				x_return_status	out	NOCOPY varchar2,
212 				x_msg_count	out	NOCOPY number,
213 				x_msg_data	out	NOCOPY varchar2)
214 RETURN integer
215 IS
216 
217    lStmtNumber 	number;
218    lLineId		number;
219    lShipFromOrgId	number;
220    lStatus		number;
221 
222    cursor c_model_lines is
223       select line_id,
224              ato_line_id,
225              inventory_item_id,
226              plan_level
227       from bom_cto_order_lines
228       where ato_line_id = pTopAtoLineId
229       and bom_item_type = 1
230       and nvl(wip_supply_type,0) <> 6
231       order by plan_level;
232 
233    cursor c_parent_src_orgs is
234       select distinct bcso.organization_id
235       from bom_cto_src_orgs bcso,
236            bom_cto_order_lines bcol
237       where bcol.line_id = lLineId
238       and bcol.parent_ato_line_id = bcso.line_id
239       and bcso.create_bom = 'Y';
240 
241    cursor c_debug is
242       select line_id,
243              model_item_id,
244              rcv_org_id,
245              organization_id,
246              create_bom,
247              create_src_rules
248       from bom_cto_src_orgs
249       where top_model_line_id = pTopAtoLineId;
250 
251 BEGIN
252 
253    	IF PG_DEBUG <> 0 THEN
254    		oe_debug_pub.add('populate_plan_level: ' || 'Populate_Src_Orgs::pTopAtoLineId::'||to_char(pTopAtoLineId),1);
255    	END IF;
256 
257 	--
258 	-- For each model item in all possible receiving orgs, call
259 	-- get_all_item_orgs to populate bom_cto_src_orgs
260 	--
261 
262 	lStmtNumber := 20;
263 	IF PG_DEBUG <> 0 THEN
264 		oe_debug_pub.add('populate_plan_level: ' || 'before loop',2);
265 	END IF;
266 
267 
268 	FOR v_model_lines IN c_model_lines LOOP
269 
270 
271 		IF PG_DEBUG <> 0 THEN
272 			oe_debug_pub.add('populate_plan_level: ' || 'loop::item::'||to_char(v_model_lines.inventory_item_id)||
273 				'::line_id::'||to_char(v_model_lines.line_id),2);
274 		END IF;
275 		lStmtNumber := 30;
276 
277 		IF v_model_lines.ato_line_id = v_model_lines.line_id THEN
278 			IF PG_DEBUG <> 0 THEN
279 				oe_debug_pub.add('populate_plan_level: ' || 'ato_line_id = line_id',2);
280 			END IF;
281 
282 
283 			lStmtNumber := 40;
284 			select ship_from_org_id
285 			into lShipFromOrgId
286 			from bom_cto_order_lines
287 			where line_id = v_model_lines.line_id;
288 
289 			lStmtNumber := 50;
290 			IF PG_DEBUG <> 0 THEN
291 				oe_debug_pub.add('populate_plan_level: ' || 'before calling GAIO',2);
292 
293 				oe_debug_pub.add('populate_plan_level: ' || 'line_id::'||to_char(v_model_lines.line_id)||
294 					'::inv_id::'||to_char(v_model_lines.inventory_item_id)||
295 					'::ship_from_org::'||to_char(lShipFromOrgId),2);
296 			END IF;
297 
298 
299 			lStatus := get_all_item_orgs(v_model_lines.line_id,
300 					v_model_lines.inventory_item_id,
301 					lShipFromOrgId,
302 					x_return_status,
303 					x_msg_count,
304 					x_msg_data);
305 
306 			IF (lStatus <> 1) AND (x_return_status = FND_API.G_RET_STS_UNEXP_ERROR) THEN
307 				IF PG_DEBUG <> 0 THEN
308 					oe_debug_pub.add('populate_plan_level: ' || 'GAIO returned with unexp error',1);
309 				END IF;
310 				raise FND_API.G_EXC_UNEXPECTED_ERROR;
311 
312 			ELSIF (lStatus <> 1) AND (x_return_status = FND_API.G_RET_STS_ERROR) THEN
313 				IF PG_DEBUG <> 0 THEN
314 					oe_debug_pub.add('populate_plan_level: ' || 'GAIO returned with exp error',1);
315 				END IF;
316 				raise FND_API.G_EXC_ERROR;
317 			END IF;
318 			IF PG_DEBUG <> 0 THEN
319 				oe_debug_pub.add('populate_plan_level: ' || 'after calling GAIO::lStatus::'||to_char(lStatus),2);
320 			END IF;
321 		ELSE
322 			IF PG_DEBUG <> 0 THEN
323 				oe_debug_pub.add('populate_plan_level: ' || 'ato_line_id <> line_id',2);
324 			END IF;
325 			lStmtNumber := 60;
326 			lLineId := v_model_lines.line_id;
327 			IF PG_DEBUG <> 0 THEN
328 				oe_debug_pub.add('populate_plan_level: ' || 'before PSO loop',2);
329 			END IF;
330 
331 			FOR v_parent_src_ogs IN c_parent_src_orgs LOOP
332 				IF PG_DEBUG <> 0 THEN
333 					oe_debug_pub.add('populate_plan_level: ' || 'in PSO loop::rcv org::'||
334 						to_char(v_parent_src_ogs.organization_id),2);
335 
336 					oe_debug_pub.add('populate_plan_level: ' || 'in PSO loop::item id::'||
337 						to_char(v_model_lines.inventory_item_id),2);
338 
339 					oe_debug_pub.add('populate_plan_level: ' || 'in PSO loop::line id::'||
340 						to_char(v_model_lines.line_id),2);
341 				END IF;
342 				lStmtNumber := 70;
343 				lStatus := get_all_item_orgs(v_model_lines.line_id,
344 					v_model_lines.inventory_item_id,
345 					v_parent_src_ogs.organization_id,
346 					x_return_status,
347 					x_msg_count,
348 					x_msg_data);
349 
350 				IF (lStatus <> 1) AND (x_return_status = FND_API.G_RET_STS_UNEXP_ERROR) THEN
351 					IF PG_DEBUG <> 0 THEN
352 						oe_debug_pub.add('populate_plan_level: ' || 'GAIO returned with unexp error',1);
353 					END IF;
354 					raise FND_API.G_EXC_UNEXPECTED_ERROR;
355 
356 				ELSIF (lStatus <> 1) AND (x_return_status = FND_API.G_RET_STS_ERROR) THEN
357 					IF PG_DEBUG <> 0 THEN
358 						oe_debug_pub.add('populate_plan_level: ' || 'GAIO returned with exp error',1);
359 					END IF;
360 					raise FND_API.G_EXC_ERROR;
361 				END IF;
362 
363 			END LOOP;
364 		END IF;
365 
366 	END LOOP;
367 
368 	IF PG_DEBUG <> 0 THEN
369 		oe_debug_pub.add('populate_plan_level: ' || 'end of loop',1);
370 
371 		oe_debug_pub.add('populate_plan_level: ' || 'printing out bcso :', 2);
372 
373 		oe_debug_pub.add('populate_plan_level: ' || 'line_id  model_item_id  rcv_org_id  org_id  create_bom create_src_rules', 2);
374 	END IF;
375 
376 	FOR v_debug IN c_debug LOOP
377 		IF PG_DEBUG <> 0 THEN
378 			oe_debug_pub.add('populate_plan_level: ' || to_char(v_debug.line_id)||'  '||
379 					to_char(v_debug.model_item_id)||'  '||
380 					nvl(to_char(v_debug.rcv_org_id),null)||'  '||
381 					to_char(v_debug.organization_id)||'  '||
382 					nvl(v_debug.create_bom, null)||'  '||
383 					nvl(v_debug.create_src_rules, null), 2);
384 		END IF;
385 	END LOOP;
386 
387 	return(1);
388 
389 EXCEPTION
390 
391 	when FND_API.G_EXC_UNEXPECTED_ERROR then
392 		IF PG_DEBUG <> 0 THEN
393 			oe_debug_pub.add('populate_plan_level: ' || 'Populate_Src_Orgs::unexp error::'||lStmtNumber||sqlerrm,1);
394 		END IF;
395 		x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
396 		CTO_MSG_PUB.Count_And_Get
397         		(p_msg_count => x_msg_count
398         		,p_msg_data  => x_msg_data
399         		);
400 		return(0);
401 
402 	when FND_API.G_EXC_ERROR then
403 		IF PG_DEBUG <> 0 THEN
404 			oe_debug_pub.add('populate_plan_level: ' || 'Populate_Src_Orgs::exp error::'||lStmtNumber||sqlerrm,1);
405 		END IF;
406 		x_return_status := FND_API.G_RET_STS_ERROR;
407 		CTO_MSG_PUB.Count_And_Get
408 			(p_msg_count => x_msg_count
409 			,p_msg_data  => x_msg_data);
410 		return(0);
411 
412 	when others then
413 		IF PG_DEBUG <> 0 THEN
414 			oe_debug_pub.add('populate_plan_level: ' || 'Populate_Src_Orgs::others::'||lStmtNumber||sqlerrm,1);
415 		END IF;
416 		x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
417 		IF FND_MSG_PUB.Check_Msg_Level(FND_MSG_PUB.G_MSG_LVL_UNEXP_ERROR) THEN
418             		FND_MSG_PUB.Add_Exc_Msg
419             			(G_PKG_NAME
420             			,'populate_src_orgs'
421             			);
422         	END IF;
423 		CTO_MSG_PUB.Count_And_Get
424         		(p_msg_count => x_msg_count
425         		,p_msg_data  => x_msg_data
426         		);
427 		return(0);
428 
429 END Populate_Src_Orgs;
430 
431 
432 
433 
434 /*--------------------------------------------------------------------------+
435    This function populates the table bom_cto_src_orgs with all the organizations
436    in which a configuration item needs to be created.
437    The organizations include all potential sourcing orgs, receiving orgs,
438    OE validation org and PO validation org.
439    The line_id, rcv_org_id, organization_id combination is unique.
440    It is called by Populate_Src_Orgs.
441 +-------------------------------------------------------------------------*/
442 
443 
444 /*--------------------------------------------------------------------------+
445  --- Modified by Renga Kannan on 08/21/01 for procuring configuration Phase I
446  --- This function is modified to support Buy sourcing and source type
447 
448     The following is the main logic for Procuring Configuration
449 
450        1. The sourcing rule should not ignore the BUY sourcing rules.
451        2. You can have more than one buy sourcing rule. But you cannot have any combinations
452        3. For the Buy model and its children in bcol the Buy_item_type_flag is populated with Y.
453 	  Otherwise it will be 'N'
454        4. For Top Buy model in bcso the source_type is populated with 3.
455           All of its child it is populated with 4.
456        5. For the given parent_ato_model there will be only one row in the combination
457 	  of create_bom = 'y' and source_type = 3.
458           That will be the top buy model in that level.
459        6. For Buy model and its lower level components the copy_src_rule will
460 	  allways set to be 'Y' in bcol.
461 
462 +-------------------------------------------------------------------------*/
463 
464 
465 FUNCTION Get_All_Item_Orgs( pLineId            in  number,
466 		            pModelItemId       in  number,
467 			    pRcvOrgId          in  number,
468 			    x_return_status    out NOCOPY varchar2,
469 			    x_msg_count	       out NOCOPY number,
470 			    x_msg_data	       out NOCOPY varchar2)
471 RETURN integer
472 IS
473 
474    gUserId		number;
475    gLoginId		number;
476    lStmtNumber		number;
477    lMrpAssignmentSet	number;
478    lTopAtoLineId	number;
479    lExists		varchar2(10);
480    lProfileVal		number;
481    lValidationOrg	number;
482    lPoVAlidationOrg	number;
483    l_curr_RcvOrgId	number;
484    l_curr_src_org	number;
485    l_curr_assg_type	number;
486    l_curr_rank		number;
487    l_circular_src	varchar2(1);
488 
489    -- Added by Renga Kannan to get the source_type value
490 
491    l_source_type           number;
492    l_sourcing_rule_count   number;
493    l_parent_ato_line_id    Number;
494    l_make_buy_code         number;
495 
496    -- End of addition on 08/26/01 for procuring configuration
497 
498    multiorg_error	exception;
499    po_multiorg_error	exception;
500    lProgramId           bom_cto_order_lines.program_id%type ;
501 
502    v_source_type_code   oe_order_lines_all.source_type_code%type ;
503 
504    CURSOR c_circular_src IS
505       select 'Y'
506       from bom_cto_src_orgs bcso
507       where line_id = pLineId
508       and model_item_id = pModelItemId
509       and rcv_org_id = l_curr_src_org;
510 
511 
512 BEGIN
513 
514 
515 	--
516 	-- pLineId is the line_id of the model line
517 	--
518 
519 	lStmtNumber := 10;
520 	gUserId := nvl(fnd_global.user_id, -1);
521 	gLoginId := nvl(fnd_global.login_id, -1);
522 
523 	/* get top model's ato_line_id */
524 	--
525 	-- The column top_model_line_id in bom_cto_src_orgs is being used
526 	-- to store the ato_line_id of the top ATO model
527 	-- This change was required in order to support multiple ATO models
528 	-- under a PTO model
529 	--
530 
531         -- Added by Renga Kannan on 08/26/01
532         -- Get the buy_item_flag from bcol for the given line id.
533         -- If the buy_item_flag = 'Y' that means this part of some buy model
534         -- In that case we should not look for sourcing rules for this model
535         -- We need to create the item in its parents org.
536 
537 	lStmtNumber := 20;
538 
539 /*
540         select ato_line_id,
541                program_id
542         into lTopAtoLineId,
543              lProgramId
544         from bom_cto_order_lines
545         where line_id = pLineId;
546 */
547 
548 
549         /* BUG#1957336 Changes introduced by sushant for preconfigure bom */
550 
551 	select ato_line_id,parent_ato_line_id, nvl(program_id,0) /* added by sushant for preconfigure bom identification */
552 	into lTopAtoLineId,l_parent_ato_line_id, lProgramId
553 	from bom_cto_order_lines
554 	where line_id = pLineId;
555 
556         -- Get the source type of its  parent Model line
557         -- If the parent model is of buy type we should not look for
558         -- sourcing this model
559 
560         lStmtNumber := 25;
561 
562         BEGIN
563            Select organization_type
564            Into   l_source_type
565            from   bom_cto_src_orgs bcso
566            where  bcso.line_id = l_parent_ato_line_id
567            and    bcso.create_bom         = 'Y';
568         EXCEPTION WHEN NO_DATA_FOUND THEN
569            Null;
570         END;
571 
572 	IF PG_DEBUG <> 0 THEN
573 		oe_debug_pub.add('populate_plan_level: ' || 'top ato line id::'||to_char(lTopAtoLineId),2);
574 
575 		oe_debug_pub.add('populate_plan_level: ' || 'rcv org id::'||to_char(pRcvOrgId),2);
576 
577 		oe_debug_pub.add('populate_plan_level: ' || 'model item id::'||to_char(pModelItemId),2);
578 	END IF;
579 
580         -- Added by Renga Kannan on 08/23/01 for procuring configuration
581 
582         IF PG_DEBUG <> 0 THEN
583         	oe_debug_pub.add('populate_plan_level: ' || 'Parent ATO line id = '||l_parent_ato_line_id,1);
584 
585         	oe_debug_pub.add('populate_plan_level: ' || 'Parent source type = '||l_source_type,1);
586         END IF;
587 
588 
589 
590 
591         lStmtNumber := 28 ;
592 
593         if( lProgramId = CTO_UTILITY_PK.PC_BOM_PROGRAM_ID ) then
594 
595             v_source_type_code := 'INTERNAL' ;
596 
597         IF PG_DEBUG <> 0 THEN
598         	oe_debug_pub.add('populate_plan_level: ' || ' pc bom source type code = '|| v_source_type_code ,1);
599         END IF;
600         else
601 
602             select source_type_code
603               into v_source_type_code
604               from oe_order_lines_all
605               where line_id = pLineId ;
606 
607         IF PG_DEBUG <> 0 THEN
608         	oe_debug_pub.add('populate_plan_level: ' || ' non pc bom source type code = '|| v_source_type_code ,1);
609         END IF;
610 
611         end if ;
612 
613         IF PG_DEBUG <> 0 THEN
614         	oe_debug_pub.add('populate_plan_level: ' || 'source type code = '|| v_source_type_code ,1);
615         END IF;
616 
617 
618 	lStmtNumber := 30;
619 	/* get MRP's default assignment set */
620 	lMrpAssignmentSet := to_number(FND_PROFILE.VALUE('MRP_DEFAULT_ASSIGNMENT_SET'));
621 
622         --- The following if condition is added by Renga Kannan
623         --- If the line is part of buy model then we need not look at the sourcing info
624         --- we can keep the parents rcv org as the org for this item also. This can be identified
625         --- from the bom_cto_order_lines_table flag
626 
627 
628         lStmtNumber := 32;
629 
630         IF nvl(l_source_type,'2') in (3,4)  THEN
631            -- Since this is part of existing buy model
632            -- Set the source_type to 4 which is the indication for child buy model
633            -- Since we are not looking at the sourcing here we need to set this flag as Y so that the sourcing rule
634            -- will be copied
635            lStmtNumber := 35;
636            l_source_type    := 4;
637            IF PG_DEBUG <> 0 THEN
638            	oe_debug_pub.add('populate_plan_level: ' || ' This is part of Buy model... No need to look for sourcing...',1);
639            END IF;
640 
641 
642 
643 
644 
645         /* BUG# 2234858
646         ** BUG# 2310356
647         ** Sushant Added this for Drop Shipment Project
648         */
649 
650         ELSIF nvl(l_source_type,'2') in (5,6)  THEN
651 
652 
653 
654            l_source_type := 6 ;
655            IF PG_DEBUG <> 0 THEN
656            	oe_debug_pub.add('populate_plan_level: ' || ' This is part of Drop Ship model...',1);
657            END IF;
658 
659 
660 
661 
662         ELSE
663 
664 	IF lMrpAssignmentSet is null THEN
665 		IF PG_DEBUG <> 0 THEN
666 			oe_debug_pub.add('populate_plan_level: ' || 'Default assignment set is null',1);
667 		END IF;
668 
669 
670                  -- added by Renga Kannan on 08/21/01
671                  -- When there is no sourcing rule defined we need to check for the make_buy_type of the
672                  -- item to determine the buy model
673 
674                  lStmtNumber := 38;
675 
676                  -- The following select statement is modified by Renga Kannan
677                  -- On 12/21/01. The where condition organization_id is modified
678 
679 
680             if( v_source_type_code = 'INTERNAL' ) then
681                  select planning_make_buy_code
682                  into   l_make_buy_code
683                  from   MTL_SYSTEM_ITEMS
684                  where  inventory_item_id = pModelItemId
685                  and    organization_id   = pRcvOrgId;
686 
687 
688                 IF PG_DEBUG <> 0 THEN
689                 	oe_debug_pub.add('populate_plan_level: ' || 'Make buy code:: 1 means make 2 means buy',1);
690 
691                 	oe_debug_pub.add('populate_plan_level: ' || 'Planning make buy code for this item is ='||to_char(l_make_buy_code),1);
692                 END IF;
693 
694                  IF l_make_buy_code = 2 then
695                    l_source_type := 3; ----- Buy Type
696                  END IF;
697 
698 
699             else
700 
701 
702                    l_source_type := 5; ----- Drop Ship Type -- BUG#2310356
703 
704 
705             end if ;
706 
707 
708 	ELSE
709 		IF PG_DEBUG <> 0 THEN
710 			oe_debug_pub.add('populate_plan_level: ' || 'Default assignment set is '||to_char(lMrpAssignmentSet),2);
711 		END IF;
712 
713 
714 		--
715 		-- For the given model_item_id, receiving org and default
716 		-- assignment set, traverse the chain of sourcing rules and
717 		-- populate bom_cto_src_orgs with each source, till the final
718 		-- source is reached.
719 		-- Set the create_bom flag in the final source only
720 		-- Error out if multiple or circular src rules are found
721 		--
722 
723 		lStmtNumber := 40;
724 
725 		l_curr_RcvOrgId := pRcvOrgId;
726 
727 		LOOP 	--for chain sourcing
728 
729 		-- The following sql statement is modified by Renga Kannan on 04/30/2001.
730                 -- If the sourcing rule is assingned in the oganization paramerter the source_type
731                 -- will be null. But we need to consider that sourcing rule also. So the where condition
732                 -- is changed to have nvl function in the query.
733 
734 		BEGIN
735 
736 		lStmtNumber := 50;
737 		IF PG_DEBUG <> 0 THEN
738 			oe_debug_pub.add('populate_plan_level: ' || 'Getting source for rcv org::'||to_char(l_curr_RcvOrgId), 2);
739 		END IF;
740 
741                 -- Modified by Renga Kannan on 08/21/01 to honor the BUY sourcing and make_buy_code also
742                 -- The where condition in the select statement for source_type is removed. The source_type
743                 -- is selected to local variable for further evaluation
744 
745 
746 		select
747 			nvl(msv.source_organization_id,l_curr_RcvOrgId),
748 			msv.assignment_type,
749 			msv.rank,
750                         nvl(msv.source_type,1)
751 		into
752 			l_curr_src_org,
753 			l_curr_assg_type,
754 			l_curr_rank,
755                         l_source_type
756 		from mrp_sources_v msv
757 		where msv.assignment_set_id = lMrpAssignmentSet
758 		and msv.inventory_item_id = pModelItemId
759 		and msv.organization_id = l_curr_RcvOrgId
760 		--and nvl(msv.source_type,1) <> 3                 -- Commented by Renga Kannan on 08/21/01
761 		and nvl(effective_date,sysdate) <= nvl(disable_date, sysdate)
762 		and nvl(disable_date, sysdate+1) > sysdate;
763 
764 
765 
766 
767                 /* Special Processing needs to be incorporated for Drop Ship
768                    If a single make or buy rule exists in the case of drop shipped orders
769                    you should be ignoring it and still be consistent with buy functionality
770                 */
771                 /* BUG#2310356 Always default source type to 5 in case of dropship */
772                 if( v_source_type_code = 'EXTERNAL' ) then
773                     if(  l_source_type =  3  ) then
774                       l_source_type    := 5; --- Drop Ship sourcing Type
775                       l_curr_src_org   := l_curr_RcvOrgId;
776                       l_curr_rank      := null;
777                     else
778                        raise NO_DATA_FOUND ;
779                     end if ;
780 
781                 end if ;
782 
783 		IF PG_DEBUG <> 0 THEN
784 			oe_debug_pub.add('populate_plan_level: ' || 'Source for this rcv org::'||to_char(l_curr_src_org),2);
785 
786                 	oe_debug_pub.add('populate_plan_level: ' || 'Source type = '||to_char(l_source_type),2);
787                 END IF;
788 
789 		EXCEPTION
790 
791 		WHEN TOO_MANY_ROWS THEN
792 
793                         -- Modified by Renga Kannan on 08/21/01
794                         -- We can define more than one buy sourcing rule. But all the sourcing should
795                         -- be of 'BUY' type. If not then it is treated as multiple sourcing error.
796                         -- This can be verified by the following query. count the no of sourcing rules other than
797                         -- Buy sourcing. If it is more than zero that means multiple sourcing found.
798 
799 
800                        lStmtNumber := 52;
801 
802                        select count(*)
803                        into l_sourcing_rule_count
804                        from mrp_sources_v msv
805                        where msv.assignment_set_id = lMrpAssignmentSet
806                        and msv.inventory_item_id = pModelItemId
807                        and msv.organization_id = l_curr_RcvOrgId
808                        and nvl(msv.source_type,1) <> 3
809                        and nvl(effective_date,sysdate) <= nvl(disable_date, sysdate)
810                        /* Nvl fun is added by Renga Kannan on 05/05/2001 */
811                        and nvl(disable_date, sysdate+1) > sysdate;
812 
813                        IF l_sourcing_rule_count > 0 then
814 
815 			-- multiple sources defined
816 			IF PG_DEBUG <> 0 THEN
817 				oe_debug_pub.add('populate_plan_level: ' || 'Multiple sources defined for model '||to_char(pModelItemId)
818                                                                               ||', org '||to_char(l_curr_RcvOrgId), 1);
819 			END IF;
820 
821 
822                         -- The following message handling is modified by Renga Kannan
823                         -- We need to give the add for once to FND function and other
824                         -- to OE, in both cases we need to set the message again
825                         -- This is because if we not set the token once again the
826                         -- second add will not get the message.
827 
828                         cto_msg_pub.cto_message('BOM','CTO_INVALID_SOURCING');
829 			raise FND_API.G_EXC_ERROR;
830                       ELSE
831 
832                         IF PG_DEBUG <> 0 THEN
833                         	oe_debug_pub.add('populate_plan_level: ' || 'This model is having buy sourcing rule...',1);
834                         END IF;
835 
836 
837                         if( v_source_type_code = 'INTERNAL' ) then
838                             l_source_type    := 3; --- Buy sourcing Type
839                             l_curr_src_org   := l_curr_RcvOrgId;
840                             l_curr_rank      := null;
841 
842                         else
843                             l_source_type    := 5; --- Drop Ship sourcing Type
844                             l_curr_src_org   := l_curr_RcvOrgId;
845                             l_curr_rank      := null;
846 
847 
848                         end if ;
849 
850 
851                         -- The assignment set is defaulted to 6 cuz, this will force the
852                         -- Create_src_rules flag to 'Y' in bcso
853                         -- the create sourcing rule will create the sourcing for buy
854                         -- Sourcing rules.
855 
856                         l_curr_assg_type := 6;
857 
858                       END IF;
859 
860 
861 		WHEN NO_DATA_FOUND THEN
862 
863 
864 
865                      if( v_source_type_code = 'INTERNAL' ) then
866 
867 
868 
869 			-- end of chain, exit out of loop
870 			-- update final src for BOM creation
871 			IF PG_DEBUG <> 0 THEN
872 				oe_debug_pub.add('populate_plan_level: ' || 'NDF::End of chain for model '||to_char(pModelItemId), 1);
873 			END IF;
874 
875                         -- added by Renga Kannan on 08/21/01
876                         -- When there is no sourcing rule defined we need to check for the make_buy_type of the
877                         -- item to determine the buy model
878 
879                         lStmtNumber := 57;
880 
881                        -- The following block of sql is modified by Renga Kannan on 11/08/01
882                        -- I've added an NO DATA FOUDN excpetion to this sql
883                        -- When the item is not defined in the sourcing org it needs to be
884                        -- treated as INVALID sourcing
885                        -- I've also modified the CTO_INVALID_SOURCING message to have this as one of the
886                        -- Causes.
887 
888                         BEGIN
889 
890                            SELECT planning_make_buy_code
891                            INTO   l_make_buy_code
892                            FROM   MTL_SYSTEM_ITEMS
893                            WHERE  inventory_item_id = pModelItemId
894                            AND    organization_id   = l_curr_RcvOrgId;
895 
896                         EXCEPTION
897                         WHEN NO_DATA_FOUND THEN
898 
899                            IF PG_DEBUG <> 0 THEN
900                            	oe_debug_pub.add('populate_plan_level: ' || 'Inventory_item_id  = '|| to_char(pModelItemId),1);
901 
902                            	oe_debug_pub.add('populate_plan_level: ' || 'Organization id    = '|| to_char(l_curr_RcvOrgId),1);
903 
904                            	oe_debug_pub.add('populate_plan_level: ' || 'ERROR::The item is not defined in the sourcing org',1);
905                            END IF;
906 
907 
908                            -- The following message handling is modified by Renga Kannan
909                            -- We need to give the add for once to FND function and other
910                            -- to OE, in both cases we need to set the message again
911                            -- This is because if we not set the token once again the
912                            -- second add will not get the message.
913 
914                            cto_msg_pub.cto_message('BOM','CTO_INVALID_SOURCING');
915                            raise FND_API.G_EXC_ERROR;
916 
917                         END;
918 
919                         -- End of addition by Renga on 11/07/01
920 
921                         IF PG_DEBUG <> 0 THEN
922                         	oe_debug_pub.add('populate_plan_level: ' || 'Planning Make_buy_code for this model = '||l_make_buy_code,1);
923                         END IF;
924 
925                         IF l_make_buy_code = 2 then
926                           l_source_type := 3; ----- Buy Type
927                           IF PG_DEBUG <> 0 THEN
928                           	oe_debug_pub.add('populate_plan_level: ' || 'This model is a buy model...',1);
929                           END IF;
930                         END IF;
931 
932 
933                       else
934 
935 
936                           l_source_type := 5; ----- Drop Ship  Type
937                           l_curr_src_org   := l_curr_RcvOrgId;
938                           l_curr_rank      := null;
939                           IF PG_DEBUG <> 0 THEN
940                           	oe_debug_pub.add('populate_plan_level: ' || 'This model is a buy model...',1);
941                           END IF;
942 
943                       end if ;
944 
945                           /* This statement needs to be there to account for all passess except first pass */
946 
947 			  lStmtNumber := 60;
948 			  update bom_cto_src_orgs
949 			  set create_bom = 'Y',organization_type = l_source_type
950 			  where line_id = pLineId
951 			  and model_item_id = pModelItemId
952 			  and organization_id = l_curr_src_org;
953 
954 			  IF PG_DEBUG <> 0 THEN
955 			  	oe_debug_pub.add('populate_plan_level: ' || 'Rows updated::'||sql%rowcount,2);
956 			  END IF;
957 			  EXIT;
958 
959 
960 
961 		END;
962 
963 		lStmtNumber := 90;
964 		OPEN c_circular_src;
965 		FETCH c_circular_src into l_circular_src;
966 		CLOSE c_circular_src;
967 
968 		lStmtNumber := 100;
969 		IF l_circular_src = 'Y' THEN
970 			-- circular sourcing defined
971 			lStmtNumber := 110;
972 			IF PG_DEBUG <> 0 THEN
973 				oe_debug_pub.add('populate_plan_level: ' || 'Circular sourcing defined for model '
974                                          ||to_char(pModelItemId)
975                                          ||' in org '
976                                          ||to_char(pRcvOrgId), 1);
977 			END IF;
978 
979                         cto_msg_pub.cto_message('BOM','CTO_INVALID_SOURCING');
980 			raise FND_API.G_EXC_ERROR;
981 		END IF;
982 
983 		lStmtNumber := 120;
984 		insert into bom_cto_src_orgs
985 				(
986 				top_model_line_id,
987 				line_id,
988 				model_item_id,
989 				rcv_org_id,
990 				organization_id,
991 				create_bom,
992 				cost_rollup,
993 				organization_type, -- Used to store the source type
994 				config_item_id,
995 				create_src_rules,
996 				rank,
997 				creation_date,
998 				created_by,
999 				last_update_date,
1000 				last_updated_by,
1001 				last_update_login,
1002 				program_application_id,
1003 				program_id,
1004 				program_update_date
1005 				)
1006 		select -- distinct
1007 				lTopAtoLineId,
1008 				pLineId,
1009 				pModelItemId,
1010 				l_curr_RcvOrgId,
1011 				l_curr_src_org,
1012 				'N',		-- create_bom
1013 				'Y',		-- cost_rollup
1014 				l_source_type,	-- org_type is used to store the source type
1015 				NULL,		-- config_item_id
1016 				decode(l_curr_assg_type, 6, 'Y', 3, 'Y', 'N'),
1017 				l_curr_rank,
1018 				sysdate,	-- creation_date
1019 				gUserId,	-- created_by
1020 				sysdate,	-- last_update_date
1021 				gUserId,	-- last_updated_by
1022 				gLoginId,	-- last_update_login
1023 				null, 		-- program_application_id,??
1024 				null, 		-- program_id,??
1025 				sysdate		-- program_update_date
1026 		from dual;
1027 
1028                 /*
1029                 This statement has to be there to exit after the first pass
1030                 for buy and dropship to avoid pursuing make/transfer, make/transfer chains
1031                 */
1032 
1033 		lStmtNumber := 130;
1034 		IF (l_curr_src_org = l_curr_RcvOrgId) THEN
1035 			-- end of chain, exit out of loop
1036 			-- update final src for BOM creation
1037 			IF PG_DEBUG <> 0 THEN
1038 				oe_debug_pub.add('populate_plan_level: ' || 'End of chain for model '||to_char(pModelItemId), 1);
1039 			END IF;
1040 
1041 
1042                         --- The source type column is added by Renga Kannan on 08/21/01
1043 
1044 			lStmtNumber := 140;
1045 			update bom_cto_src_orgs
1046 			set create_bom = 'Y', organization_type = l_source_type
1047 			where line_id = pLineId
1048 			and model_item_id = pModelItemId
1049 			and organization_id = l_curr_src_org
1050 			and rcv_org_id = l_curr_RcvOrgId;
1051 
1052 			EXIT;
1053 		END IF;
1054 
1055 		IF PG_DEBUG <> 0 THEN
1056 			oe_debug_pub.add('populate_plan_level: ' || 'inserted rcv org::'||to_char(l_curr_RcvOrgId)||' src org::'||to_char(l_curr_src_org), 2);
1057 		END IF;
1058 		l_curr_RcvOrgId := l_curr_src_org;
1059 
1060 		END LOOP;
1061 		--<<chain_loop>>
1062 		IF PG_DEBUG <> 0 THEN
1063 			oe_debug_pub.add('populate_plan_level: ' || 'after insert 1',2);
1064 		END IF;
1065 	END IF; /* MRP profile is not null */
1066 
1067         END IF; /* check for DROP SHIP , BUY_ITEM_FLAG is not Y */
1068 
1069 	--
1070 	-- If mrp_sources_v does not insert any rows into
1071 	-- bom_cto_src_orgs, this means that no sourcing rules are set-up
1072 	-- for this model item in this org. Assuming that in this case
1073 	-- the item in this org is sourced from itself, inserting a row
1074 	-- with the receiving org as the sourcing org
1075 
1076 	lStmtNumber := 150;
1077 	insert into bom_cto_src_orgs
1078 		(
1079 		top_model_line_id,
1080 		line_id,
1081 		model_item_id,
1082 		rcv_org_id,
1083 		organization_id,
1084 		create_bom,
1085 		cost_rollup,
1086 		organization_type,
1087 		config_item_id,
1088 		create_src_rules,
1089 		rank,
1090 		creation_date,
1091 		created_by,
1092 		last_update_date,
1093 		last_updated_by,
1094 		last_update_login,
1095 		program_application_id,
1096 		program_id,
1097 		program_update_date
1098 		)
1099 	select
1100 		lTopAtoLineId,
1101 		pLineId,
1102 		pModelItemId,
1103 		pRcvOrgId,
1104 		pRcvOrgId,
1105 		'Y',		-- create_bom
1106 		decode( l_source_type , 4 , 'N' , 6 , 'N' , 'Y' ) , -- cost_rollup
1107 		l_source_type,	-- org_type is used to store the source_type
1108 		NULL,		-- config_item_id
1109 		decode(l_curr_assg_type,6,'Y',3,'Y','N'), -- create_src_rules
1110 		NULL,		-- rank, n/a
1111 		sysdate,	-- creation_date
1112 		gUserId,	-- created_by
1113 		sysdate,	-- last_update_date
1114 		gUserId,	-- last_updated_by
1115 		gLoginId,	-- last_update_login
1116 		null, 		-- program_application_id,??
1117 		null, 		-- program_id,??
1118 		sysdate		-- program_update_date
1119 	from dual
1120 	where NOT EXISTS
1121 		(select NULL
1122 		from bom_cto_src_orgs
1123 		where line_id = pLineId
1124 		and model_item_id = pModelItemId);
1125 
1126 	IF PG_DEBUG <> 0 THEN
1127 		oe_debug_pub.add('populate_plan_level: ' || 'after insert 2',2);
1128 	END IF;
1129 
1130 	--
1131 	-- Next, populate bom_cto_src_orgs with the
1132 	-- receiving org for the model item
1133 	-- If the org already exists for this item,
1134 	-- do nothing, else insert a new row
1135 
1136         -- Added by Renga Kannan to include one more column source_type to it.
1137 
1138 	lStmtNumber := 160;
1139 
1140 	insert into bom_cto_src_orgs
1141 		(
1142 		top_model_line_id,
1143 		line_id,
1144 		model_item_id,
1145 		rcv_org_id,
1146 		organization_id,
1147 		create_bom,
1148 		cost_rollup,
1149 		organization_type, -- Used to store the Source type
1150 		config_item_id,
1151 		create_src_rules,
1152 		rank,
1153 		creation_date,
1154 		created_by,
1155 		last_update_date,
1156 		last_updated_by,
1157 		last_update_login,
1158 		program_application_id,
1159 		program_id,
1160 		program_update_date
1161 		)
1162 	select
1163 		lTopAtoLineId,
1164 		pLineId,
1165 		pModelItemId,
1166 		NULL,		-- rec_org_id
1167 		pRcvOrgId,
1168 		'N',		-- create_bom
1169 		'N',		-- cost_rollup
1170 		l_source_type,	-- org_type is used to store the source type
1171 		NULL,		-- config_item_id
1172 		NULL,		-- create_src_rules, n/a
1173 		NULL,		-- rank, n/a
1174 		sysdate,	-- creation_date
1175 		gUserId,	-- created_by
1176 		sysdate,	-- last_update_date
1177 		gUserId,	-- last_updated_by
1178 		gLoginId,	-- last_update_login
1179 		null, 		-- program_application_id,??
1180 		null, 		-- program_id,??
1181 		sysdate		-- program_update_date
1182 	from dual
1183 	where NOT EXISTS
1184 		(select NULL
1185 		from bom_cto_src_orgs
1186 		where line_id = pLineId
1187 		and model_item_id = pModelItemId
1188 		and organization_id = pRcvOrgId);
1189 
1190 	IF PG_DEBUG <> 0 THEN
1191 		oe_debug_pub.add('populate_plan_level: ' || 'after insert 3',2);
1192 	END IF;
1193 
1194 	--
1195 	-- Next, get the OE validation org and populate it in
1196 	-- bom_cto_src_orgs
1197 	-- If the org already exists for this item,
1198 	-- do nothing, else insert a new row
1199 	--
1200 	lStmtNumber := 170;
1201 	IF PG_DEBUG <> 0 THEN
1202 		oe_debug_pub.add('populate_plan_level: ' ||  'Before getting validation org',2);
1203 	END IF;
1204 
1205 	lStmtNumber := 180;
1206 
1207 
1208         /* BUG#1957336 Changes introduced by sushant for preconfigure bom */
1209         /* Added by Sushant for preconfigure bom module */
1210         if( lProgramId = PC_BOM_PROGRAM_ID ) then
1211             lValidationOrg := PC_BOM_VALIDATION_ORG ;
1212 
1213         else
1214 
1215           /*
1216             Bug#3484511
1217             Code has been replaced due to 11.5.10 OM data model change
1218             ----------------------------------------------------------
1219             select nvl(master_organization_id,-99)	-- bugfix 2646849: master_organization_id can be 0
1220             into   lValidationOrg
1221             from   oe_order_lines_all oel,
1222                    oe_system_parameters_all ospa
1223             where  oel.line_id = pLineid
1224             and    nvl(oel.org_id, -1) = nvl(ospa.org_id, -1)  --bug 1531691
1225             and    oel.inventory_item_id = pModelItemId;
1226 
1227           */
1228 
1229   	   IF PG_DEBUG <> 0 THEN
1230   		oe_debug_pub.add('populate_plan_level: ' ||  'Going to fetch Validation Org ' ,2);
1231   	   END IF;
1232 
1233 
1234            select nvl( oe_sys_parameters.value( 'MASTER_ORGANIZATION_ID' , oel.org_id) , -99)
1235               into lValidationOrg from oe_order_lines_all oel
1236            where oel.line_id = pLineId ;
1237 
1238 
1239 
1240         end if ;
1241 
1242 
1243      	if lVAlidationOrg = -99 then			-- bugfix 2646849
1244                 cto_msg_pub.cto_message('BOM','CTO_INVALID_SOURCING');
1245        		raise FND_API.G_EXC_ERROR;
1246     	end if;
1247   	IF PG_DEBUG <> 0 THEN
1248   		oe_debug_pub.add('populate_plan_level: ' ||  'Validation Org is :' ||  lValidationOrg,2);
1249   	END IF;
1250 
1251 	lStmtNumber := 190;
1252 
1253 	insert into bom_cto_src_orgs
1254 		(
1255 		top_model_line_id,
1256 		line_id,
1257 		model_item_id,
1258 		rcv_org_id,
1259 		organization_id,
1260 		create_bom,
1261 		cost_rollup,
1262 		organization_type,
1263 		config_item_id,
1264 		create_src_rules,
1265 		rank,
1266 		creation_date,
1267 		created_by,
1268 		last_update_date,
1269 		last_updated_by,
1270 		last_update_login,
1271 		program_application_id,
1272 		program_id,
1273 		program_update_date
1274 		)
1275 	select
1276 		lTopAtoLineId,
1277 		pLineId,
1278 		pModelItemId,
1279 		NULL,		-- rec_org_id
1280 		lValidationOrg,
1281 		'N',		-- create_bom
1282 		'N',		-- cost_rollup
1283 		NULL,		-- org_type, pending
1284 		NULL,		-- config_item_id
1285 		NULL,		-- create_src_rules, n/a
1286 		NULL,		-- rank, n/a
1287 		sysdate,	-- creation_date
1288 		gUserId,	-- created_by
1289 		sysdate,	-- last_update_date
1290 		gUserId,	-- last_updated_by
1291 		gLoginId,	-- last_update_login
1292 		null, 		-- program_application_id,??
1293 		null, 		-- program_id,??
1294 		sysdate		-- program_update_date
1295 	from dual
1296 	where NOT EXISTS
1297 		(select NULL
1298 		from bom_cto_src_orgs
1299 		where line_id = pLineId
1300 		and model_item_id = pModelItemId
1301 		and organization_id = lVAlidationOrg);
1302 
1303 	IF PG_DEBUG <> 0 THEN
1304 		oe_debug_pub.add('populate_plan_level: ' || 'after insert 4',2);
1305 	END IF;
1306 
1307 	--
1308 	-- Next, get the PO validation org and populate it in
1309 	-- bom_cto_src_orgs. If PO val org is -99, (bugfix 2646849: changed from 0 to -99) null or not setup,
1310 	-- we will not populate a row for PO val org, and will not
1311 	-- error out.
1312 	-- If the org already exists for this item,
1313 	-- do nothing, else insert a new row
1314 	--
1315 	IF PG_DEBUG <> 0 THEN
1316 		oe_debug_pub.add('populate_plan_level: ' ||  'Before getting validation org',2);
1317 	END IF;
1318 
1319 	lStmtNumber := 200;
1320 	BEGIN
1321 
1322 
1323 
1324         /* BUG#1957336 Changes introduced by sushant for preconfigure bom */
1325         /* Added by sushant for preconfigure bom */
1326 
1327         if( lProgramId = PC_BOM_PROGRAM_ID ) then
1328             lPoValidationOrg := PC_BOM_VALIDATION_ORG ;
1329 
1330         else
1331 
1332  	    -- Modifying the following sql statment.
1333             -- Right now the po validation org is derived from
1334             -- order_lines operating unit. This is wrong
1335             -- We should derive the Po_validation org for a model
1336             -- based on receiving organizations operating unit.
1337             -- I am changing the select to get the row from bcso with create_bom = 'Y'
1338             -- which will give me the last receiving organization.
1339 
1340 	    -- We have made this decision after revisiting the Operating unit issue
1341             -- for Procured configurations.
1342    	    -- Modified by Renga Kannan  03/08/01
1343 
1344 	    begin
1345             -- rkaza. 3742393. 08/12/2004.
1346             -- Replacing org_organization_definitions with
1347             -- inv_organziation_info_v
1348 
1349             select 	nvl(fsp.inventory_organization_id,-99)		--bugfix 2646849: 0 can be a valid orgn_id.
1350             into 	lPoValidationOrg
1351             from 	bom_cto_src_orgs bcso,
1352             		financials_system_params_all fsp,
1353 			inv_organization_info_v org
1354             where 	bcso.line_id = pLineId
1355             and 	bcso.create_bom = 'Y'
1356 	    and 	bcso.organization_id = org.organization_id
1357             and 	nvl(fsp.org_id, -1) = nvl(org.Operating_unit, -1);  --bug 1531691
1358             Exception when no_data_found then
1359 	          lPoValidationOrg := -99; 				-- bugfix 2646849
1360             End;
1361 
1362         end if ;
1363 
1364 
1365         IF PG_DEBUG <> 0 THEN
1366         	oe_debug_pub.add('populate_plan_level: ' || 'Po Validation Org ='||to_char(lpovalidationorg),1);
1367         END IF;
1368 
1369 
1370 
1371         /* Added By Renga Kannan on 10/23/01
1372 
1373            IF the po_validation org is not set then out program needs to error out
1374            as part of Procuring design. When I discussed this with USHA ARORA, We foudn
1375            that we need to check only if there is any procuring models. For make model
1376            case even if the po validation org is not setup we need not error out. That is the
1377            existing funtionality. Hence I am making a check for procuring model here.
1378 
1379         */
1380 
1381         IF l_source_type in (3,4, 5, 6 ) THEN
1382 
1383 	   if lPoVAlidationOrg = -99 then		--bugfix 2646849
1384                 IF PG_DEBUG <> 0 THEN
1385                 	oe_debug_pub.add('populate_plan_level: ' || 'No Povalidation org is defined .. Need to error out..',1);
1386                 END IF;
1387                	cto_msg_pub.cto_message('BOM','CTO_PO_VALIDATION');
1388        		raise po_multiorg_error;
1389     	   end if;
1390 
1391         END IF;
1392 
1393         --- Added by Renga Kannan storing the po validation org in pkg variable for further use
1394         --- Added on 08/24/01
1395 
1396         CTO_UTILITY_PK.PO_VALIDATION_ORG := lPoValidationOrg;
1397 
1398         -- End of addition
1399 
1400   	IF PG_DEBUG <> 0 THEN
1401   		oe_debug_pub.add('populate_plan_level: ' ||  'PO Validation Org is :' ||lPoValidationOrg,2);
1402   	END IF;
1403 
1404 	lStmtNumber := 210;
1405 
1406 	insert into bom_cto_src_orgs
1407 		(
1408 		top_model_line_id,
1409 		line_id,
1410 		model_item_id,
1411 		rcv_org_id,
1412 		organization_id,
1413 		create_bom,
1414 		cost_rollup,
1415 		organization_type,
1416 		config_item_id,
1417 		create_src_rules,
1418 		rank,
1419 		creation_date,
1420 		created_by,
1421 		last_update_date,
1422 		last_updated_by,
1423 		last_update_login,
1424 		program_application_id,
1425 		program_id,
1426 		program_update_date
1427 		)
1428 	select
1429 		lTopAtoLineId,
1430 		pLineId,
1431 		pModelItemId,
1432 		NULL,		-- rec_org_id
1433 		lPoValidationOrg,
1434 		'N',		-- create_bom
1435 		'N',		-- cost_rollup
1436 		NULL,		-- org_type, pending
1437 		NULL,		-- config_item_id
1438 		NULL,		-- create_src_rules, n/a
1439 		NULL,		-- rank, n/a
1440 		sysdate,	-- creation_date
1441 		gUserId,	-- created_by
1442 		sysdate,	-- last_update_date
1443 		gUserId,	-- last_updated_by
1444 		gLoginId,	-- last_update_login
1445 		null, 		-- program_application_id,??
1446 		null, 		-- program_id,??
1447 		sysdate		-- program_update_date
1448 	from dual
1449 	where NOT EXISTS
1450 		(select NULL
1451 		from bom_cto_src_orgs
1452 		where line_id = pLineId
1453 		and model_item_id = pModelItemId
1454 		and organization_id = lPoVAlidationOrg);
1455 
1456 	IF PG_DEBUG <> 0 THEN
1457 		oe_debug_pub.add('populate_plan_level: ' || 'after insert 5',2);
1458 	END IF;
1459 
1460 
1461         -- Added By Renga Kannan on 10/31/02 for Global Purchase agreement
1462         -- apart from enabling the config in all the sourcing chain orgs, we need
1463         -- to enable it in all the org where model item is active
1464         -- This is used for global purchase agreement
1465 
1466         insert into bom_cto_src_orgs
1467                 (
1468                 top_model_line_id,
1469                 line_id,
1470                 model_item_id,
1471                 rcv_org_id,
1472                 organization_id,
1473                 create_bom,
1474                 cost_rollup,
1475                 organization_type,
1476                 config_item_id,
1477                 create_src_rules,
1478                 rank,
1479                 creation_date,
1480                 created_by,
1481                 last_update_date,
1482                 last_updated_by,
1483                 last_update_login,
1484                 program_application_id,
1485                 program_id,
1486                 program_update_date
1487                 )
1488         select
1489                 lTopAtoLineId,
1490                 pLineId,
1491                 pModelItemId,
1492                 NULL,           -- rec_org_id
1493                 mtl.organization_id,
1494                 'N',            -- create_bom
1495                 'N',            -- cost_rollup
1496                 NULL,           -- org_type, pending
1497                 NULL,           -- config_item_id
1498                 NULL,           -- create_src_rules, n/a
1499                 NULL,           -- rank, n/a
1500                 sysdate,        -- creation_date
1501                 gUserId,        -- created_by
1502                 sysdate,        -- last_update_date
1503                 gUserId,        -- last_updated_by
1504                 gLoginId,       -- last_update_login
1505                 null,           -- program_application_id,??
1506                 null,           -- program_id,??
1507                 sysdate         -- program_update_date
1508         from    mtl_system_items mtl
1509         where   inventory_item_id = pModelItemId
1510         and     INVENTORY_ITEM_STATUS_CODE = 'Active'
1511         and     organization_id not in
1512                 (select organization_id
1513                  from   bom_cto_src_orgs
1514                  where  line_id = plineid
1515                  and    top_model_line_id = lTopAtoLineId);
1516 
1517 	EXCEPTION
1518 		WHEN no_data_found THEN
1519 			IF PG_DEBUG <> 0 THEN
1520 				oe_debug_pub.add('populate_plan_level: ' || 'PO validation org is NULL, not inserting row for PO val org',2);
1521 			END IF;
1522 			null;
1523 		WHEN po_multiorg_error THEN
1524 			IF PG_DEBUG <> 0 THEN
1525 				oe_debug_pub.add('populate_plan_level: ' || 'po_multiorg_error, not inserting row for PO val org',2);
1526 			END IF;
1527 			Raise FND_API.G_EXC_ERROR;
1528 		WHEN others THEN
1529 			IF PG_DEBUG <> 0 THEN
1530 				oe_debug_pub.add('populate_plan_level: ' || 'others exception in PO validation block, not inserting row for PO val org',2);
1531 			END IF;
1532 			null;
1533 	END;
1534 	return(1);
1535 
1536 EXCEPTION
1537 	when FND_API.G_EXC_ERROR then
1538 		IF PG_DEBUG <> 0 THEN
1539 			oe_debug_pub.add('populate_plan_level: ' || 'Get_All_item_orgs::exp error::'||to_char(lStmtNumber)||'::'||sqlerrm,1);
1540 		END IF;
1541 		x_return_status := FND_API.G_RET_STS_ERROR;
1542 		CTO_MSG_PUB.Count_And_Get
1543         		(p_msg_count => x_msg_count
1544         		,p_msg_data  => x_msg_data
1545         		);
1546 		return(0);
1547 
1548 	when FND_API.G_EXC_UNEXPECTED_ERROR then
1549 		IF PG_DEBUG <> 0 THEN
1550 			oe_debug_pub.add('populate_plan_level: ' || 'Get_All_item_orgs::unexp error::'||to_char(lStmtNumber)||'::'||sqlerrm,1);
1551 		END IF;
1552 		x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
1553 		CTO_MSG_PUB.Count_And_Get (
1554 			 p_msg_count => x_msg_count
1555         		,p_msg_data  => x_msg_data
1556         		);
1557 		return(0);
1558 
1559 	when OTHERS then
1560 		IF PG_DEBUG <> 0 THEN
1561 			oe_debug_pub.add('populate_plan_level: ' || 'Get_All_item_orgs::others::'||to_char(lStmtNumber)||'::'||sqlerrm,1);
1562 		END IF;
1563 		x_return_status := FND_API.G_RET_STS_UNEXP_ERROR ;
1564 		IF FND_MSG_PUB.Check_Msg_Level(FND_MSG_PUB.G_MSG_LVL_UNEXP_ERROR) THEN
1565             		FND_MSG_PUB.Add_Exc_Msg
1566             			(G_PKG_NAME
1567             			,'Get_All_Item_Orgs'
1568             			);
1569         	END IF;
1570         	CTO_MSG_PUB.Count_And_Get
1571         		(p_msg_count => x_msg_count
1572         		,p_msg_data  => x_msg_data
1573         		);
1574 		return(0);
1575 
1576 end Get_All_Item_Orgs;
1577 
1578 
1579 /*--------------------------------------------------------------------------+
1580 This function updates table bom_cto_order_lines with the config_item_id for
1581 a given model item.
1582 It is called by "Match" and "Create_Item" programs.
1583 +-------------------------------------------------------------------------*/
1584 FUNCTION Update_Order_Lines(pLineId	in 	number,
1585 			pModelId	in	number,
1586 			pConfigId	in	number)
1587 RETURN integer
1588 IS
1589 
1590 lStmtNumber		number;
1591 
1592 
1593 BEGIN
1594 
1595 	--
1596 	-- If line exists, update it with the config item id
1597 	--
1598 	lStmtNumber := 20;
1599 	update  bom_cto_order_lines
1600 	set     config_item_id = pConfigId
1601 	where   line_id = pLineId
1602 	and     inventory_item_id = pModelId;
1603 
1604 	if sql%notfound then
1605 	   IF PG_DEBUG <> 0 THEN
1606 	   	oe_debug_pub.add('populate_plan_level: ' || 'Update_Order_Lines:: ndf::model line does not exist in bcol'||to_char(lStmtNumber)||sqlerrm,1);
1607 	   END IF;
1608 	   return(0);
1609 	else
1610 	   return(1);
1611 	end if;
1612 
1613 EXCEPTION
1614 	when others then
1615 		IF PG_DEBUG <> 0 THEN
1616 			oe_debug_pub.add('populate_plan_level: ' || 'Update_Order_Lines:: others exception'||to_char(lStmtNumber)||sqlerrm,1);
1617 		END IF;
1618 		return(0);
1619 
1620 END Update_Order_Lines;
1621 
1622 
1623 /*--------------------------------------------------------------------------+
1624 This function updates table bom_cto_src_orgs with the config_item_id for
1625 a given model item.
1626 It is called by "Match" and "Create_Item" programs.
1627 +-------------------------------------------------------------------------*/
1628 FUNCTION Update_Src_Orgs(pLineId	in 	number,
1629 			pModelId	in	number,
1630 			pConfigId	in	number)
1631 RETURN integer
1632 IS
1633 
1634 BEGIN
1635 
1636 	--
1637 	-- Update all lines for the model item with the config item id
1638 	--
1639 
1640 	update bom_cto_src_orgs
1641 	set    config_item_id = pConfigId
1642 	where  line_id = pLineId
1643 	and    model_item_id = pModelId;
1644 
1645         if sql%notfound then
1646 		IF PG_DEBUG <> 0 THEN
1647 			oe_debug_pub.add('populate_plan_level: ' || 'Update_Src_Orgs:: Could not update the config item: '||sqlerrm,1);
1648 		END IF;
1649 		return(0);
1650 	else
1651 		return(1);
1652 	end if;
1653 
1654 
1655 EXCEPTION
1656 
1657 	when others then
1658 		IF PG_DEBUG <> 0 THEN
1659 			oe_debug_pub.add('populate_plan_level: ' || 'Update_Src_Orgs:: others exception'||sqlerrm,1);
1660 		END IF;
1661 		return(0);
1662 
1663 END Update_Src_Orgs;
1664 
1665 
1666 /*--------------------------------------------------------------------------+
1667 This procedure creates sourcing information for a configuration item.
1668 It copies the sourcing rule assignment of the model into the configuration
1669 item and adds this assignment to the MRP default assignment set.
1670 +-------------------------------------------------------------------------*/
1671 
1672 --- Modified by Renga Kannan on 08/22/01
1673 --- This change is done as part of procuring configuration change
1674 
1675 PROCEDURE Create_Sourcing_Rules(pModelItemId	in	number,
1676 				pConfigId	in	number,
1677 				pRcvOrgId	in	number,
1678 				x_return_status	out	NOCOPY varchar2,
1679 				x_msg_count	out	NOCOPY number,
1680 				x_msg_data	out	NOCOPY varchar2)
1681 IS
1682 
1683 lStmtNum		number;
1684 lMrpAssignmentSet	number;
1685 lAssignmentId		number;
1686 lAssignmentType		number;
1687 lConfigAssignmentId	number;
1688 lAssignmentExists	number;
1689 lAssignmentRec		MRP_Src_Assignment_PUB.Assignment_Rec_Type;
1690 lAssignmentTbl		MRP_Src_Assignment_PUB.Assignment_Tbl_Type;
1691 lAssignmentSetRec	MRP_Src_Assignment_PUB.Assignment_Set_Rec_Type;
1692 xAssignmentSetRec	MRP_Src_Assignment_PUB.Assignment_Set_Rec_Type;
1693 xAssignmentSetValRec	MRP_Src_Assignment_PUB.Assignment_Set_Val_Rec_Type;
1694 xAssignmentTbl		MRP_Src_Assignment_PUB.Assignment_Tbl_Type;
1695 xAssignmentValTbl	MRP_Src_Assignment_PUB.Assignment_Val_Tbl_Type;
1696 l_return_status		varchar2(1);
1697 l_msg_count		number;
1698 l_msg_data		varchar2(2000);
1699 
1700 No_sourcing_defined     Exception;
1701 
1702 BEGIN
1703 
1704 	x_return_status := FND_API.G_RET_STS_SUCCESS;
1705 	lAssignmentExists := 0;
1706 
1707 	lStmtNum := 10;
1708 	/* get MRP's default assignment set */
1709 	lMrpAssignmentSet := to_number(FND_PROFILE.VALUE('MRP_DEFAULT_ASSIGNMENT_SET'));
1710 
1711 	IF lMrpAssignmentSet is null THEN
1712 		IF PG_DEBUG <> 0 THEN
1713 			oe_debug_pub.add('populate_plan_level: ' || 'Default assignment set is null, returning from create_sourcing_rules procedure',1);
1714 		END IF;
1715 		return;
1716 	ELSE
1717 		IF PG_DEBUG <> 0 THEN
1718 			oe_debug_pub.add('populate_plan_level: ' || 'Default assignment set is '||to_char(lMrpAssignmentSet),2);
1719 		END IF;
1720 	END IF;
1721 
1722 	--
1723 	-- from mrp view, get Assignment_id of assignment to be copied
1724 	--
1725 
1726         -- The buy sourcing rules are also need to be selected.
1727         -- The where condition source_type <> 3 needs to be removed
1728         -- Changes are made by Renga Kannan on 08/22/01 for procuring config Change
1729 
1730 
1731 
1732         -- Modified by Renga Kannan on 13-NOV-2001
1733         -- Added condition for assignment type = 3,6
1734         -- Previously it was erroring out if the assignment type is not of 3, 6
1735         -- It should not error out, rather it should igonre this
1736         -- this is required becasue of multiple buy support
1737 
1738 
1739 	lStmtNum := 20;
1740 
1741 
1742         -- When no data found it not an exception in this case
1743         -- It may not have any sourcing for assignment_type 3,6 so we need not error out for this
1744 
1745         BEGIN
1746 
1747 	   select distinct assignment_id, assignment_type
1748 	   into lAssignmentId, lAssignmentType
1749 	   from mrp_sources_v msv
1750 	   where msv.assignment_set_id = lMrpAssignmentSet
1751 	   and msv.inventory_item_id = pModelItemId
1752 	   and msv.organization_id = pRcvOrgId
1753 	   and effective_date <= nvl(disable_date, sysdate)
1754 	   and nvl(disable_date, sysdate+1) > sysdate
1755            and assignment_type in (3,6);
1756 
1757         EXCEPTION
1758 	WHEN NO_DATA_FOUND THEN
1759 
1760            IF PG_DEBUG <> 0 THEN
1761            	oe_debug_pub.add('populate_plan_level: ' || 'There is no sourcing rule defined ',1);
1762            END IF;
1763            raise no_sourcing_defined;
1764 
1765         END;
1766 
1767 
1768 	IF PG_DEBUG <> 0 THEN
1769 		oe_debug_pub.add('populate_plan_level: ' || 'lAssnType::'||to_char(lAssignmentType)||'::lAssnId::'||to_char(lAssignmentId),2);
1770 	END IF;
1771 
1772 	--
1773 	-- copy assignment into lAssignmentRec
1774 	--
1775 	lStmtNum := 30;
1776 
1777         --
1778         -- bug 6617686
1779         -- The MRP API uses a  ASSIGNMENT_ID = p_Assignment_Id OR
1780         -- ASSIGNMENT_SET_ID = p_Assignment_Set_Id that leads to
1781         -- a full table scan on MRP_SR_ASSIGNMENTS and consequent
1782         -- performance issues. Since CTO does not pass ASSIGNMENT_SET_ID
1783         -- into the procedure, it is performance effective to directly
1784         -- query the MRP table
1785         -- ntungare
1786         --
1787         -- lAssignmentRec := MRP_Assignment_Handlers.Query_Row(lAssignmentId);
1788 
1789         SELECT  ASSIGNMENT_ID
1790              ,       ASSIGNMENT_SET_ID
1791              ,       ASSIGNMENT_TYPE
1792              ,       ATTRIBUTE1
1793              ,       ATTRIBUTE10
1794              ,       ATTRIBUTE11
1795              ,       ATTRIBUTE12
1796              ,       ATTRIBUTE13
1797              ,       ATTRIBUTE14
1798              ,       ATTRIBUTE15
1799              ,       ATTRIBUTE2
1800              ,       ATTRIBUTE3
1801              ,       ATTRIBUTE4
1802              ,       ATTRIBUTE5
1803              ,       ATTRIBUTE6
1804              ,       ATTRIBUTE7
1805              ,       ATTRIBUTE8
1806              ,       ATTRIBUTE9
1807              ,       ATTRIBUTE_CATEGORY
1808              ,       CATEGORY_ID
1809              ,       CATEGORY_SET_ID
1810              ,       CREATED_BY
1811              ,       CREATION_DATE
1812              ,       CUSTOMER_ID
1813              ,       INVENTORY_ITEM_ID
1814              ,       LAST_UPDATED_BY
1815              ,       LAST_UPDATE_DATE
1816              ,       LAST_UPDATE_LOGIN
1817              ,       ORGANIZATION_ID
1818              ,       PROGRAM_APPLICATION_ID
1819              ,       PROGRAM_ID
1820              ,       PROGRAM_UPDATE_DATE
1821              ,       REQUEST_ID
1822              ,       SECONDARY_INVENTORY
1823              ,       SHIP_TO_SITE_ID
1824              ,       SOURCING_RULE_ID
1825              ,       SOURCING_RULE_TYPE
1826              into    lAssignmentRec.ASSIGNMENT_ID
1827              ,       lAssignmentRec.ASSIGNMENT_SET_ID
1828              ,       lAssignmentRec.ASSIGNMENT_TYPE
1829              ,       lAssignmentRec.ATTRIBUTE1
1830              ,       lAssignmentRec.ATTRIBUTE10
1831              ,       lAssignmentRec.ATTRIBUTE11
1832              ,       lAssignmentRec.ATTRIBUTE12
1833              ,       lAssignmentRec.ATTRIBUTE13
1834              ,       lAssignmentRec.ATTRIBUTE14
1835              ,       lAssignmentRec.ATTRIBUTE15
1836              ,       lAssignmentRec.ATTRIBUTE2
1837              ,       lAssignmentRec.ATTRIBUTE3
1838              ,       lAssignmentRec.ATTRIBUTE4
1839              ,       lAssignmentRec.ATTRIBUTE5
1840              ,       lAssignmentRec.ATTRIBUTE6
1841              ,       lAssignmentRec.ATTRIBUTE7
1842              ,       lAssignmentRec.ATTRIBUTE8
1843              ,       lAssignmentRec.ATTRIBUTE9
1844              ,       lAssignmentRec.ATTRIBUTE_CATEGORY
1845              ,       lAssignmentRec.CATEGORY_ID
1846              ,       lAssignmentRec.CATEGORY_SET_ID
1847              ,       lAssignmentRec.CREATED_BY
1848              ,       lAssignmentRec.CREATION_DATE
1849              ,       lAssignmentRec.CUSTOMER_ID
1850              ,       lAssignmentRec.INVENTORY_ITEM_ID
1851              ,       lAssignmentRec.LAST_UPDATED_BY
1852              ,       lAssignmentRec.LAST_UPDATE_DATE
1853              ,       lAssignmentRec.LAST_UPDATE_LOGIN
1854              ,       lAssignmentRec.ORGANIZATION_ID
1855              ,       lAssignmentRec.PROGRAM_APPLICATION_ID
1856              ,       lAssignmentRec.PROGRAM_ID
1857              ,       lAssignmentRec.PROGRAM_UPDATE_DATE
1858              ,       lAssignmentRec.REQUEST_ID
1859              ,       lAssignmentRec.SECONDARY_INVENTORY
1860              ,       lAssignmentRec.SHIP_TO_SITE_ID
1861              ,       lAssignmentRec.SOURCING_RULE_ID
1862              ,       lAssignmentRec.SOURCING_RULE_TYPE
1863              FROM    MRP_SR_ASSIGNMENTS
1864              WHERE   ASSIGNMENT_ID = lAssignmentId;
1865 
1866 	IF PG_DEBUG <> 0 THEN
1867 		oe_debug_pub.add('populate_plan_level: ' || 'after query row',2);
1868 	END IF;
1869 
1870 	--
1871 	-- check if this assignment already exists for config item
1872 	--
1873 	lStmtNum := 35;
1874 	BEGIN
1875 
1876 		IF PG_DEBUG <> 0 THEN
1877 			oe_debug_pub.add('populate_plan_level: ' || 'assignment_set_id::'||to_char(lAssignmentRec.assignment_set_id),2);
1878 
1879 			oe_debug_pub.add('populate_plan_level: ' || 'assignment_type::'||to_char(lAssignmentRec.assignment_type),2);
1880 
1881 			oe_debug_pub.add('populate_plan_level: ' || 'organization_id::'||to_char(lAssignmentRec.organization_id),2);
1882 
1883 			oe_debug_pub.add('populate_plan_level: ' || 'customer_id::'||to_char(lAssignmentRec.customer_id),2);
1884 
1885 			oe_debug_pub.add('populate_plan_level: ' || 'ship_to_site_id::'||to_char(lAssignmentRec.ship_to_site_id),2);
1886 
1887 			oe_debug_pub.add('populate_plan_level: ' || 'sourcing_rule_type::'||to_char(lAssignmentRec.sourcing_rule_type),2);
1888 
1889 			oe_debug_pub.add('populate_plan_level: ' || 'inventory_item_id:: '||to_char(pConfigId),2);
1890 
1891 			oe_debug_pub.add('populate_plan_level: ' || 'category_id:: '||to_char(lAssignmentRec.category_id),2);
1892 		END IF;
1893 
1894                 -- bug 6617686
1895                 IF pConfigId IS NOT NULL THEN
1896                         select 1
1897                         into lAssignmentExists
1898                         from mrp_sr_assignments
1899                         where assignment_set_id = lAssignmentRec.assignment_set_id
1900                         and assignment_type = lAssignmentRec.assignment_type
1901                         and nvl(organization_id,-1) = nvl(lAssignmentRec.organization_id,-1)
1902                         and nvl(customer_id,-1) = nvl(lAssignmentRec.customer_id,-1)
1903                         and nvl(ship_to_site_id,-1) = nvl(lAssignmentRec.ship_to_site_id,-1)
1904                         and sourcing_rule_type = lAssignmentRec.sourcing_rule_type
1905                         and nvl(inventory_item_id,-1) = pConfigId
1906                         and nvl(category_id,-1) = nvl(lAssignmentRec.category_id,-1);
1907                ELSE
1908                          select 1
1909                          into lAssignmentExists
1910                          from mrp_sr_assignments
1911                          where assignment_set_id = lAssignmentRec.assignment_set_id
1912                          and assignment_type = lAssignmentRec.assignment_type
1913                          and nvl(organization_id,-1) = nvl(lAssignmentRec.organization_id,-1)
1914                          and nvl(customer_id,-1) = nvl(lAssignmentRec.customer_id,-1)
1915                          and nvl(ship_to_site_id,-1) = nvl(lAssignmentRec.ship_to_site_id,-1)
1916                          and sourcing_rule_type = lAssignmentRec.sourcing_rule_type
1917                          and inventory_item_id is null
1918                          and nvl(category_id,-1) = nvl(lAssignmentRec.category_id,-1);
1919                 END IF;
1920                  -- end: bug 6617686
1921 
1922 		IF lAssignmentExists = 1 THEN
1923 			IF PG_DEBUG <> 0 THEN
1924 				oe_debug_pub.add('populate_plan_level: ' || 'assignment exists already, do not recreate',2);
1925 			END IF;
1926 			return;
1927 		END IF;
1928 
1929 	EXCEPTION
1930 		when NO_DATA_FOUND then
1931 			IF PG_DEBUG <> 0 THEN
1932 				oe_debug_pub.add('populate_plan_level: ' || 'assignment does not exist, create it',2);
1933 			END IF;
1934 		when OTHERS then
1935 			IF PG_DEBUG <> 0 THEN
1936 				oe_debug_pub.add('populate_plan_level: ' || 'others exception while checking ifassignment exists, not handling, creating assignment:: '||sqlerrm,2);
1937 			END IF;
1938 	END;
1939 
1940 	--
1941 	-- get assignment id for config item
1942 	--
1943 	SELECT mrp_sr_assignments_s.nextval
1944     	INTO   lConfigAssignmentId
1945     	FROM   DUAL;
1946 
1947 	--
1948 	-- form lAssignmentTbl from lAssignmentRec
1949 	--
1950 	lStmtNum := 40;
1951 	lAssignmentTbl(1).Assignment_Id 	:= lConfigAssignmentId;
1952 	lAssignmentTbl(1).Assignment_Set_Id	:= lAssignmentRec.Assignment_Set_Id;
1953 	lAssignmentTbl(1).Assignment_Type	:= lAssignmentRec.Assignment_Type;
1954 	lAssignmentTbl(1).Attribute1		:= lAssignmentRec.Attribute1;
1955 	lAssignmentTbl(1).Attribute10 		:= lAssignmentRec.Attribute10;
1956 	lAssignmentTbl(1).Attribute11		:= lAssignmentRec.Attribute11;
1957 	lAssignmentTbl(1).Attribute12		:= lAssignmentRec.Attribute12;
1958 	lAssignmentTbl(1).Attribute13		:= lAssignmentRec.Attribute13;
1959 	lAssignmentTbl(1).Attribute14		:= lAssignmentRec.Attribute14;
1960 	lAssignmentTbl(1).Attribute15		:= lAssignmentRec.Attribute15;
1961 	lAssignmentTbl(1).Attribute2		:= lAssignmentRec.Attribute2;
1962 	lAssignmentTbl(1).Attribute3		:= lAssignmentRec.Attribute3;
1963 	lAssignmentTbl(1).Attribute4		:= lAssignmentRec.Attribute4;
1964 	lAssignmentTbl(1).Attribute5		:= lAssignmentRec.Attribute5;
1965 	lAssignmentTbl(1).Attribute6		:= lAssignmentRec.Attribute6;
1966 	lAssignmentTbl(1).Attribute7		:= lAssignmentRec.Attribute7;
1967 	lAssignmentTbl(1).Attribute8		:= lAssignmentRec.Attribute8;
1968 	lAssignmentTbl(1).Attribute9		:= lAssignmentRec.Attribute9;
1969 	lAssignmentTbl(1).Attribute_Category	:= lAssignmentRec.Attribute_Category;
1970 	lAssignmentTbl(1).Category_Id 		:= lAssignmentRec.Category_Id ;
1971 	lAssignmentTbl(1).Category_Set_Id	:= lAssignmentRec.Category_Set_Id;
1972 	lAssignmentTbl(1).Created_By		:= lAssignmentRec.Created_By;
1973 	lAssignmentTbl(1).Creation_Date		:= lAssignmentRec.Creation_Date;
1974 	lAssignmentTbl(1).Customer_Id		:= lAssignmentRec.Customer_Id;
1975 	lAssignmentTbl(1).Inventory_Item_Id	:= pConfigId;
1976 	lAssignmentTbl(1).Last_Updated_By	:= lAssignmentRec.Last_Updated_By;
1977 	lAssignmentTbl(1).Last_Update_Date	:= lAssignmentRec.Last_Update_Date;
1978 	lAssignmentTbl(1).Last_Update_Login	:= lAssignmentRec.Last_Update_Login;
1979 	lAssignmentTbl(1).Organization_Id	:= lAssignmentRec.Organization_Id;
1980 	lAssignmentTbl(1).Program_Application_Id:= lAssignmentRec.Program_Application_Id;
1981 	lAssignmentTbl(1).Program_Id		:= lAssignmentRec.Program_Id;
1982 	lAssignmentTbl(1).Program_Update_Date	:= lAssignmentRec.Program_Update_Date;
1983 	lAssignmentTbl(1).Request_Id		:= lAssignmentRec.Request_Id;
1984 	lAssignmentTbl(1).Secondary_Inventory	:= lAssignmentRec.Secondary_Inventory;
1985 	lAssignmentTbl(1).Ship_To_Site_Id	:= lAssignmentRec.Ship_To_Site_Id;
1986 	lAssignmentTbl(1).Sourcing_Rule_Id	:= lAssignmentRec.Sourcing_Rule_Id;
1987 	lAssignmentTbl(1).Sourcing_Rule_Type	:= lAssignmentRec.Sourcing_Rule_Type;
1988 	lAssignmentTbl(1).return_status		:= NULL;
1989 	lAssignmentTbl(1).db_flag    		:= NULL;
1990 	lAssignmentTbl(1).operation 		:= MRP_Globals.G_OPR_CREATE;
1991 
1992 	IF PG_DEBUG <> 0 THEN
1993 		oe_debug_pub.add('populate_plan_level: ' || 'after forming lAssignmentTbl',2);
1994 	END IF;
1995 
1996 	--
1997 	-- form lAssignmentSetRec
1998 	--
1999 	lStmtNum := 50;
2000 	lAssignmentSetRec.operation := MRP_Globals.G_OPR_NONE;
2001 	IF PG_DEBUG <> 0 THEN
2002 		oe_debug_pub.add('populate_plan_level: ' || 'after forming lAssignmentSetRec',2);
2003 	END IF;
2004 
2005 	--
2006 	-- call mrp API to insert rec into assignment set
2007 	--
2008 	lStmtNum := 60;
2009 	IF PG_DEBUG <> 0 THEN
2010 		oe_debug_pub.add('populate_plan_level: ' || 'before Process_Assignment',2);
2011 	END IF;
2012 
2013 	-- currently, not passing commented out parameters, need to
2014 	-- confirm with raghu, confirmed with stupe
2015 
2016 	MRP_Src_Assignment_PUB.Process_Assignment
2017 		(   p_api_version_number	=> 1.0
2018 		--,   p_init_msg_list                 IN  VARCHAR2 := FND_API.G_FALSE
2019 		--,   p_return_values                 IN  VARCHAR2 := FND_API.G_FALSE
2020 		--,   p_commit                        IN  VARCHAR2 := FND_API.G_FALSE
2021 		,   x_return_status		=> l_return_status
2022 		,   x_msg_count 		=> l_msg_count
2023 		,   x_msg_data  		=> l_msg_data
2024 		,   p_Assignment_Set_rec 	=> lAssignmentSetRec
2025 		--,   p_Assignment_Set_val_rec        IN  Assignment_Set_Val_Rec_Type :=  G_MISS_ASSIGNMENT_SET_VAL_REC
2026 		,   p_Assignment_tbl  		=> lAssignmentTbl
2027 		--,   p_Assignment_val_tbl            IN  Assignment_Val_Tbl_Type := G_MISS_ASSIGNMENT_VAL_TBL
2028 		,   x_Assignment_Set_rec  	=> xAssignmentSetRec
2029 		,   x_Assignment_Set_val_rec	=> xAssignmentSetValRec
2030 		,   x_Assignment_tbl   		=> xAssignmentTbl
2031 		,   x_Assignment_val_tbl  	=> xAssignmentValTbl
2032 		);
2033 
2034 	IF l_return_status = FND_API.G_RET_STS_UNEXP_ERROR THEN
2035 		IF PG_DEBUG <> 0 THEN
2036 			oe_debug_pub.add('populate_plan_level: ' || 'unexp error in process_assignment::'||sqlerrm,1);
2037 		END IF;
2038 		raise FND_API.G_EXC_UNEXPECTED_ERROR;
2039 
2040 	ELSIF	l_return_status = FND_API.G_RET_STS_ERROR THEN
2041 		IF PG_DEBUG <> 0 THEN
2042 			oe_debug_pub.add('populate_plan_level: ' || 'error in process_assignment::'||sqlerrm,1);
2043 		END IF;
2044 		raise FND_API.G_EXC_ERROR;
2045 
2046 	END IF;
2047 	IF PG_DEBUG <> 0 THEN
2048 		oe_debug_pub.add('populate_plan_level: ' || 'success in process_assignment',2);
2049 	END IF;
2050 
2051 EXCEPTION
2052         When NO_sourcing_defined THEN
2053                 null;
2054 
2055 	when FND_API.G_EXC_ERROR then
2056 		IF PG_DEBUG <> 0 THEN
2057 			oe_debug_pub.add('populate_plan_level: ' || 'Create_Src_Rules::exp error::'||to_char(lStmtNum)||'::'||sqlerrm,1);
2058 		END IF;
2059 		x_return_status := FND_API.G_RET_STS_ERROR;
2060 		CTO_MSG_PUB.Count_And_Get
2061         		(p_msg_count => x_msg_count
2062         		,p_msg_data  => x_msg_data
2063         		);
2064 
2065 	when FND_API.G_EXC_UNEXPECTED_ERROR then
2066 		IF PG_DEBUG <> 0 THEN
2067 			oe_debug_pub.add('populate_plan_level: ' || 'Create_Src_Rules::unexp error::'||to_char(lStmtNum)||'::'||sqlerrm,1);
2068 		END IF;
2069 		x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
2070 		CTO_MSG_PUB.Count_And_Get
2071         		(p_msg_count => x_msg_count
2072         		,p_msg_data  => x_msg_data
2073         		);
2074 
2075 	when OTHERS then
2076 		IF PG_DEBUG <> 0 THEN
2077 			oe_debug_pub.add('populate_plan_level: ' || 'Create_Src_Rules::others::'||to_char(lStmtNum)||'::'||sqlerrm,1);
2078 		END IF;
2079 		x_return_status := FND_API.G_RET_STS_UNEXP_ERROR ;
2080 		IF FND_MSG_PUB.Check_Msg_Level(FND_MSG_PUB.G_MSG_LVL_UNEXP_ERROR) THEN
2081             		FND_MSG_PUB.Add_Exc_Msg
2082             			(G_PKG_NAME
2083             			,'Create_Sourcing_Rules'
2084             			);
2085         	END IF;
2086         	CTO_MSG_PUB.Count_And_Get
2087         		(p_msg_count => x_msg_count
2088         		,p_msg_data  => x_msg_data
2089         		);
2090 
2091 
2092 END Create_Sourcing_Rules;
2093 
2094 
2095  PROCEDURE populate_bcol
2096  ( p_bcol_line_id        bom_cto_order_lines.line_id%type,
2097    x_return_status   out   NOCOPY varchar2,
2098    x_msg_count       out   NOCOPY number,
2099    x_msg_data	     out   NOCOPY varchar2,
2100    p_reschedule      in    varchar2 default 'N')
2101  is
2102 
2103 
2104  --cursor for retrieving components of a given top level ato model
2105  --added decode statement to populate wip supply type of null for top model ato
2106 
2107 
2108  cursor c1 ( c_organization_id oe_system_parameters_all.master_organization_id%type )
2109     is
2110     select OEOL.line_id
2111          , OEOL.top_model_line_id
2112          , OEOL.ato_line_id
2113          , OEOL.link_to_line_id
2114          , OEOL.inventory_item_id
2115          , OEOL.ship_from_org_id
2116          , OEOL.component_sequence_id
2117          , OEOL.component_code
2118          , OEOL.item_type_code
2119          , OEOL.schedule_ship_date
2120          , MSYI.bom_item_type
2121          , decode( OEOL.line_id, OEOL.ato_line_id , null , BIC.wip_supply_type )
2122          , OEOL.header_id
2123          , OEOL.ordered_quantity
2124          , OEOL.order_quantity_uom
2125          , nvl( MSYI.config_orgs , 1)
2126          , MSYI.config_match
2127     from oe_order_lines_all OEOL , bom_inventory_components BIC , mtl_system_items MSYI
2128     where ato_line_id = p_bcol_line_id
2129       and OEOL.component_sequence_id = BIC.component_sequence_id
2130       and OEOL.inventory_item_id = MSYI.inventory_item_id
2131       and MSYI.organization_id = c_organization_id
2132       and OEOL.open_flag='Y'  -- bugfix 1876618: look at only open orders
2133     order by line_id ;
2134 
2135  t_bcol TAB_BCOL ;
2136 
2137 /*
2138 ** Table to store information for top level item and all its descendants.
2139 ** This table is a sparsely populated array. Each item is populated in a location identified
2140 ** by its line_id. This helps us directly access the item in the table rather than search for it.
2141 */
2142 
2143 
2144  v_kount   			 number(9) ;
2145  l_return_status 		 varchar2(10) ;
2146  v_bcol_line_id             	 bom_cto_order_lines.line_id%type ;
2147  v_bcol_header_id           	 bom_cto_order_lines.header_id%type ;
2148  v_bcol_top_model_line_id   	 bom_cto_order_lines.top_model_line_id%type ;
2149  v_bcol_ato_line_id         	 bom_cto_order_lines.ato_line_id%type ;
2150  v_bcol_link_to_line_id     	 bom_cto_order_lines.link_to_line_id%type ;
2151  v_bcol_inventory_item_id        bom_cto_order_lines.inventory_item_id%type ;
2152  v_bcol_ship_from_org_id         bom_cto_order_lines.ship_from_org_id%type ;
2153  v_bcol_component_sequence_id    bom_cto_order_lines.component_sequence_id%type ;
2154  v_bcol_component_code           bom_cto_order_lines.component_code%type ;
2155  v_bcol_item_type_code           bom_cto_order_lines.item_type_code%type ;
2156  v_bcol_schedule_ship_date       bom_cto_order_lines.schedule_ship_date%type ;
2157  v_bcol_bom_item_type            bom_cto_order_lines.bom_item_type%type ;
2158  v_bcol_wip_supply_type          bom_cto_order_lines.wip_supply_type%type ;
2159  v_bcol_ordered_quantity         bom_cto_order_lines.ordered_quantity%type ;
2160  v_bcol_order_quantity_uom       bom_cto_order_lines.order_quantity_uom%type ;
2161  v_bcol_config_creation          bom_cto_order_lines.config_creation%type ;
2162  v_bcol_perform_match            bom_cto_order_lines.perform_match%type ;
2163 
2164  v_top_level_found          	 boolean ;
2165 
2166 
2167  /* sequence used in this program
2168  ** BOM_EXPLOSION_TEMP_S
2169  */
2170 
2171  gUserID         number       ;
2172  gLoginId        number       ;
2173 
2174  v_inventory_item_id     oe_order_lines_all.inventory_item_id%type ;
2175  v_organization_id       oe_system_parameters_all.master_organization_id%type ;
2176 
2177  v_ato_line_id         NUMBER;
2178  v_request_id          NUMBER;
2179  v_program_id          NUMBER;
2180  v_prog_update_date    DATE;
2181  v_prog_appl_id        NUMBER;
2182  v_mfg_comp_seq_id     NUMBER ;
2183  v_step                VARCHAR2(10) ;
2184 
2185  i                     number := 0 ; /* bug 1728383 for performance to use .next */
2186  lMatchProfile         number ; /* changes made for match and reserve enhancements */
2187  l_custom_match_profile         number ; /* changes made for match and reserve enhancements */
2188 
2189 
2190 
2191  v_match_flag_tab     CTO_MATCH_CONFIG.MATCH_FLAG_TBL_TYPE ;
2192  v_sparse_tab         CTO_MATCH_CONFIG.MATCH_FLAG_TBL_TYPE ;
2193 
2194 
2195 
2196  begin
2197 
2198         gUserId          := nvl(Fnd_Global.USER_ID, -1);
2199         gLoginId         := nvl(Fnd_Global.LOGIN_ID, -1);
2200 
2201 	x_return_status := FND_API.G_RET_STS_SUCCESS;
2202 
2203         v_step := 'Step A1' ;
2204 
2205         select bom_explosion_temp_s.nextval
2206         into  v_mfg_comp_seq_id
2207         from dual;
2208 
2209         IF PG_DEBUG <> 0 THEN
2210         	oe_debug_pub.add('populate_bcol: ' ||  ' sequence ' || v_mfg_comp_seq_id , 3);
2211         END IF;
2212 
2213 
2214         v_step := 'Step A2' ;
2215 
2216         select inventory_item_id
2217         into v_inventory_item_id
2218         from oe_order_lines_all
2219         where ato_line_id = p_bcol_line_id
2220         and line_id = p_bcol_line_id ;
2221 
2222 
2223        IF PG_DEBUG <> 0 THEN
2224        	oe_debug_pub.add('populate_bcol: ' ||  ' inventory item id ' || v_inventory_item_id , 3);
2225        END IF;
2226 
2227 
2228         v_step := 'Step A3' ;
2229 
2230         /*
2231         BUG:3484511
2232         ---------------
2233         select master_organization_id
2234         into   v_organization_id
2235         from   oe_order_lines_all oel,
2236            oe_system_parameters_all ospa
2237         where  oel.line_id = p_bcol_line_id
2238         and    nvl(oel.org_id, -1) = nvl(ospa.org_id, -1)  --bug 1531691
2239         and    oel.inventory_item_id = v_inventory_item_id ;
2240         */
2241 
2242 
2243 
2244 
2245            IF PG_DEBUG <> 0 THEN
2246                 oe_debug_pub.add('populate_bcol: ' ||  'Going to fetch Validation Org ' ,2);
2247            END IF;
2248 
2249 
2250            select nvl( oe_sys_parameters.value( 'MASTER_ORGANIZATION_ID' , oel.org_id) , -99)
2251               into v_organization_id from oe_order_lines_all oel
2252            where oel.line_id = p_bcol_line_id;
2253 
2254 
2255 
2256 
2257 
2258         IF PG_DEBUG <> 0 THEN
2259         	oe_debug_pub.add('populate_bcol: ' ||  ' master org id ' || v_organization_id , 3 );
2260         END IF;
2261 
2262     /*
2263     ** If the profile BOM:Allow Multilevel ATO is set to "NO" then
2264     ** we need to set wip_supply_type = 6 for lower level models
2265     ** This is done in the cursor c1
2266     */
2267 
2268     /*    v_multilevel := FND_PROFILE.VALUE('BOM:MULTILEVEL_ATO');
2269     **    v_multilevel := nvl(v_multilevel , 'N' ) ;
2270 
2271 
2272     **    oe_debug_pub.add('ML profile is '||v_multilevel, 2);
2273     */
2274 
2275 
2276     lMatchProfile := FND_PROFILE.Value('BOM:MATCH_CONFIG');
2277 
2278     l_custom_match_profile := FND_PROFILE.Value('BOM:CUSTOM_MATCH');
2279 
2280     /*
2281     ** retrieve information related to top level ato model being passed.
2282     */
2283         v_step := 'Step A4' ;
2284 
2285     begin
2286        select OEOL.line_id
2287             , OEOL.top_model_line_id
2288             , OEOL.ato_line_id
2289             , OEOL.link_to_line_id
2290             , OEOL.inventory_item_id
2291             , OEOL.ship_from_org_id
2292             , OEOL.component_sequence_id
2293             , OEOL.component_code
2294             , OEOL.item_type_code
2295             , OEOL.schedule_ship_date
2296             , MSYI.bom_item_type
2297             , OEOL.header_id
2298             , OEOL.ordered_quantity
2299             , null
2300             , OEOL.order_quantity_uom
2301             , nvl( MSYI.config_orgs , 1 )
2302             , MSYI.config_match
2303        into   v_bcol_line_id
2304             , v_bcol_top_model_line_id
2305             , v_bcol_ato_line_id
2306             , v_bcol_link_to_line_id
2307             , v_bcol_inventory_item_id
2308             , v_bcol_ship_from_org_id
2309             , v_bcol_component_sequence_id
2310             , v_bcol_component_code
2311             , v_bcol_item_type_code
2312             , v_bcol_schedule_ship_date
2313             , v_bcol_bom_item_type
2314             , v_bcol_header_id
2315             , v_bcol_ordered_quantity
2316             , v_bcol_wip_supply_type
2317             , v_bcol_order_quantity_uom
2318             , v_bcol_config_creation
2319             , v_bcol_perform_match
2320        from oe_order_lines_all OEOL , mtl_system_items MSYI
2321        where OEOL.ato_line_id = p_bcol_line_id
2322          and OEOL.line_id = p_bcol_line_id
2323          and MSYI.bom_item_type = '1'
2324          and OEOL.inventory_item_id = MSYI.inventory_item_id
2325          and v_organization_id = MSYI.organization_id ;
2326 
2327        t_bcol(v_bcol_line_id).line_id := v_bcol_line_id ;
2328        t_bcol(v_bcol_line_id).header_id := v_bcol_header_id ;
2329        t_bcol(v_bcol_line_id).top_model_line_id := v_bcol_top_model_line_id ;
2330        t_bcol(v_bcol_line_id).ato_line_id := v_bcol_ato_line_id ;
2331        t_bcol(v_bcol_line_id).link_to_line_id  := v_bcol_link_to_line_id ;
2332        t_bcol(v_bcol_line_id).inventory_item_id := v_bcol_inventory_item_id ;
2333        t_bcol(v_bcol_line_id).ship_from_org_id := v_bcol_ship_from_org_id ;
2334        t_bcol(v_bcol_line_id).component_sequence_id := v_bcol_component_sequence_id ;
2335        t_bcol(v_bcol_line_id).component_code := v_bcol_component_code ;
2336        t_bcol(v_bcol_line_id).item_type_code := v_bcol_item_type_code ;
2337        t_bcol(v_bcol_line_id).schedule_ship_date := v_bcol_schedule_ship_date ;
2338        t_bcol(v_bcol_line_id).bom_item_type := v_bcol_bom_item_type ;
2339        t_bcol(v_bcol_line_id).wip_supply_type := v_bcol_wip_supply_type ;
2340        t_bcol(v_bcol_line_id).ordered_quantity := v_bcol_ordered_quantity ;
2341        t_bcol(v_bcol_line_id).order_quantity_uom := v_bcol_order_quantity_uom ;
2342        t_bcol(v_bcol_line_id).config_creation := v_bcol_config_creation ;
2343 
2344 
2345 
2346        /* match attribute on item should be respected only when match profile = 'Y' */
2347        if( lMatchProfile = 1 ) then
2348            if( l_custom_match_profile = 2 ) then
2349                t_bcol(v_bcol_line_id).perform_match := nvl( v_bcol_perform_match , 'Y' ) ;
2350            else
2351                t_bcol(v_bcol_line_id).perform_match := nvl( v_bcol_perform_match , 'C' ) ;
2352            end if;
2353        else
2354            t_bcol(v_bcol_line_id).perform_match := 'N'  ;
2355        end if;
2356 
2357 
2358 
2359        oe_debug_pub.add('bcol info : CONC REQ PARAMS ' , 3) ;
2360        oe_debug_pub.add('bcol info : CONC REQ ' ||  FND_GLOBAL.CONC_REQUEST_ID , 3 );
2361        oe_debug_pub.add('bcol info : CONC PROG ' ||  FND_GLOBAL.CONC_PROGRAM_ID , 3 );
2362        oe_debug_pub.add('bcol info : PROG APPL ' ||  FND_GLOBAL.PROG_APPL_ID , 3 );
2363 
2364 
2365        t_bcol(v_bcol_line_id).Request_Id := FND_GLOBAL.CONC_REQUEST_ID;
2366        t_bcol(v_bcol_line_id).Program_Id := FND_GLOBAL.CONC_PROGRAM_ID;
2367        t_bcol(v_bcol_line_id).Program_Application_Id := FND_GLOBAL.PROG_APPL_ID;
2368 
2369 
2370 
2371        /* set plan level to 0 for top level item */
2372        t_bcol(v_bcol_line_id).plan_level := 0 ;
2373        IF PG_DEBUG <> 0 THEN
2374        	oe_debug_pub.add('populate_bcol: ' ||  ' ----- setting plan level = 0 for base item ' , 3  );
2375        END IF;
2376 
2377     exception
2378        when others then
2379             	IF PG_DEBUG <> 0 THEN
2380             		oe_debug_pub.add('populate_bcol: ' ||  ' got into exception for top level item at ' || v_step , 1 );
2381 
2382 			oe_debug_pub.add('populate_bcol: ' || 'error in top ato model line id::'||sqlerrm , 1 );
2383 		END IF;
2384      		cto_msg_pub.cto_message('BOM','CTO_CREATE_ITEM_ERROR');
2385 		raise FND_API.G_EXC_ERROR;
2386 
2387     end;
2388 
2389 
2390 
2391 
2392     /*
2393     ** check whether to update the oeol_all table with batchid?
2394     */
2395 
2396         v_step := 'Step A5' ;
2397 
2398     open c1( v_organization_id ) ;
2399 
2400     v_kount := 1 ;
2401 
2402     /*
2403     ** retrieve information related to components of top level item in a pl/sql table
2404     ** also check whether a config item has already been created
2405     */
2406     while( TRUE )
2407     loop
2408 
2409 
2410         v_step := 'Step 6' ;
2411 
2412        fetch c1 into v_bcol_line_id
2413                    , v_bcol_top_model_line_id
2414                    , v_bcol_ato_line_id
2415                    , v_bcol_link_to_line_id
2416                    , v_bcol_inventory_item_id
2417                    , v_bcol_ship_from_org_id
2418                    , v_bcol_component_sequence_id
2419                    , v_bcol_component_code
2420                    , v_bcol_item_type_code
2421                    , v_bcol_schedule_ship_date
2422                    , v_bcol_bom_item_type
2423                    , v_bcol_wip_supply_type
2424                    , v_bcol_header_id
2425                    , v_bcol_ordered_quantity
2426                    , v_bcol_order_quantity_uom
2427                    , v_bcol_config_creation
2428                    , v_bcol_perform_match ;
2429 
2430 
2431 
2432        exit when c1%notfound ;
2433 
2434 
2435        if( upper( v_bcol_item_type_code) = 'CONFIG' ) then
2436            /* you need to error out as the config item exists */
2437 
2438            IF PG_DEBUG <> 0 THEN
2439            	oe_debug_pub.add('populate_bcol: ' ||  ' ---- CONFIG Exists ', 1 );
2440            END IF;
2441 
2442      	   cto_msg_pub.cto_message('BOM','CTO_CONFIG_ITEM_EXISTS');
2443 	   raise FND_API.G_EXC_ERROR;
2444 
2445        end if ;
2446 
2447 
2448        t_bcol(v_bcol_line_id).line_id := v_bcol_line_id ;
2449        t_bcol(v_bcol_line_id).header_id := v_bcol_header_id ;
2450        t_bcol(v_bcol_line_id).top_model_line_id := v_bcol_top_model_line_id ;
2451        t_bcol(v_bcol_line_id).ato_line_id := v_bcol_ato_line_id ;
2452        t_bcol(v_bcol_line_id).link_to_line_id  := v_bcol_link_to_line_id ;
2453        t_bcol(v_bcol_line_id).inventory_item_id := v_bcol_inventory_item_id ;
2454        t_bcol(v_bcol_line_id).ship_from_org_id := v_bcol_ship_from_org_id ;
2455        t_bcol(v_bcol_line_id).component_sequence_id := v_bcol_component_sequence_id ;
2456        t_bcol(v_bcol_line_id).component_code := v_bcol_component_code ;
2457        t_bcol(v_bcol_line_id).item_type_code := v_bcol_item_type_code ;
2458        t_bcol(v_bcol_line_id).schedule_ship_date := v_bcol_schedule_ship_date ;
2459        t_bcol(v_bcol_line_id).bom_item_type := v_bcol_bom_item_type ;
2460        t_bcol(v_bcol_line_id).wip_supply_type := v_bcol_wip_supply_type ;
2461        t_bcol(v_bcol_line_id).ordered_quantity := v_bcol_ordered_quantity ;
2462        t_bcol(v_bcol_line_id).order_quantity_uom := v_bcol_order_quantity_uom ;
2463 
2464        t_bcol(v_bcol_line_id).config_creation := v_bcol_config_creation ;
2465        /* match attribute on item should be respected only when match profile = 'Y' */
2466        if( lMatchProfile = 1 ) then
2467            if( l_custom_match_profile = 2 ) then
2468                t_bcol(v_bcol_line_id).perform_match := nvl( v_bcol_perform_match , 'Y' ) ;
2469            else
2470                t_bcol(v_bcol_line_id).perform_match := nvl( v_bcol_perform_match , 'C' ) ;
2471            end if;
2472        else
2473            t_bcol(v_bcol_line_id).perform_match := 'N'  ;
2474        end if;
2475 
2476        oe_debug_pub.add('bcol info : CONC REQ PARAMS ' , 3) ;
2477        oe_debug_pub.add('bcol info : CONC REQ ' ||  FND_GLOBAL.CONC_REQUEST_ID , 3 );
2478        oe_debug_pub.add('bcol info : CONC PROG ' ||  FND_GLOBAL.CONC_PROGRAM_ID , 3 );
2479        oe_debug_pub.add('bcol info : PROG APPL ' ||  FND_GLOBAL.PROG_APPL_ID , 3 );
2480 
2481 
2482        t_bcol(v_bcol_line_id).Request_Id := FND_GLOBAL.CONC_REQUEST_ID;
2483        t_bcol(v_bcol_line_id).Program_Id := FND_GLOBAL.CONC_PROGRAM_ID;
2484        t_bcol(v_bcol_line_id).Program_Application_Id := FND_GLOBAL.PROG_APPL_ID;
2485 
2486 
2487        v_kount := v_kount + 1 ;
2488 
2489 
2490     end loop ;
2491 
2492     v_step := 'Step A7' ;
2493 
2494     close c1 ;
2495 
2496     /*
2497     ** this loop can be discarded
2498     */
2499 
2500     IF PG_DEBUG <> 0 THEN
2501     	oe_debug_pub.add('populate_bcol: ' ||  'source data ' , 3 );
2502 
2503     	oe_debug_pub.add('populate_bcol: ' ||  'line_id top_model ato   link_to plan_level ', 1 );
2504     END IF;
2505 
2506     v_step := 'Step A8' ;
2507 
2508     i:= t_bcol.first ;
2509 
2510     /*   for i in 1..t_bcol.last  commented out for bug 1728383 */
2511 
2512 
2513     while i is not null
2514     loop
2515 
2516        if( t_bcol.exists(i) ) then
2517           IF PG_DEBUG <> 0 THEN
2518           	oe_debug_pub.add('populate_bcol: ' ||  t_bcol(i).line_id || '  ' || t_bcol(i).top_model_line_id
2519             || ' A ' ||  t_bcol(i).ato_line_id
2520             || ' LN ' || t_bcol(i).link_to_line_id
2521             || ' PAL ' ||  t_bcol(i).parent_ato_line_id
2522             || ' P ' ||  t_bcol(i).plan_level
2523             || ' BI '  || t_bcol(i).bom_item_type
2524             || ' WS ' || t_bcol(i).wip_supply_type
2525             || ' OQ ' || t_bcol(i).ordered_quantity
2526             || ' UOM ' || t_bcol(i).order_quantity_uom
2527             || ' creation  ' ||  t_bcol(i).config_creation
2528             || ' Match  ' ||  t_bcol(i).perform_match
2529             , 1 );
2530           END IF;
2531 
2532 
2533           /*
2534           ** update these records in oe_order_lines to indicate process locks
2535           */
2536 
2537         v_step := 'Step A9' ;
2538 
2539           oe_config_util.update_mfg_comp_seq_id( t_bcol(i).line_id
2540                                        , v_mfg_comp_seq_id
2541                                        , l_return_status  );
2542 
2543 	IF l_return_status = FND_API.G_RET_STS_UNEXP_ERROR THEN
2544 		IF PG_DEBUG <> 0 THEN
2545 			oe_debug_pub.add('populate_bcol: ' || 'unexp error in update_mfg_comp_seq_id::'||sqlerrm , 1 );
2546 		END IF;
2547 		raise FND_API.G_EXC_UNEXPECTED_ERROR;
2548 
2549 	ELSIF	l_return_status = FND_API.G_RET_STS_ERROR THEN
2550 		IF PG_DEBUG <> 0 THEN
2551 			oe_debug_pub.add('populate_bcol: ' || 'error in update_mfg_comp_seq_id::'||sqlerrm , 1 );
2552 		END IF;
2553 		raise FND_API.G_EXC_ERROR;
2554 	END IF;
2555 
2556        end if ;
2557 
2558 
2559 
2560        i := t_bcol.next(i) ;
2561 
2562     end loop ;
2563 
2564 
2565     /*
2566     ** end of loop to be discarded.
2567     */
2568 
2569 
2570     /*
2571     ** call populate_line_id to populate the plan level
2572     */
2573 
2574     v_step := 'Step A10' ;
2575 
2576     populate_plan_level( t_bcol ) ;
2577 
2578     /*
2579     ** call populate_line_id to populate the plan level
2580     */
2581 
2582     v_step := 'Step A11' ;
2583 
2584     populate_parent_ato( t_bcol , p_bcol_line_id ) ;
2585 
2586     /*
2587     ** Populate parent line id of top level id as itself.
2588     ** NOTE: we need to populate this at the end to avoid ending in a recursive loop
2589     */
2590     t_bcol(p_bcol_line_id).parent_ato_line_id := p_bcol_line_id;
2591 
2592     IF PG_DEBUG <> 0 THEN
2593     	oe_debug_pub.add('populate_bcol: ' ||  'processed data ' , 4 );
2594 
2595     	oe_debug_pub.add('populate_bcol: ' ||  'line_id top_model ato   link_to plan_level ' , 3 );
2596 
2597         oe_debug_pub.add('populate_bcol: ' ||  'going to check for invalid model setup ' , 4 );
2598 
2599     END IF;
2600 
2601 
2602     /*
2603     ** CHECK FOR INVALID MODEL SETUP
2604     **
2605     */
2606 
2607 
2608     i := t_bcol.first ;
2609     while i is not null
2610     loop
2611           if( t_bcol(i).bom_item_type = 1 and nvl(t_bcol(i).wip_supply_type, 1 ) <> 6 and t_bcol(i).config_creation in (1, 2) ) then
2612 
2613              if( t_bcol(t_bcol(i).parent_ato_line_id).config_creation = 3) then
2614 
2615                  IF PG_DEBUG <> 0 THEN
2616                     oe_debug_pub.add('populate_bcol: ' || 'INVALID MODEL SETUP exists for line id  '  || t_bcol(i).line_id
2617                                                        || ' model item ' || t_bcol(i).inventory_item_id
2618                                                        || ' item type ' || t_bcol(i).config_creation
2619                                       , 1 );
2620                     oe_debug_pub.add('populate_bcol: ' || ' parent line id  '  || t_bcol(t_bcol(i).parent_ato_line_id).line_id
2621                                                        || ' parent model item ' || t_bcol(t_bcol(i).parent_ato_line_id).inventory_item_id
2622                                                        || ' parent item type ' || t_bcol(t_bcol(i).parent_ato_line_id).config_creation
2623                                       , 1 );
2624 
2625                  END IF;
2626 
2627 
2628                  cto_msg_pub.cto_message('BOM','CTO_INVALID_MODEL_SETUP');
2629                  raise FND_API.G_EXC_ERROR;
2630 
2631              end if;
2632 
2633           end if ;
2634 
2635 
2636           i := t_bcol.next(i) ;
2637 
2638     end loop ;
2639 
2640 
2641     /*
2642     **  CALL TRANSFORMED MATCH ATTRIBUTES PENDING
2643     ** PENDING WORK!!!!
2644     */
2645 
2646     if( lMatchProfile = 1 ) then
2647          oe_debug_pub.add('populate_bcol: ' ||  ' preparing information for v_match_flag_tab ' , 3 );
2648          i :=t_bcol.first ;
2649 
2650          while i is not null
2651          loop
2652 
2653              if( t_bcol(i).bom_item_type = 1 and nvl( t_bcol(i).wip_supply_type , 1 )  <> 6 ) then
2654                  v_match_flag_tab(v_match_flag_tab.count + 1).line_id := t_bcol(i).line_id ;
2655                  v_match_flag_tab(v_match_flag_tab.count ).parent_ato_line_id := t_bcol(i).parent_ato_line_id ;
2656                  v_match_flag_tab(v_match_flag_tab.count ).ato_line_id := t_bcol(i).ato_line_id ;
2657                  v_match_flag_tab(v_match_flag_tab.count ).match_flag := t_bcol(i).perform_match ;
2658 
2659              end if;
2660 
2661              i := t_bcol.next(i) ;
2662 
2663          end loop ;
2664 
2665 
2666          oe_debug_pub.add('populate_bcol: ' ||  ' going to call cto_match_config.evaluate_n_pop_match_flag ' , 3 );
2667 
2668          cto_match_config.evaluate_n_pop_match_flag( p_match_flag_tab  => v_match_flag_tab
2669                                               , x_sparse_tab => v_sparse_tab
2670                                               , x_return_status => x_return_status
2671                                               , x_msg_count => x_msg_count
2672                                               , x_msg_data => x_msg_data );
2673 
2674 
2675 
2676 
2677 
2678          oe_debug_pub.add('populate_bcol: ' ||  ' populating match flag from results ' , 3 );
2679 
2680          i := v_sparse_tab.first ;
2681 
2682          while i is not null
2683          loop
2684 
2685              t_bcol(i).perform_match := v_sparse_tab(i).match_flag ;
2686 
2687              i := v_sparse_tab.next(i) ;
2688 
2689          end loop ;
2690 
2691          oe_debug_pub.add('populate_bcol: ' ||  ' done populating match flag from results ' , 3 );
2692 
2693 
2694     else
2695 
2696          oe_debug_pub.add('populate_bcol: ' ||  ' will not be calling cto_match_config.evaluate_n_pop_match_flag ' , 3 );
2697 
2698     end if ;
2699 
2700 
2701     v_step := 'Step A12' ;
2702 
2703 
2704     i := t_bcol.first ;
2705 
2706 
2707     /*    for i in 1..t_bcol.last  commented for bug 1728383 */
2708 
2709 
2710     while i is not null
2711     loop
2712 
2713        if( t_bcol.exists(i) ) then
2714 
2715           IF PG_DEBUG <> 0 THEN
2716 
2717           	oe_debug_pub.add('populate_bcol: ' ||  t_bcol(i).line_id || '  ' || t_bcol(i).top_model_line_id
2718             || ' A ' ||  t_bcol(i).ato_line_id
2719             || ' LN ' || t_bcol(i).link_to_line_id
2720             || ' PAL ' ||  t_bcol(i).parent_ato_line_id
2721             || ' P ' ||  t_bcol(i).plan_level
2722             || ' BI '  || t_bcol(i).bom_item_type
2723             || ' WS ' || t_bcol(i).wip_supply_type
2724             || ' OQ ' || t_bcol(i).ordered_quantity
2725             || ' UOM ' || t_bcol(i).order_quantity_uom
2726             || ' creation  ' ||  t_bcol(i).config_creation
2727             || ' Match  ' ||  t_bcol(i).perform_match
2728             , 1 );
2729 
2730           END IF;
2731 
2732 
2733 
2734 
2735           v_step := 'Step A16' ;
2736 
2737 
2738           if (nvl( p_reschedule, 'N') = 'N' ) then
2739              /*
2740              ** insert this information into bom_cto_order_lines table
2741              */
2742 
2743              insert into bom_cto_order_lines (
2744                          LINE_ID
2745                         ,HEADER_ID
2746                         ,TOP_MODEL_LINE_ID
2747                         ,LINK_TO_LINE_ID
2748                         ,ATO_LINE_ID
2749                         ,PARENT_ATO_LINE_ID
2750                         ,INVENTORY_ITEM_ID
2751                         ,SHIP_FROM_ORG_ID
2752                         ,COMPONENT_SEQUENCE_ID
2753                         ,COMPONENT_CODE
2754                         ,ITEM_TYPE_CODE
2755                         ,SCHEDULE_SHIP_DATE
2756                         ,PLAN_LEVEL
2757                         ,PERFORM_MATCH
2758                         ,CONFIG_ITEM_ID
2759                         ,BOM_ITEM_TYPE
2760                         ,WIP_SUPPLY_TYPE
2761                         ,ORDERED_QUANTITY
2762                         ,ORDER_QUANTITY_UOM
2763                         ,BATCH_ID
2764                         ,CREATION_DATE
2765                         ,CREATED_BY
2766                         ,LAST_UPDATE_DATE
2767                         ,LAST_UPDATED_BY
2768                         ,LAST_UPDATE_LOGIN
2769                         ,PROGRAM_APPLICATION_ID
2770                         ,PROGRAM_ID
2771                         ,REQUEST_ID
2772                         ,PROGRAM_UPDATE_DATE
2773                         ,QTY_PER_PARENT_MODEL
2774                         ,OPTION_SPECIFIC
2775                         ,REUSE_CONFIG
2776                         ,CONFIG_CREATION)
2777                         values (
2778                          t_bcol(i).LINE_ID
2779                         ,t_bcol(i).HEADER_ID
2780                         ,t_bcol(i).TOP_MODEL_LINE_ID
2781                         ,t_bcol(i).LINK_TO_LINE_ID
2782                         ,t_bcol(i).ATO_LINE_ID
2783                         ,t_bcol(i).PARENT_ATO_LINE_ID
2784                         ,t_bcol(i).INVENTORY_ITEM_ID
2785                         ,t_bcol(i).SHIP_FROM_ORG_ID
2786                         ,t_bcol(i).COMPONENT_SEQUENCE_ID
2787                         ,t_bcol(i).COMPONENT_CODE
2788                         ,t_bcol(i).ITEM_TYPE_CODE
2789                         ,t_bcol(i).SCHEDULE_SHIP_DATE
2790                         ,t_bcol(i).PLAN_LEVEL
2791                         ,t_bcol(i).PERFORM_MATCH
2792                         ,t_bcol(i).CONFIG_ITEM_ID
2793                         ,t_bcol(i).BOM_ITEM_TYPE
2794                         ,t_bcol(i).WIP_SUPPLY_TYPE
2795                         ,t_bcol(i).ORDERED_QUANTITY
2796                         ,t_bcol(i).ORDER_QUANTITY_UOM
2797                         ,t_bcol(i).BATCH_ID
2798                         ,sysdate
2799                         ,gUserId /* CREATED_BY  */
2800                         ,sysdate /* LAST_UPDATE_DATE */
2801                         ,gUserId /* LAST_UPDATED_BY */
2802                         ,gLoginId /* LAST_UPDATE_LOGIN */
2803                         ,FND_GLOBAL.PROG_APPL_ID /* PROGRAM_APPLICATION_ID */
2804                         ,FND_GLOBAL.CONC_PROGRAM_ID /* PROGRAM_ID */
2805                         ,FND_GLOBAL.CONC_REQUEST_ID /* REQUEST_ID */
2806                         ,sysdate /* PROGRAM_UPDATE_DATE */
2807                         ,t_bcol(i).ordered_quantity / t_bcol(t_bcol(i).parent_ato_line_id).ordered_quantity
2808                         ,'N'
2809                         ,'N'
2810                         ,t_bcol(i).config_creation );
2811 
2812 
2813                         IF PG_DEBUG <> 0 THEN
2814     	                   oe_debug_pub.add('populate_bcol: bcol ' || t_bcol(i).line_id  , 1 );
2815                         END IF;
2816 
2817 
2818           else
2819 
2820 
2821              insert into bom_cto_order_lines_gt (
2822                          LINE_ID
2823                         ,HEADER_ID
2824                         ,TOP_MODEL_LINE_ID
2825                         ,LINK_TO_LINE_ID
2826                         ,ATO_LINE_ID
2827                         ,PARENT_ATO_LINE_ID
2828                         ,INVENTORY_ITEM_ID
2829                         ,SHIP_FROM_ORG_ID
2830                         ,COMPONENT_SEQUENCE_ID
2831                         ,COMPONENT_CODE
2832                         ,ITEM_TYPE_CODE
2833                         ,SCHEDULE_SHIP_DATE
2834                         ,PLAN_LEVEL
2835                         ,PERFORM_MATCH
2836                         ,CONFIG_ITEM_ID
2837                         ,BOM_ITEM_TYPE
2838                         ,WIP_SUPPLY_TYPE
2839                         ,ORDERED_QUANTITY
2840                         ,ORDER_QUANTITY_UOM
2841                         ,BATCH_ID
2842                         ,CREATION_DATE
2843                         ,CREATED_BY
2844                         ,LAST_UPDATE_DATE
2845                         ,LAST_UPDATED_BY
2846                         ,LAST_UPDATE_LOGIN
2847                         ,PROGRAM_APPLICATION_ID
2848                         ,PROGRAM_ID
2849                         ,REQUEST_ID
2850                         ,PROGRAM_UPDATE_DATE
2851                         ,QTY_PER_PARENT_MODEL
2852                         ,CONFIG_CREATION
2853                         ,OPTION_SPECIFIC
2854                         ,REUSE_CONFIG
2855 			,VALIDATION_ORG
2856              )
2857              values (
2858                          t_bcol(i).LINE_ID
2859                         ,t_bcol(i).HEADER_ID
2860                         ,t_bcol(i).TOP_MODEL_LINE_ID
2861                         ,t_bcol(i).LINK_TO_LINE_ID
2862                         ,t_bcol(i).ATO_LINE_ID
2863                         ,t_bcol(i).PARENT_ATO_LINE_ID
2864                         ,t_bcol(i).INVENTORY_ITEM_ID
2865                         ,t_bcol(i).SHIP_FROM_ORG_ID
2866                         ,t_bcol(i).COMPONENT_SEQUENCE_ID
2867                         ,t_bcol(i).COMPONENT_CODE
2868                         ,t_bcol(i).ITEM_TYPE_CODE
2869                         ,t_bcol(i).SCHEDULE_SHIP_DATE
2870                         ,t_bcol(i).PLAN_LEVEL
2871                         ,t_bcol(i).PERFORM_MATCH
2872                         ,t_bcol(i).CONFIG_ITEM_ID
2873                         ,t_bcol(i).BOM_ITEM_TYPE
2874                         ,t_bcol(i).WIP_SUPPLY_TYPE
2875                         ,t_bcol(i).ORDERED_QUANTITY
2876                         ,t_bcol(i).ORDER_QUANTITY_UOM
2877                         ,t_bcol(i).BATCH_ID
2878                         ,sysdate
2879                         ,gUserId /* CREATED_BY  */
2880                         ,sysdate /* LAST_UPDATE_DATE */
2881                         ,gUserId /* LAST_UPDATED_BY */
2882                         ,gLoginId /* LAST_UPDATE_LOGIN */
2883                         ,FND_GLOBAL.PROG_APPL_ID /* PROGRAM_APPLICATION_ID */
2884                         ,FND_GLOBAL.CONC_PROGRAM_ID /* PROGRAM_ID */
2885                         ,FND_GLOBAL.CONC_REQUEST_ID /* REQUEST_ID */
2886                         ,sysdate /* PROGRAM_UPDATE_DATE */
2887                         ,t_bcol(i).ordered_quantity / t_bcol(t_bcol(i).parent_ato_line_id).ordered_quantity
2888                         ,t_bcol(i).config_creation
2889                         , 'N'
2890                         , 'N'
2891 			,t_bcol(i).SHIP_FROM_ORG_ID --bugfix 3555026
2892              ) ;
2893 
2894              IF PG_DEBUG <> 0 THEN
2895     	        oe_debug_pub.add('populate_bcol: bcol_gt ' || t_bcol(i).line_id  , 1 );
2896              END IF;
2897 
2898 
2899           end if ; /* check for reschedule flag */
2900 
2901        end if ;
2902 
2903        i := t_bcol.next(i) ; /* added for bug 1728383 for performance */
2904 
2905     end loop ;
2906 
2907 
2908 
2909 
2910     IF PG_DEBUG <> 0 THEN
2911     	oe_debug_pub.add('populate_bcol: ' || 'success in populate bcol ', 1 );
2912     END IF;
2913 
2914  exception
2915 
2916 	when FND_API.G_EXC_ERROR then
2917 		IF PG_DEBUG <> 0 THEN
2918 			oe_debug_pub.add('populate_bcol: ' || 'populate_Bcol::exp error::'|| v_step ||'::'||sqlerrm , 1);
2919 		END IF;
2920 		x_return_status := FND_API.G_RET_STS_ERROR;
2921 		CTO_MSG_PUB.Count_And_Get
2922         		(p_msg_count => x_msg_count
2923         		,p_msg_data  => x_msg_data
2924         		);
2925 
2926 	when FND_API.G_EXC_UNEXPECTED_ERROR then
2927 		IF PG_DEBUG <> 0 THEN
2928 			oe_debug_pub.add('populate_bcol: ' || 'populate_Bcol::unexp error::'|| v_step ||'::'||sqlerrm , 1);
2929 		END IF;
2930 		x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
2931 		CTO_MSG_PUB.Count_And_Get
2932         		(p_msg_count => x_msg_count
2933         		,p_msg_data  => x_msg_data
2934         		);
2935 
2936 	when OTHERS then
2937 		IF PG_DEBUG <> 0 THEN
2938 			oe_debug_pub.add('populate_bcol: ' || 'populate_Bcol::others::'|| v_step ||'::'||sqlerrm , 1 );
2939 		END IF;
2940 		x_return_status := FND_API.G_RET_STS_UNEXP_ERROR ;
2941 		IF FND_MSG_PUB.Check_Msg_Level(FND_MSG_PUB.G_MSG_LVL_UNEXP_ERROR) THEN
2942             		FND_MSG_PUB.Add_Exc_Msg
2943             			(G_PKG_NAME
2944             			,'populate_bcol'
2945             			);
2946         	END IF;
2947         	CTO_MSG_PUB.Count_And_Get
2948         		(p_msg_count => x_msg_count
2949         		,p_msg_data  => x_msg_data
2950         		);
2951 
2952  end populate_bcol ;
2953 
2954 
2955 /*
2956  PROCEDURE validate_model_heir_behavior
2957  ( p_t_bcol  in out NOCOPY TAB_BCOL )
2958  is
2959  begin
2960 
2961 
2962 
2963 
2964 
2965  end validate_model_heir_behavior ;
2966 */
2967 
2968 
2969  PROCEDURE populate_plan_level
2970  ( p_t_bcol  in out NOCOPY TAB_BCOL )
2971  is
2972  TYPE TABNUM is TABLE of NUMBER index by binary_integer ;
2973  v_raw_line_id TABNUM ;
2974  v_src_point   number ;
2975  j             number ;
2976  v_step        VARCHAR2(10) ;
2977  i             number := 0 ;
2978 
2979  begin
2980 
2981     /*
2982     ** Strategy: Resolve plan_level for each line item by setting it to 1 + plan_level of parent.
2983     ** use the link_to_line_id column to get to the parent. if parents plan_level is not yet
2984     ** resolved, go to its immediate ancestor recursively till you find a line item with
2985     ** plan_level set( Top level plan level is always set to zero ). When coming out of recursion
2986     ** set the plan_level of any ancestors that havent been resolved yet.
2987     ** Implementation: As Pl/Sql does not support Stack built-in-datatype, an equivalent behavior
2988     ** can be achieved by storing items in a table( PUSH implementation) and retrieving them from
2989     ** the end of the table ( POP implmentation [LIFO] )
2990     */
2991 
2992         v_step := 'Step B1' ;
2993 
2994     i := p_t_bcol.first ;
2995 
2996 
2997 
2998     /*   for i in 1..p_t_bcol.last commented for bug 1728383 */
2999 
3000 
3001     while i is not null
3002     loop
3003 
3004        if( p_t_bcol.exists(i)  ) then
3005 
3006           v_src_point := i ;
3007 
3008 
3009           /*
3010           ** resolve plan level for item only if not yet resolved
3011           */
3012           while( p_t_bcol(v_src_point).plan_level is null )
3013           loop
3014 
3015              v_raw_line_id(v_raw_line_id.count + 1 ) := v_src_point  ;
3016              /* store each unresolved item in its heirarchy */
3017 
3018              v_src_point := p_t_bcol(v_src_point).link_to_line_id ;
3019 
3020           end loop ;
3021 
3022         v_step := 'Step B2' ;
3023 
3024           j := v_raw_line_id.count ; /* total number of items to be resolved */
3025 
3026           while( j >= 1 )
3027           loop
3028 
3029              p_t_bcol(v_raw_line_id(j)).plan_level := p_t_bcol(v_src_point).plan_level + 1;
3030 
3031              v_src_point := v_raw_line_id(j) ;
3032 
3033              j := j -1 ;
3034           end loop ;
3035 
3036           v_raw_line_id.delete ; /* remove all elements as they have been resolved */
3037 
3038        end if ;
3039 
3040 
3041 
3042        i := p_t_bcol.next(i) ;  /* added for bug 1728383 for performance */
3043 
3044 
3045     end loop ;
3046 
3047  end populate_plan_level ;
3048 
3049 
3050 
3051  PROCEDURE populate_parent_ato
3052  ( p_t_bcol  in out NOCOPY TAB_BCOL ,
3053   p_bcol_line_id in       bom_cto_order_lines.line_id%type )
3054  is
3055  TYPE TABNUM is TABLE of NUMBER index by binary_integer ;
3056  v_raw_line_id TABNUM ;
3057  v_src_point   number ;
3058  v_prev_src_point   number ;
3059  j             number ;
3060  v_step        VARCHAR2(10) ;
3061  i             number := 0 ;
3062 
3063  begin
3064 
3065     /*
3066     ** Strategy: Resolve parent_ato for each line item by setting it to 1 + plan_level of parent.
3067     ** use the link_to_line_id column to get to the parent. if parents plan_level is not yet
3068     ** resolved, go to its immediate ancestor recursively till you find a line item with
3069     ** plan_level set( Top level plan level is always set to zero ). When coming out of recursion
3070     ** set the plan_level of any ancestors that havent been resolved yet.
3071     ** Implementation: As Pl/Sql does not support Stack built-in-datatype, an equivalent behavior
3072     ** can be achieved by storing items in a table( PUSH implementation) and retrieving them from
3073     ** the end of the table ( POP implmentation [LIFO] )
3074     */
3075 
3076         v_step := 'Step C1' ;
3077 
3078     i := p_t_bcol.first ;
3079 
3080 
3081     /*  for i in 1..p_t_bcol.last commented for bug 1728383 */
3082 
3083     while i is not null
3084     loop
3085 
3086        if( p_t_bcol.exists(i)  ) then
3087 
3088           v_src_point := i ;
3089           /* please note, here it stores the index which is the same as line_id due to sparse array*/
3090 
3091           IF PG_DEBUG <> 0 THEN
3092           	oe_debug_pub.add('populate_parent_ato: ' ||  ' processing ' || to_char( v_src_point ) , 3 );
3093           END IF;
3094           /*
3095           ** resolve parent ato line id for item.
3096           */
3097         v_step := 'Step C2' ;
3098 
3099           while( p_t_bcol.exists(v_src_point) )
3100           loop
3101 
3102              v_raw_line_id(v_raw_line_id.count + 1 ) := v_src_point  ;
3103              /* store each unresolved item in its heirarchy */
3104 
3105              v_prev_src_point := v_src_point ;
3106 
3107              v_src_point := p_t_bcol(v_src_point).link_to_line_id ;
3108 
3109 
3110           IF PG_DEBUG <> 0 THEN
3111           	oe_debug_pub.add('populate_parent_ato: ' ||  'prev point ' || to_char( v_prev_src_point ) || ' bcol ' || to_char( p_bcol_line_id ) , 3 );
3112           END IF;
3113 
3114 
3115              if( v_src_point is null or v_prev_src_point = p_bcol_line_id ) then
3116                  v_src_point := v_prev_src_point ;
3117 
3118                  /* break if pto is on top of top level ato or
3119                     the current lineid is top level phantom ato
3120                  */
3121 
3122                  exit ;
3123              end if ;
3124 
3125              if( p_t_bcol(v_src_point).bom_item_type = '1' AND
3126                  p_t_bcol(v_src_point).ato_line_id is not null AND
3127                  nvl( p_t_bcol(v_src_point).wip_supply_type , 0 ) <> '6' ) then
3128 
3129                    exit ;
3130                   /* break if non phantom ato parent found */
3131              end if ;
3132 
3133 
3134 
3135           end loop ;
3136 
3137           j := v_raw_line_id.count ; /* total number of items to be resolved */
3138 
3139         v_step := 'Step C3' ;
3140 
3141           while( j >= 1 )
3142           loop
3143 
3144              p_t_bcol(v_raw_line_id(j)).parent_ato_line_id := v_src_point ;
3145 
3146              j := j -1 ;
3147 
3148           end loop ;
3149 
3150           v_raw_line_id.delete ; /* remove all elements as they have been resolved */
3151 
3152        end if ;
3153 
3154 
3155 
3156        i := p_t_bcol.next(i) ;  /* added for bug 1728383 for performance */
3157 
3158 
3159     end loop ;
3160 
3161  end populate_parent_ato ;
3162 
3163 
3164 /*
3165 ** This procedure checks for existence of any sourcing rules for a given Item.
3166 ** An Item will be considered sourced if the sourcing rule type is 'TRANSFER FROM'.
3167 ** This procedure flags an error if multiple sourcing rules exist for an Item.
3168 ** A no data found for sourcing rule query or a 'MAKE AT' sourcing rule is considered as end of sourcing chain.
3169 */
3170 
3171 /* Modified by Renga Kannan on 08/21/01 to support buy model sourcing. The signature
3172    of the procedure is changed. This change is done as part of the procuring fonit
3173    code changes
3174 */
3175 
3176 
3177 PROCEDURE query_sourcing_org(
3178   p_inventory_item_id    NUMBER
3179 , p_organization_id      NUMBER
3180 , p_sourcing_rule_exists out NOCOPY varchar2
3181 , p_source_type          out NOCOPY NUMBER    -- Added by Renga Kannan on 08/21/01
3182 , p_sourcing_org         out NOCOPY NUMBER
3183 , p_transit_lead_time    out NOCOPY NUMBER
3184 , x_exp_error_code       out NOCOPY NUMBER
3185 , x_return_status        out NOCOPY varchar2
3186 )
3187 is
3188 v_sourcing_rule_id    number ;
3189 l_stmt_num            number ;
3190 v_source_type         varchar2(1) ;
3191 v_sourcing_rule_count number;         -- Added by Renga Kannan on 08/21/01
3192 
3193 l_make_buy_code       number;
3194 begin
3195      /*
3196      ** This routine should consider no data found or one make at sourcing rule
3197      ** as no sourcing rule exist.
3198      */
3199            l_stmt_num := 1 ;
3200 
3201            -- Added by Renga Kannan on 06/26/01
3202            -- The following  initialize_assignment_set is used to initialize the global variable
3203 
3204            IF gMrpAssignmentSet is null THEN
3205              IF PG_DEBUG <> 0 THEN
3206              	oe_debug_pub.add('query_sourcing_org: ' || 'Initializing the assignment set',5);
3207              END IF;
3208              initialize_assignment_set(x_return_status);
3209              if x_return_status <>  FND_API.G_RET_STS_SUCCESS THEN
3210                 IF PG_DEBUG <> 0 THEN
3211                 	oe_debug_pub.add('query_sourcing_org: ' || 'Error in initializing assignment set',5);
3212                 END IF;
3213                 raise FND_API.G_EXC_UNEXPECTED_ERROR;
3214              end if;
3215            End IF;
3216 
3217 
3218            p_sourcing_rule_exists := FND_API.G_FALSE ;
3219            x_return_status := FND_API.G_RET_STS_SUCCESS ;
3220            p_transit_lead_time := 0 ;
3221 
3222 
3223           -- Added by Renga Kannan on 08/27/01
3224           -- If the default assignment set is not defined then it needs to
3225           -- get the source type based on make or buy rule;
3226 
3227            IF  gMrpAssignmentSet is NULL Then
3228                 SELECT planning_make_buy_code
3229                 INTO   l_make_buy_code
3230                 FROM   MTL_SYSTEM_ITEMS
3231                 WHERE  inventory_item_id = p_inventory_item_id
3232                 AND    organization_id   = p_organization_id;
3233 
3234                 IF l_make_buy_code = 2 THEN
3235                   p_source_type := 3;
3236                   -- Renga Kannan added on 09/13/01 to set the sourcin_rule_exists
3237                   -- Output value to Y even in the case of Buy attribute
3238                   p_sourcing_rule_exists := FND_API.G_TRUE;
3239 
3240 		ELSE
3241 		   p_source_type := 2;
3242 
3243 
3244                 END IF;
3245                 return;
3246            END IF;
3247 
3248 
3249 
3250            /*
3251            ** Fix for Bug 1610583
3252            ** Source Type values in MRP_SOURCES_V
3253            ** 1 = Transfer From, 2 = Make At, 3 = Buy From.
3254            */
3255 
3256 
3257            -- In the following sql the Where condition is fixed by Renga Kannan
3258            -- on 04/30/2001. If the sourcing is defined in the org level the source_type
3259            -- will be null. Still we need to see that sourcing rule. So the condition
3260            -- Source_type <> 3 is replaced with nvl(source_type,1). When the source_type is
3261            -- Null it will be defaulted to 1(Transfer from). As per the discussion with Sushant.
3262 
3263 
3264            /* Please note the changes done for procuring config project */
3265            -- Since the buy sourcing needs to be supported the where condition for msv.source_type is removed
3266            -- from the following query. This is done by Renga Kannan
3267 
3268            l_stmt_num := 10 ;
3269 
3270            begin
3271               select distinct
3272                 source_organization_id,
3273                 sourcing_rule_id,
3274                 nvl(source_type,1) ,
3275                 nvl( avg_transit_lead_time , 0 )
3276               into
3277                 p_sourcing_org
3278               , v_sourcing_rule_id
3279               , v_source_type
3280               , p_transit_lead_time
3281               from mrp_sources_v msv
3282               where msv.assignment_set_id = gMrpAssignmentSet
3283                 and msv.inventory_item_id = p_inventory_item_id
3284                 and msv.organization_id = p_organization_id
3285               --  and nvl(msv.source_type,1) <> 3 commented by Renga for BUY odel
3286                 and nvl(effective_date,sysdate) <= nvl(disable_date, sysdate) -- Nvl fun is added by Renga Kannan on 05/05/2001
3287                 and nvl(disable_date, sysdate+1) > sysdate;
3288 
3289               /*
3290               ** item is multi-org if sourcing rule is transfer from.
3291               */
3292               l_stmt_num := 20 ;
3293 
3294               --- The following assignment stmt is added by Renga Kannan
3295               --- to pass back the source type value as parameter
3296 
3297               p_source_type := v_source_type;
3298 
3299               if( v_source_type = 1 ) then
3300                   p_sourcing_rule_exists := FND_API.G_TRUE ;
3301 
3302               --- The following elseif clause is added by Renga Kannan
3303               --- For procuring config project change.
3304               elsif (v_source_type = 3) then
3305                   p_sourcing_rule_exists := FND_API.G_TRUE ;
3306                   IF PG_DEBUG <> 0 THEN
3307                   	oe_debug_pub.add('query_sourcing_org: ' || 'Buy Sourcing rule exists...',1);
3308                   END IF;
3309               end if ;
3310 
3311 
3312               IF PG_DEBUG <> 0 THEN
3313               	oe_debug_pub.add('query_sourcing_org: ' ||  '****$$$$ IID ' || p_inventory_item_id || ' in org ' ||
3314                       p_organization_id || ' is sourced from org ' || p_sourcing_org ||
3315                       ' type ' || v_source_type || ' $$$$****' , 1 );
3316               END IF;
3317 
3318            EXCEPTION
3319               WHEN NO_DATA_FOUND THEN
3320                 IF PG_DEBUG <> 0 THEN
3321                 	oe_debug_pub.add('query_sourcing_org: ' ||  ' came into no data when finding source ' || to_char(l_stmt_num ) , 1  );
3322                 END IF;
3323                 /* removed no sourcing flag as cascading of sourcing rules will
3324                 ** be continued till no more sourcing rules can be cascaded
3325                 */
3326 
3327                 --- Added by Renga Kannan on 08/21/01
3328                 --- When there is no sourcing rule defined we need to look at the
3329                 --- Planning_make_buy_code to determine the source_type
3330                 --- If the planning_make_buy_code is 1(Make) we can return as it is
3331                 --- If the planning_make_buy_code is 2(Buy) we need to set the p_source_type to 3 and return
3332                 --- so that the calling application will knwo this as buy model
3333 
3334                 SELECT planning_make_buy_code
3335                 INTO   l_make_buy_code
3336                 FROM   MTL_SYSTEM_ITEMS
3337                 WHERE  inventory_item_id = p_inventory_item_id
3338                 AND    organization_id   = p_organization_id;
3339 
3340                 IF l_make_buy_code = 2 THEN
3341                   p_source_type := 3;
3342                   p_sourcing_rule_exists := FND_API.G_TRUE ;
3343                 ELSE
3344 		  p_source_type := 2;
3345                 END IF;
3346 
3347 
3348                 ---- End of addition by Renga
3349 
3350 
3351               WHEN TOO_MANY_ROWS THEN
3352                 IF PG_DEBUG <> 0 THEN
3353                 	oe_debug_pub.add('query_sourcing_org: ' ||  ' came into too_many when finding source ' || to_char(l_stmt_num)  , 1  );
3354                 END IF;
3355               select count(*)
3356               into v_sourcing_rule_count
3357               from mrp_sources_v msv
3358               where msv.assignment_set_id = gMrpAssignmentSet
3359                 and msv.inventory_item_id = p_inventory_item_id
3360                 and msv.organization_id = p_organization_id
3361                 and nvl(msv.source_type,1) <> 3
3362                 and nvl(effective_date,sysdate) <= nvl(disable_date, sysdate)
3363                     /* Nvl fun is added by Renga Kannan on 05/05/2001 */
3364                 and nvl(disable_date, sysdate+1) > sysdate;
3365 
3366 
3367                 if( v_sourcing_rule_count > 0 ) then
3368 
3369                    /*  x_return_status                := FND_API.G_RET_STS_ERROR;
3370 	            cto_msg_pub.cto_message('BOM','CTO_INVALID_SOURCING');
3371                       x_exp_error_code := 66;
3372 
3373 		      */
3374 
3375 		   --by Kiran Konada , for DMF-J mutliple sources support
3376                    --from DMF-J , having multiple sources is not error
3377 		   --use 66 as source type for multiple sourcing
3378 		    p_source_type := 66;
3379                     p_sourcing_rule_exists := FND_API.G_TRUE ;
3380 
3381 
3382                 else
3383 
3384                     p_source_type := 3 ;
3385                     p_sourcing_rule_exists := FND_API.G_TRUE ;
3386 
3387 
3388                 end if ;
3389 
3390 
3391               WHEN OTHERS THEN
3392                 IF PG_DEBUG <> 0 THEN
3393                 	oe_debug_pub.add('query_sourcing_org: ' ||  'QUERY_SOURCING_ORG::others:: ' ||
3394                                    to_char(l_stmt_num) || '::' ||
3395                                   ' came into others when finding source ' , 1  );
3396 
3397                 	oe_debug_pub.add('query_sourcing_org: ' ||  ' SQLCODE ' || SQLCODE , 1 );
3398 
3399                 	oe_debug_pub.add('query_sourcing_org: ' ||  ' SQLERRM ' || SQLERRM  , 1 );
3400 
3401                 	oe_debug_pub.add('query_sourcing_org: ' ||  ' came into others when finding source ' , 1  );
3402                 END IF;
3403 
3404                 x_return_status                := FND_API.G_RET_STS_UNEXP_ERROR;
3405 
3406 
3407 
3408            END ;
3409 end query_sourcing_org ;
3410 
3411 
3412 
3413 
3414 PROCEDURE initialize_assignment_set ( x_return_status out NOCOPY varchar2 )
3415 IS
3416    l_stmt_num                  number;
3417    assign_set_name            varchar2(80);
3418    INVALID_MRP_ASSIGNMENT_SET exception ;
3419 
3420 BEGIN
3421       /* begin for static block */
3422    x_return_status := FND_API.G_RET_STS_SUCCESS ;
3423 
3424    /*
3425    ** get MRP's default assignment set
3426    */
3427    l_stmt_num := 1 ;
3428 
3429    IF gMrpAssignmentSet is null THEN
3430       begin
3431 
3432         gMrpAssignmentSet := to_number(FND_PROFILE.VALUE('MRP_DEFAULT_ASSIGNMENT_SET'));
3433       exception
3434       when others then
3435          raise invalid_mrp_assignment_set ;
3436       end ;
3437 
3438       l_stmt_num := 5 ;
3439 
3440       IF( gMrpAssignmentSet is null )
3441       THEN
3442          IF PG_DEBUG <> 0 THEN
3443          	oe_debug_pub.add('initialize_assignment_set: ' || '**$$ Default assignment set is null',  1);
3444          END IF;
3445 
3446       ELSE
3447          IF PG_DEBUG <> 0 THEN
3448          	oe_debug_pub.add('initialize_assignment_set: ' || 'Default assignment set is '||to_char(gMrpAssignmentSet),2);
3449          END IF;
3450 
3451          l_stmt_num := 10 ;
3452 
3453          begin
3454 
3455 
3456              select assignment_set_name into assign_set_name
3457              from mrp_Assignment_sets
3458              where assignment_set_id = gMrpAssignmentSet ;
3459 
3460          exception
3461             when no_data_found then
3462                IF PG_DEBUG <> 0 THEN
3463                	oe_debug_pub.add('initialize_assignment_set: ' ||  'The assignment set pointed by the
3464                                    profile MRP_DEFAULT_ASSIGNMENT_SET
3465                                    does not exist in the database ' ,1);
3466                END IF;
3467 
3468                 RAISE INVALID_MRP_ASSIGNMENT_SET ;
3469 
3470              when others then
3471 
3472                 RAISE FND_API.G_EXC_UNEXPECTED_ERROR ;
3473          end ;
3474 
3475          IF PG_DEBUG <> 0 THEN
3476          	oe_debug_pub.add('initialize_assignment_set: ' || 'Default assignment set name is '||
3477                assign_set_name ,2);
3478          END IF;
3479 
3480       END IF;
3481 
3482    END IF;
3483 exception
3484    when INVALID_MRP_ASSIGNMENT_SET then
3485         x_return_status := FND_API.G_RET_STS_ERROR;
3486 
3487         IF PG_DEBUG <> 0 THEN
3488         	oe_debug_pub.add('initialize_assignment_set: ' || 'INITIALIZE_ASSIGNMENT_SET::INVALID ASSIGNMENT SET ::'||to_char(l_stmt_num)||'::'||sqlerrm,1);
3489         END IF;
3490 
3491 
3492    when FND_API.G_EXC_UNEXPECTED_ERROR then
3493         x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
3494         IF PG_DEBUG <> 0 THEN
3495         	oe_debug_pub.add('initialize_assignment_set: ' || 'INITIALIZE_ASSIGNMENT_SET::unexp error::'||to_char(l_stmt_num)||'::'||sqlerrm,1);
3496         END IF;
3497 
3498 
3499    when OTHERS then
3500         x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
3501         IF PG_DEBUG <> 0 THEN
3502         	oe_debug_pub.add('initialize_assignment_set: ' || 'INITIALIZE_ASSIGNMENT_SET::others::'||to_char(l_stmt_num)||'::'||sqlerrm,1);
3503         END IF;
3504 
3505 
3506 END initialize_assignment_set ;
3507 
3508 
3509 
3510 /*
3511 ** This procedure checks whether a model has been sourced.
3512 ** It also checks for circular sourcing and flags an error if it detects one.
3513 ** This procedure keeps on chaining sourcing rules till no more sourcing rules exist.
3514 */
3515 
3516 
3517 /* Modified by Renga Kannan on 08/21/01 to honor Buy model sourcing also. This changes were replicated from CTOATPIB.pls
3518    file. The signature of get_model_sourcing_org is changed for this purpose.
3519 */
3520 PROCEDURE get_model_sourcing_org(
3521   p_inventory_item_id    NUMBER
3522 , p_organization_id      NUMBER
3523 , p_sourcing_rule_exists out NOCOPY varchar2
3524 , p_sourcing_org         out NOCOPY NUMBER
3525 , p_source_type          out NOCOPY NUMBER   --- Added by Renga Kannan on 08/21/01 for BUY Models
3526 , p_transit_lead_time    out NOCOPY NUMBER
3527 , x_return_status        out NOCOPY varchar2
3528 , x_exp_error_code       out NOCOPY number
3529 , p_line_id              in NUMBER
3530 , p_ship_set_name        in varchar2
3531 )
3532 IS
3533    v_sourcing_organization_id  	number ;
3534    v_assignment_type   		number ;
3535    x_msg_data     		varchar2(2000) ;
3536    x_msg_count    		number ;
3537    l_stmt_num     		number ;
3538    l_error_code   		number ;
3539    v_organization_id 		number ;
3540    v_transit_lead_time 		number ;
3541    v_circular_sourcing 		boolean ;
3542    v_location          		number := 0 ;
3543    v_sourcing_rule_exists 	varchar2(1) ;
3544    CTO_MRP_ASSIGNMENT_SET  	exception;
3545 
3546    TYPE TABNUM is TABLE of NUMBER index by binary_integer ;
3547    v_orgs_tbl         		TABNUM ;
3548 
3549    --- Added for Buy Model sourcing
3550    v_source_type       number;
3551 
3552 BEGIN
3553         l_stmt_num :=  1;
3554 
3555         p_sourcing_rule_exists := FND_API.G_FALSE ;
3556         p_transit_lead_time := 0 ;
3557 
3558         x_return_status := FND_API.G_RET_STS_SUCCESS ;
3559 
3560         v_organization_id := p_organization_id ;
3561         v_transit_lead_time := 0 ;
3562         v_circular_sourcing := FALSE ;
3563         v_orgs_tbl.delete ; /* reinitialize table to check circular sourcing */
3564 
3565 
3566         l_stmt_num := 10 ;
3567 
3568         <<OUTER>>
3569         while( TRUE )
3570         LOOP
3571 
3572 
3573            l_stmt_num := 20 ;
3574 
3575            /*
3576            ** check whether the current org exists in the orgs array
3577            */
3578            for i in 1..v_orgs_tbl.count
3579            loop
3580               if( v_orgs_tbl(i) = v_organization_id )
3581               then
3582                  v_circular_sourcing := TRUE ;
3583                  v_location := i ;
3584                  exit OUTER ;
3585               end if ;
3586            end loop ;
3587 
3588            v_orgs_tbl(v_orgs_tbl.count + 1 ) := v_organization_id ;
3589 
3590            l_stmt_num := 30 ;
3591 
3592 
3593            query_sourcing_org(
3594                 p_inventory_item_id
3595               , v_organization_id
3596               , v_sourcing_rule_exists
3597               , v_source_type              -- Added by Renga for BUY MODEL
3598               , v_sourcing_organization_id
3599               , v_transit_lead_time
3600               , x_exp_error_code
3601               , x_return_status
3602            ) ;
3603 
3604 
3605            l_stmt_num := 40 ;
3606 
3607            IF x_return_status = FND_API.G_RET_STS_ERROR
3608            THEN
3609 
3610                    RAISE FND_API.G_EXC_ERROR;
3611            ELSIF x_return_status = FND_API.G_RET_STS_UNEXP_ERROR
3612            THEN
3613 
3614                    RAISE FND_API.G_EXC_UNEXPECTED_ERROR;
3615            END IF;
3616 
3617            /* The following block is added by Renga Kannan on 08/21/01. This change is done as
3618               Part of BUY Model sourcing changes. The source type is being returned from
3619               query_sourcing_org is passed back to the calling application.
3620            */
3621 
3622            p_source_type  := v_source_type;
3623 
3624            IF (v_source_type = '3') THEN  --- If it is buy sourcing
3625              -- If the sourcing is of buy model we should not go in chain
3626              -- further. This will return the source_type to the calling
3627              -- application. The calling application will check the source_type
3628              -- and takes action based on that.
3629              p_sourcing_rule_exists := 'T' ;
3630              exit;
3631            ELSE
3632 
3633              if( FND_API.to_boolean( v_sourcing_rule_exists )  ) then
3634                p_sourcing_rule_exists := 'T' ;
3635              else
3636                exit ; /* always exit when no more sourcing rules to cascade */
3637              end if ;
3638             END IF;
3639 
3640            l_stmt_num := 50 ;
3641 
3642            /* set the query organization id to current sourcing organization to
3643            ** cascade sourcing rules.
3644            ** e.g.  M1 <- D1 , D1 <- M2  =>  M1 <- M2
3645            */
3646            v_organization_id := v_sourcing_organization_id ;
3647 
3648            /*
3649            ** please check with usha about adding lead times??.
3650            */
3651            p_transit_lead_time := p_transit_lead_time + v_transit_lead_time ;
3652 
3653         END LOOP OUTER ;
3654 
3655         l_stmt_num := 60 ;
3656 
3657         if( v_circular_sourcing )
3658         then
3659            x_exp_error_code := 66 ;
3660            IF PG_DEBUG <> 0 THEN
3661            	oe_debug_pub.add('get_model_sourcing_org: ' ||  ' circular sourcing problem ' , 1 );
3662            END IF;
3663 
3664            --bugfix 2813271: Added message to show the user
3665            cto_msg_pub.cto_message('BOM','CTO_INVALID_SOURCING'); -- bugfix 2813271
3666            RAISE FND_API.G_EXC_ERROR;
3667 
3668         end if ;
3669 
3670         p_sourcing_org := v_organization_id ;
3671 
3672         IF PG_DEBUG <> 0 THEN
3673         	oe_debug_pub.add('get_model_sourcing_org: ' || 'sourcing org is ' || p_sourcing_org || ' lead time ' || to_char( p_transit_lead_time ) , 1 );
3674         END IF;
3675 
3676 exception
3677    when FND_API.G_EXC_ERROR then
3678         IF PG_DEBUG <> 0 THEN
3679         	oe_debug_pub.add('get_model_sourcing_org: ' || 'GET_MODEL_SOURCING_ORG::exp error::'||to_char(l_stmt_num)||'::'||sqlerrm,1);
3680         END IF;
3681         x_return_status := FND_API.G_RET_STS_ERROR;
3682 
3683         CTO_MSG_PUB.Count_And_Get(
3684           p_msg_count => x_msg_count
3685         , p_msg_data  => x_msg_data
3686         );
3687 
3688    when FND_API.G_EXC_UNEXPECTED_ERROR then
3689         IF PG_DEBUG <> 0 THEN
3690         	oe_debug_pub.add('get_model_sourcing_org: ' || 'GET_MODEL_SOURCING_ORG::unexp error::'||to_char(l_stmt_num)||'::'||sqlerrm,1);
3691         END IF;
3692         x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
3693 
3694         CTO_MSG_PUB.Count_And_Get(
3695           p_msg_count => x_msg_count
3696         , p_msg_data  => x_msg_data
3697         );
3698 
3699    when OTHERS then
3700         IF PG_DEBUG <> 0 THEN
3701         	oe_debug_pub.add('get_model_sourcing_org: ' || 'GET_MODEL_SOURCING_ORG::others::'||to_char(l_stmt_num)||'::'||sqlerrm,1);
3702         END IF;
3703         x_return_status := FND_API.G_RET_STS_UNEXP_ERROR ;
3704 
3705         IF FND_MSG_PUB.Check_Msg_Level(FND_MSG_PUB.G_MSG_LVL_UNEXP_ERROR) THEN
3706            FND_MSG_PUB.Add_Exc_Msg(
3707              G_PKG_NAME
3708            , 'GET_MODEL_SOURCING_ORG'
3709            );
3710         END IF;
3711 
3712 end get_model_sourcing_org ;
3713 
3714 
3715 -- bugfix 1811007 begin
3716 -- Added a new function convert_uom
3717 
3718 --Bugfix 13554996: Adding two new parameters: lot_number, organization_id
3719 
3720 FUNCTION convert_uom(from_uom        IN VARCHAR2,
3721                      to_uom          IN VARCHAR2,
3722                      quantity        IN NUMBER,
3723                      item_id         IN NUMBER,
3724 		     lot_number      IN VARCHAR2,
3725 		     organization_id IN VARCHAR2)
3726 RETURN NUMBER
3727 IS
3728   this_item     NUMBER;
3729   to_rate       NUMBER;
3730   from_rate     NUMBER;
3731   result        NUMBER;
3732 
3733 BEGIN
3734   IF from_uom = to_uom THEN
3735      result := quantity;
3736   ELSIF    from_uom IS NULL
3737         OR to_uom   IS NULL THEN
3738      result := 0;
3739   ELSE
3740      /*Bugfix 13554996: Adding lot_number and organization_id parameters.
3741      result := INV_CONVERT.inv_um_convert(item_id,
3742                                   	  5,                      -- bugfix 2204376: pass precision of 5
3743                                           quantity,
3744                                           from_uom,
3745                                           to_uom,
3746                                           NULL,
3747                                           NULL);
3748      */
3749 
3750      result := INV_CONVERT.inv_um_convert(item_id         => item_id,
3751                                           lot_number      => lot_number,
3752 					  organization_id => organization_id,
3753 					  precision       => 5,
3754 					  from_quantity   => quantity,
3755 					  from_unit       => from_uom,
3756 					  to_unit         => to_uom,
3757 					  from_name       => NULL,
3758 					  to_name         => NULL);
3759 
3760      -- hard-coded value that means undefined conversion
3761      --  For example, conversion of FT2 to FT3 doesn't make sense...
3762      -- Reset the result to 0 to preserve compatibility before
3763      -- the bug fix made above (namely, always call inv_um_convert).
3764 
3765      /*Commenting as part of bugfix 9214765
3766      if result = -99999 then
3767         result := 0;
3768      end if;
3769      */
3770 
3771   END IF;
3772   RETURN result;
3773 
3774 END convert_uom;
3775 
3776 -- bugfix 1811007 end
3777 
3778 
3779 
3780  --bugfix 1799874 begin
3781  FUNCTION get_source_document_id (pLineId in number) RETURN NUMBER
3782  IS
3783 	  l_source_document_type_id  number;
3784  BEGIN
3785 
3786           IF PG_DEBUG <> 0 THEN
3787           	oe_debug_pub.add('get_source_document_id: ' || 'CTOUTILB: get_source_document_id: Fetching the source document type id', 1);
3788           END IF;
3789 
3790 	  select h.source_document_type_id
3791 	  into   l_source_document_type_id
3792 	  from   oe_order_headers_all h, oe_order_lines_all l
3793 	  where  h.header_id =  l.header_id
3794 	  and    l.line_id = pLineId
3795 	  and    rownum = 1;
3796 
3797           IF PG_DEBUG <> 0 THEN
3798           	oe_debug_pub.add('get_source_document_id: ' || 'CTOUTILB: get_source_document_id: source document type id = '||l_source_document_type_id, 1);
3799           END IF;
3800 
3801 	  return (l_source_document_type_id);
3802 
3803  END get_source_document_id;
3804  --bugfix 1799874 end
3805 
3806 
3807 
3808  --begin bugfix 2001824
3809  FUNCTION check_rsv_quantity (p_order_line_id  IN NUMBER,
3810 			      p_rsv_quantity   IN NUMBER)
3811  RETURN BOOLEAN is
3812 
3813 	l_source_document_type_id  	number;
3814 	allowed_unreservation_qty  	number := 0;
3815 	l_shipped_qty			number := 0;
3816 	l_reservation_qty		number := 0;
3817 
3818  BEGIN
3819 
3820 	if ( nvl(p_rsv_quantity, 0) = 0 ) then
3821 		return TRUE;
3822 	end if;
3823 
3824 
3825 	--
3826 	-- Bugfix 2109503
3827 	--
3828 	-- We should consider only CLOSED lines since STAGED lines can be unreserved.
3829 	-- For eg. if you have qty 10 as staged (after completing full w/o and p/r),
3830 	-- ship-confirm 8 (close delivery) will trigger unreservation of 2
3831 	--
3832 	-- If shipping_interface_flag is 'N', consider ordered_quantity as unshipped_quantity.
3833 	--
3834 
3835 	--
3836 	-- The latest changes to this piece of the code done on Mar 20th, 2002
3837 	-- Earlier, we used to calculate the total allowed quantity to be unreserved by
3838 	-- checking how much has NOT been shipped (the unshipped_quantity). This was done
3839 	-- by checking the released_status <> 'C'. If the line didn't reach shipping, then,
3840 	-- the ordered_quantity was the qty which could be unreserved.
3841 	--
3842 
3843 	--
3844 	-- Bugfix 2276326:
3845 	-- For Over completions, this will fail since WIP can reserve more than the ordered qty
3846 	-- (if within tolerance)
3847 	-- WIP first updates the existing wip-reservation to the overcompleted-qty and then
3848 	-- calls INV to do the transfer. INV transfers the new qty from wip to inv.
3849 	-- for eg., if workorder qty=10, and you overcomplete 15, then, wip reservation is first
3850 	-- updated to 15, and inv then transfers this to inv reservation.
3851 
3852 	-- In this scenerio, since the new qty is more than the sales order qty, CTO was preventing
3853 	-- an unreserve activity. With this fix, CTO will check wrt reservation qty and decide whether
3854 	-- to allow unreservation or not.
3855 	--
3856 
3857 	l_source_document_type_id := CTO_UTILITY_PK.get_source_document_id ( pLineId => p_order_line_id );
3858 
3859 
3860 	--
3861 	--  Get the total shipped qty for this line.
3862 	--
3863 
3864         -- Bugfix 2426866 :  If inventory interface is run, the reservations will be releived.
3865 	-- We should not consider the qty which has been interfaced to inventory. Otherwise,
3866 	-- the allowed_unreservation_qty will be incorrectly calculated.
3867 	-- l_Shipped_qty is the qty shipped but NOT interfaced to inventory.
3868 
3869 
3870         -- Modified by Renga Kannan on 06/11/02 added nvl fun.
3871         -- Removed the exception
3872 
3873 	-- Bugfix 2638216 : added LEAST fn. in case of over-shipping after discussion with Usha and Vidyesh.
3874 
3875 	   select nvl(sum( LEAST(nvl(wdd.shipped_quantity,0), nvl(wdd.picked_quantity,0)) ), 0)
3876 	   into   l_shipped_qty
3877 	   from   wsh_delivery_details_ob_grp_v wdd -- Modified by Renga on 11/02/03
3878 	   where  wdd.source_line_id = p_order_line_id
3879 	   and    wdd.source_code = 'OE'
3880 	   and    wdd.released_status = 'C'		-- Closed [C]
3881 	   and    nvl(wdd.inv_interfaced_flag, 'N') <> 'Y';
3882 
3883 
3884 
3885 	--
3886 	--  Get the total reservations for this line.
3887 	--
3888 
3889         -- Modified by Renga Kannan on 06/11/02 added nvl fun.
3890         -- Removed the exception
3891 
3892 	   select nvl(sum(mr.primary_reservation_quantity),0)
3893 	   into   l_reservation_qty
3894 	   from   mtl_reservations mr
3895 	   where  mr.demand_source_type_id = decode (l_source_document_type_id, 10,
3896                                                   inv_reservation_global.g_source_type_internal_ord,
3897                                                   inv_reservation_global.g_source_type_oe )
3898            and    mr.primary_reservation_quantity > 0
3899            and    mr.demand_source_line_id = p_order_line_id;
3900 
3901 
3902 
3903 	--
3904 	--  The total allowed qty which can be unreserved is :
3905 	--  total existing reservations minus total shipped qty.
3906 	--
3907 
3908 	allowed_unreservation_qty := nvl(l_reservation_qty,0) - nvl(l_shipped_qty,0);
3909 
3910         If PG_DEBUG <> 0 Then
3911     	CTO_WIP_WORKFLOW_API_PK.cto_debug('check_rsv_qty', 'l_shipped_qty = '||l_shipped_qty);
3912     	CTO_WIP_WORKFLOW_API_PK.cto_debug('check_rsv_qty', 'l_reservation_qty = '||l_reservation_qty);
3913     	CTO_WIP_WORKFLOW_API_PK.cto_debug('check_rsv_qty', 'allowed_unreservation_qty = '||allowed_unreservation_qty);
3914         End if;
3915 
3916     	IF PG_DEBUG <> 0 THEN
3917     		oe_debug_pub.add('check_rsv_quantity: ' || 'check_rsv_qty: l_shipped_qty = '||l_shipped_qty ||
3918     			 ' l_reservation_qty = '||l_reservation_qty ||
3919     	                 ' allowed_unreservation_qty = '||allowed_unreservation_qty, 2);
3920     	END IF;
3921 
3922 	--
3923 	-- p_rsv_quantity is the qty (in primary uom) which inv will pass us. INV is trying to unreserve this qty.
3924 	-- If this qty is greater than the allowed unreservation qty, don't allow.
3925 	--
3926 
3927 	if ( p_rsv_quantity > allowed_unreservation_qty)
3928 	then
3929 		return FALSE;
3930 	else
3931 		return TRUE;
3932 	end if;
3933 
3934  EXCEPTION
3935 
3936 	when others then
3937            	IF PG_DEBUG <> 0 THEN
3938            		oe_debug_pub.add ('check_rsv_quantity: ' || 'OTHERS excpn while checking for unreserved qty :' ||substr(sqlerrm,1,150));
3939            	END IF;
3940   		raise FND_API.G_EXC_UNEXPECTED_ERROR;
3941 
3942  END CHECK_RSV_QUANTITY;
3943  -- end bugfix 2001824
3944 
3945 
3946 
3947 FUNCTION get_cto_item_attachment(p_item_id in number,
3948 		                 p_po_val_org_id in number,
3949 				 x_return_status out nocopy varchar2)
3950 RETURN clob IS
3951 
3952 l_clob_loc          clob;
3953 l_blob_loc          blob;
3954 l_input_offset      BINARY_INTEGER;
3955 l_lob_length        BINARY_INTEGER;
3956 l_cur_chunk_size    NUMBER;
3957 l_chunk_size        NUMBER := 30000;
3958 l_buf_raw           RAW(32767);
3959 l_buffer            VARCHAR2(32767);
3960 
3961 BEGIN
3962 
3963 x_return_status := fnd_api.g_ret_sts_success;
3964 
3965 -- get the file attachment locator (blob)
3966 select fl.file_data into l_blob_loc
3967 from fnd_lobs fl, fnd_attached_documents fad, fnd_documents_tl fdt
3968 where fad.pk1_value = to_char(p_po_val_org_id)
3969 and fad.pk2_value = to_char(p_item_id)
3970 and fad.entity_name = 'MTL_SYSTEM_ITEMS'
3971 and fad.pk3_value = 'CTO:BOM:ATTACHMENT'
3972 and fad.document_id = fdt.document_id
3973 and fdt.media_id = fl.file_id
3974 and fdt.language = userenv('LANG');
3975 
3976 if l_blob_loc is null then
3977    x_return_status := fnd_api.g_ret_sts_error;
3978    oe_debug_pub.add('get_cto_item_attachment: ' || 'File attachment is null. Nothing to convert to clob... returning null', 1);
3979    return null;
3980 end if;
3981 
3982 l_lob_length := dbms_lob.getlength(l_blob_loc);
3983 l_input_offset := 1;
3984 
3985 DBMS_LOB.CREATETEMPORARY(l_clob_loc, TRUE, DBMS_LOB.SESSION);
3986 DBMS_LOB.OPEN (l_clob_loc, DBMS_LOB.LOB_READWRITE);
3987 
3988 -- Loop through the blob, and convert and copy to clob in smaller chunks.
3989 
3990 LOOP
3991    -- Exit the loop when all the chunks are copied, indicated by
3992    -- l_input_offset passing l_lob_length.
3993    EXIT WHEN l_input_offset > l_lob_length;
3994 
3995    -- If at least l_chunk_size remains in the blob, copy that
3996    -- much.  Otherwise, copy only however much remains.
3997    IF (l_lob_length - l_input_offset + 1) > l_chunk_size THEN
3998       l_cur_chunk_size := l_chunk_size;
3999    ELSE
4000       l_cur_chunk_size := l_lob_length - l_input_offset + 1;
4001    END IF;
4002 
4003    dbms_lob.read(l_blob_loc, l_cur_chunk_size, l_input_offset, l_buf_raw);
4004 
4005    l_buffer := utl_raw.cast_to_varchar2(l_buf_raw);
4006 
4007    -- Write the current chunk.
4008    DBMS_LOB.writeappend(l_clob_loc, length(l_buffer), l_buffer);
4009 
4010    -- Increment the input offset by the current chunk size.
4011    l_input_offset := l_input_offset + l_cur_chunk_size;
4012 
4013 END LOOP;
4014 
4015 DBMS_LOB.CLOSE (l_clob_loc);
4016 
4017 return l_clob_loc;
4018 
4019 Exception
4020 
4021 when no_data_found then
4022    x_return_status := fnd_api.g_ret_sts_error;
4023    IF PG_DEBUG <> 0 THEN
4024       oe_debug_pub.add('get_cto_item_attachment: ' || 'no file attachment existsfor given item and org', 1);
4025    END IF;
4026    return null;
4027 
4028 when others then
4029    x_return_status := fnd_api.g_ret_sts_unexp_error;
4030    IF PG_DEBUG <> 0 THEN
4031       oe_debug_pub.add('get_cto_item_attachment: ' || 'When others exception ..' || sqlerrm, 1);
4032    END IF;
4033    return null;
4034 
4035 END get_cto_item_attachment;
4036 
4037 
4038 
4039 -----------------------------------------------------------------------------------------------------
4040 -----------------------------------------------------------------------------------------------------
4041 -----------------------------------------------------------------------------------------------------
4042  --- The following procedure is added by Renga Kannan on 08/24/01 to add attachment to an item
4043  --- I will add enough comments later for this procedure
4044 
4045 
4046    PROCEDURE create_attachment(
4047                                p_item_id        IN mtl_system_items.inventory_item_id%type,
4048                                p_org_id         IN mtl_system_items.organization_id%type,
4049                                p_text           IN Long,
4050                                p_desc           IN varchar2,
4051                                p_doc_type       IN Varchar2,
4052                                x_return_status  OUT NOCOPY varchar2) as
4053 
4054    l_doc_id                Number;
4055    l_media_id              Number;
4056    l_doc_text              Long;
4057    l_seq_num               Number;
4058    l_attached_document_id  Number;
4059    l_row_id                Varchar2(1000);
4060    l_stmt                  Number;
4061 
4062    BEGIN
4063    x_return_status :=  FND_API.G_RET_STS_SUCCESS;
4064 
4065    l_stmt := 10;
4066    IF PG_DEBUG <> 0 THEN
4067    	oe_debug_pub.add('create_attachment: ' || 'Entering Create_attachment...',1);
4068 
4069    	oe_debug_pub.add('create_attachment: ' || 'Attachment desc = '||p_desc,1);
4070    END IF;
4071 
4072    -- The following FND API will create a document with the given Text information.
4073 
4074    -- Creating a long text document using text
4075 
4076    fnd_documents_pkg.insert_row(
4077                   x_rowid                  => l_row_id,
4078                   x_document_id            => l_doc_id,
4079                   x_creation_date          => sysdate,
4080                   x_created_by             => fnd_global.USER_ID,
4081                   x_last_update_date       => sysdate,
4082                   x_last_updated_by        => fnd_global.USER_ID,
4083                   x_last_update_login      => fnd_global.USER_ID,
4084                   x_request_id             => fnd_global.USER_ID,
4085                   x_program_application_id => fnd_global.PROG_APPL_ID,
4086                   x_program_id             => fnd_global.CONC_REQUEST_ID,
4087                   x_program_update_date    => sysdate,
4088                   x_datatype_id            => 2,
4089                   x_category_id            => 33,
4090                   x_security_type          => 4,
4091                   x_security_id            => NULL
4092                   ,x_publish_flag          => 'Y'
4093                   ,x_image_type            => null
4094                   ,x_storage_type          => null
4095                   ,x_usage_type            => 'S'
4096                   ,x_start_date_active     => sysdate
4097                   ,x_end_date_active       => null
4098                   ,x_language              => 'AMERICAN'
4099                   ,x_description           => p_desc
4100                   ,x_file_name             => null
4101                   ,x_media_id              => l_media_id
4102                   ,x_attribute_category    => null
4103                   ,x_attribute1            => null
4104                   ,x_attribute2   => null
4105                   ,x_attribute3   => null
4106                   ,x_attribute4   => null
4107                   ,x_attribute5   => null
4108                   ,x_attribute6   => null
4109                   ,x_attribute7   => null
4110                   ,x_attribute8   => null
4111                   ,x_attribute9   => null
4112                   ,x_attribute10  => null
4113                   ,x_attribute11  => null
4114                   ,x_attribute12  => null
4115                   ,x_attribute13  => null
4116                   ,x_attribute14  => null
4117                   ,x_attribute15  => null
4118 		  --Bugfix 10014847: Adding the attachment title
4119 		  ,x_title        => p_desc);
4120 
4121 
4122            IF PG_DEBUG <> 0 THEN
4123            	oe_debug_pub.add('create_attachment: ' || 'The document is created with the following id....'||to_char(l_doc_id),1);
4124 
4125            	oe_debug_pub.add('create_attachment: ' || 'Media id ...'||to_char(l_media_id),1);
4126            END IF;
4127 
4128     -- The following insert is inserting into the media and text infor into fnd_documents_long_text
4129 
4130     l_stmt := 20;
4131 
4132     Insert into fnd_documents_long_text
4133                (
4134                  Media_id,
4135                  long_text)
4136            Values
4137                ( l_media_id,p_text);
4138 
4139 
4140 
4141    -- Get the sequence no for attachment
4142 
4143     l_stmt := 30;
4144 
4145     select (nvl(max(seq_num),0) + 10)
4146     into l_seq_num
4147     from fnd_attached_documents
4148     where entity_name = 'MTL_SYSTEM_ITEMS'
4149     and pk1_value =  to_char(p_org_id)		-- 2774570
4150     and pk2_value = to_char(p_item_id);         -- 6069512: Added to improve performance, we do not need seq to be unique across items.
4151 
4152 
4153     l_stmt := 40;
4154     select fnd_attached_documents_s.nextval
4155     into l_attached_document_id
4156     from dual;
4157 
4158     l_stmt := 50;
4159 
4160     FND_ATTACHED_DOCUMENTS_PKG.INSERT_ROW
4161 		(x_rowid			=> l_row_id
4162 		, x_attached_document_id	=> l_attached_document_id
4163 		, x_document_id			=> l_doc_id
4164 		, x_seq_num			=> l_seq_num
4165 		, x_entity_name			=> 'MTL_SYSTEM_ITEMS'
4166 		, x_pk1_value			=> p_org_id
4167 		, x_pk2_value			=> p_item_id
4168 		, x_pk3_value			=> p_doc_type  -- This field is used for procuring config
4169 		, x_pk4_value			=> NULL
4170 		, x_pk5_value			=> NULL
4171 		, x_automatically_added_flag	=> 'N'
4172 		, x_creation_date		=> sysdate
4173 		, x_created_by			=> fnd_global.USER_ID
4174 		, x_last_update_date		=> sysdate
4175 		, x_last_updated_by		=> fnd_global.USER_ID
4176 		, x_last_update_login		=> fnd_global.LOGIN_ID
4177 		-- following parameters are required for the API but we do not
4178 		-- use so send in as null
4179 		, x_column1			=> null
4180 		, x_datatype_id			=> null
4181 		, x_category_id			=> null
4182 		, x_security_type		=> null
4183 		, X_security_id			=> null
4184 		, X_publish_flag		=> null
4185 		, X_image_type			=> null
4186 		, X_storage_type		=> null
4187 		, X_usage_type			=> null
4188 		, X_language			=> null
4189 		, X_description			=> null
4190 		, X_file_name			=> null
4191 		, X_media_id			=> l_media_id
4192 		, X_doc_attribute_Category      => null
4193 		, X_doc_attribute1		=> null
4194 		, X_doc_attribute2		=> null
4195 		, X_doc_attribute3		=> null
4196 		, X_doc_attribute4		=> null
4197 		, X_doc_attribute5		=> null
4198 		, X_doc_attribute6		=> null
4199 		, X_doc_attribute7		=> null
4200 		, X_doc_attribute8		=> null
4201 		, X_doc_attribute9		=> null
4202 		, X_doc_attribute10		=> null
4203 		, X_doc_attribute11		=> null
4204 		, X_doc_attribute12		=> null
4205 		, X_doc_attribute13		=> null
4206 		, X_doc_attribute14		=> null
4207 		, X_doc_attribute15		=> null
4208 		);
4209 
4210 
4211 
4212    EXCEPTION
4213 
4214         when FND_API.G_EXC_UNEXPECTED_ERROR then
4215                 IF PG_DEBUG <> 0 THEN
4216                 	oe_debug_pub.add('create_attachment: ' || 'Create_attachment::unexp error::'||l_Stmt||'::'||sqlerrm,1);
4217                 END IF;
4218                 x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
4219 
4220         when FND_API.G_EXC_ERROR then
4221                 IF PG_DEBUG <> 0 THEN
4222                 	oe_debug_pub.add('create_attachment: ' || 'Create_attachment::exp error::'||l_Stmt||'::'||sqlerrm,1);
4223                 END IF;
4224                 x_return_status := FND_API.G_RET_STS_ERROR;
4225 
4226         when others then
4227                 IF PG_DEBUG <> 0 THEN
4228                 	oe_debug_pub.add('create_attachment: ' || 'Create_attachment::OTHERS error::'||l_Stmt||'::'||sqlerrm,1);
4229                 END IF;
4230                 x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
4231 
4232 
4233    END create_attachment;
4234 
4235 
4236 
4237 /*********************************************************************************************************
4238 **********************************************************************************************************
4239 
4240            Procedure Name : Generate_Bom_attachment_text
4241             Input          : inventory_item_id and Organization_id
4242 
4243            Output         : Attachment text
4244 
4245            Purpose        : This procedure is generating the bom attachment for the given inventory_item_id
4246                             in the given organization id. This text will be used to attachment text for
4247                             config item in PO validation organization.
4248 
4249 *********************************************************************************************************
4250 *********************************************************************************************************/
4251 
4252 
4253  PROCEDURE  GENERATE_BOM_ATTACH_TEXT
4254                                    (p_line_id             bom_cto_src_orgs.line_id%type,
4255                                     x_text        in out NOCOPY long,
4256                                     x_return_status  out NOCOPY varchar2
4257                                     ) is
4258 
4259 
4260    --to get the Bom of procured configuration in correct hierarchy
4261    cursor components is
4262   	select  level,
4263  		bcol.inventory_item_id inventory_item_id,
4264 		bcol.ordered_quantity        ordered_qty,
4265 		bcol.ship_from_org_id        ship_from_org_id
4266 	from	bom_cto_order_lines bcol
4267         start   with line_id = p_line_id
4268 	connect by link_to_line_id = prior line_id;
4269 
4270 
4271 	l_desc		Mtl_system_items_kfv.description%type;
4272         l_prim_uom      Mtl_system_items_kfv.primary_uom_code%type;
4273         l_loop_switch   Boolean := TRUE;
4274 	l_item_name     Mtl_system_items_kfv.concatenated_segments%type;
4275 	l_model_ord_qty Number;
4276 
4277 
4278         l_new_line   varchar2(10) := fnd_global.newline;
4279         l_hdr_text   varchar2(1000);
4280         l_temp_text  varchar2(1000);
4281         --l_form_feed  varchar2(100) := FND_GLOBAL.local_chr(12);  Bugfix 6116881
4282         l_space      varchar2(10) := fnd_global.local_chr(32);
4283 
4284         l_page_size  Number        := 15;
4285         l_stmt       Number;
4286         l_line_count Number        := 0;
4287 
4288         l_level_width number := 5;
4289         l_qty_width number := 12;
4290         l_uom_width number := 8;
4291         l_item_width number := 25;
4292         l_desc_width number := 25;
4293 
4294         --
4295         -- bug 6717456
4296         -- ntungare
4297         --
4298         l_test_text     long;
4299         text_too_long   EXCEPTION;
4300 
4301         PRAGMA EXCEPTION_INIT(text_too_long, -06502);
4302 
4303 begin
4304 
4305 IF PG_DEBUG <> 0 THEN
4306 	oe_debug_pub.add('GENERATE_BOM_ATTACH_TEXT: ' || 'Entering GENERATE_BOM_ATTACH_TEXT',1);
4307 
4308 	oe_debug_pub.add('GENERATE_BOM_ATTACH_TEXT: ' || 'line_id =>'||p_line_id,1);
4309 END IF;
4310 
4311 
4312 x_return_status :=  FND_API.G_RET_STS_SUCCESS;
4313 
4314 l_stmt  := 10;
4315 
4316 -- rkaza. 02/06/2006. bug 4938433. FP for bug 4506153:
4317 -- Adjusted length of the fields to ensure printing allignment. PO has a hard
4318 -- limit of 76 characters while printing the attach text which CTO must honour.
4319 -- The new lengths are
4320 -- Level - 5
4321 -- Qty - 12
4322 -- UOM - 8
4323 -- item name - 25
4324 -- Description - 25
4325 -- Between any two fields there will be one additional space character.
4326 -- This makes for total 71 + 4 = 75
4327 
4328 -- Previously lenghts were adjusted thru trial and error (using tab texts) such
4329 -- that data belonging to a column appears more or less under that column
4330 -- header within a reasonable range in forms.
4331 -- Now it was decided to go with the new format as described above. It
4332 -- prints correctly. But it may not look good in forms because of variable
4333 -- versus fixed font issue.
4334 
4335 
4336 --for text attachmnet header
4337 l_hdr_text := l_new_line
4338               || 'Level' || l_space
4339               || rpad('QTY', l_qty_width, l_space) || l_space
4340               || rpad('UOM', l_uom_width, l_space) || l_space
4341               || rpad('Item#', l_item_width, l_space) || l_space
4342               || 'Description'
4343               || l_new_line;
4344 
4345 
4346 
4347 l_hdr_text := concat(l_hdr_text,rpad(' ', 75, '-')|| l_new_line || l_new_line);
4348 
4349 	-- NEW CODE WITH BCOL APPROACH
4350 
4351 	l_stmt := 20;
4352 
4353         IF PG_DEBUG <> 0 THEN
4354         	oe_debug_pub.add('GENERATE_BOM_ATTACH_TEXT: ' || 'before starting the loop (inorder to get bcol lines)',1);
4355         END IF;
4356         for comp_cur in components
4357 
4358         loop
4359                 --To get ration of model to component quantity
4360 		if l_loop_switch then
4361 			l_model_ord_qty := comp_cur.ordered_qty;
4362 			l_loop_switch := false;
4363                        IF PG_DEBUG <> 0 THEN
4364                        	oe_debug_pub.add('GENERATE_BOM_ATTACH_TEXT: ' || 'in IF block of loop_siwtch,model_ord_qty=>l_model_ord_qty',1);
4365                        END IF;
4366 		end if;
4367 
4368                 --for text attachment
4369    		if nvl(l_line_count,0) = l_page_size then
4370      			--x_text := x_text||l_form_feed;  Bugfix 6116881
4371                         --
4372                         -- bug 6717456
4373                         -- ntungare
4374                         --
4375      			--x_text := concat(x_text,l_hdr_text);
4376                         l_test_text := concat(l_test_text,l_hdr_text);
4377      			l_line_count := 0;
4378                         IF PG_DEBUG <> 0 THEN
4379                         	oe_debug_pub.add('GENERATE_BOM_ATTACH_TEXT: ' || 'should start on new line as l_line_count = 15',1);
4380                         END IF;
4381    		elsif nvl(l_line_count,0) = 0 then
4382                         --
4383                         -- bug 6717456
4384                         -- ntungare
4385                         --
4386      			--x_text := concat(x_text,l_hdr_text);
4387                         l_test_text := concat(l_test_text,l_hdr_text);
4388                         IF PG_DEBUG <> 0 THEN
4389                         	oe_debug_pub.add('GENERATE_BOM_ATTACH_TEXT: ' || 'adding header text as l_line_count = 0',1);
4390                         END IF;
4391    		end if;
4392 
4393 
4394 
4395                --to get the item details from mtl_system_items
4396 		select msi.description,
4397 		       msi.primary_uom_code,
4398 		       msi.concatenated_segments
4399 		into   l_desc,
4400 		       l_prim_uom,
4401 		       l_item_name
4402 		from   mtl_system_items_kfv msi
4403 		where  msi.inventory_item_id = comp_cur.inventory_item_id
4404 		and    msi.organization_id   = comp_cur.ship_from_org_id;
4405 
4406                 --for text attachment
4407                 --
4408                 -- bug 6717456
4409                 -- Introduced this new variable so that if text_too_long exception occurs,
4410                 -- a full line goes in the attachment
4411                 -- ntungare
4412                 --
4413                 /*
4414 		x_text :=
4415                    concat(nvl(x_text, ''), rpad(comp_cur.level-1, l_level_width, l_space) ||
4416                    l_space ||
4417                    rpad(round(comp_cur.ordered_qty/l_model_ord_qty,7), l_qty_width, l_space) ||
4418                    l_space ||
4419                    rpad(l_prim_uom, l_uom_width, l_space) ||
4420                    l_space ||
4421                    rpad(substr(l_item_name, 1, l_item_width), l_item_width, l_space) ||
4422                    l_space ||
4423                    rpad(substr(l_desc, 1, l_desc_width), l_desc_width, l_space) ||
4424                    l_new_line);	*/
4425 
4426                 l_stmt := 40;
4427 
4428                 l_test_text :=
4429                    concat(nvl(l_test_text, ''), rpad(comp_cur.level-1, l_level_width, l_space) ||
4430                    l_space ||
4431                    rpad(round(comp_cur.ordered_qty/l_model_ord_qty,7), l_qty_width, l_space) ||
4432                    l_space ||
4433                    rpad(l_prim_uom, l_uom_width, l_space) ||
4434                    l_space ||
4435                    rpad(substr(l_item_name, 1, l_item_width), l_item_width, l_space) ||
4436                    l_space ||
4437                    l_desc ||
4438                    l_new_line);
4439 
4440                 x_text := l_test_text;
4441 
4442 		l_line_count := nvl(l_line_count,0) + 1;
4443                 IF PG_DEBUG <> 0 THEN
4444                 	oe_debug_pub.add('GENERATE_BOM_ATTACH_TEXT: ' || 'value of l_line_count'||l_line_count,4);
4445                 END IF;
4446 
4447 
4448 	end loop;
4449 
4450 	IF PG_DEBUG <> 0 THEN
4451 		oe_debug_pub.add('GENERATE_BOM_ATTACH_TEXT: ' || 'End of LOOP in generate BOM attachment',1);
4452 	END IF;
4453 
4454 
4455 EXCEPTION
4456 
4457      when FND_API.G_EXC_UNEXPECTED_ERROR then
4458              IF PG_DEBUG <> 0 THEN
4459              	oe_debug_pub.add('GENERATE_BOM_ATTACH_TEXT: ' || 'GENERATE_BOM_ATTACH_TEXT::unexp error::'||l_Stmt||sqlerrm,1);
4460              END IF;
4461              x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
4462 
4463      when FND_API.G_EXC_ERROR then
4464              IF PG_DEBUG <> 0 THEN
4465              	oe_debug_pub.add('GENERATE_BOM_ATTACH_TEXT: ' || 'GENERATE_BOM_ATTACH_TEXT::exp error::'||l_Stmt||sqlerrm,1);
4466              END IF;
4467              x_return_status := FND_API.G_RET_STS_ERROR;
4468 
4469      --
4470      -- bug 6717456
4471      -- ntungare
4472      --
4473      when text_too_long THEN
4474              IF PG_DEBUG <> 0 THEN
4475                 oe_debug_pub.add('GENERATE_BOM_ATTACH_TEXT: ' || 'GENERATE_BOM_ATTACH_TEXT::text too long exception::'||l_Stmt||sqlerrm,1);
4476                 oe_debug_pub.add('GENERATE_BOM_ATTACH_TEXT: ' || 'GENERATE_BOM_ATTACH_TEXT::text too long exception:: continuing..',1);
4477              END IF;
4478 
4479      when others then
4480              IF PG_DEBUG <> 0 THEN
4481              	oe_debug_pub.add('GENERATE_BOM_ATTACH_TEXT: ' || 'GENERATE_BOM_ATTACH_TEXT::OTHERS error::'||l_Stmt||sqlerrm,1);
4482              END IF;
4483              x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
4484 
4485 END GENERATE_BOM_ATTACH_TEXT;
4486 
4487 
4488 
4489 FUNCTION CHECK_CONFIG_ITEM(
4490                            p_parent_item_id     IN Mtl_system_items.inventory_item_id%type,
4491                            p_inventory_item_id  IN Mtl_system_items.inventory_item_id%type,
4492                            p_organization_id    IN Mtl_system_items.organization_id%type) RETURN Varchar2 Is
4493 
4494 l_found          varchar2(1) := 'N';
4495 l_model_item_id  Mtl_system_items.inventory_item_id%type;
4496 
4497 BEGIN
4498 
4499    /* Select the base model_item_id from the parent. Then compare the given inventory_item with the first
4500       level bill of parent model. If you get a match it is ato item. If we cannot get a match it is config item
4501    */
4502 
4503    SELECT base_item_id
4504    INTO   l_model_item_id
4505    FROM   MTL_SYSTEM_ITEMS
4506    WHERE  Inventory_item_id = p_parent_item_id
4507    AND    organization_id   = p_organization_id;
4508 
4509    BEGIN
4510       SELECT 'Y'
4511       INTO   l_found
4512       FROM   BOM_INVENTORY_COMPONENTS BIC,
4513              BOM_BILL_OF_MATERIALS BOM
4514       WHERE  BIC.bill_sequence_id  = BOM.Common_bill_sequence_id
4515       AND    BOM.assembly_item_id  = l_model_item_id
4516       AND    BOM.Organization_id   = p_organization_id
4517       AND    BIC.component_item_id = p_inventory_item_id;
4518       return l_found;
4519    EXCEPTION WHEN NO_DATA_FOUND THEN
4520       return 'N';
4521    END;
4522 END CHECK_CONFIG_ITEM;
4523 
4524 
4525 /*---------------------------------------------------------------------------------------------
4526 Procedure : chk_all_rsv_details --bugfix 2327972
4527 Description: This procedure gets the different types of reservation done on a line_id (item)
4528              When a reservation exists,It returns success and reservation qunatity, reservation id and type of              supply are stored in table of records.
4529 Input:  p_line_Id        in         --line_id
4530         p_rsv_details    out        --table of records
4531         x_msg_count      out
4532         x_msg_data       out
4533         x_return_status  out        -returns 'S' if reservation exists
4534                                     --returns 'F' if there is no reservation
4535 
4536 -------------------------------------------------------------------------------------------*/
4537 
4538 
4539 Procedure chk_all_rsv_details
4540 (
4541          p_line_Id          in     number    ,
4542          p_rsv_details   out NOCOPY t_resv_details,
4543          x_msg_count     out NOCOPY number  ,
4544          x_msg_data      out NOCOPY varchar2,
4545          x_return_status out NOCOPY varchar2
4546 )
4547 is
4548 
4549 
4550 
4551 
4552 l_reservation_id           Number;
4553 l_reservation_quantity     Number;
4554 l_supply_source_type_id    Number;
4555 
4556 
4557 l_index NUMBER;
4558 l_stmt  Number;
4559 
4560 
4561 CURSOR c_rsv_details IS
4562 select reservation_id,reservation_quantity,supply_source_type_id
4563     from   mtl_reservations     mr,
4564            oe_order_lines_all   oel,
4565            oe_order_headers_all oeh,
4566            oe_transaction_types_all ota,
4567            oe_transaction_types_tl  otl,
4568            mtl_sales_orders     mso
4569     where  mr.demand_source_line_id = oel.line_id    --ato item line id
4570     and    oel.line_id              = p_line_Id
4571     and    oeh.header_id            = oel.header_id
4572     and    oeh.order_type_id        = ota.transaction_type_id
4573     and    ota.transaction_type_code='ORDER'
4574     and    ota.transaction_type_id  = otl.transaction_type_id
4575     and    oeh.order_number         = mso.segment1
4576     and    otl.name                 = mso.segment2
4577     and    otl.language 	    = (select language_code
4578 					from fnd_languages
4579 					where installed_flag = 'B')
4580     and    mso.sales_order_id       = mr.demand_source_header_id
4581     --and    mr.demand_source_type_id = INV_RESERVATION_GLOBAL.g_source_type_oe
4582     and    mr.demand_source_type_id = decode(oeh.source_document_type_id, 10,
4583 						INV_RESERVATION_GLOBAL.g_source_type_internal_ord,
4584                                              	INV_RESERVATION_GLOBAL.g_source_type_oe)	--bugfix 1799874
4585     and    mr.reservation_quantity  > 0;
4586 
4587 
4588 
4589 BEGIN
4590 
4591   IF PG_DEBUG <> 0 THEN
4592   	oe_debug_pub.add('chk_all_rsv_details: ' || 'Entered CTO_UTILITY_PK.chk_all_rsv_details',1);
4593   END IF;
4594   x_return_status := FND_API.G_RET_STS_SUCCESS;
4595 
4596 
4597   l_stmt := 111;
4598   OPEN c_rsv_details;
4599    LOOP
4600 
4601        FETCH c_rsv_details into l_reservation_id,
4602                                 l_reservation_quantity,
4603                                 l_supply_source_type_id;
4604         	EXIT WHEN c_rsv_details%NOTFOUND;
4605 
4606        l_stmt := 211;
4607        IF ( p_rsv_details.count=0 ) THEN
4608             p_rsv_details(1).l_reservation_id        :=  l_reservation_id;
4609             p_rsv_details(1).l_reservation_quantity  :=  l_reservation_quantity;
4610             p_rsv_details(1).l_supply_source_type_id :=  l_supply_source_type_id;
4611        ELSE
4612            p_rsv_details( p_rsv_details.LAST+1).l_reservation_id       :=  l_reservation_id;
4613            p_rsv_details(p_rsv_details.LAST).l_reservation_quantity  :=  l_reservation_quantity;
4614            p_rsv_details(p_rsv_details.LAST).l_supply_source_type_id :=  l_supply_source_type_id;
4615        END IF;
4616 
4617    END LOOP;
4618    CLOSE c_rsv_details;
4619 
4620     l_stmt := 311;
4621     IF (p_rsv_details.count>0) THEN
4622        l_index := p_rsv_details.FIRST;
4623        LOOP
4624             IF PG_DEBUG <> 0 THEN
4625             	oe_debug_pub.add('chk_all_rsv_details: ' || 'rsv id '||p_rsv_details(l_index).l_reservation_id,5);
4626 
4627             	oe_debug_pub.add('chk_all_rsv_details: ' || 'rsv qty '||p_rsv_details(l_index).l_reservation_quantity,5);
4628 
4629             	oe_debug_pub.add('chk_all_rsv_details: ' || 'suppy sourc '||p_rsv_details(l_index).l_supply_source_type_id,5);
4630             END IF;
4631 
4632             	 EXIT WHEN l_index = p_rsv_details.LAST;
4633             l_index := p_rsv_details.NEXT(l_index);
4634         END LOOP;
4635         x_return_status := FND_API.G_RET_STS_SUCCESS;--resv exists
4636     ELSE
4637         --no reservation exists
4638         x_return_status := FND_API.G_FALSE;
4639 
4640     END IF;
4641 
4642 
4643 
4644 
4645 
4646 
4647 EXCEPTION
4648       when others then
4649               x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
4650               IF PG_DEBUG <> 0 THEN
4651               	oe_debug_pub.add ('chk_all_rsv_details: ' || 'unexpected error in called program chk_all_rsv_details'|| l_stmt||sqlerrm , 1);
4652               END IF;
4653               if fnd_msg_pub.check_msg_level
4654                   (fnd_msg_pub.g_msg_lvl_unexp_error)
4655               then
4656                   fnd_msg_pub.Add_Exc_msg
4657                    ( 'CTO_WORKFLOW',
4658                      'chk_all_rsv_details'
4659                     );
4660               end if;
4661               cto_msg_pub.count_and_get
4662                 (
4663                    p_msg_count=>x_msg_count,
4664                    p_msg_data=>x_msg_data
4665                  );
4666 END  chk_all_rsv_details;
4667 
4668 
4669 
4670 /*
4671 ** Note: This procedure itentifies whether a Model is Multi-Level.
4672 ** The bill_sequence_id passed as a parameter should have a valid bill.
4673 ** for eg. if the bom is commoned you should be sending the
4674 ** common_bill_sequence_id
4675 **
4676 */
4677 FUNCTION isModelMLMO( p_bill_sequence_id in number )
4678 return number
4679 is
4680 
4681   cursor option_class ( c_bill_sequence_id  in number )
4682   is
4683         select component_item_id
4684              , component_sequence_id
4685              , bom_item_type
4686           from bom_inventory_components
4687          where bill_sequence_id = c_bill_sequence_id
4688            and ( bom_item_type = '2' OR
4689                  ( bom_item_type = '1' and nvl( wip_supply_type , 6 ) <> 6 )
4690                  /* check only non phantom models and option classes */
4691                ) ;
4692 
4693 v_model_count number ;
4694 v_organization_id number ;
4695 v_assembly_item_id number ;
4696 v_return_status number ;
4697 v_component_item_id number ;
4698 v_component_sequence_id number ;
4699 v_element_bill_seq_id number ;
4700 
4701 v_bom_item_type     bom_inventory_components.bom_item_type%type;
4702 v_stmt_number number := -1 ;
4703 
4704 x_sourcing_rule_exists varchar2(2) ;
4705 x_new_org              number ;
4706 x_source_type          number ;
4707 x_transit_lead_time    number ;
4708 x_return_status        varchar2(10) ;
4709 x_exp_error_code       number ;
4710 
4711 begin
4712 
4713 
4714            /* check whether base model is multilevel */
4715 
4716 
4717 
4718 
4719 
4720            select organization_id
4721                 , assembly_item_id
4722              into v_organization_id
4723                 , v_assembly_item_id
4724              from bom_bill_of_materials
4725             where bill_sequence_id = p_bill_sequence_id ;
4726 
4727 
4728            v_stmt_number := -4 ;
4729 
4730 
4731 
4732              get_model_sourcing_org(
4733                               v_assembly_item_id
4734                             , v_organization_id
4735                             , x_sourcing_rule_exists
4736                             , x_new_org
4737                             , x_source_type
4738                             , x_transit_lead_time
4739                             , x_return_status
4740                             , x_exp_error_code
4741                             , null
4742                             , null
4743                            ) ;
4744 
4745              IF PG_DEBUG <> 0 THEN
4746              	oe_debug_pub.add('isModelMLMO: ' ||  ' after get model source status ' || x_return_status, 4 );
4747              END IF;
4748 
4749 
4750              IF x_return_status = FND_API.G_RET_STS_ERROR
4751              THEN
4752 
4753                    RAISE FND_API.G_EXC_ERROR;
4754              ELSIF x_return_status = FND_API.G_RET_STS_UNEXP_ERROR
4755              THEN
4756                    RAISE FND_API.G_EXC_UNEXPECTED_ERROR;
4757              END IF;
4758 
4759 
4760              if( FND_API.to_boolean( x_sourcing_rule_exists )  ) then
4761                  return 1;
4762              end if ;
4763 
4764 
4765              v_stmt_number := -6 ;
4766 
4767              open option_class( p_bill_sequence_id ) ;
4768 
4769              loop
4770 
4771                    fetch option_class into v_component_item_id
4772                                         , v_component_sequence_id , v_bom_item_type ;
4773 
4774                    exit when option_class%notfound ;
4775 
4776 
4777                    if( v_bom_item_type = 1 ) then
4778                        return 1 ;
4779                    end if ;
4780 
4781 
4782 
4783 
4784                    v_stmt_number := -8 ;
4785 
4786                    select common_bill_sequence_id
4787                     into v_element_bill_seq_id
4788                     from bom_bill_of_materials
4789                    where assembly_item_id = v_component_item_id
4790                      and organization_id = v_organization_id ;
4791 
4792 
4793                   v_stmt_number := -10 ;
4794 
4795                   v_return_status := isModelMLMO( v_element_bill_seq_id ) ;
4796 
4797 
4798                   if( v_return_status = 1 ) then
4799                       return 1 ;
4800                   end if ;
4801 
4802              end loop ;
4803 
4804 
4805 
4806 
4807     return 0 ;
4808 
4809 
4810 exception
4811 when others then
4812 
4813     return v_stmt_number ;
4814 
4815 end isModelMLMO;
4816 
4817 /*----------------------------------------------------------------------+
4818 This function recursively explodes a configuration item BOM and inserts
4819 it into bom_explosion_temp with a unique group_id. It is called while
4820 displaying the configuration BOM from iSupplierPortal.
4821 +----------------------------------------------------------------------*/
4822 
4823 FUNCTION create_isp_bom
4824 (
4825 p_item_id IN number,
4826 p_org_id IN number)
4827 RETURN NUMBER IS
4828 
4829 xGrpId	number;
4830 rowcount number;
4831 l_sort number := 0;
4832 
4833 BEGIN
4834 
4835         If PG_DEBUG <> 0 Then
4836 	cto_wip_workflow_api_pk.cto_debug('create_isp_bom', 'entering');
4837         End if;
4838 
4839     	select bom_explosion_temp_s.nextval
4840     	into   xGrpId
4841     	from dual;
4842 
4843         If PG_DEBUG <> 0 Then
4844 	cto_wip_workflow_api_pk.cto_debug('create_isp_bom', 'xGrpId::'||to_char(xGrpId));
4845 	cto_wip_workflow_api_pk.cto_debug('create_isp_bom', 'ItemId::'||to_char(p_item_id));
4846 	cto_wip_workflow_api_pk.cto_debug('create_isp_bom', 'OrgId::'||to_char(p_org_id));
4847         End if;
4848 
4849 	-- insert top level config BOM
4850 
4851     	insert into bom_explosion_temp(
4852         	top_bill_sequence_id,
4853         	bill_sequence_id,
4854         	organization_id,
4855         	sort_order,
4856         	component_item_id,
4857 		--component_sequence_id,
4858         	plan_level,
4859 		component_quantity,
4860 		component_code,
4861 		item_num,
4862         	group_id)
4863    	select
4864 		bic.bill_sequence_id,
4865 		bic.bill_sequence_id,
4866 		p_org_id,
4867 		to_char(l_sort),
4868         	bic.component_item_id,
4869 		--bic.component_sequence_id,
4870 		nvl(bic.plan_level, 0),
4871 		bic.component_quantity,
4872 		to_char(bic.bill_sequence_id),
4873 		bic.item_num,
4874         	xGrpId
4875    	from
4876 		bom_inventory_components bic,
4877 		bom_bill_of_materials bbom
4878         where 	bbom.assembly_item_id = p_item_id
4879 	and	bbom.organization_id = p_org_id
4880 	and 	bbom.alternate_bom_designator is null
4881 	and 	bbom.common_bill_sequence_id = bic.bill_sequence_id
4882 	and 	nvl(bic.optional_on_model,1) = 1;
4883 
4884         If PG_DEBUG <> 0 Then
4885 	cto_wip_workflow_api_pk.cto_debug('create_isp_bom', 'rowcount::'||sql%rowcount);
4886         End if;
4887 
4888 
4889         rowcount := 1 ;
4890         while rowcount > 0 LOOP
4891 
4892 	    l_sort := l_sort + 1;
4893 
4894             insert into bom_explosion_temp(
4895                	top_bill_sequence_id,
4896                	bill_sequence_id,
4897                	organization_id,
4898                	sort_order,
4899                	component_item_id,
4900 		--component_sequence_id,
4901                	plan_level,
4902                	component_quantity,
4903 		component_code,
4904 		item_num,
4905                	group_id)
4906            select
4907 		bic.bill_sequence_id,
4908 		bic.bill_sequence_id,
4909 		p_org_id,
4910 		to_char(l_sort),
4911         	bic.component_item_id,
4912 		--concat(concat(bet.component_sequence_id,'-'),bic.component_sequence_id),
4913 		decode(bic.plan_level,null,(bet.plan_level+1),(bic.plan_level+bet.plan_level)),
4914 		bic.component_quantity,
4915 		CTO_UTILITY_PK.Concat_Values(bet.component_code,bic.bill_sequence_id),
4916 		bic.item_num,
4917         	xGrpId
4918            from
4919                 bom_inventory_components bic,
4920 		bom_bill_of_materials bbom,
4921 		bom_explosion_temp bet,
4922 		mtl_system_items msi
4923            where 	bbom.assembly_item_id = bet.component_item_id
4924 	   and	bbom.organization_id = bet.organization_id
4925 	   and 	bbom.alternate_bom_designator is null
4926 	   and 	bbom.common_bill_sequence_id = bic.bill_sequence_id
4927 	   and 	nvl(bic.optional_on_model,1) = 1
4928 	   and 	bet.group_id = xGrpId
4929 	   and 	bet.sort_order = to_char(l_sort - 1)
4930 	   and 	bet.component_item_id = msi.inventory_item_id
4931 	   and	bet.organization_id = msi.organization_id
4932 	   and	msi.base_item_id is not null
4933 	   and 	nvl(msi.auto_created_config_flag, 'N') = 'Y';
4934 
4935 
4936            rowcount := SQL%ROWCOUNT;
4937 
4938            IF PG_DEBUG <> 0 THEN
4939            oe_debug_pub.add ('Row Count : '   || rowcount, 2);
4940            END IF;
4941 
4942            If PG_DEBUG <> 0 Then
4943            cto_wip_workflow_api_pk.cto_debug('create_isp_bom', 'Row Count:'||rowcount);
4944            End if;
4945 
4946         END LOOP;
4947 
4948 	delete from bom_explosion_temp bet
4949 	where bet.group_id = xGrpId
4950 	and bet.component_item_id =
4951 		(select msi.inventory_item_id
4952 		from mtl_system_items msi
4953 		where msi.inventory_item_id = bet.component_item_id
4954 		and msi.organization_id = bet.organization_id
4955 		and msi.base_item_id is not null
4956 	   	and nvl(msi.auto_created_config_flag, 'N') = 'Y');
4957 
4958 	rowcount := SQL%ROWCOUNT;
4959         IF PG_DEBUG <> 0 THEN
4960 	oe_debug_pub.add ('Deleted Row Count : '   || rowcount, 2);
4961         END IF;
4962 
4963         If PG_DEBUG <> 0 Then
4964         cto_wip_workflow_api_pk.cto_debug('create_isp_bom', 'Deleted Row Count:'||rowcount);
4965         End if;
4966 
4967 	return xGrpId;
4968 
4969 EXCEPTION
4970 WHEN OTHERS THEN
4971         If PG_DEBUG <> 0 Then
4972    	cto_wip_workflow_api_pk.cto_debug('create_isp_bom', 'Others exception:'||sqlerrm);
4973         End if;
4974 	return xGrpId;
4975 END;
4976 
4977 FUNCTION concat_values(
4978 p_value1 IN varchar2,
4979 p_value2 IN number)
4980 RETURN Varchar2 IS
4981 
4982 p_concat_value Varchar2(2000);
4983 BEGIN
4984 
4985 p_concat_value := concat(p_value1, '-');
4986 p_concat_value := concat(p_concat_value, to_char(p_value2));
4987 IF PG_DEBUG <> 0 Then
4988 cto_wip_workflow_api_pk.cto_debug('create_isp_bom', 'Concat segment:'||p_concat_value);
4989 End if;
4990 
4991 RETURN p_concat_value;
4992 
4993 END;
4994 
4995 procedure copy_cost(
4996                              p_src_cost_type_id   number
4997                            , p_dest_cost_type_id   number
4998                            , p_config_item_id number
4999                            , p_organization_id   number
5000 )
5001 is
5002 lStmtNumber		number;
5003 begin
5004 
5005         lStmtNumber := 2;
5006 
5007 
5008         delete from cst_item_cost_details
5009         where inventory_item_id = p_config_item_id
5010           and organization_id = p_organization_id
5011           and cost_type_id = p_dest_cost_type_id ;
5012 
5013         lStmtNumber := 20 ;
5014 
5015 
5016         delete from cst_item_costs
5017         where inventory_item_id = p_config_item_id
5018           and organization_id = p_organization_id
5019           and cost_type_id = p_dest_cost_type_id ;
5020 
5021 
5022 
5023 
5024         /*-------------------------------------------------------+
5025         Insert a row into the cst_item_costs_table
5026         +------------------------------------------------------- */
5027 
5028         lStmtNumber := 220;
5029 
5030         insert into CST_ITEM_COSTS
5031                 (inventory_item_id,
5032                 organization_id,
5033                 cost_type_id,
5034                 last_update_date,
5035                 last_updated_by,
5036                 creation_date,
5037                 created_by,
5038                 last_update_login,
5039                 inventory_asset_flag,
5040                 lot_size,
5041                 based_on_rollup_flag,
5042                 shrinkage_rate,
5043                 defaulted_flag,
5044                 cost_update_id,
5045                 pl_material,
5046                 pl_material_overhead,
5047                 pl_resource,
5048                 pl_outside_processing,
5049                 pl_overhead,
5050                 tl_material,
5051                 tl_material_overhead,
5052                 tl_resource,
5053                 tl_outside_processing,
5054                 tl_overhead,
5055                 material_cost,
5056                 material_overhead_cost,
5057                 resource_cost,
5058                 outside_processing_cost ,
5059                 overhead_cost,
5060                 pl_item_cost,
5061                 tl_item_cost,
5062                 item_cost,
5063                 unburdened_cost ,
5064                 burden_cost,
5065                 attribute_category,
5066                 attribute1,
5067                 attribute2,
5068                 attribute3,
5069                 attribute4,
5070                 attribute5,
5071                 attribute6,
5072                 attribute7,
5073                 attribute8,
5074                 attribute9,
5075                 attribute10,
5076                 attribute11,
5077                 attribute12,
5078                 attribute13,
5079                 attribute14,
5080                 attribute15
5081                 )
5082         select distinct
5083                 p_config_item_id,                -- INVENTORY_ITEM_ID
5084                 p_organization_id,
5085                 p_dest_cost_type_id,
5086                 sysdate,                  -- last_update_date
5087                 -1,                       -- last_updated_by
5088                 sysdate,                  -- creation_date
5089                 -1,                       -- created_by
5090                 -1,                       -- last_update_login
5091                 C.inventory_asset_flag,
5092                 C.lot_size,
5093                 C.based_on_rollup_flag,
5094                 C.shrinkage_rate,
5095                 C.defaulted_flag,
5096                 p_src_cost_type_id,                     -- cost_update_id
5097                 C.pl_material,
5098                 C.pl_material_overhead,
5099                 C.pl_resource,
5100                 C.pl_outside_processing,
5101                 C.pl_overhead,
5102                 C.tl_material,
5103                 C.tl_material_overhead,
5104                 C.tl_resource,
5105                 C.tl_outside_processing,
5106                 C.tl_overhead,
5107                 C.material_cost,
5108                 C.material_overhead_cost,
5109                 C.resource_cost,
5110                 C.outside_processing_cost ,
5111                 C.overhead_cost,
5112                 C.pl_item_cost,
5113                 C.tl_item_cost,
5114                 C.item_cost,
5115                 C.unburdened_cost ,
5116                 C.burden_cost,
5117                 C.attribute_category,
5118                 C.attribute1,
5119                 C.attribute2,
5120                 C.attribute3,
5121                 C.attribute4,
5122                 C.attribute5,
5123                 C.attribute6,
5124                 C.attribute7,
5125                 C.attribute8,
5126                 C.attribute9,
5127                 C.attribute10,
5128                 C.attribute11,
5129                 C.ATTRIBUTE12,
5130                 C.attribute13,
5131                 C.attribute14,
5132                 C.attribute15
5133         from
5134                 cst_item_costs C
5135         where  C.inventory_item_id = p_config_item_id
5136         and    C.organization_id   = p_organization_id
5137         and    C.cost_type_id  = p_src_cost_type_id;
5138 
5139         IF PG_DEBUG <> 0 THEN
5140         	oe_debug_pub.add('copy_cost: ' || 'after insert:CST_ITEM_COSTS',2);
5141 
5142         	oe_debug_pub.add('copy_cost: ' || 'after insert:CST_ITEM_COSTS' || sql%rowcount ,2);
5143         END IF;
5144 
5145         /*------ ----------------------------------------------+
5146          Insert rows into the cst_item_cost_details table
5147         +-----------------------------------------------------*/
5148 
5149         lStmtNumber := 230;
5150 
5151         insert into cst_item_cost_details
5152                 (inventory_item_id,
5153                 cost_type_id,
5154                 last_update_date,
5155                 last_updated_by,
5156                 creation_date,
5157                 created_by,
5158                 last_update_login,
5159                 organization_id,
5160                 operation_sequence_id,
5161                 operation_seq_num,
5162                 department_id,
5163                 level_type,
5164                 activity_id,
5165                 resource_seq_num,
5166                 resource_id,
5167                 resource_rate,
5168                 item_units,
5169                 activity_units,
5170                 usage_rate_or_amount,
5171                 basis_type,
5172                 basis_resource_id,
5173                 basis_factor,
5174                 net_yield_or_shrinkage_factor,
5175                 item_cost,
5176                 cost_element_id,
5177                 rollup_source_type,
5178                 activity_context,
5179                 attribute_category,
5180                 attribute1,
5181                 attribute2,
5182                 attribute3,
5183                 attribute4,
5184                 attribute5,
5185                 attribute6,
5186                 attribute7,
5187                 attribute8,
5188                 attribute9,
5189                 attribute10,
5190                 attribute11,
5191                 attribute12,
5192                 attribute13,
5193                 attribute14,
5194                 attribute15
5195                 )
5196         select distinct
5197                 p_config_item_id,                   -- inventory_item_id
5198                 p_dest_cost_type_id,
5199                 sysdate,                     -- last_update_date
5200                 -1,                          -- last_updated_by
5201                 sysdate,                     -- creation_date
5202                 -1,                          -- created_by
5203                 -1,                          -- last_update_login
5204                 p_organization_id,
5205                 c.operation_sequence_id,
5206                 c.operation_seq_num,
5207                 c.department_id,
5208                 c.level_type,
5209                 c.activity_id,
5210                 c.resource_seq_num,
5211                 c.resource_id,
5212                 c.resource_rate,
5213                 c.item_units,
5214                 c.activity_units,
5215                 c.usage_rate_or_amount,
5216                 c.basis_type,
5217                 c.basis_resource_id,
5218                 c.basis_factor,
5219                 c.net_yield_or_shrinkage_factor,
5220                 c.item_cost,
5221                 c.cost_element_id,
5222                 C.rollup_source_type,
5223                 C.activity_context,
5224                 C.attribute_category,
5225                 C.attribute1,
5226                 C.attribute2,
5227                 C.attribute3,
5228                 C.attribute4,
5229                 C.attribute5,
5230                 C.attribute6,
5231                 C.attribute7,
5232                 C.attribute8,
5233                 C.attribute9,
5234                 C.attribute10,
5235                 C.attribute11,
5236                 C.attribute12,
5237                 C.attribute13,
5238                 C.attribute14,
5239                 C.attribute15
5240         from
5241                 cst_item_cost_details C
5242         where  C.inventory_item_id = p_config_item_id
5243         and    C.organization_id   = p_organization_id
5244         and    C.cost_type_id  = p_src_cost_type_id ;
5245 
5246         IF PG_DEBUG <> 0 THEN
5247         	oe_debug_pub.add('copy_cost: ' || 'after insert:cst_item_cost_details',2);
5248 
5249         	oe_debug_pub.add('copy_cost: ' || 'after insert:cst_item_cost_details' || sql%rowcount ,2);
5250         END IF;
5251 
5252 
5253   exception
5254     when NO_DATA_FOUND THEN
5255 /*
5256       xErrorMessage := 'CTOCSTRB:' || to_char(lStmtNum) || ':' ||
5257                         substrb(sqlerrm,1,150);
5258         xMessageName  := 'CTO_CALC_COST_ROLLUP_ERROR';
5259 */
5260 
5261         IF PG_DEBUG <> 0 THEN
5262         	oe_debug_pub.add('copy_cost: ' || 'copy_ctocost_to_frozen no data found ',2);
5263         END IF;
5264 
5265     when OTHERS THEN
5266 /*
5267       xErrorMessage := 'CTOCSTRB:' || to_char(lStmtNum) || ':' ||
5268                         substrb(sqlerrm,1,150);
5269       --xMessageName  := 'BOM_ATO_PROCESS_ERROR';
5270         xMessageName  := 'CTO_CALC_COST_ROLLUP_ERROR';
5271 */
5272 
5273         IF PG_DEBUG <> 0 THEN
5274         	oe_debug_pub.add('copy_cost: ' || 'copy_ctocost_to_frozen others ',2);
5275         END IF;
5276 
5277 
5278 
5279 
5280 
5281 end copy_cost;
5282 
5283 
5284 --This procedure checks if pllanning needs to create supply
5285 --or CTO can create supply
5286 --x_can_create_supply = Y : CTO
5287 --  = N : Planning
5288 --Calls
5289 --1. custom API Check_supply
5290 --2. query sourcing org
5291 --Added by kkonada for DMF-J
5292 PROCEDURE check_cto_can_create_supply (
5293 	P_config_item_id	IN   number,
5294 	P_org_id		IN   number,
5295 	x_can_create_supply     OUT  NOCOPY Varchar2,
5296 	--p_source_type           OUT  NOCOPY Varchar2,
5297         p_source_type           OUT  NOCOPY number,  --Bugfix 6470516
5298 	x_return_status         OUT  NOCOPY varchar2,
5299 	X_msg_count		OUT  NOCOPY    number,
5300 	X_msg_data		OUT  NOCOPY   Varchar2,
5301 	x_sourcing_org          OUT  NOCOPY NUMBER,  --opm
5302 	x_message               OUT  NOCOPY varchar2 --opm
5303  )
5304  IS
5305 
5306  P_custom_in_params_rec   CTO_CUSTOM_SUPPLY_CHECK_PK.in_params_rec_type;
5307  x_custom_out_params_rec  CTO_CUSTOM_SUPPLY_CHECK_PK.out_params_rec_type;
5308 
5309  lStmtNum number;
5310 
5311  l_sourcing_rule_exists VARCHAR2(1);
5312  l_source_type          NUMBER;
5313  l_transit_lead_time    NUMBER;
5314  l_exp_error_code       NUMBER;
5315 
5316 
5317  BEGIN
5318       x_return_status := FND_API.G_RET_STS_SUCCESS;
5319       x_can_create_supply := 'Y';
5320 
5321       IF PG_DEBUG <> 0 THEN
5322          oe_debug_pub.add('check_cto_can_create_supply : ' ||'ENTERED',1);
5323       END IF;
5324 
5325       --call custom API
5326       lStmtNum := 10;
5327       P_custom_in_params_rec.CONFIG_ITEM_ID := P_config_item_id;
5328       P_custom_in_params_rec.Org_id         := P_org_id		;
5329 
5330       IF PG_DEBUG <> 0 THEN
5331          oe_debug_pub.add('check_cto_can_create_supply : ' ||'P_config_item_id'
5332 				||P_config_item_id,1);
5333 	  oe_debug_pub.add('check_cto_can_create_supply : ' ||'P_org_id'
5334 	                         ||P_org_id,1);
5335       END IF;
5336 
5337 
5338       lStmtNum :=20;
5339       CTO_CUSTOM_SUPPLY_CHECK_PK.Check_Supply
5340                                (
5341 			         P_in_params_rec  =>P_custom_in_params_rec,
5342 				 X_out_params_rec =>x_custom_out_params_rec ,
5343 				 X_return_status  =>  x_return_status,
5344 			         X_msg_count      => X_msg_count,
5345 			         X_msg_data       => X_msg_data
5346 
5347                                 );
5348 
5349   lStmtNum:=30;
5350   IF X_return_status = FND_API.G_RET_STS_SUCCESS
5351      and
5352      X_custom_out_params_rec.can_cto_create_supply = 'Y'  THEN
5353 
5354 
5355       IF PG_DEBUG <> 0 THEN
5356          oe_debug_pub.add('check_cto_can_create_supply : '
5357 				||'success from custom API',5);
5358       END IF;
5359 
5360 
5361 
5362 
5363       --call query sourcing org
5364         lStmtNum:=40;
5365         CTO_UTILITY_PK.query_sourcing_org(
5366                           p_inventory_item_id		=> P_config_item_id,
5367                           p_organization_id		=> P_org_id,
5368                           p_sourcing_rule_exists	=> l_sourcing_rule_exists,
5369                           p_sourcing_org		=> x_sourcing_org,
5370                           p_source_type			=> p_source_type ,
5371                           p_transit_lead_time		=> l_transit_lead_time,
5372                           x_return_status		=> x_return_status,
5373                           x_exp_error_code		=> l_exp_error_code );
5374 
5375       lStmtNum:=50;
5376       IF x_return_status = FND_API.G_RET_STS_SUCCESS THEN
5377             IF PG_DEBUG <> 0 THEN
5378 		oe_debug_pub.add('check_cto_can_create_supply : '
5379 				||'success from query sourcing org',5);
5380 	    END IF;
5381 
5382 	    -- 100% trasfer rule = 1 and multiple sources = 66
5383 	    -- rkaza. ireq project. 05/02/2005.
5384             -- Previosly CTO cannot create supply for source type 1 and 66.
5385             -- Now CTO can create supply for 1. So removed it in if condition.
5386             IF p_source_type = 66 THEN
5387 
5388 		IF PG_DEBUG <> 0 THEN
5389 		oe_debug_pub.add('check_cto_can_create_supply : '
5390 				   ||'P_source_type'||p_source_type,5);
5391 		 END IF;
5392 	        x_can_create_supply := 'N';
5393 		x_message := 'MULTIPLE SOURCES PRESENT';
5394 	    END IF;
5395 
5396            --OPM
5397 	   --If x_can_create_supply=Y. Avoid make and process org combination
5398 
5399 	   IF x_can_create_supply = 'Y' and p_source_type =2 THEN
5400 
5401 	       IF INV_GMI_RSV_BRANCH.Process_Branch
5402 	              (p_organization_id =>P_org_id) THEN
5403 
5404                    IF PG_DEBUG <> 0 THEN
5405 		     oe_debug_pub.add('check_cto_can_create_supply : '
5406 				   ||'MAKE in a process org not allowed',1);
5407 		   END IF;
5408 
5409 		   x_can_create_supply := 'N';
5410 		   x_message := 'MAKE in PROCESS Org INVALID combination';
5411 
5412 	       END IF;--check process org
5413 	   END IF; --can_create = y and source_type =2
5414 
5415 
5416 
5417      ELSIF x_return_status = FND_API.G_RET_STS_UNEXP_ERROR THEN
5418          IF PG_DEBUG <> 0 THEN
5419          	oe_debug_pub.add('check_cto_can_create_supply : ' || 'Unexpected Error in the sourcing rule.',1);
5420          END IF;
5421          raise FND_API.G_EXC_UNEXPECTED_ERROR;
5422 
5423      END IF;
5424 
5425   ELSIF X_return_status = FND_API.G_RET_STS_SUCCESS --cutsom API's out param
5426         and X_custom_out_params_rec.can_cto_create_supply = 'N' THEN
5427 
5428 	  IF PG_DEBUG <> 0 THEN
5429 		oe_debug_pub.add('check_cto_can_create_supply : '
5430 			||'from custom api:can_create_supply is N',5);
5431           END IF;
5432 
5433            x_can_create_supply := 'N';
5434 	   x_message := 'Custom api for SUPPLY returned N';
5435 
5436   ELSIF X_return_status = FND_API.G_RET_STS_ERROR  THEN
5437          RAISE FND_API.G_EXC_ERROR;
5438 
5439   ELSE
5440          RAISE FND_API.G_EXC_UNEXPECTED_ERROR;
5441 
5442   END IF;
5443 
5444 EXCEPTION
5445 
5446  WHEN fnd_api.g_exc_error THEN
5447         IF PG_DEBUG <> 0 THEN
5448         	oe_debug_pub.add('check_cto_can_create_supply: ' || 'Exception in stmt num: '
5449 		                    || to_char(lStmtNum), 1);
5450         END IF;
5451         x_return_status := FND_API.G_RET_STS_ERROR;
5452         --  Get message count and data
5453         cto_msg_pub.count_and_get
5454           (  p_msg_count => x_msg_count
5455            , p_msg_data  => x_msg_data
5456            );
5457    WHEN fnd_api.g_exc_unexpected_error THEN
5458         IF PG_DEBUG <> 0 THEN
5459         	oe_debug_pub.add('check_cto_can_create_supply: ' || ' Unexpected Exception in stmt num: '
5460 		                       || to_char(lStmtNum), 1);
5461         END IF;
5462         x_return_status := FND_API.G_RET_STS_UNEXP_ERROR ;
5463         --  Get message count and data
5464          cto_msg_pub.count_and_get
5465           (  p_msg_count => x_msg_count
5466            , p_msg_data  => x_msg_data
5467            );
5468    WHEN OTHERS then
5469         IF PG_DEBUG <> 0 THEN
5470 
5471         	oe_debug_pub.add('check_cto_can_create_supply: ' || 'Others Exception in stmt num: '
5472 		                    || to_char(lStmtNum), 1);
5473 		oe_debug_pub.add('check_cto_can_create_supply: ' || 'errormsg='||sqlerrm, 1);
5474         END IF;
5475         x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
5476         --  Get message count and data
5477          cto_msg_pub.count_and_get
5478           (  p_msg_count => x_msg_count
5479            , p_msg_data  => x_msg_data
5480            );
5481 
5482 
5483 
5484 
5485  END check_cto_can_create_supply;
5486 
5487 
5488 
5489 procedure split_line (
5490 p_ato_line_id   in number ,
5491 x_return_status out nocopy varchar2,
5492 x_msg_count     out nocopy number,
5493 x_msg_data      out nocopy varchar2
5494 )
5495 is
5496 
5497 cursor config_update( c_organization_id in number)
5498 is
5499    select line_id, split_from_line_id
5500    from oe_order_lines_all  oeol , mtl_system_items msi
5501    where oeol.line_id = p_ato_line_id
5502      and oeol.inventory_item_id = msi.inventory_item_id
5503      and msi.organization_id = c_organization_id
5504      and msi.bom_item_type = 1 ;
5505 
5506 v_organization_id   number ;
5507 v_config     config_update%rowtype ;
5508 
5509 lstmtnum number:= 0 ;
5510 begin
5511 
5512 
5513 
5514      oe_debug_pub.add('CTOUTILB.split_line: entered split_line ' , 1);
5515 
5516 
5517 
5518 
5519        /*
5520          BUG:3484511
5521          -----------
5522         select master_organization_id
5523         into   v_organization_id
5524         from   oe_order_lines_all oel,
5525            oe_system_parameters_all ospa
5526         where  oel.line_id = p_ato_line_id
5527         and    nvl(oel.org_id, -1) = nvl(ospa.org_id, -1) ;  --bug 1531691
5528        */
5529 
5530 
5531 
5532            IF PG_DEBUG <> 0 THEN
5533                 oe_debug_pub.add('CTOUTILB.split_line: ' ||  'Going to fetch Validation Org ' ,2);
5534            END IF;
5535 
5536 
5537            select nvl( oe_sys_parameters.value( 'MASTER_ORGANIZATION_ID' , oel.org_id) , -99)
5538               into v_organization_id from oe_order_lines_all oel
5539            where oel.line_id = p_ato_line_id;
5540 
5541 
5542 
5543 
5544      lstmtnum := 10 ;
5545 
5546 
5547      CTO_UTILITY_PK.Populate_Bcol(
5548                p_bcol_line_id     => p_ato_line_id,
5549                x_return_status    => x_return_status ,
5550                x_msg_count        => x_msg_count,
5551                x_msg_data         => x_msg_data,
5552                p_reschedule       => 'N' ) ;
5553 
5554                /* reschedule should be always No for Split Line
5555                */
5556 
5557 
5558      oe_debug_pub.add('CTOUTILB.split_line: opening config_update cursor ' , 1);
5559 
5560 
5561 
5562      lstmtnum := 20 ;
5563 
5564 
5565      open config_update( v_organization_id ) ;
5566 
5567      loop
5568 
5569           fetch config_update into v_config ;
5570 
5571 
5572           exit when config_update%notfound ;
5573 
5574 
5575           oe_debug_pub.add('CTOUTILB.split_line: line ' || v_config.line_id , 1);
5576           oe_debug_pub.add('CTOUTILB.split_line: split line ' ||
5577                             v_config.split_from_line_id , 1);
5578 
5579 
5580           update bom_cto_order_lines set config_item_id = ( select bcol1.config_item_id
5581                              from bom_cto_order_lines bcol1
5582                              where bcol1.line_id = v_config.split_from_line_id )
5583            where line_id = v_config.line_id ;
5584 
5585           oe_debug_pub.add('CTOUTILB.split_line: update cnt ' || SQL%ROWCOUNT , 1);
5586 
5587 
5588      end loop ;
5589 
5590 
5591 
5592 exception
5593  when others then
5594        IF PG_DEBUG <> 0 THEN
5595 
5596           oe_debug_pub.add('CTO_UTILITY_PK.split_line: ' || 'Others Exception in stmt num : '
5597                             || to_char(lStmtNum), 1);
5598           oe_debug_pub.add('CTO_UTILITY_PK.split_line: ' || 'errormsg='||sqlerrm, 1);
5599 
5600        END IF;
5601        x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
5602 
5603 
5604 end split_line ;
5605 
5606 
5607 procedure adjust_bcol_for_split(
5608 p_ato_line_id   in number ,
5609 x_return_status out nocopy varchar2,
5610 x_msg_count     out nocopy number,
5611 x_msg_data      out nocopy varchar2
5612 )
5613 is
5614 begin
5615 
5616      oe_debug_pub.add('CTO_UTILITY_PK.adjust_bcol_for_split: entered ' || p_ato_line_id , 1);
5617 
5618      update bom_cto_order_lines bcol
5619         set ordered_quantity = ( select ordered_quantity
5620                   from oe_order_lines_all
5621                   where ato_line_id = bcol.ato_line_id
5622                     and line_id = bcol.line_id )
5623       where ato_line_id = p_ato_line_id ;
5624 
5625      oe_debug_pub.add('CTO_UTILITY_PK.adjust_bcol_for_split: upd cnt ' || SQL%ROWCOUNT , 1);
5626 
5627 end adjust_bcol_for_split ;
5628 
5629 
5630 procedure adjust_bcol_for_warehouse(
5631 p_ato_line_id   in number ,
5632 x_return_status out nocopy varchar2,
5633 x_msg_count     out nocopy number,
5634 x_msg_data      out nocopy varchar2
5635 )
5636 is
5637 begin
5638 
5639      oe_debug_pub.add('CTO_UTILITY_PK.adjust_bcol_for_warehouse: entered ' || p_ato_line_id , 1);
5640 
5641      update bom_cto_order_lines bcol
5642         set ship_from_org_id = ( select ship_from_org_id
5643                   from oe_order_lines_all
5644                   where ato_line_id = bcol.ato_line_id
5645                     and line_id = bcol.line_id )
5646       where ato_line_id = p_ato_line_id ;
5647 
5648      oe_debug_pub.add('CTO_UTILITY_PK.adjust_bcol_for_warehouse: upd cnt ' || SQL%ROWCOUNT , 1);
5649 
5650 
5651 
5652 end adjust_bcol_for_warehouse;
5653 
5654 
5655   PROCEDURE  Reservation_Exists(
5656                                Pconfiglineid	in	number,
5657                                x_return_status	out nocopy varchar2,
5658                                x_result		out nocopy boolean,
5659                                X_Msg_Count	out nocopy number,
5660                                X_Msg_Data	out nocopy varchar2) as
5661 
5662     l_reservation_id mtl_reservations.reservation_id%type;
5663 
5664   BEGIN
5665 
5666    IF PG_DEBUG <> 0 THEN
5667    	oe_debug_pub.add('Reservation_Exists: ' || 'Entering into Reservation_exists procedure....',1);
5668    END IF;
5669    -- Check if flow schedule exists . If not check some inv/work order Reservation
5670    -- exists. If both of them does'nt exists then return false. Other wise return true.
5671 
5672    IF CTO_WORKFLOW.flow_sch_exists(pconfigLineId) <> TRUE  THEN
5673 
5674       IF PG_DEBUG <> 0 THEN
5675       	oe_debug_pub.add('Reservation_Exists: ' || 'flow Reservation not exists..',5);
5676 
5677       	oe_debug_pub.add('Reservation_Exists: ' || 'The line_id passed for reservation = '||to_char(pconfiglineid),5);
5678       END IF;
5679 
5680       SELECT   reservation_id
5681       INTO     l_reservation_id
5682       FROM
5683             mtl_reservations mr,
5684             oe_order_lines_all oel,
5685             oe_order_headers_all oeh,
5686             oe_transaction_types_all ota,
5687             oe_transaction_types_tl otl,
5688             mtl_sales_orders mso
5689       WHERE
5690                mr.demand_source_line_id = oel.line_id
5691       and      oel.line_id              = pconfigLineId    --- Configuration item line id
5692       and      oeh.header_id            = oel.header_id
5693       and      oeh.order_type_id        = ota.transaction_type_id
5694       and      ota.transaction_type_code=  'ORDER'
5695       and      ota.transaction_type_id   = otl.transaction_type_id
5696       and      oeh.order_number         = mso.segment1
5697       and      otl.name                 = mso.segment2
5698       and      otl.language             = (select language_code
5699                                            from  fnd_languages
5700                                            where installed_flag  ='B')
5701       and      mso.sales_order_id       = mr.demand_source_header_id
5702       --and      mr.demand_source_type_id = INV_RESERVATION_GLOBAL.g_source_type_oe
5703       and      mr.demand_source_type_id = decode(oeh.source_document_type_id, 10, INV_RESERVATION_GLOBAL.g_source_type_internal_ord,
5704                                              INV_RESERVATION_GLOBAL.g_source_type_oe)	--bugfix 1799874
5705       and      mr.reservation_quantity  > 0
5706       and      rownum                   = 1;
5707       IF PG_DEBUG <> 0 THEN
5708       	oe_debug_pub.add('Reservation_Exists: ' || 'Work order/Inv reservation Exists..',5);
5709       END IF;
5710     END IF;
5711 
5712     x_result := TRUE;
5713     x_return_status := FND_API.G_RET_STS_SUCCESS;
5714 
5715  EXCEPTION
5716            WHEN no_data_found THEN
5717            	IF PG_DEBUG <> 0 THEN
5718            		oe_debug_pub.add('Reservation_Exists: ' || 'Coming out of reservation_exists procedure with FALSE...',2);
5719            	END IF;
5720            	x_return_status := FND_API.G_RET_STS_SUCCESS;
5721 	   	x_result :=  FALSE;
5722 
5723            WHEN others THEN
5724            	IF PG_DEBUG <> 0 THEN
5725            		oe_debug_pub.add('Reservation_Exists: ' || 'OTHERS excpn occured in Reservation_Exists procedure..',2);
5726 
5727            		oe_debug_pub.add('Reservation_Exists: ' || 'Error message is : '||sqlerrm,1);
5728            	END IF;
5729            	x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
5730            	x_result := FALSE;
5731 
5732  END Reservation_Exists;
5733 
5734 
5735 
5736 
5737 procedure copy_bcolgt_bcol(     p_ato_line_id   in      number,
5738                                 x_return_status out     NOCOPY varchar2,
5739                                 x_msg_count     out     NOCOPY number,
5740                                 x_msg_data      out     NOCOPY varchar2)
5741 
5742 is
5743 lStmtNumber             number;
5744 begin
5745 
5746 oe_debug_pub.add( ' entered copy bcol_gt  to bcol' , 1) ;
5747 
5748                     insert into bom_cto_order_lines (
5749                            LINE_ID
5750                           ,HEADER_ID
5751                           ,TOP_MODEL_LINE_ID
5752                           ,LINK_TO_LINE_ID
5753                           ,ATO_LINE_ID
5754                           ,PARENT_ATO_LINE_ID
5755                           ,INVENTORY_ITEM_ID
5756                           ,SHIP_FROM_ORG_ID
5757                           ,COMPONENT_SEQUENCE_ID
5758                           ,COMPONENT_CODE
5759                           ,ITEM_TYPE_CODE
5760                           ,SCHEDULE_SHIP_DATE
5761                           ,PLAN_LEVEL
5762                           ,PERFORM_MATCH
5763                           ,CONFIG_ITEM_ID
5764                           ,BOM_ITEM_TYPE
5765                           ,WIP_SUPPLY_TYPE
5766                           ,ORDERED_QUANTITY
5767                           ,ORDER_QUANTITY_UOM
5768                           ,BATCH_ID
5769                           ,CREATION_DATE
5770                           ,CREATED_BY
5771                           ,LAST_UPDATE_DATE
5772                           ,LAST_UPDATED_BY
5773                           ,LAST_UPDATE_LOGIN
5774                           ,PROGRAM_APPLICATION_ID
5775                           ,PROGRAM_ID
5776                           ,PROGRAM_UPDATE_DATE
5777                           ,REUSE_CONFIG
5778                           ,OPTION_SPECIFIC
5779                           ,QTY_PER_PARENT_MODEL
5780                           ,CONFIG_CREATION)
5781                     select /*+ INDEX (BOM_CTO_ORDER_LINES_GT BOM_CTO_ORDER_LINES_GT_N1) */
5782                            LINE_ID
5783                           ,HEADER_ID
5784                           ,TOP_MODEL_LINE_ID
5785                           ,LINK_TO_LINE_ID
5786                           ,ATO_LINE_ID
5787                           ,PARENT_ATO_LINE_ID
5788                           ,INVENTORY_ITEM_ID
5789                           ,SHIP_FROM_ORG_ID
5790                           ,COMPONENT_SEQUENCE_ID
5791                           ,COMPONENT_CODE
5792                           ,ITEM_TYPE_CODE
5793                           ,SCHEDULE_SHIP_DATE
5794                           ,PLAN_LEVEL
5795                           ,PERFORM_MATCH
5796                           ,CONFIG_ITEM_ID
5797                           ,BOM_ITEM_TYPE
5798                           ,WIP_SUPPLY_TYPE
5799                           ,ORDERED_QUANTITY
5800                           ,ORDER_QUANTITY_UOM
5801                           ,BATCH_ID
5802                           ,CREATION_DATE
5803                           ,CREATED_BY
5804                           ,LAST_UPDATE_DATE
5805                           ,LAST_UPDATED_BY
5806                           ,LAST_UPDATE_LOGIN
5807                           ,PROGRAM_APPLICATION_ID
5808                           ,PROGRAM_ID
5809                           ,PROGRAM_UPDATE_DATE
5810                           ,REUSE_CONFIG
5811                           ,OPTION_SPECIFIC
5812                           ,QTY_PER_PARENT_MODEL
5813                           ,CONFIG_CREATION
5814                       from bom_cto_order_lines_gt
5815                      where ato_line_id = p_ato_line_id ;
5816 
5817 oe_debug_pub.add( ' copied bcol_gt to bcol ' || SQL%ROWCOUNT , 1) ;
5818 
5819 
5820 
5821 
5822 end copy_bcolgt_bcol ;
5823 
5824 
5825 
5826 procedure copy_bcol_bcolgt(      p_ato_line_id   in      number,
5827                                 x_return_status out     NOCOPY varchar2,
5828                                 x_msg_count     out     NOCOPY number,
5829                                 x_msg_data      out     NOCOPY varchar2)
5830 
5831 is
5832 lStmtNumber             number;
5833 begin
5834 
5835 oe_debug_pub.add( ' entered copy bcol to bcol_gt ' , 1) ;
5836                     --bugfix#3756670
5837                     delete from bom_cto_order_lines_gt
5838 		    where ato_line_id = p_ato_line_id ;
5839 
5840                     insert into bom_cto_order_lines_gt (
5841                            LINE_ID
5842                           ,HEADER_ID
5843                           ,TOP_MODEL_LINE_ID
5844                           ,LINK_TO_LINE_ID
5845                           ,ATO_LINE_ID
5846                           ,PARENT_ATO_LINE_ID
5847                           ,INVENTORY_ITEM_ID
5848                           ,SHIP_FROM_ORG_ID
5849                           ,COMPONENT_SEQUENCE_ID
5850                           ,COMPONENT_CODE
5851                           ,ITEM_TYPE_CODE
5852                           ,SCHEDULE_SHIP_DATE
5853                           ,PLAN_LEVEL
5854                           ,PERFORM_MATCH
5855                           ,CONFIG_ITEM_ID
5856                           ,BOM_ITEM_TYPE
5857                           ,WIP_SUPPLY_TYPE
5858                           ,ORDERED_QUANTITY
5859                           ,ORDER_QUANTITY_UOM
5860                           ,BATCH_ID
5861                           ,CREATION_DATE
5862                           ,CREATED_BY
5863                           ,LAST_UPDATE_DATE
5864                           ,LAST_UPDATED_BY
5865                           ,LAST_UPDATE_LOGIN
5866                           ,PROGRAM_APPLICATION_ID
5867                           ,PROGRAM_ID
5868                           ,PROGRAM_UPDATE_DATE
5869                           ,REUSE_CONFIG
5870                           ,OPTION_SPECIFIC
5871                           ,QTY_PER_PARENT_MODEL
5872                           ,CONFIG_CREATION
5873 			  ,VALIDATION_ORG)
5874                     select
5875                            LINE_ID
5876                           ,HEADER_ID
5877                           ,TOP_MODEL_LINE_ID
5878                           ,LINK_TO_LINE_ID
5879                           ,ATO_LINE_ID
5880                           ,PARENT_ATO_LINE_ID
5881                           ,INVENTORY_ITEM_ID
5882                           ,SHIP_FROM_ORG_ID
5883                           ,COMPONENT_SEQUENCE_ID
5884                           ,COMPONENT_CODE
5885                           ,ITEM_TYPE_CODE
5886                           ,SCHEDULE_SHIP_DATE
5887                           ,PLAN_LEVEL
5888                           ,PERFORM_MATCH
5889                           ,CONFIG_ITEM_ID
5890                           ,BOM_ITEM_TYPE
5891                           ,WIP_SUPPLY_TYPE
5892                           ,ORDERED_QUANTITY
5893                           ,ORDER_QUANTITY_UOM
5894                           ,BATCH_ID
5895                           ,CREATION_DATE
5896                           ,CREATED_BY
5897                           ,LAST_UPDATE_DATE
5898                           ,LAST_UPDATED_BY
5899                           ,LAST_UPDATE_LOGIN
5900                           ,PROGRAM_APPLICATION_ID
5901                           ,PROGRAM_ID
5902                           ,PROGRAM_UPDATE_DATE
5903                           ,REUSE_CONFIG
5904                           ,OPTION_SPECIFIC
5905                           ,QTY_PER_PARENT_MODEL
5906                           ,CONFIG_CREATION
5907 			  ,SHIP_FROM_ORG_ID --3555026
5908                       from bom_cto_order_lines
5909                      where ato_line_id = p_ato_line_id ;
5910 
5911 
5912 
5913 oe_debug_pub.add( ' copied bcol to bcol_gt ' || SQL%ROWCOUNT , 1) ;
5914 
5915 
5916 end copy_bcol_bcolgt ;
5917 
5918 
5919 
5920 
5921 procedure send_notification(
5922                             P_PROCESS                       in    varchar2
5923                            ,P_LINE_ID                       in    number
5924                            ,P_SALES_ORDER_NUM               in    number
5925                            ,P_ERROR_MESSAGE                 in    varchar2
5926                            ,P_TOP_MODEL_NAME                in    varchar2
5927                            ,P_TOP_MODEL_LINE_NUM            in    varchar2
5928                            ,P_TOP_CONFIG_NAME               in    varchar2
5929                            ,P_TOP_CONFIG_LINE_NUM           in    varchar2
5930                            ,P_PROBLEM_MODEL                 in    varchar2
5931                            ,P_PROBLEM_MODEL_LINE_NUM        in    varchar2
5932                            ,P_PROBLEM_CONFIG                in    varchar2
5933                            ,P_ERROR_ORG                     in    varchar2
5934                            ,P_NOTIFY_USER                   in    varchar2
5935                            ,P_REQUEST_ID                    in    varchar2
5936                            ,P_MFG_REL_DATE                  in    date default null
5937 )
5938 is
5939    l_aname                      wf_engine.nametabtyp;
5940    l_anumvalue                  wf_engine.numtabtyp;
5941    l_atxtvalue                  wf_engine.texttabtyp;
5942    l_adatevalue                 wf_engine.datetabtyp;
5943    luser_key                    varchar2(100);
5944    litem_key                    varchar2(100);
5945    lplanner_code                mtl_system_items_vl.planner_code%type;
5946 
5947    l_dname                      wf_engine.nametabtyp;
5948   porder_no                     number := 2222 ;
5949   pline_no                      number := 1111 ;
5950 
5951   lstmt_num                     number ;
5952 
5953     l_new_line  varchar2(10) := fnd_global.local_chr(10);
5954 
5955   i     number ;
5956 
5957 
5958 begin
5959 
5960 
5961 
5962 
5963           lstmt_num := 10 ;
5964 
5965 
5966           litem_key := to_char(p_line_id)||to_char(sysdate,'mmddyyhhmiss' );
5967 
5968           oe_debug_pub.add( 'SEND_NOTIFICATION item_key ' || litem_key , 1 ) ;
5969           g_error_seq := g_error_seq + 1 ;
5970           oe_debug_pub.add( 'error_seq is ' || g_error_seq , 1 ) ;
5971 
5972           luser_key := litem_key;
5973 
5974           lplanner_code := P_NOTIFY_USER ;
5975 
5976           lstmt_num := 20 ;
5977 
5978 
5979 
5980 
5981           i := 1 ;
5982 
5983           l_aname(i) :=  'ERROR_MESSAGE' ;
5984           l_atxtvalue(i) :=  P_ERROR_MESSAGE ;
5985 
5986           i := i + 1 ;
5987 
5988           l_aname(i) :=  'TOP_MODEL' ;
5989           l_atxtvalue(i) := P_TOP_MODEL_NAME ;
5990 
5991           i := i + 1 ;
5992 
5993           l_aname(i) := 'TOP_MODEL_LINE_NUM' ;
5994           l_atxtvalue(i) := P_TOP_MODEL_LINE_NUM ;
5995 
5996 
5997 
5998           if( p_request_id is not null ) then
5999              i := i + 1 ;
6000              l_aname(i) := 'REQUEST_ID' ;
6001 
6002              l_atxtvalue(i) := P_REQUEST_ID  ;
6003 
6004           end if;
6005 
6006 
6007           /*
6008           i := i + 1 ;
6009 
6010           l_aname(i) := 'MFG_DATE' ;
6011           l_atxtvalue(i) := P_MFG_REL_DATE  ;
6012           */
6013 
6014           l_dname(1) := 'MFG_DATE' ;
6015           l_adatevalue(1) := P_MFG_REL_DATE ;
6016 
6017 
6018 
6019           lstmt_num := 30 ;
6020 
6021          if( P_PROCESS in ( 'NOTIFY_OID_INC' ,  'NOTIFY_OID_IC' ) ) then
6022 
6023           i := i + 1 ;
6024 
6025           l_aname(i) :=  'PROBLEM_MODEL' ;
6026           l_atxtvalue(i) := P_PROBLEM_MODEL   ;
6027 
6028           i := i + 1 ;
6029 
6030           l_aname(i) := 'PROBLEM_MODEL_LINE_NUM' ;
6031           l_atxtvalue(i) :=  P_PROBLEM_MODEL_LINE_NUM ;
6032 
6033           i := i + 1 ;
6034 
6035           l_aname(i) := 'ERROR_ORG' ;
6036           l_atxtvalue(i) := P_ERROR_ORG   ;
6037 
6038 
6039          end if ;
6040 
6041           lstmt_num := 40 ;
6042 
6043          if( P_PROCESS in  ( 'NOTIFY_OID_IC' , 'NOTIFY_OEE_IC'  )) then
6044 
6045           i := i + 1 ;
6046 
6047           l_aname(i) := 'TOP_CONFIG' ;
6048           l_atxtvalue(i) := P_TOP_CONFIG_NAME  ;
6049 
6050           i := i + 1 ;
6051 
6052           l_aname(i) := 'TOP_CONFIG_LINE_NUM' ;
6053           l_atxtvalue(i) := P_TOP_CONFIG_LINE_NUM ;
6054 
6055 
6056         end if ;
6057 
6058 
6059          if( P_PROCESS = 'NOTIFY_OID_IC' ) then
6060 
6061           i := i + 1 ;
6062 
6063           l_aname(i) := 'PROBLEM_CONFIG' ;
6064           l_atxtvalue(i) := P_PROBLEM_CONFIG  ;
6065 
6066 
6067         end if;
6068 
6069 
6070           lstmt_num := 50 ;
6071 
6072           if( P_PROCESS = 'NOTIFY_OID_IC' ) then
6073               oe_debug_pub.add( ' going to create process 1 ' || P_PROCESS ) ;
6074 
6075               litem_key := litem_key || to_char( g_error_seq ) || '1111' ;
6076 
6077               oe_debug_pub.add( 'SEND_NOTIFICATION modified item_key ' || litem_key , 1 ) ;
6078 
6079               wf_engine.CreateProcess (ItemType=> 'CTOEXCP',ItemKey=>litem_key,Process=>'NOTIFY_OID_IC');
6080 
6081           elsif( P_PROCESS = 'NOTIFY_OID_INC' ) then
6082 
6083               litem_key := litem_key || to_char( g_error_seq ) || '2222' ;
6084 
6085               oe_debug_pub.add( 'SEND_NOTIFICATION modified item_key ' || litem_key , 1 ) ;
6086 
6087               oe_debug_pub.add( ' going to create process 2 ' || P_PROCESS ) ;
6088               wf_engine.CreateProcess (ItemType=> 'CTOEXCP',ItemKey=>litem_key,Process=>'NOTIFY_OID_INC');
6089 
6090           elsif( P_PROCESS = 'NOTIFY_OEE_INC' ) then
6091 
6092               litem_key := litem_key || to_char( g_error_seq ) || '3333' ;
6093 
6094               oe_debug_pub.add( 'SEND_NOTIFICATION modified item_key ' || litem_key , 1 ) ;
6095 
6096 
6097               oe_debug_pub.add( ' going to create process 3 ' || P_PROCESS ) ;
6098               wf_engine.CreateProcess (ItemType=> 'CTOEXCP',ItemKey=>litem_key,Process=>'NOTIFY_OEE_INC');
6099 
6100           elsif( P_PROCESS = 'NOTIFY_OEE_IC' ) then
6101 
6102               litem_key := litem_key || to_char(g_error_seq ) || '4444' ;
6103 
6104               oe_debug_pub.add( 'SEND_NOTIFICATION modified item_key ' || litem_key , 1 ) ;
6105 
6106 
6107 
6108               oe_debug_pub.add( ' going to create process 4 ' || P_PROCESS ) ;
6109               wf_engine.CreateProcess (ItemType=> 'CTOEXCP',ItemKey=>litem_key,Process=>'NOTIFY_OEE_IC');
6110 
6111           end if;
6112 
6113 
6114           lstmt_num := 60 ;
6115           wf_engine.SetItemUserKey(ItemType=> 'CTOEXCP',ItemKey=>litem_key,UserKey=>luser_key);
6116 
6117 
6118 
6119           lstmt_num := 70 ;
6120 
6121           IF WF_DIRECTORY.USERACTIVE(lplanner_code) <>TRUE THEN
6122              -- Get the default adminstrator value from Workflow Attributes.
6123              lplanner_code := wf_engine.getItemAttrText(ItemType => 'CTOEXCP',
6124                                                  ItemKey  => litem_key,
6125                                                  aname    => 'WF_ADMINISTRATOR');
6126              oe_debug_pub.add('start_work_flow: ' || 'Planner code is not a valid workflow user...Defaulting to'||lplanner_code,5);
6127 
6128           ELSE
6129 
6130              oe_debug_pub.add('start_work_flow: ' || 'Planner code is a valid workflow user...' ,5);
6131 
6132           END IF;
6133 
6134 
6135           lstmt_num := 80 ;
6136 
6137 
6138           i := i + 1 ;
6139 
6140           l_aname(i)     := 'NOTIFY_USER';
6141           l_atxtvalue(i) := lplanner_code;
6142 
6143 
6144 
6145           lstmt_num := 90 ;
6146 
6147           wf_engine.SetItemAttrNumber(ItemType   =>'CTOEXCP',
6148                               itemkey    =>litem_key,
6149                               aname      =>'ORDER_NUM',
6150                               avalue     => p_sales_order_num );
6151 
6152           lstmt_num := 100 ;
6153           wf_engine.SetItemAttrTextArray(ItemType =>'CTOEXCP',ItemKey=>litem_key,aname=>l_aname,avalue=>l_atxtvalue);
6154 
6155           lstmt_num := 110 ;
6156           wf_engine.SetItemAttrDateArray(ItemType =>'CTOEXCP',ItemKey=>litem_key,aname=>l_dname,avalue=>l_adatevalue);
6157 
6158 
6159           lstmt_num := 120 ;
6160           wf_engine.SetItemOwner(Itemtype=>'CTOEXCP',itemkey=>litem_key,owner=>lplanner_code);
6161 
6162 
6163           lstmt_num := 130 ;
6164           wf_engine.StartProcess(itemtype=>'CTOEXCP',ItemKey=>litem_key);
6165 
6166 
6167           oe_debug_pub.add( ' done till stmt ' || lstmt_num ) ;
6168 
6169 
6170 
6171 exception
6172 when others then
6173 
6174  oe_debug_pub.add( ' exception in others at stmt ' || lstmt_num ) ;
6175  oe_debug_pub.add( ' exception in others ' || SQLCODE ) ;
6176  oe_debug_pub.add( ' exception in others ' || SQLERRM ) ;
6177 
6178 
6179 end send_notification ;
6180 
6181 
6182 
6183 procedure notify_expected_errors ( P_PROCESS                       in    varchar2
6184                            ,P_LINE_ID                       in    number
6185                            ,P_SALES_ORDER_NUM               in    number
6186                            ,P_TOP_MODEL_NAME                in    varchar2
6187                            ,P_TOP_MODEL_LINE_NUM            in    varchar2
6188                            ,P_MSG_COUNT                     in    number
6189                            ,P_NOTIFY_USER                   in    varchar2
6190                            ,P_REQUEST_ID                    in    varchar2
6191                            ,P_ERROR_MESSAGE                 in    varchar2 default null
6192                            ,P_TOP_CONFIG_NAME               in    varchar2 default null
6193                            ,P_TOP_CONFIG_LINE_NUM           in    varchar2 default null
6194                            ,P_PROBLEM_MODEL                 in    varchar2 default null
6195                            ,P_PROBLEM_MODEL_LINE_NUM        in    varchar2 default null
6196                            ,P_PROBLEM_CONFIG                in    varchar2 default null
6197                            ,P_ERROR_ORG                     in    varchar2 default null
6198 )
6199 is
6200 PRAGMA AUTONOMOUS_TRANSACTION  ;
6201 
6202   l_new_line  varchar2(10) := fnd_global.local_chr(10);
6203   v_error_message    varchar2(2300) ;
6204   l_msg_data         varchar2(2300) ;
6205 
6206 
6207 begin
6208 
6209               oe_debug_pub.add('CTO_UTILITY_PK.notify_expected_errors: ******** BEGIN AUTONOMOUS TRANSACTION    **********' , 1 );
6210 
6211 
6212 
6213               oe_debug_pub.add('CTO_UTILITY_PK.notify_expected_errors: msg count ' || P_MSG_COUNT , 1 );
6214 
6215 
6216               if ( nvl( p_msg_count , 0 ) = 0 ) then
6217                    oe_debug_pub.add('CTO_UTILITY_PK.notify_expected_errors: nothing to notify' , 1 );
6218                    return ;
6219               end if;
6220 
6221 
6222               FOR l_index IN 1..P_MSG_COUNT LOOP
6223 	         -- Fixed bug 5639511
6224 		 -- Added substr function to avoid buffer overflow error
6225 
6226                  l_msg_data := substr(fnd_msg_pub.get(
6227                                    p_msg_index => l_index,
6228                                    p_encoded  => FND_API.G_FALSE),1,2000);
6229 
6230                  oe_debug_pub.add('CTO_UTILITY_PK.notify_expected_error: '||substr(l_msg_data,1,250));
6231 
6232                  -- Fixed bug 5639511
6233 		 -- Added Substr fucntion to avoid buffer overflow error
6234 
6235                  v_error_message := substr(v_error_message || l_msg_data  || l_new_line,1,2000) ;
6236 
6237 	         -- Fixed bug 5639511
6238 		 -- If the string reached 2000 char length exit out of loop
6239                  if( length (v_error_message ) >= 2000 ) then
6240 
6241                      v_error_message := substr(v_error_message, 1 , 2000)  ;
6242 
6243                      oe_debug_pub.add('CTO_UTILITY_PK.notify_expected_error: truncated v_error_message to 4000 chars ' );
6244 		     exit; -- Added exit statement for bug fix 5639511
6245                  end if;
6246 
6247 
6248               END LOOP;
6249 
6250 
6251               oe_debug_pub.add('CTO_UTILITY_PK.notify_expected_errors: error_message  : ' || v_error_message  );
6252 
6253               g_t_expected_error_info(1).NOTIFY_USER           := P_NOTIFY_USER ;
6254               g_t_expected_error_info(1).SALES_ORDER_NUM       := P_SALES_ORDER_NUM ;
6255               g_t_expected_error_info(1).TOP_MODEL_NAME        := p_top_model_name ;
6256               g_t_expected_error_info(1).TOP_MODEL_LINE_NUM    := p_top_model_line_num ;
6257               g_t_expected_error_info(1).ERROR_MESSAGE         := v_error_message ;
6258               g_t_expected_error_info(1).TOP_CONFIG_NAME       := p_top_config_name ;
6259               g_t_expected_error_info(1).TOP_CONFIG_LINE_NUM   := p_top_config_line_num ;
6260               g_t_expected_error_info(1).REQUEST_ID             :=  P_REQUEST_ID ;
6261               g_t_expected_error_info(1).LINE_ID             :=  P_LINE_ID ;
6262               g_t_expected_error_info(1).PROCESS := P_PROCESS ;  /* WORKFLOW PROCESS */
6263 
6264 
6265               g_t_expected_error_info(1).TOP_CONFIG_NAME        := p_top_config_name ;
6266               g_t_expected_error_info(1).TOP_CONFIG_LINE_NUM    := p_top_config_line_num ;
6267 
6268           /*
6269            following are not supported for now
6270           g_t_dropped_item_type(v_table_count).LINE_ID               := pLineId ;
6271           g_t_dropped_item_type(v_table_count).PROBLEM_MODEL         := v_problem_model ;
6272           g_t_dropped_item_type(v_table_count).PROBLEM_MODEL_LINE_NUM := v_problem_model_line_num ;
6273           g_t_dropped_item_type(v_table_count).PROBLEM_CONFIG         := v_problem_config ;
6274           g_t_dropped_item_type(v_table_count).ERROR_ORG              := v_error_org ;
6275           g_t_dropped_item_type(v_table_count).ERROR_ORG_ID           := pOrgId ;
6276           */
6277 
6278 
6279                  oe_debug_pub.add( 'PROCESS: ' || g_t_expected_error_info(1).PROCESS  , 1 ) ;
6280                  oe_debug_pub.add( 'LINE_ID: ' || g_t_expected_error_info(1).LINE_ID  , 1 ) ;
6281                  oe_debug_pub.add( 'SALES_ORDER_NUM: ' || g_t_expected_error_info(1).SALES_ORDER_NUM ,1 );
6282                  oe_debug_pub.add( 'ERROR_MESSAGE: ' || g_t_expected_error_info(1).ERROR_MESSAGE  , 1 ) ;
6283                  oe_debug_pub.add( 'TOP_MODEL_NAME: ' || g_t_expected_error_info(1).TOP_MODEL_NAME , 1 ) ;
6284                  oe_debug_pub.add( 'TOP_MODEL_LINE_NUM: ' || g_t_expected_error_info(1).TOP_MODEL_LINE_NUM , 1 ) ;
6285                  oe_debug_pub.add( 'TOP_CONFIG_NAME: ' || g_t_expected_error_info(1).TOP_CONFIG_NAME , 1 ) ;
6286                  oe_debug_pub.add( 'TOP_CONFIG_LINE_NUM: ' || g_t_expected_error_info(1).TOP_CONFIG_LINE_NUM , 1) ;
6287                  oe_debug_pub.add( 'PROBLEM_MODEL: ' || g_t_expected_error_info(1).PROBLEM_MODEL , 1 ) ;
6288                  oe_debug_pub.add( 'PROBLEM_MODEL_LINE_NUM: ' || g_t_expected_error_info(1).PROBLEM_MODEL_LINE_NUM , 1 ) ;
6289                  oe_debug_pub.add( 'PROBLEM_CONFIG: ' || g_t_expected_error_info(1).PROBLEM_CONFIG  , 1) ;
6290                  oe_debug_pub.add( 'ERROR_ORG: ' || g_t_expected_error_info(1).ERROR_ORG , 1 ) ;
6291                  oe_debug_pub.add( 'ERROR_ORG_ID: ' || g_t_expected_error_info(1).ERROR_ORG_ID , 1) ;
6292                  oe_debug_pub.add( 'NOTIFY_USER: ' || g_t_expected_error_info(1).NOTIFY_USER, 1) ;
6293                  oe_debug_pub.add( 'REQUEST_ID: ' || g_t_expected_error_info(1).REQUEST_ID  , 1 ) ;
6294 
6295 
6296               oe_debug_pub.add('CTO_UTILITY_PK.notify_expected_errors: done expected errors ' , 1 );
6297 
6298 
6299 
6300 
6301               oe_debug_pub.add('CTO_UTILITY_PK.notify_expected_errors: going to call send notification ' , 1 );
6302 
6303                       send_notification (
6304                             P_PROCESS                      =>  g_t_expected_error_info(1).process
6305                            ,P_LINE_ID                      =>  g_t_expected_error_info(1).line_id
6306                            ,P_SALES_ORDER_NUM              => g_t_expected_error_info(1).sales_order_num
6307                            ,P_ERROR_MESSAGE                => g_t_expected_error_info(1).error_message
6308                            ,P_TOP_MODEL_NAME               => g_t_expected_error_info(1).top_model_name
6309                            ,P_TOP_MODEL_LINE_NUM           => g_t_expected_error_info(1).top_model_line_num
6310                            ,P_TOP_CONFIG_NAME              => g_t_expected_error_info(1).top_config_name
6311                            ,P_TOP_CONFIG_LINE_NUM          => g_t_expected_error_info(1).top_config_line_num
6312                            ,P_PROBLEM_MODEL                => g_t_expected_error_info(1).problem_model
6313                            ,P_PROBLEM_MODEL_LINE_NUM       => g_t_expected_error_info(1).problem_model_line_num
6314                            ,P_PROBLEM_CONFIG               => g_t_expected_error_info(1).problem_config
6315                            ,P_ERROR_ORG                    => g_t_expected_error_info(1).error_org
6316                            ,P_NOTIFY_USER                  => g_t_expected_error_info(1).notify_user
6317                            ,P_REQUEST_ID                   =>  g_t_expected_error_info(1).request_id );
6318 
6319 
6320               commit ;    /* COMMIT FOR AUTONOMOUS TRANSACTION */
6321 
6322 
6323               oe_debug_pub.add('CTO_UTILITY_PK.notify_expected_errors: done send notification ' , 1 );
6324 
6325               oe_debug_pub.add('CTO_UTILITY_PK.notify_expected_errors: ******** END AUTONOMOUS TRANSACTION FOR NOTIFY_EXPECTED_ERRORS   **********' , 1 );
6326 end notify_expected_errors ;
6327 
6328 
6329 PROCEDURE APPLY_CREATE_CONFIG_HOLD( p_line_id        in  number
6330                                   , p_header_id      in  number
6331                                   , x_return_status  out NOCOPY varchar2
6332                                   , x_msg_count      out NOCOPY number
6333                                   , x_msg_data       out NOCOPY varchar2)
6334 is
6335       Pragma AUTONOMOUS_TRANSACTION;
6336       l_hold_source_rec           OE_Holds_PVT.Hold_Source_REC_type;
6337       l_return_stutus     varchar2(10) ;
6338       l_msg_count         number ;
6339       l_msg_data          varchar2(200) ;
6340 
6341 BEGIN
6342 
6343                     IF PG_DEBUG <> 0 THEN
6344                        oe_debug_pub.add('******************APPLY_CREATE_CONFIG_HOLD:BEGIN APPLY AUTONOMOUS TRANSACTION   ****************  ' ,1);
6345                     END IF;
6346 
6347 
6348 
6349 
6350                     IF PG_DEBUG <> 0 THEN
6351                        oe_debug_pub.add('APPLY_CREATE_CONFIG_HOLD:Calling OM api to apply create config activity hold.' ,1);
6352                     END IF;
6353 
6354                     l_hold_source_rec.hold_entity_code   := 'O';
6355                     l_hold_source_rec.hold_id            := 60 ;  /* Change hold id 1062 to 60 after getting script  from gayatri */
6356                     l_hold_source_rec.hold_entity_id     := p_header_id;
6357                     l_hold_source_rec.header_id          := p_header_id;
6358                     l_hold_source_rec.line_id            := p_line_id;
6359 
6360                     OE_Holds_PUB.Apply_Holds (
6361                                    p_api_version        => 1.0
6362                                ,   p_hold_source_rec    => l_hold_source_rec
6363                                ,   x_return_status      => x_return_status
6364                                ,   x_msg_count          => x_msg_count
6365                                ,   x_msg_data           => x_msg_data);
6366 
6367                     IF (x_return_status = FND_API.G_RET_STS_ERROR) THEN
6368                         IF PG_DEBUG <> 0 THEN
6369                            oe_debug_pub.add('CTOCITMB:Failed in Apply Holds with expected error.' ,1);
6370                         END IF;
6371                         raise FND_API.G_EXC_ERROR;
6372 
6373                     ELSIF (x_return_status = FND_API.G_RET_STS_UNEXP_ERROR) THEN
6374                         IF PG_DEBUG <> 0 THEN
6375                            oe_debug_pub.add('CTOCITMB:Failed in Apply Holds with unexpected error.' ,1);
6376                         END IF;
6377                         raise FND_API.G_EXC_UNEXPECTED_ERROR;
6378                     END IF;
6379 
6380                     commit ;   /* COMMIT FOR AUTONOMOUS TRANSACTION  */
6381 
6382 
6383                     IF PG_DEBUG <> 0 THEN
6384                        oe_debug_pub.add('******************APPLY_CREATE_CONFIG_HOLD:END APPLY AUTONOMOUS TRANSACTION   ****************  ' ,1);
6385                     END IF;
6386 
6387 
6388 END APPLY_CREATE_CONFIG_HOLD ;
6389 
6390 
6391 
6392 procedure send_oid_notification
6393 is
6394 PRAGMA AUTONOMOUS_TRANSACTION  ;
6395 begin
6396 
6397              oe_debug_pub.add('SEND_OID_NOTIFICATION : ******** BEGIN AUTONOMOUS TRANSACTION FOR SEND_OID_NOTIFICATION **********' , 1 );
6398 
6399 
6400                if( CTO_CONFIG_BOM_PK.g_t_dropped_item_type.count > 0 ) then
6401 
6402 
6403 
6404 
6405                     oe_debug_pub.add( 'DROPPED ITEM TABLE '  || CTO_CONFIG_BOM_PK.g_t_dropped_item_type.count , 1 ) ;
6406 
6407                    for i in 1..CTO_CONFIG_BOM_PK.g_t_dropped_item_type.count
6408                    loop
6409                        oe_debug_pub.add( 'PROCESS: ' || CTO_CONFIG_BOM_PK.g_t_dropped_item_type(i).PROCESS  , 1 ) ;
6410                        oe_debug_pub.add( 'LINE_ID: ' || CTO_CONFIG_BOM_PK.g_t_dropped_item_type(i).LINE_ID  , 1 ) ;
6411                        oe_debug_pub.add( 'SALES_ORDER_NUM: ' || CTO_CONFIG_BOM_PK.g_t_dropped_item_type(i).SALES_ORDER_NUM ,1 );
6412                        oe_debug_pub.add( 'ERROR_MESSAGE: ' || CTO_CONFIG_BOM_PK.g_t_dropped_item_type(i).ERROR_MESSAGE  , 1 ) ;
6413                        oe_debug_pub.add( 'TOP_MODEL_NAME: ' || CTO_CONFIG_BOM_PK.g_t_dropped_item_type(i).TOP_MODEL_NAME , 1 ) ;
6414                        oe_debug_pub.add( 'TOP_MODEL_LINE_NUM: ' || CTO_CONFIG_BOM_PK.g_t_dropped_item_type(i).TOP_MODEL_LINE_NUM , 1 ) ;
6415                        oe_debug_pub.add( 'TOP_CONFIG_NAME: ' || CTO_CONFIG_BOM_PK.g_t_dropped_item_type(i).TOP_CONFIG_NAME , 1 ) ;
6416                        oe_debug_pub.add( 'TOP_CONFIG_LINE_NUM: ' || CTO_CONFIG_BOM_PK.g_t_dropped_item_type(i).TOP_CONFIG_LINE_NUM , 1) ;
6417                        oe_debug_pub.add( 'PROBLEM_MODEL: ' || CTO_CONFIG_BOM_PK.g_t_dropped_item_type(i).PROBLEM_MODEL , 1 ) ;
6418                        oe_debug_pub.add( 'PROBLEM_MODEL_LINE_NUM: ' || CTO_CONFIG_BOM_PK.g_t_dropped_item_type(i).PROBLEM_MODEL_LINE_NUM , 1 ) ;
6419                        oe_debug_pub.add( 'PROBLEM_CONFIG: ' || CTO_CONFIG_BOM_PK.g_t_dropped_item_type(i).PROBLEM_CONFIG  , 1) ;
6420                        oe_debug_pub.add( 'ERROR_ORG: ' || CTO_CONFIG_BOM_PK.g_t_dropped_item_type(i).ERROR_ORG , 1 ) ;
6421                        oe_debug_pub.add( 'ERROR_ORG_ID: ' || CTO_CONFIG_BOM_PK.g_t_dropped_item_type(i).ERROR_ORG_ID , 1) ;
6422                        oe_debug_pub.add( 'NOTIFY_USER: ' || CTO_CONFIG_BOM_PK.g_t_dropped_item_type(i).NOTIFY_USER, 1) ;
6423                        oe_debug_pub.add( 'REQUEST_ID: ' || CTO_CONFIG_BOM_PK.g_t_dropped_item_type(i).REQUEST_ID  , 1 ) ;
6424 
6425                        if( CTO_CONFIG_BOM_PK.g_t_dropped_item_type(i).MFG_REL_DATE is not null ) then
6426                        oe_debug_pub.add( 'MFG_REL_DATE: ' || to_char(CTO_CONFIG_BOM_PK.g_t_dropped_item_type(i).MFG_REL_DATE)  , 1 ) ;
6427                        else
6428 
6429                            oe_debug_pub.add( 'MFG REL DATE is null '  , 1 ) ;
6430                        end if;
6431 
6432 
6433 
6434                       oe_debug_pub.add( 'DROPPED ITEM TABLE '  || ' going to send notification ' , 1 ) ;
6435 
6436                       CTO_UTILITY_PK.send_notification (
6437                             P_PROCESS                      =>  CTO_CONFIG_BOM_PK.g_t_dropped_item_type(i).process
6438                            ,P_LINE_ID                      =>  CTO_CONFIG_BOM_PK.g_t_dropped_item_type(i).line_id
6439                            ,P_SALES_ORDER_NUM              => CTO_CONFIG_BOM_PK.g_t_dropped_item_type(i).sales_order_num
6440                            ,P_ERROR_MESSAGE                => CTO_CONFIG_BOM_PK.g_t_dropped_item_type(i).error_message
6441                            ,P_TOP_MODEL_NAME               => CTO_CONFIG_BOM_PK.g_t_dropped_item_type(i).top_model_name
6442                            ,P_TOP_MODEL_LINE_NUM           => CTO_CONFIG_BOM_PK.g_t_dropped_item_type(i).top_model_line_num
6443                            ,P_TOP_CONFIG_NAME              => CTO_CONFIG_BOM_PK.g_t_dropped_item_type(i).top_config_name
6444                            ,P_TOP_CONFIG_LINE_NUM          => CTO_CONFIG_BOM_PK.g_t_dropped_item_type(i).top_config_line_num
6445                            ,P_PROBLEM_MODEL                => CTO_CONFIG_BOM_PK.g_t_dropped_item_type(i).problem_model
6446                            ,P_PROBLEM_MODEL_LINE_NUM       => CTO_CONFIG_BOM_PK.g_t_dropped_item_type(i).problem_model_line_num
6447                            ,P_PROBLEM_CONFIG               => CTO_CONFIG_BOM_PK.g_t_dropped_item_type(i).problem_config
6448                            ,P_ERROR_ORG                    => CTO_CONFIG_BOM_PK.g_t_dropped_item_type(i).error_org
6449                            ,P_NOTIFY_USER                  => CTO_CONFIG_BOM_PK.g_t_dropped_item_type(i).notify_user
6450                            ,P_REQUEST_ID                   =>  CTO_CONFIG_BOM_PK.g_t_dropped_item_type(i).request_id
6451                            ,P_MFG_REL_DATE                 =>  CTO_CONFIG_BOM_PK.g_t_dropped_item_type(i).mfg_rel_date );
6452 
6453                       oe_debug_pub.add( 'DROPPED ITEM TABLE '  || ' sent notification ' , 1 ) ;
6454 
6455 
6456                    end loop ;
6457 
6458                else
6459 
6460                       oe_debug_pub.add( 'DROPPED ITEM TABLE '  || ' is empty ' , 1 ) ;
6461 
6462                end if ;
6463 
6464 
6465               commit ;  -- AUTONOMOUS TRANSACTION
6466 
6467              oe_debug_pub.add('SEND_OID_NOTIFICATION : ******** END AUTONOMOUS TRANSACTION FOR SEND_OID_NOTIFICATION **********' , 1 );
6468              CTO_CONFIG_BOM_PK.g_t_dropped_item_type.delete;
6469 
6470 end send_oid_notification ;
6471 
6472 
6473 
6474 
6475 
6476 procedure get_planner_code( p_inventory_item_id   in number
6477                          , p_organization_id     in number
6478                          , x_planner_code        out NOCOPY fnd_user.user_name%type )
6479 is
6480 begin
6481 
6482           IF PG_DEBUG <> 0 THEN
6483              oe_debug_pub.add('create_bom_ml: ' || 'Getting the planner code ..',3);
6484           END IF;
6485 
6486           BEGIN
6487             -- bugfix 2203802: Instead of getting the planner code directly from MSI,
6488             --                 get the corresponding application user.
6489 
6490                SELECT  u.user_name
6491                 INTO   x_planner_code
6492                 FROM   mtl_system_items_vl item
6493                       ,mtl_planners p
6494                       ,fnd_user u
6495                WHERE item.inventory_item_id = p_inventory_item_id
6496                and   item.organization_id   = p_organization_id
6497                and   p.organization_id = item.organization_id
6498                and   p.planner_code = item.planner_code
6499                and   p.employee_id = u.employee_id(+);         --outer join b'cos employee need not be an fnd user.
6500 
6501 
6502               oe_debug_pub.add('create_bom_ml: ' || '****PLANNER CODE DATA' || x_planner_code ,2);
6503 
6504 
6505           EXCEPTION
6506 
6507               WHEN OTHERS THEN
6508                    IF PG_DEBUG <> 0 THEN
6509                       oe_debug_pub.add('create_bom_ml: ' || 'Error in getting the planner code data. Defaulting to SYSADMIN.',2);
6510 
6511                       oe_debug_pub.add('create_bom_ml: ' || 'Error Message : '||sqlerrm,2);
6512 
6513                       x_planner_code := 'SYSADMIN' ;
6514 
6515                    END IF;
6516           END;
6517 
6518 
6519           oe_debug_pub.add('create_bom_ml: ' || '****PLANNER CODE DATA' || x_planner_code ,2);
6520 
6521 end get_planner_code ;
6522 
6523 
6524 procedure handle_expected_error( p_error_type           in number
6525                      , p_inventory_item_id    in number
6526                      , p_organization_id      in number
6527                      , p_line_id              in number
6528                      , p_sales_order_num      in number
6529                      , p_top_model_name       in varchar2
6530                      , p_top_model_line_num   in varchar2
6531                      , p_top_config_name       in varchar2 default null
6532                      , p_top_config_line_num   in varchar2 default null
6533                      , p_msg_count            in number
6534                      , p_planner_code         in varchar2
6535                      , p_request_id           in varchar2
6536                      , p_process              in varchar2 )
6537 is
6538 v_recipient      varchar2(200) ;
6539 begin
6540 
6541                     IF PG_DEBUG <> 0 THEN
6542                        oe_debug_pub.add('handle_expected_error: entered handle_expected_error ' , 3);
6543                        oe_debug_pub.add('handle_expected_error: p_inventory_item_id ' || p_inventory_item_id , 3);
6544                        oe_debug_pub.add('handle_expected_error: p_organization_id ' || p_organization_id , 3);
6545                        oe_debug_pub.add('handle_expected_error: p_line_id ' || p_line_id , 3);
6546                        oe_debug_pub.add('handle_expected_error: p_sales_order_num ' || p_sales_order_num , 3);
6547                        oe_debug_pub.add('handle_expected_error: p_top_model_name ' || p_top_model_name , 3);
6548                        oe_debug_pub.add('handle_expected_error: p_top_model_line_num ' || p_top_model_line_num , 3);
6549                        oe_debug_pub.add('handle_expected_error: p_top_config_name ' || p_top_config_name , 3);
6550                        oe_debug_pub.add('handle_expected_error: p_top_config_line_num ' || p_top_config_line_num , 3);
6551                        oe_debug_pub.add('handle_expected_error: p_msg_count ' || p_msg_count , 3);
6552                        oe_debug_pub.add('handle_expected_error: p_planner_code ' || p_planner_code , 3);
6553                        oe_debug_pub.add('handle_expected_error: p_request_id ' || p_request_id , 3);
6554                        oe_debug_pub.add('handle_expected_error: ********    P_PROCESS ******** ' || p_process , 3);
6555 
6556 
6557                        oe_debug_pub.add('handle_expected_error: ' || 'Getting Custom Recipient..',3);
6558                     END IF;
6559 
6560                     v_recipient := CTO_CUSTOM_NOTIFY_PK.get_recipient( p_error_type        => p_error_type
6561                                                                       ,p_inventory_item_id => p_inventory_item_id
6562                                                                       ,p_organization_id   => p_organization_id
6563                                                                       ,p_line_id           => p_line_id );
6564 
6565 
6566 
6567 
6568                     if( v_recipient is not null ) then
6569 
6570                         IF PG_DEBUG <> 0 THEN
6571                            oe_debug_pub.add('handle_expected_error: ' || 'Recipient returned from CTO_CUSTOM_NOTIFY_PK..' || v_recipient ,3);
6572                         END IF;
6573 
6574                     else
6575                         v_recipient := p_planner_code ;
6576                         IF PG_DEBUG <> 0 THEN
6577                            oe_debug_pub.add('handle_expected_error: ' || 'planner code is ..' || v_recipient ,3);
6578                         END IF;
6579                     end if;
6580 
6581 
6582 
6583 
6584 
6585                     CTO_UTILITY_PK.notify_expected_errors ( P_PROCESS        => p_process
6586                            ,P_LINE_ID               => p_line_id
6587                            ,P_SALES_ORDER_NUM       => p_sales_order_num
6588                            ,P_TOP_MODEL_NAME        => p_top_model_name
6589                            ,P_TOP_MODEL_LINE_NUM    => p_top_model_line_num
6590                            ,P_TOP_CONFIG_NAME        => p_top_config_name
6591                            ,P_TOP_CONFIG_LINE_NUM    => p_top_config_line_num
6592                            ,P_MSG_COUNT             => p_msg_count
6593                            ,P_NOTIFY_USER           => v_recipient
6594                            ,P_REQUEST_ID            => p_request_id ) ;
6595 
6596                     IF PG_DEBUG <> 0 THEN
6597                            oe_debug_pub.add('handle_expected_error: ' || 'done handle_expected_error..' ,3);
6598                     END IF;
6599 
6600 
6601 end handle_expected_error;
6602 
6603 
6604 /********************************************************************************************************************************
6605  *                 The following procedure create_item_attachments is added by
6606  *                 Renga Kannan on 01/20/04. This procedure will create item
6607  *                 attachment for all the PO validations orgs for a specific
6608  *                 config item. Based on the new design for J, we will create
6609  *                 attachment for all the config irrespective of make or
6610  *                 buy.This is because in the case of cib attribute 3, it will
6611  *                 be very difficult to find out the model sourcing info. for
6612  *                 cib 1 and 2 it will be very difficult to derive this info.
6613  *                 Also, just having an item level attachment will not affect
6614  *                 any other functionality. Hence, As per Uhsa it is ok to
6615  *                 create attachment for all the configs in all possible po
6616  *                 validation orgs.
6617  *
6618  *
6619  **********************************************************************************************************************************/
6620 
6621  Procedure Create_item_attachments(
6622                                     p_ato_line_id     in   Number,
6623                                     x_return_status   out  NOCOPY Varchar2,
6624                                     x_msg_count       out  NOCOPY Number,
6625                                     x_msg_data        out  NOCOPY Varchar2)  is
6626 
6627    l_attach_text			long;
6628    l_document_id			Number;
6629 
6630    Cursor config_items_cur is
6631       Select bcol.line_id,
6632 	     bcol.config_item_id
6633        from  bom_cto_order_lines bcol
6634        where ato_line_id = p_ato_line_id
6635        and   config_item_id is not null;
6636 
6637    Cursor config_orgs_cur(p_config_item_id  Number) is
6638 
6639        SELECT distinct nvl(fsp.inventory_organization_id,0) po_valid_org
6640        FROM   financials_system_params_all fsp
6641         Where fsp.org_id in (select org.operating_unit
6642 	                     from   inv_organization_info_v org,
6643 			            mtl_system_items msi
6644 			     where  msi.inventory_item_id = p_config_item_id
6645 			     and    msi.organization_id   = org.organization_id);
6646 
6647 Begin
6648 
6649   For config_items_rec in config_items_cur
6650   Loop
6651 
6652      l_attach_text := '';
6653      CTO_UTILITY_PK.generate_bom_attach_text
6654 			(p_line_id		=> config_items_rec.line_id
6655 			,x_text			=> l_attach_text
6656 			,x_Return_Status	=> x_Return_Status);
6657 
6658      For config_orgs_rec in config_orgs_cur(config_items_rec.config_item_id)
6659      Loop
6660 
6661         -- The validation part is added by Renga Kannan on 08/29/01
6662         -- Before creating the attachments first we need to verify that
6663         -- they are already existing for this item. It they are existing
6664         -- We should not create it once again.
6665 
6666         IF PG_DEBUG <> 0 THEN
6667      	   oe_debug_pub.add('Cto_Utility_pk: ' || 'Creating attachment for line id = '
6668    	                                                     ||to_char(config_items_rec.line_id),1);
6669 	   oe_debug_pub.add('Cto_Utility_pk: '|| 'Config item id = '||to_char(config_items_rec.config_item_id),1);
6670 	   oe_debug_pub.add('Cto_Utility_pk: '|| 'Po Validation Org = '||to_char(config_orgs_rec.po_valid_org),1);
6671         END IF;
6672 
6673         BEGIN
6674            SELECT document_id
6675            INTO   l_document_id
6676            FROM   FND_ATTACHED_DOCUMENTS
6677            WHERE  pk1_value   = to_char(config_orgs_rec.po_valid_org)	-- 2774570
6678            AND    pk2_value   = to_char(config_items_rec.config_item_id)	-- 2774570
6679            AND    entity_name = 'MTL_SYSTEM_ITEMS'
6680            AND    Pk3_value   = 'CTO:BOM:ATTACHMENT';
6681 
6682            IF PG_DEBUG <> 0 THEN
6683         	oe_debug_pub.add('Cto_Utility_pk: '
6684 		                 || 'Bom attachment already exists for this item.. document_id ='||to_char(l_document_id),1);
6685            END IF;
6686         EXCEPTION
6687 	   WHEN NO_DATA_FOUND THEN
6688            IF PG_DEBUG <> 0 THEN
6689         	oe_debug_pub.add('Cto_Utility_pk: '
6690 		                 || 'There is no bom document  attached to this item.. We need to attach the document',1);
6691            END IF;
6692 
6693            IF l_attach_text is not null THEN
6694 
6695               CTO_UTILITY_PK.create_attachment
6696 				(p_item_id	=> config_items_rec.config_item_id,
6697                                  p_org_id	=> config_orgs_rec.po_valid_org,
6698                                  p_text		=> l_attach_text,
6699 				 p_desc		=> 'Bill Of Material Details',
6700                                  p_doc_type	=> 'CTO:BOM:ATTACHMENT',
6701                                  x_Return_Status => x_Return_Status);
6702 
6703               IF PG_DEBUG <> 0 THEN
6704            	oe_debug_pub.add('Cto_Utility_pk: ' || 'Return status from create_attachment after bom attachment='
6705 		                                                  ||x_Return_Status,1);
6706               END IF;
6707 
6708            END IF;
6709         END;
6710 
6711       End Loop;
6712   End Loop;
6713 Exception When Others Then
6714     oe_debug_pub.add('Some Error occured in generating attachment',1);
6715     oe_debug_pub.add('Ignoring the error and continuing the process',1);
6716 End Create_item_attachments;
6717 
6718 
6719 
6720 -- bugfix 4044709 : Created new procedure to handle validation
6721 
6722   PROCEDURE validate_oe_data (  p_bcol_line_id  in      bom_cto_order_lines.line_id%type,
6723                                 x_return_status out NOCOPY varchar2)
6724   is
6725 
6726   v_step                VARCHAR2(15) ;
6727   vbcol_line_id         NUMBER;
6728   voe_match_flag        VARCHAR2(1);
6729   bcol_count            NUMBER;
6730   oe_count              NUMBER;
6731 
6732   Type bcol_line_tbl_type IS TABLE OF number INDEX BY BINARY_INTEGER;
6733 
6734   l_bcol_line_tbl       bcol_line_tbl_type ;
6735   l_last_index          NUMBER;
6736 
6737   v_oe_bcol_diff     varchar2(1) := 'N' ;
6738 
6739 
6740   begin
6741 
6742     x_return_status := FND_API.G_RET_STS_SUCCESS ;
6743 
6744     v_step := 'Step A17' ;
6745 
6746     --
6747     -- We will check if BCOL picture is in sync with OEOL picture.
6748     -- First, we will see if the count matches. If not, raise error.
6749     -- Then, check if the line_ids match. If not, raise error.
6750     -- This is to avoid situations as mentioned in bug 3443450
6751     --
6752 
6753      select count(*) into bcol_count
6754     from bom_cto_order_lines
6755     where ato_line_id = p_bcol_line_id;
6756 
6757     select count(*) into oe_count
6758     from oe_order_lines_all
6759     where ato_line_id = p_bcol_line_id
6760     and item_type_code <>'CONFIG'
6761     and ordered_quantity > 0 ;  -- Added this condition to take care of cancel line cases.
6762 
6763     if bcol_count <> oe_count then
6764         IF PG_DEBUG <> 0 THEN
6765           oe_debug_pub.add ('validate_oe_data: '||v_step||': OE count '||oe_count||' and BCOL count '||bcol_count||' does not match.');
6766         END IF;
6767         raise FND_API.G_EXC_UNEXPECTED_ERROR;
6768     end if;
6769 
6770 
6771 
6772 
6773 
6774 
6775 
6776 
6777 
6778 
6779 
6780      v_oe_bcol_diff:= 'N' ;
6781 
6782      begin
6783              select 'Y' into v_oe_bcol_diff from dual
6784              where exists
6785                    ((Select 1
6786                     from oe_order_lines_all oel
6787                     Where not exists
6788                          ( Select bcol.line_id,
6789                                   bcol.ordered_quantity,
6790                                   bcol.inventory_item_id
6791                              from bom_cto_order_lines bcol
6792                             where bcol.ato_line_id = p_bcol_line_id
6793                               and bcol.line_id = oel.line_id
6794                               and bcol.ordered_quantity = oel.ordered_quantity
6795                               and bcol.inventory_item_id = oel.inventory_item_id
6796                           )
6797                       AND oel.top_model_line_id is not null
6798                       AND oel.ato_line_id = p_bcol_line_id
6799                       AND oel.item_type_code <>'CONFIG'
6800                       AND oel.ordered_quantity > 0  ) -- Added this condition to take care of cancel line cases.
6801                     UNION
6802                     (Select 1
6803                     from bom_cto_order_lines bcol
6804                     Where not exists
6805                           ( Select oel.line_id,
6806                                    oel.ordered_quantity,
6807                                    oel.inventory_item_id
6808                               from oe_order_lines_all oel
6809                              where oel.ato_line_id = p_bcol_line_id
6810                               and oel.line_id = bcol.line_id
6811                               and oel.ordered_quantity = bcol.ordered_quantity
6812                               and oel.inventory_item_id = bcol.inventory_item_id
6813                               and oel.item_type_code <>'CONFIG'
6814                               and oel.ordered_quantity > 0  -- Added this condition to take care of cancel line cases.
6815                           )
6816                       AND bcol.top_model_line_id is not null
6817                       AND bcol.ato_line_id = p_bcol_line_id )) ;
6818 
6819            IF PG_DEBUG <> 0 THEN
6820               oe_debug_pub.add ('validate_oe_data: Symmetric Difference between OEL and BCOL did return rows .');
6821            END IF;
6822 
6823 
6824            v_oe_bcol_diff := 'Y' ;
6825 
6826      exception
6827      when no_data_found then
6828 
6829            IF PG_DEBUG <> 0 THEN
6830               oe_debug_pub.add ('validate_oe_data: Symmetric Difference between OEL and BCOL did not return any rows .');
6831            END IF;
6832 
6833      when others then
6834 
6835            IF PG_DEBUG <> 0 THEN
6836               oe_debug_pub.add ('validate_oe_data: Symmetric Difference between OEL and BCOL did result in error .' || SQLCODE );
6837               oe_debug_pub.add ('validate_oe_data: Symmetric Difference between OEL and BCOL did result in error .' || SQLERRM );
6838            END IF;
6839 
6840            v_oe_bcol_diff := 'Y' ;
6841 
6842 
6843      end ;
6844 
6845 
6846     if( v_oe_bcol_diff = 'Y' ) then
6847            IF PG_DEBUG <> 0 THEN
6848               oe_debug_pub.add ('validate_oe_data: data in BCOL and OE_ORDER_LINES_ALL does not match' , 1);
6849            END IF;
6850            raise FND_API.G_EXC_UNEXPECTED_ERROR;
6851     end if;
6852 
6853 
6854 
6855 
6856 
6857   exception
6858      when OTHERS then
6859         x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
6860         oe_debug_pub.add('validate_oe_data: ' || 'validate_oe_data::others:: '||sqlerrm,1);
6861 
6862 
6863   end validate_oe_data ;
6864 
6865     /* end bugfix 4044709 */
6866 
6867 --
6868 -- bugfix 4227993: added private function get_lock_handle.
6869 -- This function allocates a unique user lock handle.
6870 --
6871 --
6872 -- bug 7203643
6873 -- changed the hash value variable type to varchar2
6874 -- ntungare
6875 --
6876 FUNCTION get_lock_handle (
6877 	 p_hash_string   IN VARCHAR2) RETURN VARCHAR2 IS
6878 
6879    PRAGMA AUTONOMOUS_TRANSACTION;
6880    l_lock_handle VARCHAR2(128);
6881    l_lock_name   VARCHAR2(30);
6882 BEGIN
6883 
6884    l_lock_name := 'CTO_' || p_hash_string;
6885    --
6886    -- bug 7203643
6887    -- added expiration seconds equal to 1 day instead of
6888    -- the default 10 days
6889    -- ntungare
6890    --
6891    dbms_lock.allocate_unique(
6892 	 lockname	 => utl_raw.cast_to_raw(l_lock_name)
6893 	,lockhandle	 => l_lock_handle
6894         ,expiration_secs => 86400);
6895    return l_lock_handle;
6896 
6897 END get_lock_handle;
6898 
6899 --
6900 -- bugfix 4227993: added public procedure lock_for_match.
6901 --
6902 -- This procedure performs the following steps:
6903 -- 1. Builds up a string to uniquely identify a configuration in BAC
6904 -- 2. For large configurations, it gets the 1st and the last 50-components (hardcoded) and
6905 --    appends it to the count of optional components selected.
6906 -- 3. Get the hash-value of this string and then get the user-lock handle by calling
6907 --    the above function get_lock_handle.
6908 -- 4. If lock cannot be acquired, it is possible that some other process is processing
6909 --    the same configuration (although for a different order-line). In this case,
6910 --    it will just wait until the other process commits.
6911 -- 5. If a deadlock or other internal error occurs, lock_status is accordingly set and
6912 --    passed to the calling program.
6913 --
6914 -- bug 7203643
6915 -- changed the hash value variable type to varchar2
6916 -- ntungare
6917 --
6918 PROCEDURE lock_for_match(
6919 		x_return_status	OUT nocopy varchar2,
6920         	xMsgCount       OUT nocopy number,
6921         	xMsgData        OUT nocopy varchar2,
6922 		x_lock_status	OUT nocopy number,
6923     		x_hash_value	OUT nocopy varchar2,
6924 		p_line_id	IN  number)
6925 IS
6926 
6927     g_hash_base 	number := 1;
6928     g_hash_size 	number := power(2, 25);
6929 
6930     l_lock_handle 	varchar2(128);
6931 
6932     -- Hardcode the COMPARESIZE to 50. We decided not to go with a profile as it is
6933     -- technical in nature and we thought its an overkill.
6934 
6935     COMPARESIZE	number := 50;
6936     str			varchar2(2000);
6937     j			number;
6938     loop_limit		number;
6939 
6940     type l_comp_item_id_tab 	is TABLE OF number index by binary_integer;
6941     l_comp_item_id  		l_comp_item_id_tab;
6942 
6943 
6944     cursor c1 is
6945        select  nvl(decode(bcolOptions.line_id, bcolModel.line_id, bcolOptions.inventory_item_id,
6946                                                                   bcolOptions.config_item_id),
6947                    bcolOptions.inventory_item_id) COMPONENT_ITEM_ID
6948        from
6949                bom_cto_order_lines_gt bcolModel,       -- Model  /* sushant made changes for bug 4341156 */
6950                bom_cto_order_lines_gt bcolOptions      -- Options /* sushant made changes for bug 4341156 */
6951         where  bcolModel.line_id = p_line_id
6952         and    (bcolOptions.parent_ato_line_id = bcolModel.line_id or
6953                 bcolOptions.line_id = bcolModel.line_id)
6954 	order by 1;
6955 
6956 BEGIN
6957        x_return_status := FND_API.G_RET_STS_SUCCESS;
6958        x_lock_status   := 0;
6959        FND_FILE.PUT_LINE(FND_FILE.LOG, 'Lock_For_Match Start Time: '||to_char(sysdate , 'MM/DD/YYYY HH24:MI:SS'));
6960 
6961        OPEN c1;
6962        FETCH c1 BULK COLLECT INTO l_comp_item_id;
6963 
6964        if l_comp_item_id.count = 0 then
6965 	-- This situation should never arise. If it does, raise error.
6966 	     oe_debug_pub.add ('l_comp_item_id.count = 0. Raising error..');
6967 	     raise FND_API.G_EXC_UNEXPECTED_ERROR;
6968        end if;
6969 
6970        IF PG_DEBUG <> 0 THEN
6971           oe_debug_pub.add ('Number of records selected = '|| l_comp_item_id.count);
6972           oe_debug_pub.add ('COMPARESIZE = '|| COMPARESIZE);
6973        END IF;
6974 
6975        if (l_comp_item_id.count > COMPARESIZE) then
6976 	-- Get the first N components
6977 	  for i in 1 .. COMPARESIZE
6978 	  loop
6979 	     str := str || l_comp_item_id(i);
6980    	     IF PG_DEBUG <> 0 THEN
6981 	        oe_debug_pub.add (' str = '||str);
6982 	     END IF;
6983 	     if (i < COMPARESIZE) then
6984 	        str := str || '-';	-- Append "-" for each value.
6985 	     end if;
6986 	  end loop;
6987 
6988 	  str := str || '***';	-- Append "***" between directions
6989 
6990 	-- Get the last N components
6991           j := l_comp_item_id.count;
6992  	  loop_limit := j - COMPARESIZE;
6993 
6994           while (j <> loop_limit)
6995           loop
6996 	     str := str || l_comp_item_id(j);
6997    	     IF PG_DEBUG <> 0 THEN
6998 	        oe_debug_pub.add (' str = '||str);
6999 	     END IF;
7000              j := j - 1;
7001 	     if (j <> loop_limit) then
7002 		  str := str || '-';
7003 	     end if;
7004    	  end loop;
7005 
7006        elsif (l_comp_item_id.count > 0 and l_comp_item_id.count < COMPARESIZE) then
7007 	-- Get all the components
7008 	  for i in 1 .. l_comp_item_id.count
7009 	  loop
7010 	     str := str || l_comp_item_id(i);
7011    	     IF PG_DEBUG <> 0 THEN
7012 	        oe_debug_pub.add (' str = '||str);
7013 	     END IF;
7014 	     if (i < l_comp_item_id.count) then
7015 	        str := str || '-';	-- Append "-" for each value.
7016 	     end if;
7017 	  end loop;
7018        end if;
7019 
7020 	str := l_comp_item_id.count||'*'||str;
7021 
7022    	IF PG_DEBUG <> 0 THEN
7023 	   oe_debug_pub.add ('str = '|| str);
7024    	END IF;
7025 
7026         --
7027         -- bug 7203643
7028         -- Using the MD5 hashing algorithm to get the hash values
7029         -- ntungare
7030         --
7031 	/*
7032         x_hash_value := dbms_utility.get_hash_value(
7033                                   name => str,
7034                                   base => g_hash_base,
7035                                   hash_size =>g_hash_size );*/
7036 
7037         x_hash_value := DBMS_OBFUSCATION_TOOLKIT.MD5(
7038                                   input_string => str);
7039 
7040    	IF PG_DEBUG <> 0 THEN
7041             -- bug 7203643
7042 	    --oe_debug_pub.add ('x_hash_value = '||x_hash_value);
7043             oe_debug_pub.add ('x_hash_value = '||utl_raw.cast_to_raw(x_hash_value));
7044    	END IF;
7045 
7046 	l_lock_handle := get_lock_handle (p_hash_string => x_hash_value );
7047 
7048    	IF PG_DEBUG <> 0 THEN
7049             -- bug 7203643
7050 	    --oe_debug_pub.add ('x_hash_value = '||x_hash_value);
7051             oe_debug_pub.add ('l_lock_handle = '||l_lock_handle);
7052    	END IF;
7053 
7054         --
7055         -- request lock with release_on_commit TRUE so that we dont have to manually
7056 	-- release the lock later.
7057 	--
7058         x_lock_status := dbms_lock.request(
7059 	   lockhandle	   => l_lock_handle
7060 	  ,lockmode	   => dbms_lock.x_mode
7061 	  ,timeout	   => dbms_lock.maxwait
7062           ,release_on_commit => TRUE);
7063 
7064    	IF PG_DEBUG <> 0 THEN
7065 	   oe_debug_pub.add ('lock_for_match: Returning from lock_for_match.');
7066    	END IF;
7067         FND_FILE.PUT_LINE(FND_FILE.LOG, 'Lock_For_Match End Time: '||to_char(sysdate , 'MM/DD/YYYY HH24:MI:SS'));
7068 
7069 EXCEPTION
7070 
7071    WHEN FND_API.G_EXC_UNEXPECTED_ERROR then
7072       	oe_debug_pub.add('lock_for_match: ' || 'Unexpected Error.');
7073         x_Return_Status := FND_API.G_RET_STS_UNEXP_ERROR;
7074         --  Get message count and data
7075         cto_msg_pub.count_and_get
7076           (  p_msg_count  => xMsgCount
7077            , p_msg_data   => xMsgData
7078              );
7079    WHEN OTHERS then
7080       	oe_debug_pub.add('lock_for_match: ' || 'Others Exception : ' || sqlerrm);
7081         x_Return_Status := FND_API.G_RET_STS_UNEXP_ERROR;
7082         --  Get message count and data
7083         cto_msg_pub.count_and_get
7084           (  p_msg_count  => xMsgCount
7085            , p_msg_data   => xMsgData
7086              );
7087 END;
7088 
7089 
7090 -- bugfix 4227993:
7091 -- Procedure
7092 --   release_lock
7093 -- Description
7094 --   this function releases the user lock on the generated hash-value.
7095 --   Users who call lock_for_match do not always have to call release_lock explicitly.
7096 --   The lock is released automatically at commit, rollback, or session loss.
7097 --
7098 -- bug 7203643
7099 -- changed the hash value variable type to varchar2
7100 -- ntungare
7101 --
7102 PROCEDURE release_lock(
7103      x_return_status        OUT NOCOPY VARCHAR2
7104    , x_msg_count            OUT NOCOPY NUMBER
7105    , x_msg_data             OUT NOCOPY VARCHAR2
7106    , p_hash_value	    IN  VARCHAR2)
7107 
7108 IS
7109    l_return_status        VARCHAR2(1) := fnd_api.g_ret_sts_success;
7110    l_lock_handle          VARCHAR2(128);
7111    l_status               INTEGER;
7112 
7113 
7114 BEGIN
7115 
7116    --validate hash_value
7117    IF (p_hash_value IS NULL) THEN
7118 	--raise error condition
7119 	 oe_debug_pub.add('RELEASE_LOCK: Hash Value is null but required for releasing lock.');
7120          RAISE fnd_api.g_exc_error;
7121    END IF;
7122 
7123 
7124    --get lock handle by calling helper function
7125    l_lock_handle := get_lock_handle( p_hash_string   => p_hash_value);
7126 
7127 
7128    l_status := dbms_lock.release(l_lock_handle);
7129 
7130    --if success (status = 0) or session does not own lock (status=4),
7131    -- 	do nothing
7132    --if parameter error or illegal lock handle (internal error)
7133    if l_status IN (3,5) THEN
7134       cto_msg_pub.cto_message('BOM','BOM_LOCK_RELEASE_ERROR');
7135       RAISE fnd_api.g_exc_error;
7136    end if;
7137 
7138    x_return_status := l_return_status;
7139 
7140 EXCEPTION
7141 
7142    WHEN fnd_api.g_exc_error THEN
7143       	oe_debug_pub.add('release_lock: ' || 'expected error');
7144         x_return_status := fnd_api.g_ret_sts_error;
7145 
7146    WHEN fnd_api.g_exc_unexpected_error THEN
7147       	oe_debug_pub.add('release_lock: ' || 'Unexpected error');
7148         x_return_status := fnd_api.g_ret_sts_unexp_error ;
7149 
7150     WHEN OTHERS THEN
7151       	oe_debug_pub.add('release_lock: ' || 'Others Exception : ' || sqlerrm);
7152         x_return_status := fnd_api.g_ret_sts_unexp_error ;
7153 
7154 END release_lock;
7155 
7156 
7157 
7158 
7159 /*******************************************************************************************
7160 -- API name : get_resv_qty
7161 -- Type     : Public
7162 -- Pre-reqs : None.
7163 -- Function : Given config/ato item Order line id  it returns
7164 --            the supply details tied to this line in a record structure. Also, it return the
7165               total supply qty in primary uom and pass the primary uom code to the calling module.
7166 -- Parameters:
7167 -- IN       : p_order_line_id     Expects the config/ato item order line       Required
7168 --
7169 -- OUT      : x_rsv_rec           Record strcutre with each supply type
7170                                   and supply qty in primary uom
7171               x_primary_uom_code  Primary uom code of the order line's
7172                                   inventory item id .
7173               x_sum_rsv_qty       Sum of supply quantities tied to the
7174                                   order line in primary uom.
7175               x_return_status     Standard error message status
7176               x_msg_count         Std. error message count in the message stack
7177               x_msg_data          Std. error message data in the message stack
7178 -- Version  :
7179 --
7180 --
7181 ******************************************************************************************/
7182 
7183 PROCEDURE Get_Resv_Qty
7184                ( p_order_line_id                 NUMBER,
7185                  x_rsv_rec          OUT  NOCOPY  CTO_UTILITY_PK.resv_tbl_rec_type,
7186                  x_primary_uom_code OUT  NOCOPY  VARCHAR2,
7187                  x_sum_rsv_qty      OUT  NOCOPY  NUMBER,
7188                  x_return_status    OUT  NOCOPY  VARCHAR2,
7189                  x_msg_count        OUT  NOCOPY  NUMBER,
7190                  x_msg_data         OUT  NOCOPY  VARCHAR2
7191                 )
7192 IS
7193 
7194 l_index number;
7195 
7196 v_open_flow_qty NUMBER; --OPM and Ireq
7197 i number;
7198 lStmtNum number;
7199 k        number;
7200 l        number;
7201 l_message VARCHAR2(200);
7202 l_source_document_type_id    number;
7203 
7204 --Bugfix 13554996: New variables
7205 l_conv_qty_lot_level  number;
7206 l_conv_qty_item_level number;
7207 l_item_id mtl_system_items_kfv.inventory_item_id%type;
7208 l_order_uom_code oe_order_lines_all.order_quantity_uom%type;
7209 
7210 --This gets the reservation_qty and the type of reservation
7211 -- Modified by Renga Kannan on 06/24/05 for Cross Dock project
7212 -- getting reservation qty for ASN, Internal req and Receiving supply types also
7213 -- Also, getting the primary UOM
7214 
7215 CURSOR c_resv IS
7216   select sum(nvl(primary_reservation_quantity,0)) primary_reservation_quantity,--bugfix2466429
7217          sum(nvl(reservation_quantity,0)) secondary_reservation_quantity, --OPM
7218          supply_source_type_id,
7219          --Bugfix 13554996
7220          lot_number,
7221          max(organization_id) organization_id
7222   from   mtl_reservations
7223   where  demand_source_type_id = decode (l_source_document_type_id, 10,
7224                                          inv_reservation_global.g_source_type_internal_ord,
7225                                          inv_reservation_global.g_source_type_oe )      -- bugfix 1799874
7226   and    demand_source_line_id = p_order_line_id
7227   and    supply_source_type_id IN
7228                                  ( inv_reservation_global.g_source_type_inv,
7229                                    inv_reservation_global.g_source_type_wip,
7230                                    inv_reservation_global.g_source_type_po,
7231                                    inv_reservation_global.g_source_type_req,
7232                                    inv_reservation_global.g_source_type_internal_req,
7233                                    inv_reservation_global.g_source_type_asn,
7234                                    inv_reservation_global.g_source_type_rcv
7235                                   )
7236   group by supply_source_type_id,
7237            lot_number;  --Bugfix 13554996
7238 
7239  --opm and ireq
7240  l_ext_req_qty            number;
7241  l_int_req_qty            number;
7242  l_ext_req_secondary_qty  Number;
7243  l_int_req_secondary_qty  Number;
7244 
7245  -- Bugfix 16236435
7246  l_routing_type           bom_operational_routings.cfm_routing_flag%type;
7247 
7248 BEGIN
7249 
7250       x_return_status := FND_API.G_RET_STS_SUCCESS;
7251       --need this for flow and interface data alone
7252 
7253       -- Bugfix 16236435: Modifying this sql to get routing type for the item.
7254       -- This is needed to determine if the GET_FLOW_QUANTITY() API needs to
7255       -- be called.
7256 
7257       --Bugfix 13554996: Adding order_quantity_uom and item_id.
7258       -- Select msi.primary_uom_code,
7259       --        oel.order_quantity_uom,
7260       --        oel.inventory_item_id
7261       --   into   x_primary_uom_code,
7262       --          l_order_uom_code,
7263       --          l_item_id
7264       --   from   mtl_system_items msi,
7265       --          oe_order_lines_all oel
7266       --   where  msi.inventory_item_id = oel.inventory_item_id
7267       --   and    msi.organization_id   = oel.ship_from_org_id
7268       --   and    oel.line_id = p_order_line_id; --bugfix 4557050
7269 
7270       Select msi.primary_uom_code,
7271              oel.order_quantity_uom,
7272              oel.inventory_item_id,
7273              Nvl(cfm_routing_flag, 2)
7274       into x_primary_uom_code,
7275            l_order_uom_code,
7276            l_item_id,
7277            l_routing_type
7278       from mtl_system_items msi,
7279            oe_order_lines_all oel,
7280            bom_operational_routings bor
7281       where msi.inventory_item_id = oel.inventory_item_id
7282         and msi.organization_id   = oel.ship_from_org_id
7283         and oel.line_id = p_order_line_id
7284         and oel.inventory_item_id = bor.assembly_item_id(+)
7285         and oel.ship_from_org_id = bor.organization_id(+)
7286         and bor.alternate_routing_designator(+) IS null;
7287 
7288       IF PG_DEBUG <> 0 THEN
7289              oe_debug_pub.add('get_resv_qty: ' || 'Entered get_resv_qty', 1);
7290              l_message := 'Entered get_rsv_qty_code';
7291              cto_wip_workflow_api_pk.cto_debug('get_resv_qty:', l_message);
7292              oe_debug_pub.add('get_resv_qty: ' || 'Before cursor c_resv', 5);
7293              l_message := 'Before cursor c_resv';
7294              cto_wip_workflow_api_pk.cto_debug('get_resv_qty:', l_message);
7295 
7296              --Bugfix 13554996: New messages
7297              oe_debug_pub.add('get_resv_qty: x_primary_uom_code::' || x_primary_uom_code, 1);
7298              oe_debug_pub.add('get_resv_qty: l_order_uom_code::' || l_order_uom_code, 1);
7299              oe_debug_pub.add('get_resv_qty: l_item_id::' || l_item_id, 1);
7300              oe_debug_pub.add('get_resv_qty: l_routing_type::' || l_routing_type, 1);
7301       END IF;
7302 
7303       l_source_document_type_id := CTO_UTILITY_PK.get_source_document_id ( pLineId => p_order_line_id );
7304 
7305       lStmtNum := 10;
7306       FOR cur_var in c_resv
7307       LOOP
7308         IF PG_DEBUG <> 0 THEN
7309              oe_debug_pub.add('get_resv_qty:'||'source_id=>' || cur_var.supply_source_type_id, 5);
7310              l_message := 'source_id=>'|| cur_var.supply_source_type_id;
7311              cto_wip_workflow_api_pk.cto_debug('get_resv_qty:', l_message);
7312 
7313              oe_debug_pub.add('get_resv_qty:'||'prim_rsv_qty=>' || cur_var.primary_reservation_quantity, 5);
7314              l_message := 'rsv_qty=>' || cur_var.primary_reservation_quantity;
7315              cto_wip_workflow_api_pk.cto_debug('get_resv_qty:', l_message);
7316 
7317              oe_debug_pub.add('get_resv_qty:'||'sec_rsv_qty=>' || cur_var.secondary_reservation_quantity, 5);
7318              l_message := 'sec_rsv_qty=>' || cur_var.secondary_reservation_quantity;
7319              cto_wip_workflow_api_pk.cto_debug('get_resv_qty:', l_message);
7320 
7321              --Bugfix 13554996: New debug messages.
7322              oe_debug_pub.add('get_resv_qty:'||'lot_num=>' || cur_var.lot_number, 5);
7323              l_message := 'lot_num=>' || cur_var.lot_number;
7324              cto_wip_workflow_api_pk.cto_debug('get_resv_qty:', l_message);
7325 
7326              oe_debug_pub.add('get_resv_qty:'||'organization_id=>' || cur_var.organization_id, 5);
7327              l_message := 'organization_id=>' || cur_var.organization_id;
7328              cto_wip_workflow_api_pk.cto_debug('get_resv_qty:', l_message);
7329 
7330         END IF;
7331 
7332         l_index := cur_var.supply_source_type_id;
7333 
7334         --Begin Bugfix 13554996
7335         --Check if lot information exists. If it exists, we need a double conversion.
7336         if cur_var.lot_number is null then
7337           lStmtNum := 12;
7338           l_conv_qty_item_level := cur_var.primary_reservation_quantity;
7339         else
7340           --Double convert cur_var.primary_reservation_quantity using lot and then item level
7341           --conversions before assigning it to x_rsv_rec(l_index).primary_reservation_quantity.
7342 
7343           --Level1 conversion: Primary UOM to Order UOM using lot level conversion.
7344           lStmtNum := 14;
7345           l_conv_qty_lot_level := CTO_UTILITY_PK.convert_uom
7346                                                     (from_uom        => x_primary_uom_code,
7347                                                      to_uom          => l_order_uom_code,
7348                                                      quantity        => cur_var.primary_reservation_quantity,
7349                                                      item_id         => l_item_id,
7350                                                      lot_number      => cur_var.lot_number,
7351                                                      organization_id => cur_var.organization_id);
7352 
7353           IF PG_DEBUG <> 0 THEN
7354             oe_debug_pub.add('get_resv_qty:'||'Level1 conversion:: l_conv_qty_lot_level=>' || l_conv_qty_lot_level, 5);
7355             l_message := 'Level1 conversion:: l_conv_qty_lot_level=>'|| l_conv_qty_lot_level;
7356             cto_wip_workflow_api_pk.cto_debug('get_resv_qty:', l_message);
7357           END IF;
7358 
7359           --Level2 conversion: Order UOM to Primary UOM using item level conversion.
7360           lStmtNum := 16;
7361           l_conv_qty_item_level := CTO_UTILITY_PK.convert_uom
7362                                                     (from_uom        => l_order_uom_code,
7363                                                      to_uom          => x_primary_uom_code,
7364                                                      quantity        => l_conv_qty_lot_level,
7365                                                      item_id         => l_item_id,
7366                                                      lot_number      => NULL,
7367                                                      organization_id => NULL);
7368 
7369           IF PG_DEBUG <> 0 THEN
7370             oe_debug_pub.add('get_resv_qty:'||'Level2 conversion:: l_conv_qty_item_level=>' || l_conv_qty_item_level, 5);
7371             l_message := 'Level2 conversion:: l_conv_qty_item_level=>'|| l_conv_qty_item_level;
7372             cto_wip_workflow_api_pk.cto_debug('get_resv_qty:', l_message);
7373           END IF;
7374         end if;  --cur_var.lot_number is null
7375 
7376         if x_rsv_rec.exists(l_index) then
7377           lStmtNum := 18;
7378           x_rsv_rec(l_index).primary_reservation_quantity   := x_rsv_rec(l_index).primary_reservation_quantity +
7379                                                                l_conv_qty_item_level;
7380           x_rsv_rec(l_index).secondary_reservation_quantity := x_rsv_rec(l_index).secondary_reservation_quantity +
7381                                                                cur_var.secondary_reservation_quantity;
7382         else
7383           lStmtNum := 19;
7384           x_rsv_rec(l_index).supply_source_type_id          := l_index;
7385           x_rsv_rec(l_index).primary_reservation_quantity   := l_conv_qty_item_level;
7386           x_rsv_rec(l_index).secondary_reservation_quantity := cur_var.secondary_reservation_quantity;
7387         end if;  --x_rsv_rec.exists(l_index)
7388         --End Bugfix 13554996
7389       END LOOP;
7390 
7391       IF PG_DEBUG = 5 THEN
7392          oe_debug_pub.add('get_resv_qty:'||'printing rsv source type and qty in loop', 5);
7393          l_message := 'printing rsv source type and qty in loop';
7394          cto_wip_workflow_api_pk.cto_debug('get_resv_qty:', l_message);
7395 
7396          oe_debug_pub.add('get_resv_qty:'||'RSV_SRC_TYP  '||' Prim Quantity '
7397                                                   ||' Sec qunatity ', 5);
7398 
7399          IF x_rsv_rec.count <> 0 THEN
7400            k := x_rsv_rec.first;
7401            WHILE(k is not null)
7402            LOOP
7403              oe_debug_pub.add('get_resv_qty:'||x_rsv_rec(k).supply_source_type_id
7404                                ||' => ' ||x_rsv_rec(k).primary_reservation_quantity
7405                                ||' => ' ||x_rsv_rec(k).secondary_reservation_quantity,5);
7406 
7407              l_message := x_rsv_rec(k).supply_source_type_id
7408                                ||' => ' ||x_rsv_rec(k).primary_reservation_quantity
7409                                ||' => ' ||x_rsv_rec(k).secondary_reservation_quantity;
7410 
7411              cto_wip_workflow_api_pk.cto_debug('get_resv_qty:', l_message);
7412 
7413              k := x_rsv_rec.next(k);
7414            END LOOP;
7415          END IF;
7416       END IF;
7417 
7418       lStmtNum := 20;
7419       -- 3076061  Flow Schedule status : 1 = Open  2 = Closed/Completed
7420 
7421       -- begin bugfix 3174334
7422       -- Since flow does not update the schedule with new line_id when the order line is split, we need
7423       -- to call the following function which will determine the open quantity.
7424       -- If open_qty exists, we should keep the line status in PRODUCTION_OPEN
7425 
7426       --OPM and IREQ (kkonada), get flow open quantity from MRP api
7427       --This would work for both fresh order line and split order line
7428 
7429       -- As per Kiran, Flow API allwasy returns in primary reservation qty.
7430 
7431       -- Bugfix 16236435: Calling this API only if the item has flow routings defined.
7432       if l_routing_type = 1 then
7433         IF PG_DEBUG <> 0 THEN
7434           oe_debug_pub.add('get_resv_qty: Calling GET_FLOW_QUANTITY for line_id::' || p_order_line_id);
7435         END IF;
7436 
7437         v_open_flow_qty :=
7438               MRP_FLOW_SCHEDULE_UTIL.GET_FLOW_QUANTITY( p_demand_source_line     => to_char(p_order_line_id),
7439                                                         p_demand_source_type     => inv_reservation_global.g_source_type_oe,
7440                                                         p_demand_source_delivery => NULL,
7441                                                         p_use_open_quantity      => 'Y');
7442         IF PG_DEBUG <> 0 THEN
7443           oe_debug_pub.add('get_resv_qty:'||'flow open quantity =>' || v_open_flow_qty, 5);
7444         END IF;
7445         -- Added by Renga Kannan on 06/27/05
7446         -- Getting the primary uom code from mtl system items.
7447 
7448         If v_open_flow_qty <> 0 then
7449           -- end bugfix 3174334
7450 
7451           lStmtNum := 25;
7452 
7453           IF PG_DEBUG <> 0 THEN
7454             oe_debug_pub.add('get_resv_qty:'||'adding flow to x_rsv_rec', 5);
7455           END IF;
7456 
7457           --add this to record structure
7458           l_index := CTO_UTILITY_PK.g_source_type_flow;
7459 
7460           --flow qty is not reserved thru inv so cannot consider as reservation_qty
7461           --Hence assigimng the qty to record structure
7462           --Supply source type id is hard coded to in CTOWFAPS as constant
7463           x_rsv_rec(l_index).primary_reservation_quantity           := v_open_flow_qty;
7464           x_rsv_rec(l_index).supply_source_type_id                  := l_index;
7465 
7466         End if; /* v_open_flow_qty */
7467       end if;  -- l_routing_type = 1
7468 
7469       --OPM and Ireq kkonada , get interface data
7470       --added join with oel as part of code review
7471 
7472       lStmtNum := 30;
7473       Select sum(CTO_UTILITY_PK.convert_uom(po.uom_code,x_primary_uom_code,nvl(po.quantity,0),po.item_id)),
7474              sum(nvl(po.secondary_quantity,0))
7475       into   l_ext_req_qty,
7476              l_ext_req_secondary_qty
7477       from   po_requisitions_interface_all po,
7478              oe_order_lines_all oel
7479       where  po.interface_source_line_id = oel.line_id
7480       and    oel.line_id = p_order_line_id
7481       and    po.item_id = oel.inventory_item_id
7482       and    po.source_type_code = 'VENDOR'
7483       and    po.process_flag is null;
7484 
7485       lStmtNum := 35;
7486       Select sum(CTO_UTILITY_PK.convert_uom(po.uom_code,x_primary_uom_code,nvl(po.quantity,0),po.item_id)),
7487              sum(nvl(po.secondary_quantity,0))
7488       into   l_int_req_qty,
7489              l_int_req_secondary_qty --changed as part of opm code review
7490       from   po_requisitions_interface_all po,
7491              oe_order_lines_all oel
7492       where  po.interface_source_line_id = oel.line_id
7493       and    oel.line_id = p_order_line_id
7494       and    po.item_id = oel.inventory_item_id
7495       and    po.source_type_code = 'INVENTORY'
7496       and    po.process_flag is null;
7497 
7498 
7499       --add external and internal req intf data to record struc
7500       If l_ext_req_qty is not null then
7501         lStmtNum := 40;
7502         l_index := CTO_UTILITY_PK.g_source_type_ext_req_if;
7503         x_rsv_rec(l_index).primary_reservation_quantity           := l_ext_req_qty;
7504         x_rsv_rec(l_index).secondary_reservation_quantity         := l_ext_req_secondary_qty;
7505         x_rsv_rec(l_index).supply_source_type_id                  := l_index;
7506       end if;
7507 
7508       If l_int_req_qty is not null then
7509         lStmtNum := 45;
7510         l_index := CTO_UTILITY_PK.g_source_type_int_req_if;
7511         x_rsv_rec(l_index).primary_reservation_quantity           := l_int_req_qty;
7512         x_rsv_rec(l_index).secondary_reservation_quantity         := l_int_req_secondary_qty;
7513         x_rsv_rec(l_index).supply_source_type_id                  := l_index;
7514       end if;
7515 
7516       lStmtNum := 50;
7517       x_sum_rsv_qty := 0;
7518       i := x_rsv_rec.first;
7519       WHILE(i is not null)
7520       LOOP
7521         x_sum_rsv_qty :=  x_sum_rsv_qty + x_rsv_rec(i).primary_reservation_quantity;
7522         i := x_rsv_rec.next(i);
7523       END LOOP;
7524 
7525 
7526 EXCEPTION
7527    WHEN fnd_api.g_exc_error THEN
7528         IF PG_DEBUG <> 0 THEN
7529                 oe_debug_pub.add('get_resv_qty: ' || 'Exception in stmt num: '
7530                                     || to_char(lStmtNum), 1);
7531         END IF;
7532         x_return_status := FND_API.G_RET_STS_ERROR;
7533         --  Get message count and data
7534         cto_msg_pub.count_and_get
7535           (  p_msg_count => x_msg_count
7536            , p_msg_data  => x_msg_data
7537            );
7538    WHEN fnd_api.g_exc_unexpected_error THEN
7539         IF PG_DEBUG <> 0 THEN
7540                 oe_debug_pub.add('get_resv_qty: '|| ' Unexpected Exception in stmt num: '
7541                                        || to_char(lStmtNum), 1);
7542        END IF;
7543         x_return_status := FND_API.G_RET_STS_UNEXP_ERROR ;
7544         --  Get message count and data
7545         cto_msg_pub.count_and_get
7546           (  p_msg_count => x_msg_count
7547            , p_msg_data  => x_msg_data
7548            );
7549    WHEN OTHERS then
7550         oe_debug_pub.add('errmsg'||sqlerrm);
7551        IF PG_DEBUG <> 0 THEN
7552 
7553                 oe_debug_pub.add('get_resv_qty: ' || 'Others Exception in stmt num: '
7554                                     || to_char(lStmtNum), 1);
7555        END IF;
7556         x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
7557         --  Get message count and data
7558         cto_msg_pub.count_and_get
7559           (  p_msg_count => x_msg_count
7560            , p_msg_data  => x_msg_data
7561            );
7562 END Get_Resv_Qty;
7563 
7564 END CTO_UTILITY_PK;