DBA Data[Home] [Help]

PACKAGE BODY: APPS.CTO_UTILITY_PK

Source


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