DBA Data[Home] [Help]

PACKAGE BODY: APPS.ENG_CHANGE_LIFECYCLE_UTIL

Source


1 PACKAGE BODY ENG_CHANGE_LIFECYCLE_UTIL AS
2 /* $Header: ENGULCMB.pls 120.39.12020000.4 2013/03/05 06:46:29 jewen ship $ */
3 
4   -- ---------------------------------------------------------------------------
5   -- Global variables and constants
6   -- ---------------------------------------------------------------------------
7   G_PKG_NAME                VARCHAR2(30) := 'ENG_CHANGE_LIFECYCLE_UTIL';
8 
9   -- For Debug
10   g_debug_flag            BOOLEAN       := FALSE ;
11   g_output_dir            VARCHAR2(240) := NULL ;
12   g_debug_filename        VARCHAR2(200) := NULL ;
13   g_debug_errmesg         VARCHAR2(240);
14   G_BO_IDENTIFIER         VARCHAR2(30) := 'ENG_CHANGE_LC_UTIL';
15   G_ERRFILE_PATH_AND_NAME VARCHAR2(10000);
16   g_profile_debug_option  VARCHAR2(10) ;
17   g_profile_debug_level   VARCHAR2(10) ;
18 
19 
20   -- ---------------------------------------------------------------------------
21   -- Global cursors
22   -- ---------------------------------------------------------------------------
23 
24 
25   /********************************************************************
26   * Debug APIs    : Open_Debug_Session, Close_Debug_Session,
27   *                 Write_Debug
28   * Parameters IN :
29   * Parameters OUT:
30   * Purpose       : These procedures are for test and debug
31   *********************************************************************/
32 
33   ----------------------------------------------------------
34   -- Internal procedure to open Debug Session.            --
35   ----------------------------------------------------------
36   -- Open_Debug_Session
37   PROCEDURE Open_Debug_Session
38   (  p_output_dir IN VARCHAR2 := NULL
39   ,  p_file_name  IN VARCHAR2 := NULL
40   )
41   IS
42 
43     CURSOR c_get_utl_file_dir IS
44        SELECT VALUE
45         FROM V$PARAMETER
46         WHERE NAME = 'utl_file_dir';
47 
48     --local variables
49     l_found                NUMBER;
50   -- Bug 	13074883 swuppala : Modified the datatype with the database column datatype
51     l_log_output_dir        v$parameter.value%type;
52     l_log_return_status    VARCHAR2(99);
53     l_errbuff              VARCHAR2(2000);
54 
55   BEGIN
56 
57 
58     -- Ignore open_debug_session call if package debugging mode is already ON
59     IF ( g_debug_flag AND Error_Handler.Get_Debug = 'Y' ) THEN
60       RETURN ;
61     END IF ;
62 
63     l_found := 0 ;
64     Error_Handler.initialize();
65     Error_Handler.set_bo_identifier(G_BO_IDENTIFIER);
66 
67     ---------------------------------------------------------------------------------
68     -- Open_Debug_Session should set the value
69     -- appropriately, so that when the Debug Session is successfully opened :
70     -- will return Error_Handler.Get_Debug = 'Y', else Error_Handler.Get_Debug = 'N'
71     ---------------------------------------------------------------------------------
72 
73     IF p_output_dir IS NOT NULL THEN
74         g_output_dir := p_output_dir ;
75     END IF;
76 
77     IF p_file_name IS NOT NULL THEN
78         g_debug_filename := p_file_name ;
79     END IF;
80 
81     OPEN c_get_utl_file_dir;
82     FETCH c_get_utl_file_dir INTO l_log_output_dir;
83 
84     IF c_get_utl_file_dir%FOUND THEN
85 
86       IF g_output_dir IS NOT NULL
87       THEN
88          l_found := INSTR(l_log_output_dir, g_output_dir);
89          IF l_found = 0
90          THEN
91              g_output_dir := NULL ;
92          END IF;
93       END IF;
94 
95       ------------------------------------------------------
96       -- Trim to get only the first directory in the list --
97       ------------------------------------------------------
98       IF INSTR(l_log_output_dir,',') <> 0 THEN
99         l_log_output_dir := SUBSTR(l_log_output_dir, 1, INSTR(l_log_output_dir, ',') - 1);
100       END IF;
101 
102 
103       IF g_output_dir IS NULL
104       THEN
105          g_output_dir := l_log_output_dir ;
106       END IF ;
107 
108 
109       IF g_debug_filename IS NULL
110       THEN
111           g_debug_filename := G_BO_IDENTIFIER ||'_' || to_char(sysdate, 'DDMONYYYY_HH24MISS')||'.log';
112       END IF ;
113 
114       -----------------------------------------------------------------------
115       -- To open the Debug Session to write the Debug Log.                 --
116       -- This sets Debug value so that Error_Handler.Get_Debug returns 'Y' --
117       -----------------------------------------------------------------------
118       Error_Handler.Open_Debug_Session(
119         p_debug_filename   => g_debug_filename
120        ,p_output_dir       => g_output_dir
121        ,x_return_status    => l_log_return_status
122        ,x_error_mesg       => l_errbuff
123        );
124 
125       FND_FILE.put_line(FND_FILE.LOG, 'Log file location --> '||l_log_output_dir||'/'||g_debug_filename ||' created with status '|| l_log_return_status);
126 
127       IF (l_log_return_status <> FND_API.G_RET_STS_SUCCESS)
128       THEN
129          FND_FILE.put_line(FND_FILE.LOG, 'Unable to open error log file. Error => '||l_errbuff) ;
130       END IF;
131 
132     END IF; --IF c_get_utl_file_dir%FOUND THEN
133     -- Bug : 4099546
134     CLOSE c_get_utl_file_dir;
135 
136     -- Set Global Debug Flag
137 
138     g_debug_flag := TRUE ;
139 
140   EXCEPTION
141       WHEN OTHERS THEN
142          g_debug_errmesg := Substr(To_Char(SQLCODE)||'/'||SQLERRM,1,240);
143          FND_FILE.put_line(FND_FILE.LOG, G_PKG_NAME || ' Open_Debug_Session LOGGING SQL ERROR => '||g_debug_errmesg);
144          g_debug_flag := FALSE;
145   END Open_Debug_Session ;
146 
147 
148    -----------------------------------------------------------
149    -- Open the Debug Session, conditionally if the profile: --
150    -- INV Debug Trace is set to TRUE                        --
151    -----------------------------------------------------------
152   PROCEDURE Check_And_Open_Debug_Session
153   (  p_debug_flag IN VARCHAR2
154   ,  p_output_dir IN VARCHAR2 := NULL
155   ,  p_file_name  IN VARCHAR2 := NULL
156   )
157   IS
158 
159 
160   BEGIN
161     ----------------------------------------------------------------
162     -- Open the Debug Log Session, p_debug_flag is TRUE or
163     -- if Profile is set to TRUE: INV_DEBUG_TRACE Yes, INV_DEBUG_LEVEL 20
164     ----------------------------------------------------------------
165     g_profile_debug_option := NVL(FND_PROFILE.VALUE('INV_DEBUG_TRACE'), TO_CHAR(0));
166     g_profile_debug_level := NVL(FND_PROFILE.VALUE('INV_DEBUG_LEVEL'), TO_CHAR(0));
167 
168     IF (g_profile_debug_option = '1' AND TO_NUMBER(g_profile_debug_level) >= 20)
169        OR FND_API.to_Boolean(p_debug_flag)
170     THEN
171 
172        ----------------------------------------------------------------------------------
173        -- Opens Error_Handler debug session, only if Debug session is not already open.
174        -- Suggested by RFAROOK, so that multiple debug sessions are not open PER
175        -- Concurrent Request.
176        ----------------------------------------------------------------------------------
177        IF (Error_Handler.Get_Debug <> 'Y') THEN
178 
179 FND_FILE.put_line(FND_FILE.LOG, G_PKG_NAME || ' Error_Handler.Get_Debug is not Y, calling Open_Debug_Session  ');
180          Open_Debug_Session(p_output_dir => p_output_dir, p_file_name => p_file_name) ;
181        END IF;
182 
183     END IF;
184 
185   EXCEPTION
186       WHEN OTHERS THEN
187          g_debug_errmesg := Substr(To_Char(SQLCODE)||'/'||SQLERRM,1,240);
188          FND_FILE.put_line(FND_FILE.LOG, G_PKG_NAME || ' Check_And_Open_Debug_Session LOGGING SQL ERROR => '||g_debug_errmesg);
189          g_debug_flag := FALSE;
190   END Check_And_Open_Debug_Session;
191 
192   -- Close Debug_Session
193   PROCEDURE Close_Debug_Session
194   IS
195   BEGIN
196 
197        -----------------------------------------------------------------------------
198        -- Close Error_Handler debug session, only if Debug session is already open.
199        -----------------------------------------------------------------------------
200        IF (Error_Handler.Get_Debug = 'Y') THEN
201 
202 FND_FILE.put_line(FND_FILE.LOG, G_PKG_NAME || ' Error_Handler.Get_Debug is not Y, calling Close_Debug_Session  ');
203          Error_Handler.Close_Debug_Session;
204 
205        END IF;
206 
207        g_debug_flag := FALSE;
208 
209   EXCEPTION
210       WHEN OTHERS THEN
211          g_debug_errmesg := Substr(To_Char(SQLCODE)||'/'||SQLERRM,1,240);
212          FND_FILE.put_line(FND_FILE.LOG, G_PKG_NAME || ' Close_Debug_Session LOGGING SQL ERROR => '||g_debug_errmesg);
213          g_debug_flag := FALSE;
214 
215   END Close_Debug_Session;
216 
217   -- Test Debug
218   PROCEDURE Write_Debug
219   (  p_debug_message      IN  VARCHAR2 )
220   IS
221   BEGIN
222       -- Sometimes Error_Handler.Write_Debug would not write
223       -- the debug message properly
224       -- So as workaround, I added special developer debug mode here
225       -- to write debug message forcedly
226       IF (TO_NUMBER(g_profile_debug_level) = 999)
227       THEN
228         FND_FILE.put_line(FND_FILE.LOG
229                         , G_PKG_NAME
230                           || '['||TO_CHAR(SYSDATE,'DD-MON-YYYY HH24:MI:SS')||'] '
231                           || p_debug_message
232                          );
233 
234       END IF ;
235 
236       Error_Handler.Write_Debug('['||TO_CHAR(SYSDATE,'DD-MON-YYYY HH24:MI:SS')||'] '|| p_debug_message);
237 
238   EXCEPTION
239       WHEN OTHERS THEN
240          g_debug_errmesg := Substr(To_Char(SQLCODE)||'/'||SQLERRM,1,240);
241          FND_FILE.put_line(FND_FILE.LOG, G_PKG_NAME || ' Write_Debug LOGGING SQL ERROR => '||g_debug_errmesg);
242          g_debug_flag := FALSE;
243   END Write_Debug;
244 
245 
246   PROCEDURE Get_Debug_Mode
247   (   p_item_type         IN  VARCHAR2
248    ,  p_item_key          IN  VARCHAR2
249    ,  x_debug_flag        OUT NOCOPY BOOLEAN
250    ,  x_output_dir        OUT NOCOPY VARCHAR2
251    ,  x_debug_filename    OUT NOCOPY VARCHAR2
252   )
253   IS
254 
255       l_debug_flag VARCHAR2(1) ;
256 
257   BEGIN
258 
259       -- Get Debug Flag
260       l_debug_flag := WF_ENGINE.GetItemAttrText
261                               (  p_item_type
262                                , p_item_key
263                                , '.DEBUG_FLAG'
264                                );
265 
266       IF FND_API.to_Boolean( l_debug_flag ) THEN
267          x_debug_flag := TRUE ;
268       END IF;
269 
270       -- Get Debug Output Directory
271       x_output_dir  := WF_ENGINE.GetItemAttrText
272                               (  p_item_type
273                                , p_item_key
274                                , '.DEBUG_OUTPUT_DIR'
275                                );
276 
277       -- Get Debug File Name
278       x_debug_filename := WF_ENGINE.GetItemAttrText
279                               (  p_item_type
280                                , p_item_key
281                                , '.DEBUG_FILE_NAME'
282                                );
283 
284   EXCEPTION
285       WHEN OTHERS THEN
286          g_debug_errmesg := Substr(To_Char(SQLCODE)||'/'||SQLERRM,1,240);
287          g_debug_flag := FALSE;
288 
289 
290   END Get_Debug_Mode ;
291 
292 
293   /********************************************************************
294   * API Type      : Local APIs
295   *********************************************************************/
296   FUNCTION CheckChangeObjApplication
297   ( p_change_id         IN     NUMBER
298   , p_appl_id           IN     NUMBER
299   )
300   RETURN NUMBER
301   IS
302       l_change_obj_appl_id  NUMBER ;
303 
304       CURSOR  c_change_appl_rec (p_change_id NUMBER
305                                 ,p_appl_id   NUMBER)
306       IS
307          SELECT eec.change_id,
308                 eec.change_mgmt_type_code ,
309                 changecategory.base_change_mgmt_type_code,
310                 type_appl.application_id
311           FROM ENG_ENGINEERING_CHANGES eec,
312                ENG_CHANGE_ORDER_TYPES ChangeCategory,
313                ENG_CHANGE_TYPE_APPLICATIONS type_appl
314           WHERE type_appl.change_type_id = ChangeCategory.change_order_type_id
315           and type_appl.application_id = p_appl_id
316           AND ChangeCategory.type_classification = 'CATEGORY'
317           AND ChangeCategory.change_mgmt_type_code = eec.change_mgmt_type_code
318           AND eec.change_id = p_change_id  ;
319 
320   BEGIN
321 
322       FOR l_rec IN c_change_appl_rec (p_change_id => p_change_id ,
323                                       p_appl_id => p_appl_id)
324       LOOP
325           l_change_obj_appl_id :=  l_rec.application_id  ;
326       END LOOP ;
327 
328       RETURN l_change_obj_appl_id ;
329 
330   END CheckChangeObjApplication ;
331 
332 
333 
334   -- Internal utility procedure to check if the header is CO and on its last
335   -- implement phase
336   PROCEDURE Is_CO_On_Last_Imp_Phase
337   (
338     p_change_id                 IN   NUMBER
339    ,p_api_caller                IN   VARCHAR2
340    ,x_is_co_last_phase          OUT  NOCOPY  VARCHAR2
341    --,x_curr_status_code          OUT  NOCOPY  NUMBER
342    --,x_last_status_code          OUT  NOCOPY  NUMBER
343    ,x_auto_demote_status        OUT  NOCOPY  NUMBER
344   )
345   IS
346 
347     l_fnd_user_id        NUMBER := TO_NUMBER(FND_PROFILE.VALUE('USER_ID'));
348     l_fnd_login_id       NUMBER := TO_NUMBER(FND_PROFILE.VALUE('LOGIN_ID'));
349 
350     l_cm_type_code       eng_engineering_changes.CHANGE_MGMT_TYPE_CODE%TYPE;
351     l_base_cm_type_code  eng_change_order_types.BASE_CHANGE_MGMT_TYPE_CODE%TYPE;
352 
353     l_next_status_code   NUMBER;
354 
355     --l_curr_status_code   NUMBER;
356 
357     l_last_status_code   NUMBER;
358     l_max_phase_sn       eng_lifecycle_statuses.sequence_number%TYPE;
359 
360     l_last_imp_flag      VARCHAR2(1) := 'N';
361 
362 
363   BEGIN
364     -- Standard Start of API savepoint
365     --SAVEPOINT  Is_CO_On_Last_Imp_Phase;
366 
367     -- Default return value
368     x_is_co_last_phase := 'F';
369     --x_last_status_code := NULL;
370     --x_curr_status_code := NULL;
371 
372     -- Write debug message if debug mode is on
373     IF g_debug_flag THEN
374        Write_Debug('ENG_CHANGE_LIFECYCLE_UTIL.Is_CO_On_Last_Imp_Phase log');
375        Write_Debug('-----------------------------------------------------');
376        Write_Debug('p_change_id         : ' || p_change_id );
377        Write_Debug('-----------------------------------------------------');
378        Write_Debug('Initializing return status... ' );
379     END IF;
380 
381     -- FND_PROFILE package is not available for workflow (WF),
382     -- therefore manually set WHO column values
383     IF p_api_caller = 'WF' THEN
384       l_fnd_user_id := G_ENG_WF_USER_ID;
385       l_fnd_login_id := G_ENG_WF_LOGIN_ID;
386     ELSIF p_api_caller = 'CP' THEN
387       l_fnd_user_id := G_ENG_CP_USER_ID;
388       l_fnd_login_id := G_ENG_CP_LOGIN_ID;
389     END IF;
390 
391     -- Real code starts here -----------------------------------------------
392 
393     -- Get the change header's cm type, and promote_status_code
394     SELECT eec.change_mgmt_type_code, eec.promote_status_code, --eec.status_code
395            ecot.base_change_mgmt_type_code
396       INTO l_cm_type_code, l_next_status_code, --l_curr_status_code
397            l_base_cm_type_code
398       FROM eng_engineering_changes eec,
399            eng_change_order_types ecot
400       WHERE eec.change_id = p_change_id
401         AND ecot.change_order_type_id = eec.change_order_type_id;
402 
403     --x_curr_status_code := l_curr_status_code;
404 
405     -- If the change header is of type ECO and the current running phase
406     -- is the last implement phase, return true, otherwise false
407     IF (l_base_cm_type_code = G_ENG_ECO OR l_next_status_code IS NOT NULL) THEN
408 
409       IF g_debug_flag THEN
410         Write_Debug('Info: change category is CO, and header promote_status_code is not null' );
411       END IF;
412 
413       -- Get the sequence_number of the last phase
414       -- Note that only phase of IMPLEMENT type can be the last phase
415       SELECT max(sequence_number)
416         INTO l_max_phase_sn
417         FROM eng_lifecycle_statuses
418         WHERE entity_name = G_ENG_CHANGE
419           AND entity_id1 = p_change_id
420           AND active_flag = 'Y';
421 
422       -- Get the sequence number of the last phase
423       SELECT status_code
424         INTO l_last_status_code
425         FROM eng_lifecycle_statuses
426         WHERE entity_name = G_ENG_CHANGE
427           AND entity_id1 = p_change_id
428           AND active_flag = 'Y'
429           AND sequence_number = l_max_phase_sn;
430       /*
431       x_last_status_code := l_last_status_code;
432       */
433 
434       IF ( l_next_status_code = l_last_status_code ) THEN
435         x_is_co_last_phase := 'T';
436       END IF;
437 
438     END IF;
439 
440 
441     -- Standard ending code ------------------------------------------------
442     IF g_debug_flag THEN
443       Write_Debug('x_is_co_last_phase        : ' || x_is_co_last_phase );
444       --Write_Debug('x_curr_status_code        : ' || x_curr_status_code );
445       --Write_Debug('x_last_status_code        : ' || x_last_status_code );
446       Write_Debug('x_auto_demote_status      : ' || x_auto_demote_status );
447       Write_Debug('Finish. End Of procedure: Is_CO_On_Last_Imp_Phase') ;
448     END IF;
449 
450   END Is_CO_On_Last_Imp_Phase;
451 
452 
453   -- Internal utility procedure to check if the header is CO and its last
454   -- implement phase has been used
455   PROCEDURE Is_CO_Last_Imp_Phase_Used
456   (
457     p_change_id                 IN   NUMBER
458    ,x_is_used                   OUT  NOCOPY  VARCHAR2
459    ,x_last_status_type          OUT  NOCOPY  NUMBER
460    ,x_last_status_code          OUT  NOCOPY  NUMBER
461   )
462   IS
463     l_cm_type_code       eng_engineering_changes.CHANGE_MGMT_TYPE_CODE%TYPE;
464     l_base_cm_type_code  eng_change_order_types.BASE_CHANGE_MGMT_TYPE_CODE%TYPE;
465     l_max_phase_sn       eng_lifecycle_statuses.sequence_number%TYPE;
466     l_start_date         eng_lifecycle_statuses.start_date%TYPE;
467   BEGIN
468     -- Standard Start of API savepoint
469     --SAVEPOINT  Is_CO_Last_Imp_Phase_Used;
470 
471     -- Default return value
472     x_is_used := 'F';
473     x_last_status_type := NULL;
474     x_last_status_code := NULL;
475 
476     -- Write debug message if debug mode is on
477     IF g_debug_flag THEN
478        Write_Debug('ENG_CHANGE_LIFECYCLE_UTIL.Is_CO_Last_Imp_Phase_Used log');
479        Write_Debug('-----------------------------------------------------');
480        Write_Debug('p_change_id         : ' || p_change_id );
481        Write_Debug('-----------------------------------------------------');
482        Write_Debug('Initializing return status... ' );
483     END IF;
484 
485     -- Real code starts here -----------------------------------------------
486 
487     -- Get the change header's cm type, and promote_status_code
488     SELECT eec.change_mgmt_type_code, ecot.base_change_mgmt_type_code
489       INTO l_cm_type_code, l_base_cm_type_code
490       FROM eng_engineering_changes eec,
491            eng_change_order_types ecot
492       WHERE eec.change_id = p_change_id
493         AND ecot.change_order_type_id = eec.change_order_type_id;
494 
495     IF (l_base_cm_type_code = G_ENG_ECO) THEN
496 
497       -- Get the sequence_number of the last phase
498       -- Note that only phase of IMPLEMENT type can be the last phase
499       SELECT max(sequence_number)
500         INTO l_max_phase_sn
501         FROM eng_lifecycle_statuses
502         WHERE entity_name = G_ENG_CHANGE
503           AND entity_id1 = p_change_id
504           AND active_flag = 'Y';
505 
506       -- Get the start_date of the last phase (to see if it's been used)
507       SELECT status_code, start_date
508         INTO x_last_status_code, l_start_date
509         FROM eng_lifecycle_statuses
510         WHERE entity_name = G_ENG_CHANGE
511           AND entity_id1 = p_change_id
512           AND active_flag = 'Y'
513           AND sequence_number = l_max_phase_sn
514           AND rownum = 1;
515 
516       IF ( l_start_date IS NOT NULL ) THEN
517         x_is_used := 'T';
518       END IF;
519 
520       -- Get the status_type of the last phase
521       SELECT status_type
522         INTO x_last_status_type
523         FROM eng_change_statuses
524         WHERE status_code = x_last_status_code;
525 
526     END IF;
527 
528 
529     -- Standard ending code ------------------------------------------------
530     IF g_debug_flag THEN
531       Write_Debug('x_is_used            : ' || x_is_used );
532       Write_Debug('x_last_status_type   : ' || x_last_status_type );
533       Write_Debug('x_last_status_code   : ' || x_last_status_code );
534       Write_Debug('Finish. End Of procedure: Is_CO_Last_Imp_Phase_Used') ;
535     END IF;
536 
537   END Is_CO_Last_Imp_Phase_Used;
538 
539 
540 
541   -- Internal procedure to return if a co has active revised items
542   -- active revised items are defined as those with status other than
543   -- 5(cancelled) or 6(implemented)
544   PROCEDURE Has_Active_RevItem
545   (
546     p_change_id                 IN   NUMBER
547    ,x_found                     OUT  NOCOPY VARCHAR2
548   )
549   IS
550     l_rev_item_seq_id    NUMBER;
551     CURSOR c_activeRevItem IS
552       SELECT revised_item_sequence_id
553         FROM eng_revised_items eri
554         WHERE eri.change_id = p_change_id
555           AND eri.status_type NOT IN (G_ENG_CANCELLED, G_ENG_IMPLEMENTED);
556   BEGIN
557     OPEN c_activeRevItem;
558       LOOP
559         FETCH c_activeRevItem INTO l_rev_item_seq_id;
560         IF (c_activeRevItem%FOUND)
561         THEN
562           x_found := 'Y';
563         ELSE
564           x_found := 'N';
565         END IF;
566         EXIT;
567       END LOOP;
568     CLOSE c_activeRevItem;
569 
570   END Has_Active_RevItem;
571 
572   -- Internal utility procedure to update header approval status
573   -- together with launching associated workflow
574   PROCEDURE Update_Header_Appr_Status
575   (
576     p_api_version               IN   NUMBER                             --
577    ,p_init_msg_list             IN   VARCHAR2 := FND_API.G_FALSE        --
578    ,p_commit                    IN   VARCHAR2 := FND_API.G_FALSE        --
579    ,p_validation_level          IN   NUMBER   := FND_API.G_VALID_LEVEL_FULL
580    ,p_debug                     IN   VARCHAR2 := FND_API.G_FALSE        --
581    ,p_output_dir                IN   VARCHAR2 := NULL
582    ,p_debug_filename            IN   VARCHAR2 := NULL
583    ,x_return_status             OUT  NOCOPY  VARCHAR2                   --
584    ,x_msg_count                 OUT  NOCOPY  NUMBER                     --
585    ,x_msg_data                  OUT  NOCOPY  VARCHAR2                   --
586    ,p_change_id                 IN   NUMBER                             -- header's change_id
587    ,p_status_code               IN   NUMBER
588    ,p_appr_status               IN   NUMBER                             -- header approval status
589    ,p_route_status              IN   VARCHAR2                           -- workflow routing status (for document types)
590    ,p_api_caller                IN   VARCHAR2 := 'UI'                   -- must
591    ,p_bypass                    IN   VARCHAR2 := 'N'                    -- flag to bypass phase type check
592    ,x_sfa_line_items_exists     OUT  NOCOPY  VARCHAR2
593   )
594   IS
595     l_api_name           CONSTANT VARCHAR2(30)  := 'Update_Header_Appr_Status';
596     l_api_version        CONSTANT NUMBER := 1.0;
597 
598     l_return_status      VARCHAR2(1);
599     l_msg_count          NUMBER;
600     l_msg_data           VARCHAR2(2000);
601 
602     l_fnd_user_id        NUMBER := TO_NUMBER(FND_PROFILE.VALUE('USER_ID'));
603     l_fnd_login_id       NUMBER := TO_NUMBER(FND_PROFILE.VALUE('LOGIN_ID'));
604 
605     l_updated            BOOLEAN      := FALSE ;
606 
607     l_phase_sn           eng_lifecycle_statuses.sequence_number%TYPE;
608     l_max_appr_phase_sn  eng_lifecycle_statuses.sequence_number%TYPE;
609 
610     l_status_type        eng_engineering_changes.status_type%TYPE;
611 
612     l_wf_item_key        wf_item_activity_statuses.item_key%TYPE := NULL;
613 
614     l_cm_type_code       eng_engineering_changes.change_mgmt_type_code%TYPE;
615     l_base_cm_type_code  eng_change_order_types.BASE_CHANGE_MGMT_TYPE_CODE%TYPE;
616 
617     l_param_list         WF_PARAMETER_LIST_T := WF_PARAMETER_LIST_T();
618 
619     l_appl_id            NUMBER ;
620 
621 
622     l_doc_lc_object_flag BOOLEAN := FALSE ;
623     l_message_list Error_Handler.Error_Tbl_Type;  --added for bug 10128347
624 
625   BEGIN
626     -- Standard Start of API savepoint
627     --SAVEPOINT  Update_Header_Appr_Status;
628     Error_Handler.Initialize;    --added for bug 10128347
629     -- Standard call to check for call compatibility
630     IF NOT FND_API.Compatible_API_Call ( l_api_version
631                                         ,p_api_version
632                                         ,l_api_name
633                                         ,G_PKG_NAME )
634     THEN
635       RAISE FND_API.G_EXC_UNEXPECTED_ERROR;
636     END IF;
637     -- Initialize message list if p_init_msg_list is set to TRUE.
638     IF FND_API.to_Boolean( p_init_msg_list ) THEN
639        FND_MSG_PUB.initialize;
640     END IF;
641 
642     -- For Test/Debug
643     Check_And_Open_Debug_Session(p_debug, p_output_dir, p_debug_filename) ;
644     -- R12 Comment out
645     -- IF FND_API.to_Boolean( p_debug ) THEN
646     --     Open_Debug_Session(p_output_dir, p_debug_filename ) ;
647     -- END IF;
648 
649     -- Write debug message if debug mode is on
650     IF g_debug_flag THEN
651        Write_Debug('ENG_CHANGE_LIFECYCLE_UTIL.Update_Header_Appr_Status log');
652        Write_Debug('-----------------------------------------------------');
653        Write_Debug('p_change_id         : ' || p_change_id );
654        Write_Debug('p_status_code       : ' || p_status_code );
655        Write_Debug('p_appr_status       : ' || p_appr_status );
656        Write_Debug('p_api_caller        : ' || p_api_caller );
657        Write_Debug('p_bypass            : ' || p_bypass );
658        Write_Debug('-----------------------------------------------------');
659        Write_Debug('Initializing return status... ' );
660     END IF;
661 
662     -- Initialize API return status to success
663     x_return_status := FND_API.G_RET_STS_SUCCESS;
664 
665     -- FND_PROFILE package is not available for workflow (WF),
666     -- therefore manually set WHO column values
667     IF p_api_caller = 'WF' THEN
668       l_fnd_user_id := G_ENG_WF_USER_ID;
669       l_fnd_login_id := G_ENG_WF_LOGIN_ID;
670     ELSIF p_api_caller = 'CP' THEN
671       l_fnd_user_id := G_ENG_CP_USER_ID;
672       l_fnd_login_id := G_ENG_CP_LOGIN_ID;
673     END IF;
674 
675 
676     -- Real code starts here -----------------------------------------------
677 
678     -- get phase type
679     SELECT status_type
680       INTO l_status_type
681       FROM eng_change_statuses
682       WHERE status_code = p_status_code;
683 
684      -- Select cm type and base type code for upcoming API calls
685         SELECT eec.change_mgmt_type_code, ecot.base_change_mgmt_type_code
686           INTO l_cm_type_code, l_base_cm_type_code
687           FROM eng_engineering_changes eec,
688                eng_change_order_types ecot
689           WHERE eec.change_id = p_change_id
690           AND ecot.change_order_type_id = eec.change_order_type_id;
691 
692     l_doc_lc_object_flag := ENG_DOCUMENT_UTIL.Is_Dom_Document_Lifecycle
693                                ( p_change_id => p_change_id
694                                , p_base_change_mgmt_type_code => l_base_cm_type_code
695                                )  ;
696     -- update header approval status only for phase of type APPROVAL or REVIEW for Doc
697     IF ( l_status_type = G_ENG_APPROVED OR p_bypass = 'Y'
698          OR (l_doc_lc_object_flag AND l_status_type = G_ENG_REVIEWED)) THEN
699       IF g_debug_flag THEN
700          Write_Debug('Phase type is APPROVAL or p_bypass = ''Y'' (for NIR)');
701       END IF;
702 
703       -- update header approval status
704       IF (p_appr_status = G_ENG_APPR_REQUESTED ) THEN
705         UPDATE eng_engineering_changes
706           SET approval_status_type = p_appr_status,
707               approval_request_date = sysdate,
708               approval_date = null,
709               last_update_date = sysdate,
710               last_updated_by = l_fnd_user_id,
711               last_update_login = l_fnd_login_id
712           WHERE change_id = p_change_id;
713         l_updated := TRUE;
714         IF g_debug_flag THEN
715           Write_Debug('After updating eng_engineering_changes.approval_* columns.');
716           Write_Debug('  Row count = ' || SQL%ROWCOUNT);
717         END IF;
718         IF g_debug_flag THEN
719            Write_Debug('After: updating header approval columns FOR APPROVAL REQUESTED');
720         END IF;
721 
722       ELSIF (p_appr_status = G_ENG_APPR_APPROVED) THEN
723         -- Update header to approved only for the last phase of type APPROVAL
724 
725         -- Get the current phase's sequence number
726         SELECT sequence_number
727           INTO l_phase_sn
728           FROM eng_lifecycle_statuses
729           WHERE entity_name = G_ENG_CHANGE
730             AND entity_id1 = p_change_id
731             AND status_code = p_status_code
732             AND active_flag = 'Y'
733             AND rownum = 1;
734 
735         -- Get the sequence number of the last phase of type APPROVAL
736         SELECT max(lcs.sequence_number)
737           INTO l_max_appr_phase_sn
738           FROM eng_lifecycle_statuses lcs,
739                eng_change_statuses chs
740           WHERE lcs.entity_name = G_ENG_CHANGE
741             AND lcs.entity_id1 = p_change_id
742             AND lcs.active_flag = 'Y'
743             AND chs.status_code = lcs.status_code
744             AND chs.status_type = G_ENG_APPROVED;
745 
746         -- Check if the specified phase is the last phase of type APPROVAL
747         -- Update header approval status if so
748         -- Note for case: p_api_caller is null: previous if condition
749         -- garrantees l_status_type = G_ENG_APPROVED
750         IF ( l_phase_sn = l_max_appr_phase_sn OR (p_api_caller IS NULL) ) THEN
751           IF g_debug_flag THEN
752             Write_Debug('Current phase is the last of such type');
753           END IF;
754 
755           UPDATE eng_engineering_changes
756             SET approval_status_type = p_appr_status,
757                 approval_date = sysdate,
758                 last_update_date = sysdate,
759                 last_updated_by = l_fnd_user_id,
760                 last_update_login = l_fnd_login_id
761             WHERE change_id = p_change_id;
762             l_updated := TRUE;
763           IF g_debug_flag THEN
764             Write_Debug('After updating eng_engineering_changes.approval_* columns.');
765             Write_Debug('  Row count = ' || SQL%ROWCOUNT);
766           END IF;
767           IF g_debug_flag THEN
768              Write_Debug('After: updating header approval columns FOR APPROVED');
769           END IF;
770         END IF;
771 
772       ELSIF (   p_appr_status = G_ENG_APPR_REJECTED
773              OR p_appr_status = G_ENG_APPR_PROC_ERR
774              OR p_appr_status = G_ENG_APPR_TIME_OUT)
775       THEN
776         UPDATE eng_engineering_changes
777           SET approval_status_type = p_appr_status,
778               approval_date = null,
779               last_update_date = sysdate,
780               last_updated_by = l_fnd_user_id,
781               last_update_login = l_fnd_login_id
782           WHERE change_id = p_change_id;
783         l_updated := TRUE;
784         IF g_debug_flag THEN
785           Write_Debug('After updating eng_engineering_changes.approval_* columns.');
786           Write_Debug('  Row count = ' || SQL%ROWCOUNT);
787         END IF;
788         IF g_debug_flag THEN
789            Write_Debug('After: updating header approval columns FOR REJECTED, PROC_ERR, TIME_OUT');
790         END IF;
791 
792        ELSIF  (l_doc_lc_object_flag AND l_status_type = G_ENG_REVIEWED)
793        THEN
794         l_updated := TRUE;
795 	ELSE
796         UPDATE eng_engineering_changes
797           SET approval_status_type = p_appr_status,
798               approval_request_date = null,
799               approval_date = null,
800               last_update_date = sysdate,
801               last_updated_by = l_fnd_user_id,
802               last_update_login = l_fnd_login_id
803           WHERE change_id = p_change_id;
804         l_updated := TRUE;
805         IF g_debug_flag THEN
806           Write_Debug('After updating eng_engineering_changes.approval_* columns.');
807           Write_Debug('  Row count = ' || SQL%ROWCOUNT);
808         END IF;
809         IF g_debug_flag THEN
810            Write_Debug('After: updating header approval columns FOR other approval types');
811         END IF;
812       END IF;
813 
814       -- Since in some cases header approval status won't be updated
815       -- using l_updated flag to skip follow-up code here
816       IF (l_updated = TRUE)
817       THEN
818         -- Select cm type and base type code for upcoming API calls
819         /*SELECT eec.change_mgmt_type_code, ecot.base_change_mgmt_type_code
820           INTO l_cm_type_code, l_base_cm_type_code
821           FROM eng_engineering_changes eec,
822                eng_change_order_types ecot
823           WHERE eec.change_id = p_change_id
824           AND ecot.change_order_type_id = eec.change_order_type_id;*/
825 
826 
827         --
828         -- R12B
829         -- Document Lifecycle Support
830         -- Check if this change object is Document LC Change Object
831         --
832        /* l_doc_lc_object_flag := ENG_DOCUMENT_UTIL.Is_Dom_Document_Lifecycle
833                                ( p_change_id => p_change_id
834                                , p_base_change_mgmt_type_code => l_base_cm_type_code
835                                )  ;*/
836 
837         -- In case of Document LC Change Object, the Approval Status change and
838         -- the event should not be raised
839         IF (NOT l_doc_lc_object_flag)
840         THEN
841             IF g_debug_flag THEN
842                Write_Debug('Before: Approval Status Change WF and Event');
843             END IF;
844 
845 
846             -- Skip workflow notification if approval status is set back to not_submitted
847             IF (p_appr_status <> G_ENG_NOT_SUBMITTED)
848             THEN
849 
850 
851               -- Launch header approval status change workflow
852               IF g_debug_flag THEN
853                  Write_Debug('Before: Launch header approval status change workflow');
854               END IF;
855 
856               Eng_Workflow_Util.StartWorkflow
857               (  p_api_version       => 1.0
858               ,  p_init_msg_list     => FND_API.G_FALSE
859               ,  p_commit            => FND_API.G_FALSE
860               ,  p_validation_level  => FND_API.G_VALID_LEVEL_FULL
861               ,  x_return_status     => l_return_status
862               ,  x_msg_count         => l_msg_count
863               ,  x_msg_data          => l_msg_data
864               ,  p_item_type         => Eng_Workflow_Util.G_CHANGE_ACTION_ITEM_TYPE
865               ,  x_item_key          => l_wf_item_key
866               ,  p_process_name      => Eng_Workflow_Util.G_APPROVAL_STATUS_CHANGE_PROC
867               ,  p_change_id         => p_change_id
868               ,  p_wf_user_id        => l_fnd_user_id
869               ,  p_route_id          => 0 --l_wf_route_id
870               ,  p_debug             => p_debug --FND_API.G_FALSE
871               ,  p_output_dir        => p_output_dir
872               ,  p_debug_filename    => NULL  --p_debug_filename
873               ) ;
874 
875               IF g_debug_flag THEN
876                  Write_Debug('After: Launch header approval status change workflow: ' || l_return_status );
877               END IF;
878 
879               IF ( l_return_status <>  FND_API.G_RET_STS_SUCCESS )
880               THEN
881                 x_return_status := l_return_status;
882                 x_msg_count := l_msg_count;
883                 x_msg_data := l_msg_data;
884                 --#FND_MESSAGE.Set_Name('ENG','ENG_ERROR_CALLING_WF_API');
885                 --#FND_MSG_PUB.Add;
886                 RAISE FND_API.G_EXC_ERROR;
887               END IF;
888               l_wf_item_key := NULL;
889               IF g_debug_flag THEN
890                  Write_Debug('Successful: Launch header approval status change workflow');
891               END IF;
892             END IF;
893 
894 
895             -- Raise the approval status change business event
896             -- Adding event parameters to the list
897             ENG_CHANGE_BES_UTIL.Raise_Appr_Status_Change_Event
898             ( p_change_id         => p_change_id
899              ,p_appr_status       => p_appr_status
900              ,p_wf_route_status   => p_route_status
901              );
902 
903 
904         END IF ; -- Check IF (NOT l_doc_lc_object_flag)
905 
906      --   R12C Enhancement
907      --   When the NIR is demoted to Approval status from a later phase or when the workflow in the Approval phase is aborted
908      --   The Line items have to go through the Item Approval process again
909      --   All the Rejected line items have to be reset to Submitted for Approval / Open
910      --   Approved Items can anyhow be rejected later if required by other workflow assignees
911      IF p_appr_status <> G_ENG_APPR_APPROVED AND p_appr_status <> G_ENG_APPR_REJECTED THEN
912           ENG_NIR_UTIL_PKG.Update_Line_Items_App_St(p_change_id, 3, x_sfa_line_items_exists); -- Reset it to SFA
913      END IF;
914 
915         -- Other calls and updates triggered by the header approval status update
916         -- call item part request API if applicable
917          IF (l_base_cm_type_code = G_ENG_NEW_ITEM_REQ
918 		AND p_appr_status in (G_ENG_APPR_REJECTED, G_ENG_APPR_TIME_OUT) ) THEN
919           IF g_debug_flag THEN
920              Write_Debug('Before: calling new item request API');
921              Write_Debug('  p_change_id =   ' || p_change_id);
922              Write_Debug('  p_appr_status = ' || p_appr_status);
923           END IF;
924          ENG_NIR_UTIL_PKG.set_nir_item_approval_status
925           ( p_change_id          => p_change_id
926            ,p_approval_status    => p_appr_status
927            ,x_return_status      => l_return_status
928            ,x_msg_count          => l_msg_count
929            ,x_msg_data           => l_msg_data
930            );
931 
932           IF g_debug_flag THEN
933              Write_Debug('After: calling new item request API: ' || l_return_status) ;
934           END IF;
935 
936           IF ( l_return_status <>  FND_API.G_RET_STS_SUCCESS )
937           THEN
938             x_return_status := l_return_status;
939             x_msg_count := l_msg_count;
940             x_msg_data := l_msg_data;
941             --#FND_MESSAGE.Set_Name('ENG','ENG_ERROR_CALLING_PS_API');
942             --#FND_MESSAGE.Set_Token('OBJECT_NAME', 'ENG_NIR_UTIL_PKG.set_nir_item_approval_status');
943             --#FND_MSG_PUB.Add;
944             RAISE FND_API.G_EXC_ERROR;
945           END IF;
946           l_wf_item_key := NULL;
947           IF g_debug_flag THEN
948              Write_Debug('Successful: calling new item request API');
949           END IF;
950         END IF;
951 
952         -- Update attachment approval if needed
953         IF g_debug_flag THEN
954           Write_Debug('Before: calling update DM attachment approval/review API');
955         END IF;
956 
957         -- obsolete for bug 3429353 fix
958         -- IF ( p_appr_status <> G_ENG_APPR_APPROVED
959         --    AND (l_base_cm_type_code = G_ENG_ATTACHMENT_APPR
960         --         OR l_base_cm_type_code = G_ENG_ATTACHMENT_REVW)
961         --    )
962         --
963 
964         -- Added condition to call DM attachment approval/review API
965         -- if approval status is REJECTED for Bug4187851
966         -- in order to support
967         -- 6. Document status will get changed to Rejected as soon as the first
968         -- rejection happens in any of the approval workflow in the lifecycle.
969         -- then we will leave the final approval update to
970         -- Update_Lifecycle_States procedure final implement phase handling
971         -- Note:
972         -- This call will be moved to BES Subscription in future release
973         -- In the meantime, we put the call to minimize the code impact
974 
975         IF (   l_base_cm_type_code = G_ENG_ATTACHMENT_APPR
976             OR l_base_cm_type_code = G_ENG_ATTACHMENT_REVW )
977            AND p_appr_status = G_ENG_APPR_REJECTED
978         THEN
979           IF g_debug_flag THEN
980             Write_Debug('In: calling DM attachment approval/review API');
981             Write_Debug('p_workflow_status : ' || p_status_code );
982             Write_Debug('p_approval_status : ' || p_appr_status );
983           END IF;
984           ENG_ATTACHMENT_IMPLEMENTATION.Update_Attachment_Status
985           (
986             p_api_version         => 1.0
987            ,p_init_msg_list       => FND_API.G_FALSE
988            ,p_commit              => FND_API.G_FALSE
989            ,p_validation_level    => p_validation_level
990            ,p_debug               => p_debug --FND_API.G_FALSE
991            ,p_output_dir          => p_output_dir
992            ,p_debug_filename      => NULL  --p_debug_filename
993            ,x_return_status       => l_return_status
994            ,x_msg_count           => l_msg_count
995            ,x_msg_data            => l_msg_data
996            ,p_change_id           => p_change_id
997            ,p_workflow_status     => p_route_status
998            ,p_approval_status     => p_appr_status
999            ,p_api_caller          => p_api_caller
1000           );
1001 
1002           IF g_debug_flag THEN
1003               Write_Debug('After: calling update DM attachment approval/review API: ' || l_return_status) ;
1004           END IF;
1005 
1006 
1007           IF ( l_return_status <>  FND_API.G_RET_STS_SUCCESS ) THEN
1008             x_return_status := l_return_status;
1009             x_msg_count := l_msg_count;
1010             x_msg_data := l_msg_data;
1011             --#FND_MESSAGE.Set_Name('ENG','ENG_ERROR_CALLING_PS_API');
1012             --#FND_MESSAGE.Set_Token('OBJECT_NAME', 'ENG_ATTACHMENT_IMPLEMENTATION.Update_Attachment_Status');
1013             --#FND_MSG_PUB.Add;
1014             RAISE FND_API.G_EXC_ERROR;
1015           END IF;
1016         END IF;
1017 
1018 
1019         -- AMW/ICM Application to Application integration calls
1020         -- triggered by the header approval status update
1021         -- call ENG_ICMDB_APIS_UTIL.Update_Approval_Status if applicable
1022 
1023         l_appl_id := CheckChangeObjApplication( p_change_id => p_change_id ,
1024                                                 p_appl_id => 242 -- AMW Applciation ID
1025                                               )  ;
1026 
1027         IF  (l_appl_id IS NOT NULL)
1028         THEN
1029           IF g_debug_flag THEN
1030              Write_Debug('Before: calling ENG_ICMDB_APIS_UTIL.Update_Approval_Status');
1031              Write_Debug('  p_change_id =   ' || p_change_id);
1032              Write_Debug('  p_base_change_mgmt_type_code =   ' || l_base_cm_type_code);
1033              Write_Debug('  p_appr_status = ' || p_appr_status);
1034              Write_Debug('  p_workflow_status_code =   ' || p_route_status);
1035           END IF;
1036 
1037           ENG_ICMDB_APIS_UTIL.Update_Approval_Status
1038           ( p_change_id => p_change_id
1039            ,p_base_change_mgmt_type_code => l_base_cm_type_code
1040            ,p_new_approval_status_cde  => p_appr_status
1041            ,p_workflow_status_code => p_route_status
1042            ,x_return_status      => l_return_status
1043            ,x_msg_count          => l_msg_count
1044            ,x_msg_data           => l_msg_data
1045            );
1046 
1047           IF g_debug_flag THEN
1048              Write_Debug('After: calling ENG_ICMDB_APIS_UTIL.Update_Approval_Status: ' || l_return_status) ;
1049           END IF;
1050 
1051           IF ( l_return_status <>  FND_API.G_RET_STS_SUCCESS )
1052           THEN
1053             x_return_status := l_return_status;
1054             x_msg_count := l_msg_count;
1055             x_msg_data := l_msg_data;
1056             --#FND_MESSAGE.Set_Name('ENG','ENG_ERROR_CALLING_PS_API');
1057             --#FND_MESSAGE.Set_Token('OBJECT_NAME', 'ENG_NIR_UTIL_PKG.set_nir_item_approval_status');
1058             --#FND_MSG_PUB.Add;
1059             RAISE FND_API.G_EXC_ERROR;
1060           END IF;
1061 
1062           IF g_debug_flag THEN
1063              Write_Debug('Successful: ENG_ICMDB_APIS_UTIL.Update_Approval_Status');
1064           END IF;
1065 
1066         END IF; -- if ( Change Object is AMW Appl)
1067 
1068         IF g_debug_flag THEN
1069           Write_Debug('After: calling update DM attachment approval/review API');
1070         END IF;
1071 
1072 
1073         --
1074         -- R12B
1075         -- Document Lifecycle Support
1076         -- triggered by the header approval status update
1077         -- call ENG_DOCUMENT_UTIL.Update_Approval_Status if applicable
1078 
1079         IF ( l_doc_lc_object_flag)
1080         THEN
1081             IF g_debug_flag THEN
1082                Write_Debug('Before: calling ENG_DOCUMENT_UTIL.Update_Approval_Status');
1083                Write_Debug('  p_change_id =   ' || p_change_id);
1084                Write_Debug('  p_base_change_mgmt_type_code =   ' || l_base_cm_type_code);
1085                Write_Debug('  p_appr_status = ' || p_appr_status);
1086                Write_Debug('  p_workflow_status_code =   ' || p_route_status);
1087             END IF;
1088 
1089 
1090             ENG_DOCUMENT_UTIL.Update_Approval_Status
1091             ( p_api_version         => 1.0
1092              ,p_init_msg_list       => FND_API.G_FALSE
1093              ,p_commit              => FND_API.G_FALSE
1094              ,p_validation_level    => p_validation_level
1095              ,p_debug               => FND_API.G_FALSE
1096              ,p_output_dir          => p_output_dir
1097              ,p_debug_filename      => p_debug_filename
1098              ,x_return_status       => l_return_status     --
1099              ,x_msg_count           => l_msg_count         --
1100              ,x_msg_data            => l_msg_data          --
1101              ,p_change_id           => p_change_id         -- header's change_id
1102              ,p_approval_status     => p_appr_status       -- header approval status
1103              ,p_wf_route_status     => p_route_status      -- workflow routing status (for document types)
1104              ,p_api_caller          => p_api_caller        -- Optionnal for future use
1105             );
1106 
1107             IF g_debug_flag THEN
1108                Write_Debug('After: calling ENG_DOCUMENT_UTIL.Update_Approval_Status: ' || l_return_status) ;
1109             END IF;
1110 
1111             IF ( l_return_status <>  FND_API.G_RET_STS_SUCCESS )
1112             THEN
1113               x_return_status := l_return_status;
1114               x_msg_count := l_msg_count;
1115               x_msg_data := l_msg_data;
1116               RAISE FND_API.G_EXC_ERROR;
1117             END IF;
1118 
1119             IF g_debug_flag THEN
1120                Write_Debug('Successful: ENG_DOCUMENT_UTIL.Update_Approval_Status');
1121             END IF;
1122 
1123         END IF; -- if ( Change Object is Documet LC Object)
1124 
1125 
1126       END IF; -- if (l_updated = true)
1127 
1128     END IF; -- if (p_status_code's phase type is APPROVAL
1129 
1130 
1131 
1132     -- Standard ending code ------------------------------------------------
1133     IF FND_API.To_Boolean ( p_commit ) THEN
1134       COMMIT WORK;
1135     END IF;
1136 
1137     FND_MSG_PUB.Count_And_Get
1138     ( p_count        =>      x_msg_count,
1139       p_data         =>      x_msg_data );
1140 
1141     IF g_debug_flag THEN
1142       Write_Debug('Finish. End Of procedure: Update_Header_Appr_Status') ;
1143     END IF;
1144 
1145     IF FND_API.to_Boolean( p_debug ) THEN
1146       Close_Debug_Session;
1147     END IF;
1148 
1149   EXCEPTION
1150     WHEN EGO_USER_ATTRS_COMMON_PVT.G_SUBSCRIPTION_EXC then  -- bug 10128347, when catch G_SUBSCRIPTION_EXC exception
1151      ROLLBACK WORK;
1152      x_return_status := FND_API.G_RET_STS_ERROR;
1153      ERROR_HANDLER.Get_Message_List(l_message_list);
1154      			FOR i IN l_message_list.FIRST..l_message_list.LAST
1155      					LOOP
1156     					x_msg_data := x_msg_data || l_message_list(i).message_text;
1157     			END LOOP;
1158      IF g_debug_flag THEN
1159         Write_Debug('Rollback and Finish with expected error.') ;
1160       END IF;
1161       IF FND_API.to_Boolean( p_debug ) THEN
1162         Close_Debug_Session;
1163       END IF;
1164     WHEN FND_API.G_EXC_ERROR THEN
1165       --ROLLBACK TO Update_Header_Appr_Status;
1166       x_return_status := FND_API.G_RET_STS_ERROR;
1167       FND_MSG_PUB.Count_And_Get
1168       ( p_count        =>      x_msg_count
1169        ,p_data         =>      x_msg_data );
1170       IF g_debug_flag THEN
1171         Write_Debug('Rollback and Finish with expected error.') ;
1172       END IF;
1173       IF FND_API.to_Boolean( p_debug ) THEN
1174         Close_Debug_Session;
1175       END IF;
1176     WHEN FND_API.G_EXC_UNEXPECTED_ERROR THEN
1177       --ROLLBACK TO Update_Header_Appr_Status;
1178       x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
1179       FND_MSG_PUB.Count_And_Get
1180       ( p_count        =>      x_msg_count
1181        ,p_data         =>      x_msg_data );
1182       IF g_debug_flag THEN
1183         Write_Debug('Rollback and Finish with unexpected error.') ;
1184       END IF;
1185       IF FND_API.to_Boolean( p_debug ) THEN
1186         Close_Debug_Session;
1187       END IF;
1188     WHEN OTHERS THEN
1189       --ROLLBACK TO Update_Header_Appr_Status;
1190       x_return_status := FND_API.G_RET_STS_UNEXP_ERROR ;
1191       IF FND_MSG_PUB.Check_Msg_Level ( FND_MSG_PUB.G_MSG_LVL_UNEXP_ERROR )
1192       THEN
1193         FND_MSG_PUB.Add_Exc_Msg (  G_PKG_NAME, l_api_name );
1194       END IF;
1195       FND_MSG_PUB.Count_And_Get
1196       ( p_count        =>      x_msg_count
1197        ,p_data         =>      x_msg_data );
1198       IF g_debug_flag THEN
1199         Write_Debug('Rollback and Finish with other error.') ;
1200       END IF;
1201       IF FND_API.to_Boolean( p_debug ) THEN
1202         Close_Debug_Session;
1203       END IF;
1204 
1205   END Update_Header_Appr_Status;
1206 
1207   PROCEDURE Update_Header_Appr_Status
1208   (
1209     p_api_version               IN   NUMBER                             --
1210    ,p_init_msg_list             IN   VARCHAR2 := FND_API.G_FALSE        --
1211    ,p_commit                    IN   VARCHAR2 := FND_API.G_FALSE        --
1212    ,p_validation_level          IN   NUMBER   := FND_API.G_VALID_LEVEL_FULL
1213    ,p_debug                     IN   VARCHAR2 := FND_API.G_FALSE        --
1214    ,p_output_dir                IN   VARCHAR2 := NULL
1215    ,p_debug_filename            IN   VARCHAR2 := NULL
1216    ,x_return_status             OUT  NOCOPY  VARCHAR2                   --
1217    ,x_msg_count                 OUT  NOCOPY  NUMBER                     --
1218    ,x_msg_data                  OUT  NOCOPY  VARCHAR2                   --
1219    ,p_change_id                 IN   NUMBER                             -- header's change_id
1220    ,p_status_code               IN   NUMBER
1221    ,p_appr_status               IN   NUMBER                             -- header approval status
1222    ,p_route_status              IN   VARCHAR2                           -- workflow routing status (for document types)
1223    ,p_api_caller                IN   VARCHAR2 := 'UI'                   -- must
1224    ,p_bypass                    IN   VARCHAR2 := 'N'                    -- flag to bypass phase type check
1225   )
1226   IS
1227      l_sfa_line_items_exists VARCHAR2(1);
1228   BEGIN
1229       Update_Header_Appr_Status
1230       (
1231         p_api_version               =>  p_api_version
1232        ,p_init_msg_list             =>  p_init_msg_list
1233        ,p_commit                    =>  p_commit
1234        ,p_validation_level          =>  p_validation_level
1235        ,p_debug                     =>  p_debug
1236        ,p_output_dir                =>  p_output_dir
1237        ,p_debug_filename            =>  p_debug_filename
1238        ,x_return_status             =>  x_return_status
1239        ,x_msg_count                 =>  x_msg_count
1240        ,x_msg_data                  =>  x_msg_data
1241        ,p_change_id                 =>  p_change_id
1242        ,p_status_code               =>  p_status_code
1243        ,p_appr_status               =>  p_appr_status
1244        ,p_route_status              =>  p_route_status
1245        ,p_api_caller                =>  p_api_caller
1246        ,p_bypass                    =>  p_bypass
1247        ,x_sfa_line_items_exists     => l_sfa_line_items_exists
1248       );
1249   END Update_Header_Appr_Status;
1250 
1251 
1252   -- R12B
1253   -- Internal procedure to automatically launch line 'Not Started' workflow if necessary
1254   -- when line workflow is defined and Start After Status is specified phase.
1255   --
1256   PROCEDURE Start_Line_Workflow
1257   (
1258     p_api_version               IN   NUMBER                             --
1259    ,p_init_msg_list             IN   VARCHAR2 := FND_API.G_FALSE        --
1260    ,p_commit                    IN   VARCHAR2 := FND_API.G_FALSE        --
1261    ,p_validation_level          IN   NUMBER   := FND_API.G_VALID_LEVEL_FULL
1262    ,p_debug                     IN   VARCHAR2 := FND_API.G_FALSE        --
1263    ,p_output_dir                IN   VARCHAR2 := NULL
1264    ,p_debug_filename            IN   VARCHAR2 := NULL
1265    ,x_return_status             OUT  NOCOPY  VARCHAR2                   --
1266    ,x_msg_count                 OUT  NOCOPY  NUMBER                     --
1267    ,x_msg_data                  OUT  NOCOPY  VARCHAR2                   --
1268    ,p_change_id                 IN   NUMBER                             -- header's change_id
1269    ,p_new_status_code           IN   NUMBER                             -- new status code to be promoted to
1270    ,p_cur_status_code           IN   NUMBER                             -- curre status code
1271    ,p_api_caller                IN   VARCHAR2 := NULL                   -- can also be 'WF', or other internal procedure names
1272    ,p_action_type               IN   VARCHAR2 := NULL                   -- or PROMOTE, DEMOTE
1273   )
1274   IS
1275     l_api_name           CONSTANT VARCHAR2(30)  := 'Start_Line_Workflow';
1276     l_api_version        CONSTANT NUMBER := 1.0;
1277 
1278     l_return_status      VARCHAR2(1);
1279     l_msg_count          NUMBER;
1280     l_msg_data           VARCHAR2(2000);
1281 
1282     l_api_caller         VARCHAR2(2) := NULL;
1283     l_fnd_user_id        NUMBER := TO_NUMBER(FND_PROFILE.VALUE('USER_ID'));
1284     l_fnd_login_id       NUMBER := TO_NUMBER(FND_PROFILE.VALUE('LOGIN_ID'));
1285 
1286 
1287     l_change_line_id     NUMBER ;
1288     l_line_wf_route_id   NUMBER ;
1289     l_line_wf_item_key   wf_item_activity_statuses.item_key%TYPE := NULL;
1290 
1291 
1292     -- Select Line Workflow to be started for the passed status_code
1293     CURSOR c_line_wf ( c_change_id       IN NUMBER
1294                      , c_new_status_code IN NUMBER
1295                      , c_cur_status_code IN NUMBER
1296                      )
1297     IS
1298         SELECT DISTINCT route.route_id wf_route_id
1299              , line.change_line_id
1300         FROM eng_change_routes route,
1301              eng_change_statuses s,
1302              eng_change_lines line,
1303              eng_lifecycle_statuses line_start_after,
1304              eng_lifecycle_statuses new_status,
1305              eng_lifecycle_statuses cur_status
1306         WHERE route.status_code = Eng_Workflow_Util.G_RT_NOT_STARTED
1307         AND route.route_id = line.route_id
1308         AND s.status_type <> G_ENG_COMPLETED
1309         AND s.status_type <> G_ENG_IMPLEMENTED
1310         AND s.status_type <> G_ENG_CANCELLED
1311         AND s.status_code = line.status_code
1312         AND line.start_after_status_code = c_new_status_code
1313         AND line.change_id = c_change_id
1314         AND line_start_after.sequence_number <= new_status.sequence_number
1315         AND line_start_after.sequence_number > cur_status.sequence_number
1316         AND line_start_after.entity_name = G_ENG_CHANGE
1317         AND line_start_after.entity_id1 = c_change_id
1318         AND line_start_after.status_code = line.start_after_status_code
1319         AND line_start_after.active_flag = 'Y'
1320         AND new_status.entity_name =  G_ENG_CHANGE
1321         AND new_status.entity_id1 = c_change_id
1322         AND new_status.status_code = c_new_status_code
1323         AND new_status.active_flag = 'Y'
1324         AND cur_status.entity_name = G_ENG_CHANGE
1325         AND cur_status.entity_id1 = c_change_id
1326         AND cur_status.status_code = c_cur_status_code
1327         AND cur_status.active_flag = 'Y' ;
1328 
1329   BEGIN
1330     -- Standard Start of API savepoint
1331     --SAVEPOINT Start_Line_Workflow;
1332     -- Standard call to check for call compatibility
1333     IF NOT FND_API.Compatible_API_Call ( l_api_version
1334                                         ,p_api_version
1335                                         ,l_api_name
1336                                         ,G_PKG_NAME )
1337     THEN
1338       RAISE FND_API.G_EXC_UNEXPECTED_ERROR;
1339     END IF;
1340     -- Initialize message list if p_init_msg_list is set to TRUE.
1341     IF FND_API.to_Boolean( p_init_msg_list ) THEN
1342        FND_MSG_PUB.initialize;
1343     END IF;
1344 
1345     -- For Test/Debug
1346     Check_And_Open_Debug_Session(p_debug, p_output_dir, p_debug_filename) ;
1347     -- R12 Comment out
1348     -- IF FND_API.to_Boolean( p_debug ) THEN
1349     --     Open_Debug_Session(p_output_dir, p_debug_filename ) ;
1350     -- END IF;
1351 
1352     -- Write debug message if debug mode is on
1353     IF g_debug_flag THEN
1354        Write_Debug('ENG_CHANGE_LIFECYCLE_UTIL.Start_Line_Workflow log');
1355        Write_Debug('-----------------------------------------------------');
1356        Write_Debug('p_change_id         : ' || p_change_id );
1357        Write_Debug('p_new_status_code       : ' || p_new_status_code );
1358        Write_Debug('p_cur_status_code       : ' || p_cur_status_code);
1359        Write_Debug('-----------------------------------------------------');
1360        Write_Debug('Initializing return status... ' );
1361     END IF;
1362 
1363     -- Initialize API return status to success
1364     x_return_status := FND_API.G_RET_STS_SUCCESS;
1365 
1366     -- FND_PROFILE package is not available for workflow (WF),
1367     -- therefore manually set WHO column values
1368     IF p_api_caller = 'WF' THEN
1369       l_fnd_user_id := G_ENG_WF_USER_ID;
1370       l_fnd_login_id := G_ENG_WF_LOGIN_ID;
1371     ELSIF p_api_caller = 'CP' THEN
1372       l_fnd_user_id := G_ENG_CP_USER_ID;
1373       l_fnd_login_id := G_ENG_CP_LOGIN_ID;
1374     END IF;
1375 
1376     -- Real code starts here -----------------------------------------------
1377 
1378     -- Start phase workflow only for PROMOTE action
1379     -- (When demoting to a new phase, do not auto-start new phase workflow)
1380     IF g_debug_flag THEN
1381        Write_Debug('Before: handling new phase workflow');
1382     END IF;
1383 
1384     IF (p_action_type = G_ENG_DEMOTE) THEN
1385       IF g_debug_flag THEN
1386          Write_Debug('  Branch: p_action_type = DEMOTE, do nothing');
1387       END IF;
1388 
1389     ELSE  --G_ENG_PROMOTE
1390 
1391       IF g_debug_flag THEN
1392          Write_Debug('  Branch: p_action_type is not DEMOTE, check if Line workflow auto-start is needed');
1393       END IF;
1394 
1395 
1396       FOR l_rec IN c_line_wf (c_change_id => p_change_id ,
1397                               c_new_status_code => p_new_status_code ,
1398                               c_cur_status_code => p_cur_status_code
1399                               )
1400       LOOP
1401 
1402         l_change_line_id     := l_rec.change_line_id  ;
1403         l_line_wf_route_id   := l_rec.wf_route_id  ;
1404         l_line_wf_item_key   := NULL;
1405 
1406         IF g_debug_flag THEN
1407           Write_Debug('calling Eng_Workflow_Util.StartWorkflow API for Line') ;
1408           Write_Debug('l_change_line_id: '  || TO_CHAR(l_change_line_id) ) ;
1409           Write_Debug('l_line_wf_route_id: '  || TO_CHAR(l_line_wf_route_id) ) ;
1410         END IF;
1411 
1412         -- start phase-level workflow
1413         Eng_Workflow_Util.StartWorkflow
1414         (  p_api_version       => 1.0
1415         ,  p_init_msg_list     => FND_API.G_FALSE
1416         ,  p_commit            => FND_API.G_FALSE
1417         ,  p_validation_level  => FND_API.G_VALID_LEVEL_FULL
1418         ,  x_return_status     => l_return_status
1419         ,  x_msg_count         => l_msg_count
1420         ,  x_msg_data          => l_msg_data
1421         ,  p_item_type         => Eng_Workflow_Util.G_CHANGE_ROUTE_ITEM_TYPE
1422         ,  x_item_key          => l_line_wf_item_key
1423         ,  p_process_name      => Eng_Workflow_Util.G_ROUTE_AGENT_PROC
1424         ,  p_change_id         => p_change_id
1425         ,  p_change_line_id    => l_change_line_id
1426         ,  p_wf_user_id        => l_fnd_user_id
1427         ,  p_route_id          => l_line_wf_route_id
1428         ,  p_debug             => p_debug --FND_API.G_FALSE
1429         ,  p_output_dir        => p_output_dir
1430         ,  p_debug_filename    => NULL
1431         ) ;
1432 
1433         IF g_debug_flag THEN
1434           Write_Debug('After: calling Eng_Workflow_Util.StartWorkflow API for ' || TO_CHAR(l_change_line_id) || l_return_status) ;
1435           Write_Debug('l_line_wf_item_key: '  || l_line_wf_item_key) ;
1436         END IF;
1437 
1438         IF ( l_return_status <>  FND_API.G_RET_STS_SUCCESS )
1439         THEN
1440           x_return_status := l_return_status;
1441           x_msg_count := l_msg_count;
1442           x_msg_data := l_msg_data;
1443         ELSE
1444           IF g_debug_flag THEN
1445              Write_Debug('Successful: calling workflow routing agent');
1446           END IF;
1447         END IF;
1448 
1449       END LOOP ; -- c_line_wf loop
1450 
1451     END IF; -- if (action = PROMOTE)
1452 
1453     -- Standard ending code ------------------------------------------------
1454     IF FND_API.To_Boolean ( p_commit ) THEN
1455       COMMIT WORK;
1456     END IF;
1457 
1458     FND_MSG_PUB.Count_And_Get
1459     ( p_count        =>      x_msg_count,
1460       p_data         =>      x_msg_data );
1461 
1462     IF g_debug_flag THEN
1463       Write_Debug('Finish. End Of procedure: Start_Line_Workflow');
1464     END IF;
1465 
1466     IF FND_API.to_Boolean( p_debug ) THEN
1467       Close_Debug_Session;
1468     END IF;
1469 
1470   EXCEPTION
1471     WHEN FND_API.G_EXC_ERROR THEN
1472       --ROLLBACK TO Start_Line_Workflow;
1473       x_return_status := FND_API.G_RET_STS_ERROR;
1474       FND_MSG_PUB.Count_And_Get
1475       ( p_count        =>      x_msg_count
1476        ,p_data         =>      x_msg_data );
1477       IF g_debug_flag THEN
1478         Write_Debug('Rollback and Finish with expected error.') ;
1479       END IF;
1480       IF FND_API.to_Boolean( p_debug ) THEN
1481         Close_Debug_Session;
1482       END IF;
1483     WHEN FND_API.G_EXC_UNEXPECTED_ERROR THEN
1484       --ROLLBACK TO Start_Line_Workflow;
1485       x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
1486       FND_MSG_PUB.Count_And_Get
1487       ( p_count        =>      x_msg_count
1488        ,p_data         =>      x_msg_data );
1489       IF g_debug_flag THEN
1490         Write_Debug('Rollback and Finish with unexpected error.') ;
1491       END IF;
1492       IF FND_API.to_Boolean( p_debug ) THEN
1493         Close_Debug_Session;
1494       END IF;
1495     WHEN OTHERS THEN
1496       --ROLLBACK TO Start_Line_Workflow;
1497       x_return_status := FND_API.G_RET_STS_UNEXP_ERROR ;
1498       IF FND_MSG_PUB.Check_Msg_Level ( FND_MSG_PUB.G_MSG_LVL_UNEXP_ERROR )
1499       THEN
1500         FND_MSG_PUB.Add_Exc_Msg ( G_PKG_NAME, l_api_name );
1501       END IF;
1502       FND_MSG_PUB.Count_And_Get
1503       ( p_count        =>      x_msg_count
1504        ,p_data         =>      x_msg_data );
1505       IF g_debug_flag THEN
1506         Write_Debug('Rollback and Finish with other error.') ;
1507       END IF;
1508       IF FND_API.to_Boolean( p_debug ) THEN
1509         Close_Debug_Session;
1510       END IF;
1511   END Start_Line_Workflow ;
1512 
1513 
1514 
1515 
1516   -- Internal procedure to automatically launch workflow if necessary
1517   -- (i.e., when workflow is defined) for the specified phase
1518   -- Note that this procedure may also submit the concurrent program for
1519   -- implementing ECO as well!!!
1520   PROCEDURE Start_WF_OnlyIf_Necessary
1521   (
1522     p_api_version               IN   NUMBER                             --
1523    ,p_init_msg_list             IN   VARCHAR2 := FND_API.G_FALSE        --
1524    ,p_commit                    IN   VARCHAR2 := FND_API.G_FALSE        --
1525    ,p_validation_level          IN   NUMBER   := FND_API.G_VALID_LEVEL_FULL
1526    ,p_debug                     IN   VARCHAR2 := FND_API.G_FALSE        --
1527    ,p_output_dir                IN   VARCHAR2 := NULL
1528    ,p_debug_filename            IN   VARCHAR2 := NULL
1529    ,x_return_status             OUT  NOCOPY  VARCHAR2                   --
1530    ,x_msg_count                 OUT  NOCOPY  NUMBER                     --
1531    ,x_msg_data                  OUT  NOCOPY  VARCHAR2                   --
1532    ,p_change_id                 IN   NUMBER                             -- header's change_id
1533    ,p_status_code               IN   NUMBER                             -- new phase
1534    ,p_status_type               IN   NUMBER                             -- new phase type
1535    ,p_sequence_number           IN   NUMBER                             -- new phase sequence number
1536    ,p_imp_eco_flag              IN   VARCHAR2 := 'N'                    -- flag for implementECO
1537    ,p_api_caller                IN   VARCHAR2 := NULL                   -- can also be 'WF', or other internal procedure names
1538    ,p_action_type               IN   VARCHAR2 := NULL                   -- or PROMOTE, DEMOTE
1539    ,p_comment                   IN   VARCHAR2 := NULL                   -- only used for co promote-to-implement action
1540    ,p_skip_wf                   IN   VARCHAR2 := 'N'                    -- used for eco's last implement phase
1541   )
1542   IS
1543     l_api_name           CONSTANT VARCHAR2(30)  := 'Start_WF_OnlyIf_Necessary';
1544     l_api_version        CONSTANT NUMBER := 1.0;
1545 
1546     l_return_status      VARCHAR2(1);
1547     l_msg_count          NUMBER;
1548     l_msg_data           VARCHAR2(2000);
1549 
1550     l_api_caller         VARCHAR2(2) := NULL;
1551     l_fnd_user_id        NUMBER := TO_NUMBER(FND_PROFILE.VALUE('USER_ID'));
1552     l_fnd_login_id       NUMBER := TO_NUMBER(FND_PROFILE.VALUE('LOGIN_ID'));
1553 
1554     l_action_id          eng_change_actions.action_id%TYPE;
1555 
1556     l_wf_route_id        eng_lifecycle_statuses.change_wf_route_id%TYPE;
1557     l_wf_route_temp_id   eng_lifecycle_statuses.change_wf_route_template_id%TYPE;
1558     l_wf_item_key        wf_item_activity_statuses.item_key%TYPE := NULL;
1559 
1560     l_chg_notice         eng_engineering_changes.change_notice%TYPE;
1561     l_org_id             eng_engineering_changes.organization_id%TYPE;
1562     l_request_id         NUMBER;
1563 
1564     l_min_appr_sn        eng_lifecycle_statuses.sequence_number%TYPE;
1565     l_doc_lc_object_flag BOOLEAN := FALSE ;
1566 
1567 
1568   BEGIN
1569     -- Standard Start of API savepoint
1570     --SAVEPOINT Start_WF_OnlyIf_Necessary;
1571     -- Standard call to check for call compatibility
1572     IF NOT FND_API.Compatible_API_Call ( l_api_version
1573                                         ,p_api_version
1574                                         ,l_api_name
1575                                         ,G_PKG_NAME )
1576     THEN
1577       RAISE FND_API.G_EXC_UNEXPECTED_ERROR;
1578     END IF;
1579     -- Initialize message list if p_init_msg_list is set to TRUE.
1580     IF FND_API.to_Boolean( p_init_msg_list ) THEN
1581        FND_MSG_PUB.initialize;
1582     END IF;
1583 
1584     -- For Test/Debug
1585     Check_And_Open_Debug_Session(p_debug, p_output_dir, p_debug_filename) ;
1586     -- R12 Comment out
1587     -- IF FND_API.to_Boolean( p_debug ) THEN
1588     --     Open_Debug_Session(p_output_dir, p_debug_filename ) ;
1589     -- END IF;
1590 
1591     -- Write debug message if debug mode is on
1592     IF g_debug_flag THEN
1593        Write_Debug('ENG_CHANGE_LIFECYCLE_UTIL.Start_WF_OnlyIf_Necessary log');
1594        Write_Debug('-----------------------------------------------------');
1595        Write_Debug('p_change_id         : ' || p_change_id );
1596        Write_Debug('p_status_code       : ' || p_status_code );
1597        -- bug 9577905
1598        Write_Debug('p_skip_wf           : ' || p_skip_wf );
1599        Write_Debug('p_api_caller        : ' || p_api_caller );
1600        Write_Debug('p_action_type       : ' || p_action_type );
1601        Write_Debug('p_imp_eco_flag      : ' || p_imp_eco_flag );
1602        Write_Debug('-----------------------------------------------------');
1603        Write_Debug('Initializing return status... ' );
1604     END IF;
1605 
1606     -- Initialize API return status to success
1607     x_return_status := FND_API.G_RET_STS_SUCCESS;
1608 
1609     -- FND_PROFILE package is not available for workflow (WF),
1610     -- therefore manually set WHO column values
1611     IF p_api_caller = 'WF' THEN
1612       l_fnd_user_id := G_ENG_WF_USER_ID;
1613       l_fnd_login_id := G_ENG_WF_LOGIN_ID;
1614     ELSIF p_api_caller = 'CP' THEN
1615       l_fnd_user_id := G_ENG_CP_USER_ID;
1616       l_fnd_login_id := G_ENG_CP_LOGIN_ID;
1617     END IF;
1618 
1619     -- Real code starts here -----------------------------------------------
1620 
1621     -- Log action log only for calls not coming from the UI
1622     -- (implying automatic promotion/demotion),
1623     -- but not from Init_Lifecycle procedure
1624     -- Also: skip logging action and status change workflow in case of special
1625     -- ECO implement phase
1626     IF (    (p_api_caller IS NULL OR p_api_caller <> 'UI')
1627          AND p_action_type IS NOT NULL
1628          AND(p_imp_eco_flag IS NULL OR p_imp_eco_flag <> 'Y')
1629          )
1630     THEN
1631 
1632       IF g_debug_flag THEN
1633          Write_Debug('Before: saving action log');
1634       END IF;
1635       l_action_id := 0;
1636       -- create new action log
1637       ENG_CHANGE_ACTIONS_UTIL.Create_Change_Action
1638       ( p_api_version           => 1.0
1639       , p_init_msg_list         => FND_API.G_FALSE        --
1640       , p_commit                => FND_API.G_FALSE        --
1641       , p_validation_level      => FND_API.G_VALID_LEVEL_FULL
1642       , p_debug                 => p_debug --FND_API.G_FALSE
1643       , p_output_dir            => p_output_dir
1644       , p_debug_filename        => NULL
1645       , x_return_status         => l_return_status
1646       , x_msg_count             => l_msg_count
1647       , x_msg_data              => l_msg_data
1648       , p_action_type           => p_action_type
1649       , p_object_name           => G_ENG_CHANGE
1650       , p_object_id1            => p_change_id
1651       , p_object_id2            => NULL
1652       , p_object_id3            => NULL
1653       , p_object_id4            => NULL
1654       , p_object_id5            => NULL
1655       , p_parent_action_id      => -1
1656       , p_status_code           => p_status_code
1657       , p_action_date           => SYSDATE
1658       , p_change_description    => NULL
1659       , p_user_id               => l_fnd_user_id
1660       , p_api_caller            => p_api_caller
1661       , x_change_action_id      => l_action_id
1662       );
1663       IF g_debug_flag THEN
1664          Write_Debug('After: saving action log: ' || l_return_status) ;
1665          Write_Debug('l_action_id       : ' || l_action_id );
1666       END IF;
1667       IF ( l_return_status <>  FND_API.G_RET_STS_SUCCESS )
1668       THEN
1669         x_return_status := l_return_status;
1670         x_msg_count := l_msg_count;
1671         x_msg_data := l_msg_data;
1672         --#FND_MESSAGE.Set_Name('ENG','ENG_ERROR_CALLING_PS_API');
1673         --#FND_MESSAGE.Set_Token('OBJECT_NAME', 'ENG_CHANGE_ACTIONS_UTIL.Create_Change_Action');
1674         --#FND_MSG_PUB.Add;
1675         RAISE FND_API.G_EXC_ERROR;
1676       END IF;
1677       IF g_debug_flag THEN
1678          Write_Debug('Successful: saving action log');
1679       END IF;
1680 
1681 
1682       -- R12B
1683       -- In case of Document LC Change Object
1684       -- We don't need to start workflow and riase event
1685       l_doc_lc_object_flag := ENG_DOCUMENT_UTIL.Is_Dom_Document_Lifecycle
1686                              ( p_change_id => p_change_id
1687                              , p_base_change_mgmt_type_code => NULL
1688                              )  ;
1689 
1690       IF (NOT l_doc_lc_object_flag)
1691       THEN
1692 
1693           ENG_CHANGE_BES_UTIL.Raise_Status_Change_Event
1694           ( p_change_id         => p_change_id
1695            ,p_status_code       => p_status_code
1696            ,p_action_type       => p_action_type
1697            ,p_action_id         => l_action_id
1698            );
1699 
1700 
1701           -- Force commit to make sure workflow picks up the latest phase
1702           IF FND_API.To_Boolean ( p_commit ) THEN -- fix by 14018580, in PIP session, using XA Datsource and hard commits will cause this subordination session error.
1703             COMMIT WORK;
1704           END IF;
1705 
1706           -- launch the standard action workflow for new action if needed
1707           IF g_debug_flag THEN
1708             Write_Debug('Before: calling status change workflow API');
1709           END IF;
1710 
1711           Eng_Workflow_Util.StartWorkflow
1712           (  p_api_version       => 1.0
1713           ,  p_init_msg_list     => FND_API.G_FALSE
1714           ,  p_commit            => FND_API.G_FALSE
1715           ,  p_validation_level  => FND_API.G_VALID_LEVEL_FULL
1716           ,  x_return_status     => l_return_status
1717           ,  x_msg_count         => l_msg_count
1718           ,  x_msg_data          => l_msg_data
1719           ,  p_item_type         => Eng_Workflow_Util.G_CHANGE_ACTION_ITEM_TYPE
1720           ,  x_item_key          => l_wf_item_key
1721           ,  p_process_name      => Eng_Workflow_Util.G_STATUS_CHANGE_PROC
1722           ,  p_change_id         => p_change_id
1723           ,  p_action_id         => l_action_id
1724           ,  p_wf_user_id        => l_fnd_user_id
1725           ,  p_route_id          => 0 --l_wf_route_id
1726           ,  p_debug             => p_debug --FND_API.G_FALSE
1727           ,  p_output_dir        => p_output_dir
1728           ,  p_debug_filename    => NULL
1729           ) ;
1730           -- note that the returned wf item_key won't be saved on the ENG side
1731           IF g_debug_flag THEN
1732             Write_Debug('After: calling status change workflow API: ' || l_return_status) ;
1733           END IF;
1734 
1735           IF ( l_return_status <>  FND_API.G_RET_STS_SUCCESS )
1736           THEN
1737             x_return_status := l_return_status;
1738             x_msg_count := l_msg_count;
1739             x_msg_data := l_msg_data;
1740             --#FND_MESSAGE.Set_Name('ENG','ENG_ERROR_CALLING_WF_API');
1741             --#FND_MSG_PUB.Add;
1742             --#RAISE FND_API.G_EXC_ERROR;
1743           END IF;
1744           l_wf_item_key := NULL;
1745 
1746           IF g_debug_flag THEN
1747             Write_Debug('Successful: calling status change workflow API');
1748           END IF;
1749 
1750        END IF ;   -- IF (NOT l_doc_lc_object_flag)
1751 
1752     END IF; -- if (not calling from UI)
1753 
1754     -- Start phase workflow only for PROMOTE action
1755     -- (When demoting to a new phase, do not auto-start new phase workflow)
1756     IF g_debug_flag THEN
1757        Write_Debug('Before: handling new phase workflow');
1758     END IF;
1759 
1760     IF (p_action_type = G_ENG_DEMOTE) THEN
1761       IF g_debug_flag THEN
1762          Write_Debug('  Branch: p_action_type = DEMOTE, do nothing');
1763       END IF;
1764 
1765     ELSE  --G_ENG_PROMOTE
1766       IF g_debug_flag THEN
1767          Write_Debug('  Branch: p_action_type is not DEMOTE, check if workflow auto-start is needed');
1768       END IF;
1769       -- Check if automatic wf start is needed
1770       SELECT change_wf_route_id, change_wf_route_template_id
1771         INTO l_wf_route_id, l_wf_route_temp_id
1772         FROM eng_lifecycle_statuses
1773         WHERE entity_name = G_ENG_CHANGE
1774           AND entity_id1 = p_change_id
1775           AND status_code = p_status_code
1776           AND active_flag = 'Y'
1777           AND rownum = 1;
1778 
1779 
1780       IF (p_skip_wf <> 'Y'   -- fix for bug 3479509 design change of launching wf after concurrent program
1781           AND l_wf_route_id IS NOT NULL )
1782       THEN
1783         IF g_debug_flag THEN
1784            Write_Debug('Auto-starting workflow is needed, calling workflow routing agent');
1785         END IF;
1786 
1787         -- start phase-level workflow
1788         Eng_Workflow_Util.StartWorkflow
1789         (  p_api_version       => 1.0
1790         ,  p_init_msg_list     => FND_API.G_FALSE
1791         ,  p_commit            => FND_API.G_FALSE
1792         ,  p_validation_level  => FND_API.G_VALID_LEVEL_FULL
1793         ,  x_return_status     => l_return_status
1794         ,  x_msg_count         => l_msg_count
1795         ,  x_msg_data          => l_msg_data
1796         ,  p_item_type         => Eng_Workflow_Util.G_CHANGE_ROUTE_ITEM_TYPE
1797         ,  x_item_key          => l_wf_item_key
1798         ,  p_process_name      => Eng_Workflow_Util.G_ROUTE_AGENT_PROC
1799         ,  p_change_id         => p_change_id
1800         ,  p_wf_user_id        => l_fnd_user_id
1801         ,  p_route_id          => l_wf_route_id
1802         ,  p_debug             => p_debug --FND_API.G_FALSE
1803         ,  p_output_dir        => p_output_dir
1804         ,  p_debug_filename    => NULL
1805         ) ;
1806 
1807         IF g_debug_flag THEN
1808           Write_Debug('After: calling Eng_Workflow_Util.StartWorkflow API: ' || l_return_status) ;
1809         END IF;
1810 
1811 
1812         IF ( l_return_status <>  FND_API.G_RET_STS_SUCCESS )
1813         THEN
1814           x_return_status := l_return_status;
1815           x_msg_count := l_msg_count;
1816           x_msg_data := l_msg_data;
1817           --#FND_MESSAGE.Set_Name('ENG','ENG_ERROR_CALLING_WF_API');
1818           --#FND_MSG_PUB.Add;
1819           --#RAISE FND_API.G_EXC_ERROR;
1820         ELSE
1821           IF g_debug_flag THEN
1822              Write_Debug('Successful: calling workflow routing agent');
1823           END IF;
1824         END IF;
1825         l_wf_item_key := NULL;
1826 
1827       -- If phase workflow is defined by wf template id, but wf instance id
1828       -- has not been populated, do nothing
1829       ELSIF (p_skip_wf <> 'Y'   -- fix for bug 3479509 design change of launching wf after concurrent program
1830              AND l_wf_Route_id IS NULL AND l_wf_route_temp_id IS NOT NULL ) THEN
1831         IF g_debug_flag THEN
1832            Write_Debug('Only phase workflow template id is defined,');
1833            Write_Debug('Workflow instance id needs to be populated before the phase workflow can be started');
1834         END IF;
1835 
1836       -- If p_skip_wf is true, or there is no workflow defined for the phase at all
1837       ELSE
1838         IF g_debug_flag THEN
1839            Write_Debug('Auto-starting workflow is not needed, do post workflow update right away');
1840         END IF;
1841 
1842         -- determine API caller - 'UI' should be used only once in case promotion/demote recursion occurs
1843         IF (p_api_caller = 'WF' OR p_api_caller = 'CP') THEN
1844           l_api_caller := p_api_caller;
1845         ELSE
1846           l_api_caller := NULL;
1847         END IF;
1848 
1849         -- Do post workflow update right away
1850         Update_Lifecycle_States
1851         (
1852           p_api_version        => 1.0
1853          ,p_init_msg_list      => FND_API.G_FALSE
1854          ,p_commit             => FND_API.G_FALSE
1855          ,p_validation_level   => p_validation_level
1856          ,p_debug              => FND_API.G_FALSE
1857          ,p_output_dir         => p_output_dir
1858          ,p_debug_filename     => p_debug_filename
1859          ,x_return_status      => l_return_status
1860          ,x_msg_count          => l_msg_count
1861          ,x_msg_data           => l_msg_data
1862          ,p_change_id          => p_change_id
1863          ,p_api_caller         => l_api_caller
1864          ,p_wf_route_id        => NULL
1865          ,p_route_status       => NULL
1866          ,p_comment            => p_comment
1867         );
1868 
1869         IF g_debug_flag THEN
1870           Write_Debug('After: calling Update_Lifecycle_States API: ' || l_return_status) ;
1871         END IF;
1872 
1873 
1874         IF ( l_return_status <>  FND_API.G_RET_STS_SUCCESS ) THEN
1875           x_return_status := l_return_status;
1876           x_msg_count := l_msg_count;
1877           x_msg_data := l_msg_data;
1878           --#FND_MESSAGE.Set_Name('ENG','ENG_ERROR_CALLING_PS_API');
1879           --#FND_MESSAGE.Set_Token('OBJECT_NAME', 'Update_Lifecycle_States');
1880           --#FND_MSG_PUB.Add;
1881           RAISE FND_API.G_EXC_ERROR;
1882         END IF;
1883 
1884       END IF; -- if (phase workflow instance id and workflow template id)
1885 
1886     END IF; -- if (action = PROMOTE)
1887 
1888     -- Standard ending code ------------------------------------------------
1889     IF FND_API.To_Boolean ( p_commit ) THEN
1890       COMMIT WORK;
1891     END IF;
1892 
1893     FND_MSG_PUB.Count_And_Get
1894     ( p_count        =>      x_msg_count,
1895       p_data         =>      x_msg_data );
1896 
1897     IF g_debug_flag THEN
1898       Write_Debug('Finish. End Of procedure: Start_WF_OnlyIf_Necessary');
1899     END IF;
1900 
1901     IF FND_API.to_Boolean( p_debug ) THEN
1902       Close_Debug_Session;
1903     END IF;
1904 
1905   EXCEPTION
1906     WHEN FND_API.G_EXC_ERROR THEN
1907       --ROLLBACK TO Start_WF_OnlyIf_Necessary;
1908       x_return_status := FND_API.G_RET_STS_ERROR;
1909       FND_MSG_PUB.Count_And_Get
1910       ( p_count        =>      x_msg_count
1911        ,p_data         =>      x_msg_data );
1912       IF g_debug_flag THEN
1913         Write_Debug('Rollback and Finish with expected error.') ;
1914       END IF;
1915       IF FND_API.to_Boolean( p_debug ) THEN
1916         Close_Debug_Session;
1917       END IF;
1918     WHEN FND_API.G_EXC_UNEXPECTED_ERROR THEN
1919       --ROLLBACK TO Start_WF_OnlyIf_Necessary;
1920       x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
1921       FND_MSG_PUB.Count_And_Get
1922       ( p_count        =>      x_msg_count
1923        ,p_data         =>      x_msg_data );
1924       IF g_debug_flag THEN
1925         Write_Debug('Rollback and Finish with unexpected error.') ;
1926       END IF;
1927       IF FND_API.to_Boolean( p_debug ) THEN
1928         Close_Debug_Session;
1929       END IF;
1930     WHEN OTHERS THEN
1931       --ROLLBACK TO Start_WF_OnlyIf_Necessary;
1932       x_return_status := FND_API.G_RET_STS_UNEXP_ERROR ;
1933       IF FND_MSG_PUB.Check_Msg_Level ( FND_MSG_PUB.G_MSG_LVL_UNEXP_ERROR )
1934       THEN
1935         FND_MSG_PUB.Add_Exc_Msg ( G_PKG_NAME, l_api_name );
1936       END IF;
1937       FND_MSG_PUB.Count_And_Get
1938       ( p_count        =>      x_msg_count
1939        ,p_data         =>      x_msg_data );
1940       IF g_debug_flag THEN
1941         Write_Debug('Rollback and Finish with other error.') ;
1942       END IF;
1943       IF FND_API.to_Boolean( p_debug ) THEN
1944         Close_Debug_Session;
1945       END IF;
1946   END Start_WF_OnlyIf_Necessary;
1947 
1948 
1949   -- Internal procedure for promotion of change header (inc. revItems)
1950   PROCEDURE Promote_Header
1951   (
1952     p_api_version               IN   NUMBER                             --
1953    ,p_init_msg_list             IN   VARCHAR2 := FND_API.G_FALSE        --
1954    ,p_commit                    IN   VARCHAR2 := FND_API.G_FALSE        --
1955    ,p_validation_level          IN   NUMBER   := FND_API.G_VALID_LEVEL_FULL
1956    ,p_debug                     IN   VARCHAR2 := FND_API.G_FALSE        --
1957    ,p_output_dir                IN   VARCHAR2 := NULL
1958    ,p_debug_filename            IN   VARCHAR2 := NULL
1959    ,x_return_status             OUT  NOCOPY  VARCHAR2                   --
1960    ,x_msg_count                 OUT  NOCOPY  NUMBER                     --
1961    ,x_msg_data                  OUT  NOCOPY  VARCHAR2                   --
1962    ,p_change_id                 IN   NUMBER                             -- header's change_id
1963    ,p_status_code               IN   NUMBER                             -- new phase
1964    ,p_update_ri_flag            IN   VARCHAR2 := 'Y'                    -- can also be 'N'
1965    ,p_api_caller                IN   VARCHAR2 := NULL                   -- can also be 'WF'
1966    ,p_comment                   IN   VARCHAR2 := NULL                   -- only used for co promote-to-implement action
1967   )
1968   IS
1969     l_api_name           CONSTANT VARCHAR2(30)  := 'Promote_Header';
1970     l_api_version        CONSTANT NUMBER := 1.0;
1971 
1972     l_fnd_user_id        NUMBER := TO_NUMBER(FND_PROFILE.VALUE('USER_ID'));
1973     l_fnd_login_id       NUMBER := TO_NUMBER(FND_PROFILE.VALUE('LOGIN_ID'));
1974 
1975     l_is_imp_phase_used  VARCHAR2(1) := 'F';
1976 
1977     l_last_status_type   NUMBER;
1978     l_last_status_code   NUMBER;
1979 
1980     l_return_status      VARCHAR2(1);
1981     l_msg_count          NUMBER;
1982     l_msg_data           VARCHAR2(2000);
1983 
1984     l_curr_status_code   eng_engineering_changes.status_code%TYPE;
1985 
1986     l_curr_phase_sn      eng_lifecycle_statuses.sequence_number%TYPE;
1987     l_new_phase_sn       eng_lifecycle_statuses.sequence_number%TYPE;
1988     l_max_sn             eng_lifecycle_statuses.sequence_number%TYPE;
1989     l_phase_sn           eng_lifecycle_statuses.sequence_number%TYPE;
1990     -- bug 9577905
1991     l_new_wf_status      eng_lifecycle_statuses.workflow_status%TYPE;
1992     -- bug 9577905
1993 
1994     l_new_status_type    eng_change_statuses.status_type%TYPE;
1995     l_ri_status_type     eng_change_statuses.status_type%TYPE;
1996 
1997     l_skip_promotion     VARCHAR2(1) := 'N';
1998 
1999     -- Select status_type of all lines of the header
2000     CURSOR c_lines IS
2001       SELECT s.status_type,
2002              l.complete_before_status_code,
2003              l.required_flag,
2004              l.change_type_id ,
2005              route.status_code wf_status_code
2006         FROM eng_change_routes route,
2007              eng_change_statuses s,
2008              eng_change_lines l
2009         WHERE s.status_code = l.status_code
2010         AND route.route_id(+) = l.route_id
2011         AND l.change_id = p_change_id ;
2012 
2013     l_line_status_type   eng_change_statuses.status_type%TYPE;
2014     l_status_code        eng_change_lines.complete_before_status_code%TYPE;
2015     l_required_flag      eng_change_lines.required_flag%TYPE := NULL;
2016     l_change_type_id     NUMBER ;
2017     l_wf_status_code     eng_change_routes.status_code%TYPE;
2018 
2019     -- Select all revised items
2020     CURSOR c_revItems IS
2021       SELECT status_code
2022         FROM eng_revised_items
2023         WHERE change_id = p_change_id
2024       FOR UPDATE;
2025 
2026 
2027     l_ri_status_code      eng_change_lines.status_code%TYPE;
2028     -- revItem's status_code's sequence_number
2029     l_ri_phase_sn         eng_lifecycle_statuses.sequence_number%TYPE;
2030 
2031     l_last_imp_flag       VARCHAR2(1) := 'N';
2032     l_cm_type_code        eng_engineering_changes.CHANGE_MGMT_TYPE_CODE%TYPE;
2033     l_base_cm_type_code   eng_change_order_types.BASE_CHANGE_MGMT_TYPE_CODE%TYPE;
2034     l_imp_eco_flag        VARCHAR2(1) := 'N';
2035 
2036     --l_co_type_id          eng_engineering_changes.CHANGE_ORDER_TYPE_ID%TYPE;
2037     l_auto_prop_flag      eng_type_org_properties.AUTO_PROPAGATE_FLAG%TYPE;
2038     l_change_notice       eng_engineering_changes.change_notice%TYPE;
2039     l_hierarchy_name      per_organization_structures.name%TYPE;
2040     l_org_name            org_organization_definitions.organization_name%TYPE;
2041     l_row_cnt             NUMBER := 0;
2042 
2043     l_doc_lc_object_flag  BOOLEAN := FALSE ;
2044 
2045 
2046     CURSOR c_orgProp IS
2047       SELECT op.auto_propagate_flag,
2048              ec.change_notice,
2049              pos.name,
2050              ood.name organization_name
2051         FROM eng_type_org_properties op,
2052              eng_engineering_changes ec,
2053              per_organization_structures pos,
2054              hr_all_organization_units_tl ood
2055         WHERE ec.change_id = p_change_id
2056           --AND ec.PLM_OR_ERP_CHANGE = 'PLM'
2057           AND op.change_type_id = ec.change_order_type_id
2058           AND op.organization_id = ec.organization_id
2059           AND op.propagation_status_code = p_status_code
2060           AND ec.hierarchy_id IS NOT NULL
2061           AND ec.organization_id IS NOT NULL
2062           AND pos.organization_structure_id(+) = ec.hierarchy_id
2063           AND ood.organization_id(+) = ec.organization_id
2064           AND ood.LANGUAGE = USERENV('LANG')
2065           -- R12 UT: Added where clause to not autopropagated if propagation has
2066           -- been initiated to any of the organizations manually or by the
2067           -- TTM process.
2068           AND NOT EXISTS (SELECT 1
2069                             FROM eng_change_obj_relationships
2070                            WHERE change_id = ec.change_id
2071                              AND object_to_name = 'ENG_CHANGE'
2072                              AND relationship_code = 'PROPAGATED_TO');
2073 
2074     --Bug No: 4767315
2075     --returns Y if there exists no revised items which are not cancelled for the CO
2076     CURSOR c_no_revisedItem IS
2077       SELECT 'Y'
2078       FROM DUAL
2079       WHERE not exists (SELECT 1
2080                         FROM eng_revised_items
2081                         WHERE change_id=p_change_id
2082                         AND status_code <> 5
2083                         );
2084 
2085     l_request_id          NUMBER := 0;
2086 
2087     l_action_id           eng_change_actions.action_id%TYPE;
2088 
2089     l_wf_status           eng_lifecycle_statuses.workflow_status%TYPE;
2090     l_wf_route_id         eng_lifecycle_statuses.change_wf_route_id%TYPE;
2091     l_new_route_id        eng_lifecycle_statuses.change_wf_route_id%TYPE;
2092 
2093     l_found_rev_item      VARCHAR2(1) := 'N';
2094 
2095     l_skip_wf             VARCHAR2(1) := 'N';
2096 
2097     l_skip        VARCHAR2(1) := 'N';
2098 
2099     l_eco_approval_status VARCHAR2(1); -- Bug 3769329
2100 
2101     -- bug 6695079 start
2102     l_temp_flag           VARCHAR2(1) := 'Y';
2103     l_obj_id1		  NUMBER := 0;
2104 
2105 		CURSOR c_lifecyc IS
2106 		   SELECT change_wf_route_id
2107 		   FROM eng_lifecycle_statuses
2108 		   WHERE entity_name = G_ENG_CHANGE
2109 		    AND entity_id1 = p_change_id
2110 		    AND active_flag = 'Y'
2111 		    and change_wf_route_id is not null;
2112 		-- bug 6695079 end
2113 
2114 
2115   BEGIN
2116 
2117     -- Standard Start of API savepoint
2118     SAVEPOINT Promote_Header;
2119     -- Standard call to check for call compatibility
2120     IF NOT FND_API.Compatible_API_Call ( l_api_version
2121                                         ,p_api_version
2122                                         ,l_api_name
2123                                         ,G_PKG_NAME )
2124     THEN
2125       RAISE FND_API.G_EXC_UNEXPECTED_ERROR;
2126     END IF;
2127     -- Initialize message list if p_init_msg_list is set to TRUE.
2128     IF FND_API.to_Boolean( p_init_msg_list ) THEN
2129        FND_MSG_PUB.initialize;
2130     END IF;
2131 
2132 
2133     -- For Test/Debug
2134     Check_And_Open_Debug_Session(p_debug, p_output_dir, p_debug_filename) ;
2135 
2136     -- R12 Comment out
2137     -- IF FND_API.to_Boolean( p_debug ) THEN
2138     --     Open_Debug_Session(p_output_dir, p_debug_filename ) ;
2139     -- END IF;
2140 
2141 
2142 
2143     -- Write debug message if debug mode is on
2144     IF g_debug_flag THEN
2145        Write_Debug('ENG_CHANGE_LIFECYCLE_UTIL.Promote_Header log');
2146        Write_Debug('-----------------------------------------------------');
2147        Write_Debug('p_change_id         : ' || p_change_id );
2148        Write_Debug('p_status_code       : ' || p_status_code );
2149        Write_Debug('p_api_caller        : ' || p_api_caller );
2150        Write_Debug('-----------------------------------------------------');
2151        Write_Debug('Initializing return status... ' );
2152     END IF;
2153 
2154     -- Initialize API return status to success
2155     x_return_status := FND_API.G_RET_STS_SUCCESS;
2156 
2157     -- FND_PROFILE package is not available for workflow (WF),
2158     -- therefore manually set WHO column values
2159     IF p_api_caller = 'WF' THEN
2160       l_fnd_user_id := G_ENG_WF_USER_ID;
2161       l_fnd_login_id := G_ENG_WF_LOGIN_ID;
2162     ELSIF p_api_caller = 'CP' THEN
2163       l_fnd_user_id := G_ENG_CP_USER_ID;
2164       l_fnd_login_id := G_ENG_CP_LOGIN_ID;
2165     END IF;
2166 
2167     -- Real code starts here -----------------------------------------------
2168 		-- bug 6695079 start
2169 		For lifecyc in c_lifecyc
2170 		loop
2171 				select template_flag, object_id1
2172 				into l_temp_flag, l_obj_id1
2173 				from eng_change_routes
2174 				where route_id = lifecyc.change_wf_route_id;
2175 
2176 			if ((l_temp_flag = 'N' or l_temp_flag = 'H') and l_obj_id1 = 0) then
2177 			      FND_MESSAGE.Set_Name('ENG','ENG_ROUTE_APPLY_NO_TEMP');
2178 			      FND_MSG_PUB.Add;
2179 			      RAISE FND_API.G_EXC_ERROR;
2180 			end if;
2181 		end loop;
2182 		-- bug 6695079 end
2183 
2184 
2185     -- First check if the header is CO and last implement phase has been used
2186     Is_CO_Last_Imp_Phase_Used
2187     ( p_change_id          => p_change_id
2188      ,x_is_used            => l_is_imp_phase_used
2189      ,x_last_status_type   => l_last_status_type
2190      ,x_last_status_code   => l_last_status_code
2191      );
2192 
2193     -- If so, refresh the last implement phase before promotion
2194     IF ( l_is_imp_phase_used = 'T' ) THEN
2195 
2196       -- Refresh workflow id and its status if applicable
2197       IF g_debug_flag THEN
2198         Write_Debug('Before: calling Refresh_WF_Route procedure ');
2199       END IF;
2200       Refresh_WF_Route
2201       ( p_api_version         => 1.0
2202        ,p_init_msg_list       => FND_API.G_FALSE
2203        ,p_commit              => FND_API.G_FALSE        --
2204        ,p_validation_level    => p_validation_level
2205        ,p_debug               => FND_API.G_FALSE
2206        ,p_output_dir          => p_output_dir
2207        ,p_debug_filename      => p_debug_filename
2208        ,x_return_status       => l_return_status
2209        ,x_msg_count           => l_msg_count
2210        ,x_msg_data            => l_msg_data
2211        ,p_change_id           => p_change_id
2212        ,p_status_code         => l_last_status_code
2213        ,p_wf_route_id         => NULL
2214        ,p_api_caller          => p_api_caller
2215        );
2216       IF g_debug_flag THEN
2217         Write_Debug('After: calling Refresh_WF_Route procedure: ' || l_return_status) ;
2218       END IF;
2219 
2220       -- Update the remaining columns of the phase row
2221       UPDATE eng_lifecycle_statuses
2222         SET start_date = null,
2223             completion_date = null,
2224             last_update_date = sysdate,
2225             last_updated_by = l_fnd_user_id,
2226             last_update_login = l_fnd_login_id
2227         WHERE entity_name = G_ENG_CHANGE
2228           AND entity_id1 = p_change_id
2229           AND status_code = l_last_status_code
2230           AND active_flag = 'Y'
2231           AND rownum = 1;
2232 
2233     END IF;
2234     -- Finished checking and refreshing the ECO final implement phase
2235 
2236     -- Get the sequence number for the current phase of the change header
2237     SELECT sequence_number, status_code
2238       INTO l_curr_phase_sn, l_curr_status_code
2239       FROM eng_lifecycle_statuses
2240       WHERE entity_name = G_ENG_CHANGE
2241         AND entity_id1 = p_change_id
2242         AND status_code = ( SELECT status_code
2243                               FROM eng_engineering_changes
2244                               WHERE change_id = p_change_id)
2245         AND active_flag = 'Y'
2246         AND rownum = 1;
2247 
2248     -- Get the sequence number for the new phase of the change header
2249     -- bug 9577905, add param l_new_wf_status
2250     SELECT sequence_number, workflow_status
2251       INTO l_new_phase_sn, l_new_wf_status
2252       FROM eng_lifecycle_statuses
2253       WHERE entity_name = G_ENG_CHANGE
2254         AND entity_id1 = p_change_id
2255         AND status_code = p_status_code
2256         AND active_flag = 'Y'
2257         AND rownum = 1;
2258 
2259     -- Get the status_type of the new phase
2260     SELECT status_type
2261       INTO l_new_status_type
2262       FROM eng_change_statuses
2263       WHERE status_code = p_status_code
2264         AND rownum = 1;
2265 
2266     -- Get the max sequence number in the lifecycle
2267     SELECT max(sequence_number)
2268       INTO l_max_sn
2269       FROM eng_lifecycle_statuses
2270       WHERE entity_name = G_ENG_CHANGE
2271         AND entity_id1 = p_change_id
2272         AND active_flag = 'Y';
2273 
2274     IF g_debug_flag THEN
2275        Write_Debug('Before comparing l_new_phase_sn = l_curr_phase_sn');
2276        Write_Debug('l_new_phase_sn      : ' || l_new_phase_sn );
2277        Write_Debug('l_curr_phase_sn     : ' || l_curr_phase_sn );
2278        -- bug 9577905
2279        Write_Debug('l_new_wf_status     : ' || l_new_wf_status );
2280     END IF;
2281 
2282     -- Sanity check to make sure the new phase is after the current phase
2283     -- bug 9577905, if the new phase is not be completed
2284     IF (l_new_phase_sn <= l_curr_phase_sn
2285         and l_new_wf_status = Eng_Workflow_Util.G_RT_COMPLETED)THEN
2286       FND_MESSAGE.Set_Name('ENG','ENG_OBJ_STATE_CHANGED');
2287       FND_MSG_PUB.Add;
2288       RAISE FND_API.G_EXC_ERROR;
2289     END IF;
2290 
2291 
2292     --
2293     -- Check for all open line/tasks complete_before_status_code
2294     -- R12B Change Line will support complete_before_status_code
2295     -- without required_flag
2296     --
2297     IF g_debug_flag THEN
2298        Write_Debug('Before checking open line/tasks'' complete_before_status_code');
2299     END IF;
2300     OPEN c_lines;
2301       LOOP
2302         FETCH c_lines
2303           INTO l_line_status_type,
2304                l_status_code,  -- line's complete_before_status_code
2305                l_required_flag,
2306                l_change_type_id,
2307                l_wf_status_code ;
2308 
2309         EXIT WHEN c_lines%NOTFOUND;
2310 
2311 
2312         -- R12B, In case of Line, assuming Required Flag is always NULL
2313         IF ( ( l_required_flag IS NULL OR l_required_flag = 'Y' )
2314              AND l_status_code IS NOT NULL
2315              AND l_line_status_type <> G_ENG_COMPLETED
2316              AND l_line_status_type <> G_ENG_IMPLEMENTED
2317              AND l_line_status_type <> G_ENG_CANCELLED )
2318         THEN
2319 
2320           IF g_debug_flag THEN
2321             Write_Debug('Found one open line or mandatory task... ');
2322             Write_Debug('  line status type = ' || l_line_status_type );
2323             Write_Debug('  l_wf_status_code = ' || l_wf_status_code );
2324             Write_Debug('  l_change_type_id = ' || l_change_type_id );
2325 
2326             IF ( l_required_flag IS NULL OR l_required_flag = 'Y' ) THEN
2327               Write_Debug('  line/task required flag is NULL or Y ');
2328             END IF;
2329 
2330           END IF;
2331 
2332 
2333           --
2334           -- R12B
2335           -- There is no additional logic required so far for the Line Status check
2336           --
2337           -- Get the sequence_number for line/task's complete_before_status_code
2338           SELECT sequence_number
2339             INTO l_phase_sn
2340             FROM eng_lifecycle_statuses
2341             WHERE entity_name = G_ENG_CHANGE
2342               AND entity_id1 = p_change_id
2343               AND status_code = l_status_code
2344               AND active_flag = 'Y'
2345               AND rownum = 1;
2346 
2347           -- If open line's complete_before_status_code is behind the new phase's
2348           -- status_code, raise error
2349           IF (l_phase_sn <= l_new_phase_sn ) THEN
2350             FND_MESSAGE.Set_Name('ENG','ENG_EXIST_LINE_COMP_BF');
2351             FND_MSG_PUB.Add;
2352             RAISE FND_API.G_EXC_ERROR;
2353           END IF;
2354 
2355         END IF;
2356       END LOOP;
2357     CLOSE c_lines;
2358 
2359 
2360     IF g_debug_flag THEN
2361        Write_Debug('After checking open line/tasks'' complete_before_status_code');
2362     END IF;
2363 
2364 
2365     -- Removing last sequence check on implement phase for bug 3446436
2366     -- Replacing it by simple implement phase type check
2367     IF (l_new_status_type = G_ENG_IMPLEMENTED) THEN
2368       -- New phase type is implementation
2369       IF g_debug_flag THEN
2370          Write_Debug('Branch: New phase type is implementation.');
2371       END IF;
2372 
2373       -- Check if the new phase is the last in the lifecycle definition
2374       -- and set the flag if so
2375       IF g_debug_flag THEN
2376          Write_Debug('Before comparing l_new_phase_sn = l_max_sn');
2377       END IF;
2378       IF (l_new_phase_sn = l_max_sn) THEN
2379         -- New phase is the last lifecycle phase
2380         IF g_debug_flag THEN
2381            Write_Debug('Branch: New phase is the last implement phase');
2382         END IF;
2383         -- bug 9899944
2384         -- if the last approval workflow is skipped, the approval status
2385         -- is still in 'Approval Request' provided multiple workflow defined for the change type
2386         -- Hence need to set the approval status from 'Approval request' to 'Approved' before it's get implemented
2387         UPDATE eng_engineering_changes
2388             SET approval_status_type = G_ENG_APPR_APPROVED,
2389                 approval_date = sysdate,
2390                 last_update_date = sysdate,
2391                 last_updated_by = l_fnd_user_id,
2392                 last_update_login = l_fnd_login_id
2393             WHERE change_id = p_change_id
2394             and approval_status_type = G_ENG_APPR_REQUESTED;
2395         -- Set the flag
2396         l_last_imp_flag := 'Y';
2397       END IF;
2398 
2399     -- Fix for bug 3731977
2400     -- Get the change header's cm type and base cm type
2401     SELECT eec.change_mgmt_type_code, ecot.base_change_mgmt_type_code, eec.approval_status_type
2402       INTO l_cm_type_code, l_base_cm_type_code, l_eco_approval_status
2403       FROM eng_engineering_changes eec,
2404            eng_change_order_types ecot
2405       WHERE eec.change_id = p_change_id
2406         AND ecot.change_order_type_id = eec.change_order_type_id;
2407 
2408       -- If there are still open lines or mandatory tasks, raise error message
2409       OPEN c_lines;
2410         LOOP
2411           FETCH c_lines INTO l_line_status_type,
2412                              l_status_code,
2413                              l_required_flag,
2414                              l_change_type_id,
2415                              l_wf_status_code ;
2416 
2417           EXIT WHEN c_lines%NOTFOUND;
2418           IF ( (l_required_flag IS NULL OR l_required_flag = 'Y')
2419                -- line: NULL; task: 'Y'
2420                AND l_line_status_type <> G_LINE_COMPLETED
2421                AND l_line_status_type <> G_ENG_IMPLEMENTED
2422                AND l_line_status_type <> G_LINE_CANCELLED
2423                --   R12.C Enhancement : Added following condition because NIRs can have different line statuses
2424                AND l_base_cm_type_code <> G_ENG_NEW_ITEM_REQ)
2425           THEN
2426 
2427             IF g_debug_flag THEN
2428               Write_Debug('Found one mandatory open line/task... ');
2429               Write_Debug('  line status type = ' || l_line_status_type );
2430               IF ( l_required_flag IS NULL OR l_required_flag = 'Y' ) THEN
2431                 Write_Debug('  line required flag is NULL or Y' );
2432               END IF;
2433             END IF;
2434 
2435             --
2436             -- R12B
2437             -- There is no additional logic required so far for the Line Status check
2438             --
2439             -- In case of the wf triggered session
2440             IF ( p_api_caller = 'WF' ) THEN
2441               l_skip_promotion := 'Y';
2442             ELSE
2443               -- Stop and return error message
2444               FND_MESSAGE.Set_Name('ENG','ENG_EXIST_ACTIVE_LINES');
2445               FND_MSG_PUB.Add;
2446               RAISE FND_API.G_EXC_ERROR;
2447             END IF;
2448 
2449           END IF;
2450         END LOOP;
2451       CLOSE c_lines;
2452       IF g_debug_flag THEN
2453          Write_Debug('After open mandatory lines check');
2454       END IF;
2455 
2456     END IF; -- end of if (phase type = implementation)
2457 
2458 
2459     --Bug No:4767315
2460     --Skip implementation if no active or implemented revised items exist for a change order.
2461     open c_no_revisedItem;
2462     fetch c_no_revisedItem into l_skip;
2463     close c_no_revisedItem;
2464 
2465 
2466 
2467     -- Skip promoting CO to implement phase w/o active revised item
2468     IF (l_base_cm_type_code = G_ENG_ECO
2469         AND l_last_imp_flag = 'Y'
2470         AND l_skip = 'Y'
2471         )
2472     THEN
2473       -- Do not promote CO to implement phase in order to comply with the ERP behavior
2474       l_skip_promotion := 'Y';
2475       IF g_debug_flag THEN
2476         Write_Debug('Do not promote CO to implement phase to comply with ERP');
2477       END IF;
2478       -- Raise error message to the caller
2479       FND_MESSAGE.Set_Name('ENG','ENG_IMP_STOP_WO_ACT_REV_ITEM');
2480       FND_MSG_PUB.Add;
2481       RAISE FND_API.G_EXC_ERROR;
2482 
2483     END IF;
2484 
2485 
2486     -- Fix for bug 4767315 - end
2487     -- Fix for Bug 3769329
2488     IF (l_base_cm_type_code = G_ENG_ECO
2489         AND l_last_imp_flag = 'Y'
2490         AND l_eco_approval_status = Eng_Workflow_Util.G_REJECTED
2491         )
2492     THEN
2493       -- Do not promote CO to implement phase in order to comply with the ERP approval status validation
2494       l_skip_promotion := 'Y';
2495       IF g_debug_flag THEN
2496         Write_Debug('Do not promote CO to implement phase to comply with ERP approval status validation');
2497       END IF;
2498       -- Raise error message to the caller
2499       FND_MESSAGE.Set_Name('ENG','ENG_IMP_STOP_APPR_REJECTED');
2500       FND_MSG_PUB.Add;
2501       RAISE FND_API.G_EXC_ERROR;
2502 
2503     END IF;
2504     -- End of fix for 3769329
2505 
2506     IF (l_skip_promotion = 'Y') THEN
2507       IF g_debug_flag THEN
2508          Write_Debug('Branch: skipping auto promotion');
2509       END IF;
2510     ELSE
2511 
2512       -- If the change header is of type ECO and the new phase is of type IMPLEMENTED,
2513       -- then do not update change header and revised items' status_code (phase)
2514       -- only save the new phase into the header's promote_status_code column
2515       -- actual promotion will be taken care of later in the concurrent program
2516       -- as a special case
2517       IF (l_base_cm_type_code = G_ENG_ECO AND l_last_imp_flag = 'Y') THEN
2518         l_imp_eco_flag := 'Y';
2519         l_skip_wf := 'Y';   -- fix for bug 3479509 design change of launching wf after concurrent program
2520 
2521         -- save new phase into header's promote_status_code column
2522         UPDATE eng_engineering_changes
2523           SET promote_status_code = p_status_code,
2524               last_update_date = sysdate,
2525               last_updated_by = l_fnd_user_id,
2526               last_update_login = l_fnd_login_id
2527           WHERE change_id = p_change_id;
2528 
2529         IF g_debug_flag THEN
2530            Write_Debug('Skipped: Updating header and revised items to the new phase');
2531            Write_Debug('But: last <implement> phase saved into promote_status_code column');
2532         END IF;
2533         -- Fix for 3479509 by commenting out code
2534         -- Behavior changed to leaving completion_date of previous phase and
2535         -- start_date of implement phase blank in case of CO promotion to
2536         -- implement phase
2537         /*
2538         -- Update start_date of the implement phase
2539         UPDATE eng_lifecycle_statuses
2540           SET start_date = sysdate,
2541               completion_date = null,
2542               last_update_date = sysdate,
2543               last_updated_by = l_fnd_user_id,
2544               last_update_login = l_fnd_login_id
2545           WHERE entity_name = G_ENG_CHANGE
2546             AND entity_id1 = p_change_id
2547             AND status_code = p_status_code
2548             AND active_flag = 'Y';
2549         */
2550         -- Fix for 3479509 - end
2551 
2552         -- If the CO's last implement type phase is already used, refresh its workflow id and status
2553         SELECT workflow_status, change_wf_route_id
2554         INTO l_wf_status, l_wf_route_id
2555         FROM eng_lifecycle_statuses
2556         WHERE entity_name = G_ENG_CHANGE
2557         AND entity_id1 = p_change_id
2558         AND status_code = p_status_code
2559         AND active_flag = 'Y'
2560         AND rownum = 1;
2561 
2562 
2563         IF (l_wf_route_id IS NOT NULL AND l_wf_status <> Eng_Workflow_Util.G_RT_NOT_STARTED)
2564         THEN
2565 
2566           -- Get a new workflow route_id
2567           Eng_Change_Route_Util.REFRESH_ROUTE
2568           ( X_NEW_ROUTE_ID   => l_new_route_id,
2569             P_ROUTE_ID       => l_wf_route_id,
2570             P_USER_ID        => l_fnd_user_id,
2571             P_API_CALLER     => p_api_caller
2572           );
2573 
2574           -- refresh imp phase row
2575           UPDATE eng_lifecycle_statuses
2576             SET change_wf_route_id = l_new_route_id,
2577                 workflow_status = Eng_Workflow_Util.G_RT_NOT_STARTED,
2578                 last_update_date = sysdate,
2579                 last_updated_by = l_fnd_user_id,
2580                 last_update_login = l_fnd_login_id
2581             WHERE entity_name = G_ENG_CHANGE
2582               AND entity_id1 = p_change_id
2583               AND status_code = p_status_code
2584               AND active_flag = 'Y';
2585 
2586         END IF;
2587 
2588         --
2589         -- Bug 4967289 Fix
2590         -- Call ENG_ATTACHMENT_IMPLEMENTATION.Validate_floating_version
2591         --Removed this code from here as it is not required here Attachment impl is taking care of it.
2592        /* IF g_debug_flag THEN
2593             Write_Debug('Calling ENG_ATTACHMENT_IMPLEMENTATION.Validate_floating_version ');
2594         END IF;
2595 
2596         ENG_ATTACHMENT_IMPLEMENTATION.Validate_floating_version
2597         ( p_api_version          => 1.0
2598          ,x_return_status        =>    l_return_status
2599          ,x_msg_count            =>    l_msg_count
2600          ,x_msg_data             =>    l_msg_data
2601          ,p_change_id            =>    p_change_id
2602          ,p_rev_item_seq_id      =>    NULL
2603         );
2604 
2605         IF g_debug_flag THEN
2606             Write_Debug('After: calling ENG_ATTACHMENT_IMPLEMENTATION.Validate_floating_version API: ' || l_return_status) ;
2607         END IF;*/
2608 
2609         IF ( l_return_status <>  FND_API.G_RET_STS_SUCCESS ) THEN
2610             x_return_status := l_return_status;
2611             x_msg_count := l_msg_count;
2612             x_msg_data := l_msg_data;
2613             --#FND_MESSAGE.Set_Name('ENG','ENG_ERROR_CALLING_PS_API');
2614             --#FND_MESSAGE.Set_Token('OBJECT_NAME', 'ENG_ECO_UTIL.Propagate_ECO');
2615             --#FND_MSG_PUB.Add;
2616             RAISE FND_API.G_EXC_ERROR;
2617         END IF;
2618         -- End of Bug4967289 Fix
2619 
2620       ELSE
2621         -- Normal phase promotion
2622         -- Complete the current phase
2623         UPDATE eng_lifecycle_statuses
2624           SET completion_date = sysdate,
2625               last_update_date = sysdate,
2626               last_updated_by = l_fnd_user_id,
2627               last_update_login = l_fnd_login_id
2628           WHERE entity_name = G_ENG_CHANGE
2629             AND entity_id1 = p_change_id
2630             AND status_code = l_curr_status_code
2631             AND active_flag = 'Y';
2632         IF g_debug_flag THEN
2633           Write_Debug('After updating eng_lifecycle_statuses.completion_date.');
2634           Write_Debug('  Row count = ' || SQL%ROWCOUNT);
2635         END IF;
2636         -- Sanity check, only one record can qualify the condition
2637         IF SQL%ROWCOUNT <> 1 THEN
2638           FND_MESSAGE.Set_Name('ENG','ENG_NOT_EXACTLY_ONE_RECORD');
2639           FND_MSG_PUB.Add;
2640           RAISE FND_API.G_EXC_ERROR;
2641         END IF;
2642         IF g_debug_flag THEN
2643            Write_Debug('After: Completing the current phase and promote to the next phase');
2644         END IF;
2645 
2646         -- Promote change header to the new phase
2647         UPDATE eng_engineering_changes
2648           SET status_code = p_status_code,
2649               promote_status_code = null,
2650               status_type = l_new_status_type,
2651               last_update_date = sysdate,
2652               last_updated_by = l_fnd_user_id,
2653               last_update_login = l_fnd_login_id
2654           WHERE change_id = p_change_id;
2655 
2656         -- Bug 5989058.
2657 				-- Set the implementation date if the status is completed or implemented
2658 				if( l_new_status_type = G_ENG_COMPLETED OR
2659 				    l_new_status_type = G_ENG_IMPLEMENTED  ) THEN
2660 					UPDATE eng_engineering_changes SET
2661 						completion_date = SYSDATE
2662 					WHERE change_id = p_change_id;
2663 				END IF;
2664 
2665         IF g_debug_flag THEN
2666           Write_Debug('After updating eng_engineering_changes.');
2667           Write_Debug('  Row count = ' || SQL%ROWCOUNT);
2668         END IF;
2669 
2670         IF g_debug_flag THEN
2671           Write_Debug('Before updateing revised items.');
2672         END IF;
2673         IF ( p_update_ri_flag = 'Y' ) THEN
2674           IF g_debug_flag THEN
2675             Write_Debug('In updateing revised items.');
2676           END IF;
2677 
2678           -- Promote revised items to the new phase
2679           OPEN c_revItems;
2680           LOOP
2681             FETCH c_revItems INTO l_ri_status_code;
2682             EXIT WHEN c_revItems%NOTFOUND;
2683 
2684             IF g_debug_flag THEN
2685               Write_Debug('In Cursor c_revItems to update revised items.');
2686             END IF;
2687 
2688             -- Get the status_type of the revised item phase
2689             SELECT status_type
2690               INTO l_ri_status_type
2691               FROM eng_change_statuses
2692               WHERE status_code = l_ri_status_code
2693                 AND rownum = 1;
2694 
2695             -- Update only those which are open
2696             -- and whose phase is behind the new promoting phase
2697             IF (l_ri_status_type <> G_ENG_IMPLEMENTED
2698                 AND l_ri_status_type <> G_ENG_CANCELLED) THEN
2699 
2700               -- Get the sequence_number of the revised item phase
2701               -- Note: moved this query inside this IF block because cancel
2702               --       status is not in the regular lifecycle phase definitions
2703               SELECT sequence_number
2704                 INTO l_ri_phase_sn
2705                 FROM eng_lifecycle_statuses
2706                 WHERE entity_name = G_ENG_CHANGE
2707                   AND entity_id1 = p_change_id
2708                   AND status_code = l_ri_status_code
2709                   AND active_flag = 'Y'
2710                   AND rownum = 1;
2711 
2712               -- Only promote those revised items whose phase are lower than
2713               -- the new header promotion phase
2714               IF (l_ri_phase_sn < l_new_phase_sn) THEN
2715                 UPDATE eng_revised_items
2716                   SET status_code = p_status_code,
2717                       status_type = l_new_status_type,
2718                       last_update_date = sysdate,
2719                       last_updated_by = l_fnd_user_id,
2720                       last_update_login = l_fnd_login_id
2721                   WHERE CURRENT OF c_revItems;
2722                 IF g_debug_flag THEN
2723                   Write_Debug('After updating eng_revised_items.');
2724                   Write_Debug('  Row count = ' || SQL%ROWCOUNT);
2725                 END IF;
2726               END IF; -- ri_phase < new_header_phase
2727             END IF; -- not imp or cancelled
2728 
2729           END LOOP;
2730           CLOSE c_revItems;
2731         END IF; -- p_update_ri_flag = 'Y'
2732 
2733         IF g_debug_flag THEN
2734            Write_Debug('Done: Updating header and revised items to the new phase');
2735         END IF;
2736 
2737         -- Update the new phase's start_date
2738         -- Bug 13810488: In some cases, completion_date is not null and which is earlier than start_date
2739         UPDATE eng_lifecycle_statuses
2740           SET start_date = sysdate,
2741               completion_date = null, -- Bug 13810488
2742               last_update_date = sysdate,
2743               last_updated_by = l_fnd_user_id,
2744               last_update_login = l_fnd_login_id
2745           WHERE entity_name = G_ENG_CHANGE
2746             AND entity_id1 = p_change_id
2747             AND status_code = p_status_code
2748             AND active_flag = 'Y';
2749         IF g_debug_flag THEN
2750           Write_Debug('After updating eng_lifecycle_statuses.start_date and null completion_date.');
2751           Write_Debug('  Row count = ' || SQL%ROWCOUNT);
2752         END IF;
2753 
2754       END IF;
2755 
2756 
2757       -- auto propagate if necessary
2758       l_row_cnt := 0;
2759       OPEN c_orgProp;
2760         LOOP
2761           FETCH c_orgProp
2762             INTO l_auto_prop_flag,
2763                  l_change_notice,
2764                  l_hierarchy_name,
2765                  l_org_name;
2766           EXIT WHEN c_orgProp%NOTFOUND;
2767 
2768           l_row_cnt := l_row_cnt + 1;
2769           -- verify the uniqueness of the record
2770           IF (l_row_cnt > 1) THEN
2771             IF g_debug_flag THEN
2772               Write_Debug('Error: more than one propagation policy is found');
2773             END IF;
2774           END IF;
2775 
2776           IF g_debug_flag THEN
2777             Write_Debug('one record for propagation policy is found');
2778             Write_Debug('l_auto_prop_flag         : ' || l_auto_prop_flag );
2779             Write_Debug('l_change_notice          : ' || l_change_notice );
2780             Write_Debug('l_hierarchy_name         : ' || l_hierarchy_name );
2781             Write_Debug('l_org_name               : ' || l_org_name );
2782           END IF;
2783 
2784           IF ( l_auto_prop_flag = 'Y') THEN
2785             IF g_debug_flag THEN
2786               Write_Debug('which needs auto propagation');
2787             END IF;
2788 
2789             ENG_ECO_UTIL.Propagate_ECO
2790             (
2791               p_api_version          =>    1.0
2792              ,p_init_msg_list        =>    FND_API.G_FALSE
2793              ,p_commit               =>    FND_API.G_FALSE
2794              ,p_validation_level     =>    FND_API.G_VALID_LEVEL_FULL
2795              ,p_debug                =>    p_debug --FND_API.G_FALSE
2796              ,p_output_dir           =>    p_output_dir
2797              ,p_debug_filename       =>    NULL  --p_debug_filename
2798              ,x_return_status        =>    l_return_status
2799              ,x_msg_count            =>    l_msg_count
2800              ,x_msg_data             =>    l_msg_data
2801              ,p_change_id            =>    p_change_id
2802              ,p_change_notice        =>    l_change_notice
2803              ,p_hierarchy_name       =>    l_hierarchy_name
2804              ,p_org_name             =>    l_org_name
2805              ,x_request_id           =>    l_request_id
2806             );
2807 
2808             IF g_debug_flag THEN
2809               Write_Debug('After: calling propagate_eco API: ' || l_return_status) ;
2810             END IF;
2811 
2812             IF ( l_return_status <>  FND_API.G_RET_STS_SUCCESS ) THEN
2813               x_return_status := l_return_status;
2814               x_msg_count := l_msg_count;
2815               x_msg_data := l_msg_data;
2816               --#FND_MESSAGE.Set_Name('ENG','ENG_ERROR_CALLING_PS_API');
2817               --#FND_MESSAGE.Set_Token('OBJECT_NAME', 'ENG_ECO_UTIL.Propagate_ECO');
2818               --#FND_MSG_PUB.Add;
2819               RAISE FND_API.G_EXC_ERROR;
2820             END IF;
2821 
2822             IF g_debug_flag THEN
2823               Write_Debug('Successful: calling propagate_eco API');
2824               Write_Debug('l_request_id       : ' || l_request_id );
2825             END IF;
2826 
2827             IF g_debug_flag THEN
2828                Write_Debug('Before: saving action log');
2829             END IF;
2830             l_action_id := 0;
2831             -- create new action log
2832             -- Bug Fix: 3547844
2833             -- In case of Auto-Propgation Action Log
2834             -- Who column is Workflow
2835             ENG_CHANGE_ACTIONS_UTIL.Create_Change_Action
2836             ( p_api_version           => 1.0
2837             , p_init_msg_list         => FND_API.G_FALSE        --
2838             , p_commit                => FND_API.G_FALSE        --
2839             , p_validation_level      => FND_API.G_VALID_LEVEL_FULL
2840             , p_debug                 => p_debug --FND_API.G_FALSE
2841             , p_output_dir            => p_output_dir
2842             , p_debug_filename        => NULL
2843             , x_return_status         => l_return_status
2844             , x_msg_count             => l_msg_count
2845             , x_msg_data              => l_msg_data
2846             , p_action_type           => ENG_CHANGE_ACTIONS_UTIL.G_ACT_PROPAGATE
2847             , p_object_name           => G_ENG_CHANGE
2848             , p_object_id1            => p_change_id
2849             , p_object_id2            => NULL
2850             , p_object_id3            => NULL
2851             , p_object_id4            => NULL
2852             , p_object_id5            => NULL
2853             , p_parent_action_id      => -1
2854             , p_status_code           => NULL
2855             , p_action_date           => SYSDATE
2856             , p_change_description    => NULL
2857             , p_user_id               => G_ENG_WF_USER_ID
2858             , p_api_caller            => 'WF'
2859             , x_change_action_id      => l_action_id
2860             );
2861 
2862 
2863             IF g_debug_flag THEN
2864                Write_Debug('After: saving action log: ' || l_return_status) ;
2865                Write_Debug('l_action_id       : ' || l_action_id );
2866             END IF;
2867 
2868             IF ( l_return_status <>  FND_API.G_RET_STS_SUCCESS )
2869             THEN
2870               x_return_status := l_return_status;
2871               x_msg_count := l_msg_count;
2872               x_msg_data := l_msg_data;
2873               --#FND_MESSAGE.Set_Name('ENG','ENG_ERROR_CALLING_PS_API');
2874               --#FND_MESSAGE.Set_Token('OBJECT_NAME', 'ENG_CHANGE_ACTIONS_UTIL.Create_Change_Action');
2875               --#FND_MSG_PUB.Add;
2876               RAISE FND_API.G_EXC_ERROR;
2877             END IF;
2878 
2879             IF g_debug_flag THEN
2880                Write_Debug('Successful: saving action log');
2881             END IF;
2882 
2883           ELSE
2884             IF g_debug_flag THEN
2885               Write_Debug('which does not need auto propagation');
2886             END IF;
2887           END IF;
2888 
2889         END LOOP;
2890       CLOSE c_orgProp;
2891       IF g_debug_flag THEN
2892          Write_Debug('After checking propagation policy');
2893       END IF;
2894 
2895 
2896       -- R12B
2897       -- In case of Document LC Change Object, call ENG_DOCUMENT_UTIL.Change_Doc_LC_Phase
2898       -- to validate and sync Document LC Phase
2899       l_doc_lc_object_flag := ENG_DOCUMENT_UTIL.Is_Dom_Document_Lifecycle
2900                              ( p_change_id => p_change_id
2901                              , p_base_change_mgmt_type_code => l_base_cm_type_code
2902                              ) ;
2903 
2904       IF (l_doc_lc_object_flag)
2905       THEN
2906           IF g_debug_flag THEN
2907              Write_Debug('Before: calling ENG_DOCUMENT_UTIL.Change_Doc_LC_Phase');
2908              Write_Debug('  p_change_id =   ' || p_change_id);
2909              Write_Debug('  p_status_code = ' || p_status_code);
2910              Write_Debug('  p_action_type =   ' || G_ENG_PROMOTE);
2911           END IF;
2912 
2913           ENG_DOCUMENT_UTIL.Change_Doc_LC_Phase
2914           ( p_api_version         => 1.0
2915            ,p_init_msg_list       => FND_API.G_FALSE
2916            ,p_commit              => FND_API.G_FALSE
2917            ,p_validation_level    => p_validation_level
2918            ,p_debug               => FND_API.G_FALSE
2919            ,p_output_dir          => p_output_dir
2920            ,p_debug_filename      => p_debug_filename
2921            ,x_return_status       => l_return_status
2922            ,x_msg_count           => l_msg_count
2923            ,x_msg_data            => l_msg_data
2924            ,p_change_id           => p_change_id
2925            ,p_lc_phase_code       => p_status_code
2926            ,p_action_type         =>  G_ENG_PROMOTE
2927            ,p_api_caller          => p_api_caller
2928           ) ;
2929 
2930 
2931           IF g_debug_flag THEN
2932              Write_Debug('After: calling ENG_DOCUMENT_UTIL.Change_Doc_LC_Phase: ' || l_return_status) ;
2933           END IF;
2934 
2935           IF ( l_return_status <>  FND_API.G_RET_STS_SUCCESS )
2936           THEN
2937             x_return_status := l_return_status;
2938             x_msg_count := l_msg_count;
2939             x_msg_data := l_msg_data;
2940             RAISE FND_API.G_EXC_ERROR;
2941           END IF;
2942 
2943           IF g_debug_flag THEN
2944              Write_Debug('Successful: ENG_DOCUMENT_UTIL.Change_Doc_LC_Phase');
2945           END IF;
2946 
2947       END IF ; -- if ( Change Object is Documet LC Object)
2948       --
2949       -- End of R12B Document LC Change Object Enh Change
2950       --
2951 
2952 
2953 
2954 -- Bug 13810488 Start
2955 -- Note: If new workflow status is already IN_PROGRESS, do not start WF
2956       IF (l_new_phase_sn > l_curr_phase_sn
2957           or  l_new_wf_status <> Eng_Workflow_Util.G_RT_IN_PROGRESS) THEN
2958           -- Start workflow for new phase if necessary
2959           Start_WF_OnlyIf_Necessary
2960           ( p_api_version       => 1.0
2961            ,p_init_msg_list     => FND_API.G_FALSE
2962            ,p_commit            => FND_API.G_FALSE
2963            ,p_validation_level  => p_validation_level
2964            ,p_debug             => FND_API.G_FALSE
2965            ,p_output_dir        => p_output_dir
2966            ,p_debug_filename    => p_debug_filename
2967            ,x_return_status     => l_return_status
2968            ,x_msg_count         => l_msg_count
2969            ,x_msg_data          => l_msg_data
2970            ,p_change_id         => p_change_id
2971            ,p_status_code       => p_status_code
2972            ,p_status_type       => l_new_status_type
2973            ,p_sequence_number   => l_new_phase_sn
2974            ,p_imp_eco_flag      => l_imp_eco_flag
2975            ,p_api_caller        => p_api_caller
2976            ,p_action_type       => G_ENG_PROMOTE
2977            ,p_comment           => p_comment        -- only used for co promote-to-implement action
2978            ,p_skip_wf           => l_skip_wf        -- fix for bug 3479509 design change of launching wf after concurrent program
2979           );
2980 
2981           IF g_debug_flag THEN
2982              Write_Debug('After call to procedure Start_WF_OnlyIf_Necessary');
2983           END IF;
2984 
2985           IF ( l_return_status <>  FND_API.G_RET_STS_SUCCESS ) THEN
2986             x_return_status := l_return_status;
2987             x_msg_count := l_msg_count;
2988             x_msg_data := l_msg_data;
2989             --#FND_MESSAGE.Set_Name('ENG','ENG_ERROR_CALLING_WF_API');
2990             --#FND_MSG_PUB.Add;
2991             RAISE FND_API.G_EXC_ERROR;
2992           END IF;
2993      END IF; -- IF l_new_phase_sn ... or l_new_wf_statusor ...
2994 -- Bug 13810488 End
2995 
2996 
2997       --
2998       -- R12B
2999       -- Change Line and Line Workflow Enhancement
3000       -- Kick off Change Line Workflow if Start After Status is defined in
3001       -- Change Line and the Change Line has a Workflow "Not Started"
3002       --
3003       --
3004       -- The associated Line Workflow will be automatically started once
3005       -- the Header Workflow Status reaches the status specified in 'Start After Status'
3006       -- if the Line Workflow is still Not Started.
3007       --
3008       -- Start workflow for new phase if necessary
3009       IF (NOT l_doc_lc_object_flag AND l_skip_wf <> 'Y')
3010       THEN
3011 
3012           IF g_debug_flag THEN
3013              Write_Debug('calling procedure Start_Line_Workflow');
3014           END IF;
3015 
3016           Start_Line_Workflow
3017           ( p_api_version           => 1.0
3018            ,p_init_msg_list         => FND_API.G_FALSE
3019            ,p_commit                => FND_API.G_FALSE
3020            ,p_validation_level      => p_validation_level
3021            ,p_debug                 => FND_API.G_FALSE
3022            ,p_output_dir            => p_output_dir
3023            ,p_debug_filename        => p_debug_filename
3024            ,x_return_status         => l_return_status
3025            ,x_msg_count             => l_msg_count
3026            ,x_msg_data              => l_msg_data
3027            ,p_change_id             => p_change_id
3028            ,p_new_status_code       => p_status_code
3029            ,p_cur_status_code       => l_curr_status_code
3030            ,p_api_caller            => p_api_caller
3031            ,p_action_type           => G_ENG_PROMOTE
3032           );
3033 
3034           IF g_debug_flag THEN
3035              Write_Debug('After call to procedure Start_Line_Workflow');
3036           END IF;
3037 
3038           IF ( l_return_status <>  FND_API.G_RET_STS_SUCCESS ) THEN
3039             x_return_status := l_return_status;
3040             x_msg_count := l_msg_count;
3041             x_msg_data := l_msg_data;
3042             RAISE FND_API.G_EXC_ERROR;
3043           END IF;
3044       END IF ;
3045       --
3046       -- End of R12B Change Line and Line Workflow Enhancement
3047       --
3048 
3049     END IF; -- if (p_skip_promotion='Y')
3050 
3051 
3052     -- Standard ending code ------------------------------------------------
3053     IF FND_API.To_Boolean ( p_commit ) THEN
3054       COMMIT WORK;
3055     END IF;
3056 
3057     FND_MSG_PUB.Count_And_Get
3058     ( p_count        =>      x_msg_count,
3059       p_data         =>      x_msg_data );
3060 
3061     IF g_debug_flag THEN
3062       Write_Debug('Finish. End Of procedure: Promote_Header');
3063     END IF;
3064 
3065     IF FND_API.to_Boolean( p_debug ) THEN
3066       Close_Debug_Session;
3067     END IF;
3068 
3069   EXCEPTION
3070     WHEN FND_API.G_EXC_ERROR THEN
3071       --ROLLBACK TO Promote_Header;
3072       x_return_status := FND_API.G_RET_STS_ERROR;
3073       FND_MSG_PUB.Count_And_Get
3074       ( p_count        =>      x_msg_count
3075        ,p_data         =>      x_msg_data );
3076       IF g_debug_flag THEN
3077         Write_Debug('Rollback and Finish with expected error.') ;
3078       END IF;
3079       IF FND_API.to_Boolean( p_debug ) THEN
3080         Close_Debug_Session;
3081       END IF;
3082     WHEN FND_API.G_EXC_UNEXPECTED_ERROR THEN
3083       --ROLLBACK TO Promote_Header;
3084       x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
3085       FND_MSG_PUB.Count_And_Get
3086       ( p_count        =>      x_msg_count
3087        ,p_data         =>      x_msg_data );
3088       IF g_debug_flag THEN
3089         Write_Debug('Rollback and Finish with unexpected error.') ;
3090       END IF;
3091       IF FND_API.to_Boolean( p_debug ) THEN
3092         Close_Debug_Session;
3093       END IF;
3094     WHEN OTHERS THEN
3095       --ROLLBACK TO Promote_Header;
3096       x_return_status := FND_API.G_RET_STS_UNEXP_ERROR ;
3097       IF FND_MSG_PUB.Check_Msg_Level ( FND_MSG_PUB.G_MSG_LVL_UNEXP_ERROR )
3098       THEN
3099         FND_MSG_PUB.Add_Exc_Msg ( G_PKG_NAME, l_api_name );
3100       END IF;
3101       FND_MSG_PUB.Count_And_Get
3102       ( p_count        =>      x_msg_count
3103        ,p_data         =>      x_msg_data );
3104       IF g_debug_flag THEN
3105         Write_Debug('Rollback and Finish with other error.') ;
3106       END IF;
3107       IF FND_API.to_Boolean( p_debug ) THEN
3108         Close_Debug_Session;
3109       END IF;
3110   END Promote_Header;
3111 
3112   -- Internal procedure for demotion of change header (inc. revItems)
3113   -- Note that even though this procedure shares the same argument list
3114   -- as Promote_Header procedure, the internal logic is quite different,
3115   -- so it is written as a seperate procedure for easier understanding.
3116   PROCEDURE Demote_Header
3117   (
3118     p_api_version               IN   NUMBER                             --
3119    ,p_init_msg_list             IN   VARCHAR2 := FND_API.G_FALSE        --
3120    ,p_commit                    IN   VARCHAR2 := FND_API.G_FALSE        --
3121    ,p_validation_level          IN   NUMBER   := FND_API.G_VALID_LEVEL_FULL
3122    ,p_debug                     IN   VARCHAR2 := FND_API.G_FALSE        --
3123    ,p_output_dir                IN   VARCHAR2 := NULL
3124    ,p_debug_filename            IN   VARCHAR2 := NULL
3125    ,x_return_status             OUT  NOCOPY  VARCHAR2                   --
3126    ,x_msg_count                 OUT  NOCOPY  NUMBER                     --
3127    ,x_msg_data                  OUT  NOCOPY  VARCHAR2                   --
3128    ,p_change_id                 IN   NUMBER                             -- header's change_id
3129    ,p_status_code               IN   NUMBER                             -- new phase
3130    ,p_update_ri_flag            IN   VARCHAR2 := 'Y'                    -- can also be 'N'
3131    ,p_api_caller                IN   VARCHAR2 := NULL                   -- can also be 'WF'
3132    ,x_sfa_line_items_exists     OUT NOCOPY VARCHAR2
3133   )
3134   IS
3135     l_api_name           CONSTANT VARCHAR2(30)  := 'Demote_Header';
3136     l_api_version        CONSTANT NUMBER := 1.0;
3137 
3138     l_fnd_user_id        NUMBER := TO_NUMBER(FND_PROFILE.VALUE('USER_ID'));
3139     l_fnd_login_id       NUMBER := TO_NUMBER(FND_PROFILE.VALUE('LOGIN_ID'));
3140 
3141     l_curr_appr_status   eng_engineering_changes.approval_status_type%TYPE;
3142 
3143     l_is_imp_phase_used  VARCHAR2(1) := 'F';
3144 
3145     l_last_status_type   NUMBER;
3146     l_last_status_code   NUMBER;
3147 
3148     l_return_status      VARCHAR2(1);
3149     l_msg_count          NUMBER;
3150     l_msg_data           VARCHAR2(2000);
3151 
3152     l_curr_phase_sn      eng_lifecycle_statuses.sequence_number%TYPE;
3153     l_new_phase_sn       eng_lifecycle_statuses.sequence_number%TYPE;
3154 
3155     l_new_status_type    eng_change_statuses.status_type%TYPE;
3156 
3157     l_change_mgmt_type_code eng_engineering_changes.change_mgmt_type_code%TYPE;
3158 
3159     -- Cursor to get all lifecycle phases between (inclusive) [demotionStatus, currentStatus]
3160     CURSOR c_lcStatuses IS
3161       SELECT *
3162         FROM eng_lifecycle_statuses
3163         WHERE entity_name = G_ENG_CHANGE
3164           AND entity_id1 = p_change_id
3165           AND active_flag = 'Y'
3166           AND sequence_number >= l_new_phase_sn
3167           AND sequence_number <= l_curr_phase_sn
3168       FOR UPDATE;
3169 
3170     l_temp_status_type   NUMBER;
3171     l_has_approval_phase VARCHAR2(1) := 'F';  -- in between curr and demotion phases
3172 
3173     -- Cursor to get all lifecycle phases between (inclusive) [demotionStatus, maxStatus]
3174     CURSOR c_lcStatusesToMax IS
3175       SELECT *
3176         FROM eng_lifecycle_statuses
3177         WHERE entity_name = G_ENG_CHANGE
3178           AND entity_id1 = p_change_id
3179           AND active_flag = 'Y'
3180           AND sequence_number >= l_new_phase_sn
3181       FOR UPDATE;
3182     l_lcStatuses_row     eng_lifecycle_statuses%ROWTYPE;
3183     l_old_iter_num       eng_lifecycle_statuses.iteration_number%TYPE := -1;
3184     l_old_row_id         NUMBER;
3185     l_new_row_id         NUMBER;
3186     l_new_route_id       NUMBER;
3187 
3188     CURSOR c_statusProp IS
3189       SELECT *
3190         FROM eng_status_properties
3191         WHERE change_lifecycle_status_id = l_old_row_id
3192       FOR UPDATE;
3193     l_status_prop_row   eng_status_properties%ROWTYPE;
3194 
3195     CURSOR c_revItems IS
3196       SELECT status_code
3197         FROM eng_revised_items
3198         WHERE change_id = p_change_id
3199       FOR UPDATE;
3200     l_ri_status_code      eng_change_lines.status_code%TYPE;
3201     -- revItem's status_code's sequence_number
3202     l_ri_phase_sn         eng_lifecycle_statuses.sequence_number%TYPE;
3203     l_ri_status_type     eng_change_statuses.status_type%TYPE;
3204 
3205 
3206     l_base_cm_type_code  VARCHAR2(30) ;
3207     l_doc_lc_object_flag BOOLEAN := FALSE ;
3208     l_old_status_code NUMBER;
3209     l_old_status_type NUMBER;
3210 
3211     -- Bug 6695079 Start
3212     l_temp_flag           VARCHAR2(1) := 'Y';
3213     l_obj_id1		  NUMBER := 0;
3214 
3215     	CURSOR c_lifecyc IS
3216 	   SELECT change_wf_route_id
3217 	   FROM eng_lifecycle_statuses
3218 	   WHERE entity_name = G_ENG_CHANGE
3219 	    AND entity_id1 = p_change_id
3220 	    AND active_flag = 'Y'
3221 	    and change_wf_route_id is not null;
3222     -- Bug 6695079 End
3223 
3224   BEGIN
3225 select status_type, status_code into l_old_status_code, l_old_status_type from eng_engineering_changes where change_id = p_change_id;
3226     -- Standard Start of API savepoint
3227     SAVEPOINT Demote_Header;
3228     -- Standard call to check for call compatibility
3229     IF NOT FND_API.Compatible_API_Call ( l_api_version
3230                                         ,p_api_version
3231                                         ,l_api_name
3232                                         ,G_PKG_NAME )
3233     THEN
3234       RAISE FND_API.G_EXC_UNEXPECTED_ERROR;
3235     END IF;
3236     -- Initialize message list if p_init_msg_list is set to TRUE.
3237     IF FND_API.to_Boolean( p_init_msg_list ) THEN
3238        FND_MSG_PUB.initialize;
3239     END IF;
3240 
3241     -- For Test/Debug
3242     Check_And_Open_Debug_Session(p_debug, p_output_dir, p_debug_filename) ;
3243     -- R12 Comment out
3244     -- IF FND_API.to_Boolean( p_debug ) THEN
3245     --     Open_Debug_Session(p_output_dir, p_debug_filename ) ;
3246     -- END IF;
3247 
3248     -- Write debug message if debug mode is on
3249     IF g_debug_flag THEN
3250        Write_Debug('ENG_CHANGE_LIFECYCLE_UTIL.Demote_Header log');
3251        Write_Debug('-----------------------------------------------------');
3252        Write_Debug('p_change_id         : ' || p_change_id );
3253        Write_Debug('p_status_code       : ' || p_status_code );
3254        Write_Debug('p_api_caller        : ' || p_api_caller );
3255        Write_Debug('-----------------------------------------------------');
3256        Write_Debug('Initializing return status... ' );
3257     END IF;
3258 
3259     -- Initialize API return status to success
3260     x_return_status := FND_API.G_RET_STS_SUCCESS;
3261 
3262     -- FND_PROFILE package is not available for workflow (WF),
3263     -- therefore manually set WHO column values
3264     IF p_api_caller = 'WF' THEN
3265       l_fnd_user_id := G_ENG_WF_USER_ID;
3266       l_fnd_login_id := G_ENG_WF_LOGIN_ID;
3267     ELSIF p_api_caller = 'CP' THEN
3268       l_fnd_user_id := G_ENG_CP_USER_ID;
3269       l_fnd_login_id := G_ENG_CP_LOGIN_ID;
3270     END IF;
3271 
3272     -- Real code starts here -----------------------------------------------
3273 		-- Bug 6695079 Start
3274 		For lifecyc in c_lifecyc
3275 		loop
3276 				select template_flag, object_id1
3277 				into l_temp_flag, l_obj_id1
3278 				from eng_change_routes
3279 				where route_id = lifecyc.change_wf_route_id;
3280 
3281 			if ((l_temp_flag = 'N' or l_temp_flag = 'H') and l_obj_id1 = 0) then
3282 			      FND_MESSAGE.Set_Name('ENG','ENG_ROUTE_APPLY_NO_TEMP');
3283 			      FND_MSG_PUB.Add;
3284 			      RAISE FND_API.G_EXC_ERROR;
3285 			end if;
3286 		end loop;
3287 	 -- Bug 6695079 end
3288     -- Get the current header approval status
3289     SELECT approval_status_type
3290       INTO l_curr_appr_status
3291       FROM eng_engineering_changes
3292       where change_id = p_change_id;
3293 
3294     -- First check if the header is CO and last implement phase has been used
3295     Is_CO_Last_Imp_Phase_Used
3296     ( p_change_id          => p_change_id
3297      ,x_is_used            => l_is_imp_phase_used
3298      ,x_last_status_type   => l_last_status_type
3299      ,x_last_status_code   => l_last_status_code
3300      );
3301 
3302     -- If so, adjust header phase to implemented phase before demotion
3303     IF ( l_is_imp_phase_used = 'T' ) THEN
3304       UPDATE eng_engineering_changes
3305         SET status_type = l_last_status_type,
3306             status_code = l_last_status_code,
3307             promote_status_code = NULL
3308         WHERE change_id = p_change_id;
3309 
3310     END IF;
3311 
3312     -- Get the sequence number for the current phase of the change header
3313     SELECT sequence_number
3314       INTO l_curr_phase_sn
3315       FROM eng_lifecycle_statuses
3316       WHERE entity_name = G_ENG_CHANGE
3317         AND entity_id1 = p_change_id
3318         AND active_flag = 'Y'
3319         AND status_code = ( SELECT status_code
3320                               FROM eng_engineering_changes
3321                               WHERE change_id = p_change_id)
3322         AND rownum = 1;
3323 
3324     -- Get the sequence number for the new phase of the change header
3325     SELECT sequence_number
3326       INTO l_new_phase_sn
3327       FROM eng_lifecycle_statuses
3328       WHERE entity_name = G_ENG_CHANGE
3329         AND entity_id1 = p_change_id
3330         AND status_code = p_status_code
3331         AND active_flag = 'Y'
3332         AND rownum = 1;
3333 
3334     IF g_debug_flag THEN
3335        Write_Debug('Before comparing l_new_phase_sn >= l_curr_phase_sn');
3336     END IF;
3337 
3338     -- Sanity check to make sure the new phase is after the current phase
3339     IF ( l_new_phase_sn >= l_curr_phase_sn ) THEN
3340       FND_MESSAGE.Set_Name('ENG','ENG_OBJ_STATE_CHANGED');
3341       FND_MSG_PUB.Add;
3342       RAISE FND_API.G_EXC_ERROR;
3343     END IF;
3344 
3345     -- Finish the current phase before demotion
3346     UPDATE eng_lifecycle_statuses
3347       SET completion_date = sysdate,
3348           last_update_date = sysdate,
3349           last_updated_by = l_fnd_user_id,
3350           last_update_login = l_fnd_login_id
3351       WHERE entity_name = G_ENG_CHANGE
3352         AND entity_id1 = p_change_id
3353         AND active_flag = 'Y'
3354         AND status_code = ( SELECT status_code
3355                               FROM eng_engineering_changes
3356                               WHERE change_id = p_change_id)
3357         AND sequence_number = l_curr_phase_sn
3358         AND rownum = 1;
3359     IF g_debug_flag THEN
3360       Write_Debug('After updating eng_lifecycle_statuses.completion_date.');
3361       Write_Debug('  Row count = ' || SQL%ROWCOUNT);
3362     END IF;
3363 
3364 
3365     -- obsolete all the lifecycle phases in the range of [demotionStatus, currStatus]
3366     OPEN c_lcStatuses;
3367       LOOP
3368         FETCH c_lcStatuses INTO l_lcStatuses_row;
3369         EXIT WHEN c_lcStatuses%NOTFOUND;
3370 
3371         -- l_old_iter_num initialization and sanity check
3372         /*
3373         IF (l_old_iter_num = -1) THEN
3374           -- make sure the original iteration number is not null
3375           IF (l_lcStatuses_row.iteration_number IS NULL) THEN
3376             FND_MESSAGE.Set_Name('ENG','ENG_OBJECT_CANT_BE_NULL');
3377             FND_MESSAGE.Set_Token('OBJECT_NAME', 'ITERATION_NUMBER');
3378             FND_MSG_PUB.Add;
3379             RAISE FND_API.G_EXC_ERROR;
3380           END IF;
3381           l_old_iter_num := l_lcStatuses_row.iteration_number;
3382         ELSE
3383           IF ( l_lcStatuses_row.iteration_number <> l_old_iter_num ) THEN
3384             -- Stop and return error message
3385             IF g_debug_flag THEN
3386               Write_Debug('Error: inconsistent lifecycle phase sequence numbers');
3387               Write_Debug('l_lcStatuses_row.iteration_number : '|| l_lcStatuses_row.iteration_number);
3388               Write_Debug('l_old_iter_num     : ' || l_old_iter_num );
3389             END IF;
3390             FND_MESSAGE.Set_Name('ENG','ENG_SN_INCONSISTENT');
3391             FND_MSG_PUB.Add;
3392             RAISE FND_API.G_EXC_ERROR;
3393           END IF;
3394         END IF;
3395         */
3396 
3397         -- Check existence of approval phase between curr and demotion phase
3398         SELECT status_type
3399           INTO l_temp_status_type
3400           FROM eng_change_statuses
3401           WHERE status_code = l_lcStatuses_row.STATUS_CODE;
3402         IF (l_temp_status_type = G_ENG_APPROVED)
3403         THEN
3404           l_has_approval_phase := 'T';
3405         END IF;
3406 
3407         -- Obsolete (but not delete) the old phase row
3408         UPDATE eng_lifecycle_statuses
3409           SET active_flag = 'N',
3410               last_update_date = sysdate,
3411               last_updated_by = l_fnd_user_id,
3412               last_update_login = l_fnd_login_id
3413           WHERE CURRENT OF c_lcStatuses;
3414 
3415         -- First get the new unique index id value for the new row (also save the old id)
3416         l_old_row_id := l_lcStatuses_row.change_lifecycle_status_id;
3417         SELECT eng_lifecycle_statuses_s.nextval
3418           INTO l_new_row_id
3419           FROM DUAL;
3420 
3421         -- Secondly get the new wf_route_id if needed
3422         IF (l_lcStatuses_row.change_wf_route_id IS NULL) THEN
3423           l_new_route_id := NULL;
3424         ELSE
3425           -- Get a new workflow route_id
3426           Eng_Change_Route_Util.REFRESH_ROUTE
3427           ( X_NEW_ROUTE_ID   => l_new_route_id,
3428             P_ROUTE_ID       => l_lcStatuses_row.change_wf_route_id,
3429             P_USER_ID        => l_fnd_user_id,
3430             P_API_CALLER     => p_api_caller
3431           );
3432         END IF;
3433 
3434         -- Prepare for the new phase row
3435         l_lcStatuses_row.change_lifecycle_status_id := l_new_row_id;
3436         l_lcStatuses_row.change_wf_route_id := l_new_route_id;
3437         l_lcStatuses_row.active_flag := 'Y';
3438         l_lcStatuses_row.creation_date := sysdate;
3439         l_lcStatuses_row.created_by := l_fnd_user_id;
3440         l_lcStatuses_row.last_update_date := sysdate;
3441         l_lcStatuses_row.last_updated_by := l_fnd_user_id;
3442         l_lcStatuses_row.last_update_login := l_fnd_login_id;
3443         -- populate wf_status based upon wf availibility of the phase
3444         IF ( l_lcStatuses_row.change_wf_route_id IS NULL ) THEN
3445           l_lcStatuses_row.workflow_status := null;
3446         ELSE
3447           l_lcStatuses_row.workflow_status := Eng_Workflow_Util.G_RT_NOT_STARTED;
3448         END IF;
3449         -- populate start_date only if it is the newly demoted phase
3450         IF ( l_lcStatuses_row.status_code = p_status_code ) THEN
3451           l_lcStatuses_row.start_date := sysdate;
3452         ELSE
3453         l_lcStatuses_row.start_date := null;
3454         END IF;
3455         -- populate completion_date to null for all new phase rows
3456         l_lcStatuses_row.completion_date := null;
3457 
3458 
3459         -- Before insertion, update all the corresponding rows in eng_status_properties table
3460         OPEN c_statusProp;
3461           LOOP
3462             FETCH c_statusProp INTO l_status_prop_row;
3463             EXIT WHEN c_statusProp%NOTFOUND;
3464               UPDATE eng_status_properties
3465                 SET change_lifecycle_status_id = l_new_row_id,
3466                     last_update_date = sysdate,
3467                     last_updated_by = l_fnd_user_id,
3468                     last_update_login = l_fnd_login_id
3469                 WHERE current of c_statusProp;
3470             END LOOP;
3471         CLOSE c_statusProp;
3472         IF g_debug_flag THEN
3473           Write_Debug('After updating eng_status_properties row''s change_lifecycle_status_id');
3474         END IF;
3475 
3476         -- Insert the new phase row
3477         /* Only Oracle 9.2+ supports this directly row insertion feature
3478         INSERT INTO eng_lifecycle_statuses
3479           VALUES l_lcStatuses_row;
3480         */
3481         INSERT INTO eng_lifecycle_statuses
3482                     ( CHANGE_LIFECYCLE_STATUS_ID,
3483                       ENTITY_NAME,
3484                       ENTITY_ID1,
3485                       ENTITY_ID2,
3486                       ENTITY_ID3,
3487                       ENTITY_ID4,
3488                       ENTITY_ID5,
3489                       SEQUENCE_NUMBER,
3490                       STATUS_CODE,
3491                       START_DATE,
3492                       COMPLETION_DATE,
3493                       CHANGE_WF_ROUTE_ID,
3494                       CHANGE_WF_ROUTE_TEMPLATE_ID,
3495                       AUTO_PROMOTE_STATUS,
3496                       AUTO_DEMOTE_STATUS,
3497                       WORKFLOW_STATUS,
3498                       CHANGE_EDITABLE_FLAG,
3499                       CREATION_DATE,
3500                       CREATED_BY,
3501                       LAST_UPDATE_DATE,
3502                       LAST_UPDATED_BY,
3503                       LAST_UPDATE_LOGIN,
3504                       ITERATION_NUMBER,
3505                       ACTIVE_FLAG,
3506                       WF_SIG_POLICY )
3507           VALUES
3508                     ( l_lcStatuses_row.CHANGE_LIFECYCLE_STATUS_ID,
3509                       l_lcStatuses_row.ENTITY_NAME,
3510                       l_lcStatuses_row.ENTITY_ID1,
3511                       l_lcStatuses_row.ENTITY_ID2,
3512                       l_lcStatuses_row.ENTITY_ID3,
3513                       l_lcStatuses_row.ENTITY_ID4,
3514                       l_lcStatuses_row.ENTITY_ID5,
3515                       l_lcStatuses_row.SEQUENCE_NUMBER,
3516                       l_lcStatuses_row.STATUS_CODE,
3517                       l_lcStatuses_row.START_DATE,
3518                       l_lcStatuses_row.COMPLETION_DATE,
3519                       l_lcStatuses_row.CHANGE_WF_ROUTE_ID,
3520                       l_lcStatuses_row.CHANGE_WF_ROUTE_TEMPLATE_ID,
3521                       l_lcStatuses_row.AUTO_PROMOTE_STATUS,
3522                       l_lcStatuses_row.AUTO_DEMOTE_STATUS,
3523                       l_lcStatuses_row.WORKFLOW_STATUS,
3524                       l_lcStatuses_row.CHANGE_EDITABLE_FLAG,
3525                       l_lcStatuses_row.CREATION_DATE,
3526                       l_lcStatuses_row.CREATED_BY,
3527                       l_lcStatuses_row.LAST_UPDATE_DATE,
3528                       l_lcStatuses_row.LAST_UPDATED_BY,
3529                       l_lcStatuses_row.LAST_UPDATE_LOGIN,
3530                       l_lcStatuses_row.ITERATION_NUMBER,
3531                       l_lcStatuses_row.ACTIVE_FLAG,
3532                       l_lcStatuses_row.WF_SIG_POLICY );
3533 
3534       END LOOP;
3535     CLOSE c_lcStatuses;
3536 
3537     -- Update all phase rows from the demotion phase all the way to the last phase
3538     OPEN c_lcStatusesToMax;
3539       LOOP
3540         FETCH c_lcStatusesToMax INTO l_lcStatuses_row;
3541         EXIT WHEN c_lcStatusesToMax%NOTFOUND;
3542 
3543         -- make sure the original iteration number is not null
3544         IF (l_lcStatuses_row.iteration_number IS NULL) THEN
3545           FND_MESSAGE.Set_Name('ENG','ENG_OBJECT_CANT_BE_NULL');
3546           FND_MESSAGE.Set_Token('OBJECT_NAME', 'ITERATION_NUMBER');
3547           FND_MSG_PUB.Add;
3548           RAISE FND_API.G_EXC_ERROR;
3549         END IF;
3550         l_old_iter_num := l_lcStatuses_row.iteration_number;
3551 
3552         -- Increment sequence number of the active phases
3553         UPDATE eng_lifecycle_statuses
3554           SET iteration_number = l_old_iter_num + 1,
3555               last_update_date = sysdate,
3556               last_updated_by = l_fnd_user_id,
3557               last_update_login = l_fnd_login_id
3558           WHERE CURRENT OF c_lcStatusesToMax;
3559 
3560       END LOOP;
3561     CLOSE c_lcStatusesToMax;
3562 
3563     -- Get the status_type of the new phase
3564     SELECT status_type
3565       INTO l_new_status_type
3566       FROM eng_change_statuses
3567       WHERE status_code = p_status_code;
3568 
3569     -- Demote change header record
3570     UPDATE eng_engineering_changes
3571       SET status_code = p_status_code,
3572           promote_status_code = null,
3573           status_type = l_new_status_type,
3574           last_update_date = sysdate,
3575           last_updated_by = l_fnd_user_id,
3576           last_update_login = l_fnd_login_id
3577       WHERE change_id = p_change_id;
3578     IF g_debug_flag THEN
3579       Write_Debug('After updating eng_engineering_changes.');
3580       Write_Debug('  Row count = ' || SQL%ROWCOUNT);
3581     END IF;
3582 
3583     -- Fix for bug 3775865: Reset header approval status
3584     IF (l_has_approval_phase = 'T' AND l_curr_appr_status <> G_ENG_NOT_SUBMITTED)
3585     THEN
3586 
3587       IF g_debug_flag THEN
3588         Write_Debug('Before: calling Update_Header_Appr_Status');
3589       END IF;
3590 
3591       -- Update change header approval status
3592       -- Launch header approval status change workflow
3593       Update_Header_Appr_Status
3594       (
3595         p_api_version               =>  1.0
3596        ,p_init_msg_list             =>  FND_API.G_FALSE
3597        ,p_commit                    =>  FND_API.G_FALSE
3598        ,p_validation_level          =>  FND_API.G_VALID_LEVEL_FULL
3599        ,p_debug                     =>  FND_API.G_FALSE
3600        ,p_output_dir                =>  p_output_dir
3601        ,p_debug_filename            =>  p_debug_filename
3602        ,x_return_status             =>  l_return_status
3603        ,x_msg_count                 =>  l_msg_count
3604        ,x_msg_data                  =>  l_msg_data
3605        ,p_change_id                 =>  p_change_id
3606        ,p_status_code               =>  p_status_code
3607        ,p_appr_status               =>  G_ENG_NOT_SUBMITTED
3608        ,p_route_status              =>  NULL
3609        ,p_api_caller                =>  p_api_caller
3610        ,p_bypass                    =>  'Y'
3611        ,x_sfa_line_items_exists     => x_sfa_line_items_exists
3612       );
3613 
3614       IF g_debug_flag THEN
3615         Write_Debug('After: calling Update_Header_Appr_Status: ' || l_return_status) ;
3616       END IF;
3617 
3618 
3619       IF ( l_return_status <>  FND_API.G_RET_STS_SUCCESS )
3620       THEN
3621         x_return_status := l_return_status;
3622         x_msg_count := l_msg_count;
3623         x_msg_data := l_msg_data;
3624         RAISE FND_API.G_EXC_ERROR;
3625       END IF;
3626       IF g_debug_flag THEN
3627         Write_Debug('After: calling Update_Header_Appr_Status');
3628       END IF;
3629 
3630     END IF;
3631     -- Fix for bug 3775865 - end
3632 
3633     IF ( p_update_ri_flag = 'Y' ) THEN
3634       -- Demote revised items to the new phase
3635       OPEN c_revItems;
3636       LOOP
3637         FETCH c_revItems INTO l_ri_status_code;
3638         EXIT WHEN c_revItems%NOTFOUND;
3639 
3640         IF g_debug_flag THEN
3641           Write_Debug('In Cursor c_revItems to update revised items.');
3642         END IF;
3643 
3644         -- Get the status_type of the revised item phase
3645         SELECT status_type
3646           INTO l_ri_status_type
3647           FROM eng_change_statuses
3648           WHERE status_code = l_ri_status_code
3649             AND rownum = 1;
3650 
3651         IF (l_ri_status_type <> G_ENG_IMPLEMENTED
3652             AND l_ri_status_type <> G_ENG_CANCELLED) THEN
3653 
3654           -- Get the sequence_number of the revised item phase
3655           -- Note: moved this query inside this IF block because cancel
3656           --       status is not in the regular lifecycle phase definitions
3657           SELECT sequence_number
3658             INTO l_ri_phase_sn
3659             FROM eng_lifecycle_statuses
3660             WHERE entity_name = G_ENG_CHANGE
3661               AND entity_id1 = p_change_id
3662               AND status_code = l_ri_status_code
3663               AND active_flag = 'Y'
3664               AND rownum = 1;
3665 
3666           -- Update only those which are active
3667           -- and whose phase is ahead of the new demotion phase
3668           IF (l_ri_phase_sn > l_new_phase_sn) THEN
3669             UPDATE eng_revised_items
3670               SET status_code = p_status_code,
3671                   status_type = l_new_status_type,
3672                   last_update_date = sysdate,
3673                   last_updated_by = l_fnd_user_id,
3674                   last_update_login = l_fnd_login_id
3675               WHERE CURRENT OF c_revItems;
3676           END IF;
3677         END IF; -- revItem not implmented or cancelled
3678       END LOOP;
3679       CLOSE c_revItems;
3680     END IF; -- p_update_ri_flag = 'Y'
3681 
3682 
3683     -- R12B
3684     -- In case of Document LC Change Object, call ENG_DOCUMENT_UTIL.Change_Doc_LC_Phase
3685     -- to validate and sync Document LC Phase
3686     l_doc_lc_object_flag := ENG_DOCUMENT_UTIL.Is_Dom_Document_Lifecycle
3687                            ( p_change_id => p_change_id
3688                            , p_base_change_mgmt_type_code => l_base_cm_type_code
3689                            )  ;
3690 
3691     IF (l_doc_lc_object_flag)
3692     THEN
3693         IF g_debug_flag THEN
3694            Write_Debug('Before: calling ENG_DOCUMENT_UTIL.Change_Doc_LC_Phase');
3695            Write_Debug('  p_change_id =   ' || p_change_id);
3696            Write_Debug('  p_base_change_mgmt_type_code =   ' || l_base_cm_type_code);
3697            Write_Debug('  p_status_code = ' || p_status_code);
3698            Write_Debug('  p_action_type =   ' || G_ENG_DEMOTE);
3699         END IF;
3700 
3701         ENG_DOCUMENT_UTIL.Change_Doc_LC_Phase
3702         ( p_api_version         => 1.0
3703          ,p_init_msg_list       => FND_API.G_FALSE
3704          ,p_commit              => FND_API.G_FALSE
3705          ,p_validation_level    => p_validation_level
3706          ,p_debug               => FND_API.G_FALSE
3707          ,p_output_dir          => p_output_dir
3708          ,p_debug_filename      => p_debug_filename
3709          ,x_return_status       => l_return_status
3710          ,x_msg_count           => l_msg_count
3711          ,x_msg_data            => l_msg_data
3712          ,p_change_id           => p_change_id
3713          ,p_lc_phase_code       => p_status_code
3714          ,p_action_type         => G_ENG_DEMOTE
3715          ,p_api_caller          => p_api_caller
3716         ) ;
3717 
3718 
3719         IF g_debug_flag THEN
3720            Write_Debug('After: calling ENG_DOCUMENT_UTIL.Change_Doc_LC_Phase: ' || l_return_status) ;
3721         END IF;
3722 
3723         IF ( l_return_status <>  FND_API.G_RET_STS_SUCCESS )
3724         THEN
3725           x_return_status := l_return_status;
3726           x_msg_count := l_msg_count;
3727           x_msg_data := l_msg_data;
3728           RAISE FND_API.G_EXC_ERROR;
3729         END IF;
3730 
3731         IF g_debug_flag THEN
3732            Write_Debug('Successful: ENG_DOCUMENT_UTIL.Change_Doc_LC_Phase');
3733         END IF;
3734 
3735     END IF ; -- if ( Change Object is Documet LC Object)
3736 
3737 
3738 
3739     -- Start workflow for new phase if necessary
3740     Start_WF_OnlyIf_Necessary
3741     ( p_api_version       => 1.0
3742      ,p_init_msg_list     => FND_API.G_FALSE
3743      ,p_commit            => FND_API.G_FALSE
3744      ,p_validation_level  => p_validation_level
3745      ,p_debug             => FND_API.G_FALSE
3746      ,p_output_dir        => p_output_dir
3747      ,p_debug_filename    => p_debug_filename
3748      ,x_return_status     => l_return_status
3749      ,x_msg_count         => l_msg_count
3750      ,x_msg_data          => l_msg_data
3751      ,p_change_id         => p_change_id
3752      ,p_status_code       => p_status_code
3753      ,p_status_type       => l_new_status_type
3754      ,p_sequence_number   => l_new_phase_sn
3755      --,p_imp_eco_flag      => 'N'
3756      ,p_api_caller        => p_api_caller
3757      ,p_action_type       => G_ENG_DEMOTE
3758     );
3759 
3760 
3761       IF g_debug_flag THEN
3762         Write_Debug('After: calling Start_WF_OnlyIf_Necessary: ' || l_return_status) ;
3763       END IF;
3764 
3765 
3766     IF ( l_return_status <>  FND_API.G_RET_STS_SUCCESS ) THEN
3767       x_return_status := l_return_status;
3768       x_msg_count := l_msg_count;
3769       x_msg_data := l_msg_data;
3770       --#FND_MESSAGE.Set_Name('ENG','ENG_ERROR_CALLING_WF_API');
3771       --#FND_MSG_PUB.Add;
3772       RAISE FND_API.G_EXC_ERROR;
3773     END IF;
3774 
3775     -- Standard ending code ------------------------------------------------
3776     IF FND_API.To_Boolean ( p_commit ) THEN
3777       COMMIT WORK;
3778     END IF;
3779 
3780     FND_MSG_PUB.Count_And_Get
3781     ( p_count        =>      x_msg_count,
3782       p_data         =>      x_msg_data );
3783 
3784     IF g_debug_flag THEN
3785       Write_Debug('Finish. End Of procedure: Demote_Header');
3786     END IF;
3787 
3788     IF FND_API.to_Boolean( p_debug ) THEN
3789       Close_Debug_Session;
3790     END IF;
3791 
3792   EXCEPTION
3793     WHEN FND_API.G_EXC_ERROR THEN
3794       --ROLLBACK TO Demote_Header;
3795       x_return_status := FND_API.G_RET_STS_ERROR;
3796       FND_MSG_PUB.Count_And_Get
3797       ( p_count        =>      x_msg_count
3798        ,p_data         =>      x_msg_data );
3799       IF g_debug_flag THEN
3800         Write_Debug('Rollback and Finish with expected error.') ;
3801       END IF;
3802       IF FND_API.to_Boolean( p_debug ) THEN
3803         Close_Debug_Session;
3804       END IF;
3805     WHEN FND_API.G_EXC_UNEXPECTED_ERROR THEN
3806       --ROLLBACK TO Demote_Header;
3807       x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
3808       FND_MSG_PUB.Count_And_Get
3809       ( p_count        =>      x_msg_count
3810        ,p_data         =>      x_msg_data );
3811       IF g_debug_flag THEN
3812         Write_Debug('Rollback and Finish with unexpected error.') ;
3813       END IF;
3814       IF FND_API.to_Boolean( p_debug ) THEN
3815         Close_Debug_Session;
3816       END IF;
3817     WHEN OTHERS THEN
3818       --ROLLBACK TO Demote_Header;
3819       x_return_status := FND_API.G_RET_STS_UNEXP_ERROR ;
3820       IF FND_MSG_PUB.Check_Msg_Level ( FND_MSG_PUB.G_MSG_LVL_UNEXP_ERROR )
3821       THEN
3822         FND_MSG_PUB.Add_Exc_Msg ( G_PKG_NAME, l_api_name );
3823       END IF;
3824       FND_MSG_PUB.Count_And_Get
3825       ( p_count        =>      x_msg_count
3826        ,p_data         =>      x_msg_data );
3827       IF g_debug_flag THEN
3828         Write_Debug('Rollback and Finish with other error.') ;
3829       END IF;
3830       IF FND_API.to_Boolean( p_debug ) THEN
3831         Close_Debug_Session;
3832       END IF;
3833   END Demote_Header;
3834 
3835   PROCEDURE Demote_Header
3836   (
3837     p_api_version               IN   NUMBER                             --
3838    ,p_init_msg_list             IN   VARCHAR2 := FND_API.G_FALSE        --
3839    ,p_commit                    IN   VARCHAR2 := FND_API.G_FALSE        --
3840    ,p_validation_level          IN   NUMBER   := FND_API.G_VALID_LEVEL_FULL
3841    ,p_debug                     IN   VARCHAR2 := FND_API.G_FALSE        --
3842    ,p_output_dir                IN   VARCHAR2 := NULL
3843    ,p_debug_filename            IN   VARCHAR2 := NULL
3844    ,x_return_status             OUT  NOCOPY  VARCHAR2                   --
3845    ,x_msg_count                 OUT  NOCOPY  NUMBER                     --
3846    ,x_msg_data                  OUT  NOCOPY  VARCHAR2                   --
3847    ,p_change_id                 IN   NUMBER                             -- header's change_id
3848    ,p_status_code               IN   NUMBER                             -- new phase
3849    ,p_update_ri_flag            IN   VARCHAR2 := 'Y'                    -- can also be 'N'
3850    ,p_api_caller                IN   VARCHAR2 := NULL                   -- can also be 'WF'
3851   )
3852   IS
3853      l_sfa_line_items_exists VARCHAR2(1);
3854   BEGIN
3855      Demote_Header
3856              ( p_api_version        => p_api_version
3857               ,p_init_msg_list      => p_init_msg_list
3858               ,p_commit             => p_commit
3859               ,p_validation_level   => p_validation_level
3860               ,p_debug              => p_debug
3861               ,p_output_dir         => p_output_dir
3862               ,p_debug_filename     => p_debug_filename
3863               ,x_return_status      => x_return_status
3864               ,x_msg_count          => x_msg_count
3865               ,x_msg_data           => x_msg_data
3866               ,p_change_id          => p_change_id
3867               ,p_status_code        => p_status_code
3868               ,p_update_ri_flag     => p_update_ri_flag
3869               ,p_api_caller         => p_api_caller
3870               ,x_sfa_line_items_exists => l_sfa_line_items_exists
3871              );
3872   END Demote_Header;
3873 
3874   -- Internal procedure for promotion of a revised item
3875   PROCEDURE Promote_Revised_Item
3876   (
3877     p_api_version               IN   NUMBER                             --
3878    ,p_init_msg_list             IN   VARCHAR2 := FND_API.G_FALSE        --
3879    ,p_commit                    IN   VARCHAR2 := FND_API.G_FALSE        --
3880    ,p_validation_level          IN   NUMBER   := FND_API.G_VALID_LEVEL_FULL
3881    ,p_debug                     IN   VARCHAR2 := FND_API.G_FALSE        --
3882    ,p_output_dir                IN   VARCHAR2 := NULL
3883    ,p_debug_filename            IN   VARCHAR2 := NULL
3884    ,x_return_status             OUT  NOCOPY  VARCHAR2                   --
3885    ,x_msg_count                 OUT  NOCOPY  NUMBER                     --
3886    ,x_msg_data                  OUT  NOCOPY  VARCHAR2                   --
3887    ,p_change_id                 IN   NUMBER                             -- header's change_id
3888    ,p_object_id2                IN   NUMBER                             -- revised item sequence id
3889    ,p_status_code               IN   NUMBER                             -- new phase
3890    ,p_api_caller                IN   VARCHAR2 := NULL                   -- can also be 'WF'
3891   )
3892   IS
3893     l_api_name           CONSTANT VARCHAR2(30)  := 'Promote_Revised_Item';
3894     l_api_version        CONSTANT NUMBER := 1.0;
3895 
3896     l_fnd_user_id        NUMBER := TO_NUMBER(FND_PROFILE.VALUE('USER_ID'));
3897     l_fnd_login_id       NUMBER := TO_NUMBER(FND_PROFILE.VALUE('LOGIN_ID'));
3898 
3899     l_return_status      VARCHAR2(1);
3900     l_msg_count          NUMBER;
3901     l_msg_data           VARCHAR2(2000);
3902 
3903     l_ri_phase_sn        eng_lifecycle_statuses.sequence_number%TYPE;
3904     l_new_phase_sn       eng_lifecycle_statuses.sequence_number%TYPE;
3905     l_max_sn             eng_lifecycle_statuses.sequence_number%TYPE;
3906     l_phase_sn           eng_lifecycle_statuses.sequence_number%TYPE;
3907 
3908     l_last_imp_flag       VARCHAR2(1) := 'N';
3909 
3910     l_new_status_type    eng_change_statuses.status_type%TYPE;
3911     l_ri_status_code     eng_change_lines.status_code%TYPE;
3912     l_ri_status_type     eng_change_statuses.status_type%TYPE;
3913 
3914     l_chg_notice         eng_engineering_changes.change_notice%TYPE;
3915     l_org_id             eng_engineering_changes.organization_id%TYPE;
3916     l_request_id         NUMBER;
3917 
3918     l_row_cnt            NUMBER := 0;
3919   BEGIN
3920     -- Standard Start of API savepoint
3921     SAVEPOINT Promote_Revised_Item;
3922     -- Standard call to check for call compatibility
3923     IF NOT FND_API.Compatible_API_Call ( l_api_version
3924                                         ,p_api_version
3925                                         ,l_api_name
3926                                         ,G_PKG_NAME )
3927     THEN
3928       RAISE FND_API.G_EXC_UNEXPECTED_ERROR;
3929     END IF;
3930     -- Initialize message list if p_init_msg_list is set to TRUE.
3931     IF FND_API.to_Boolean( p_init_msg_list ) THEN
3932        FND_MSG_PUB.initialize;
3933     END IF;
3934 
3935     -- For Test/Debug
3936     Check_And_Open_Debug_Session(p_debug, p_output_dir, p_debug_filename) ;
3937     -- R12 Comment out
3938     -- IF FND_API.to_Boolean( p_debug ) THEN
3939     --     Open_Debug_Session(p_output_dir, p_debug_filename ) ;
3940     -- END IF;
3941 
3942     -- Write debug message if debug mode is on
3943     IF g_debug_flag THEN
3944        Write_Debug('ENG_CHANGE_LIFECYCLE_UTIL.Promote_Revised_Item log');
3945        Write_Debug('-----------------------------------------------------');
3946        Write_Debug('p_change_id         : ' || p_change_id );
3947        Write_Debug('p_object_id2        : ' || p_object_id2 );
3948        Write_Debug('p_status_code       : ' || p_status_code );
3949        Write_Debug('p_api_caller        : ' || p_api_caller );
3950        Write_Debug('-----------------------------------------------------');
3951        Write_Debug('Initializing return status... ' );
3952     END IF;
3953 
3954     -- Initialize API return status to success
3955     x_return_status := FND_API.G_RET_STS_SUCCESS;
3956 
3957     -- FND_PROFILE package is not available for workflow (WF),
3958     -- therefore manually set WHO column values
3959     IF p_api_caller = 'WF' THEN
3960       l_fnd_user_id := G_ENG_WF_USER_ID;
3961       l_fnd_login_id := G_ENG_WF_LOGIN_ID;
3962     ELSIF p_api_caller = 'CP' THEN
3963       l_fnd_user_id := G_ENG_CP_USER_ID;
3964       l_fnd_login_id := G_ENG_CP_LOGIN_ID;
3965     END IF;
3966 
3967     -- Real code starts here -----------------------------------------------
3968 
3969     -- Get the sequence number for the current phase of the revised item
3970     SELECT sequence_number, status_code
3971       INTO l_ri_phase_sn, l_ri_status_code
3972       FROM eng_lifecycle_statuses
3973       WHERE entity_name = G_ENG_CHANGE
3974         AND entity_id1 = p_change_id
3975         AND status_code = ( SELECT status_code
3976                               FROM eng_revised_items
3977                               WHERE revised_item_sequence_id = p_object_id2)
3978         AND active_flag = 'Y'
3979         AND rownum = 1;
3980 
3981     -- Get the sequence number for the new phase of the revised item
3982     SELECT sequence_number
3983       INTO l_new_phase_sn
3984       FROM eng_lifecycle_statuses
3985       WHERE entity_name = G_ENG_CHANGE
3986         AND entity_id1 = p_change_id
3987         AND status_code = p_status_code
3988         AND active_flag = 'Y'
3989         AND rownum = 1;
3990 
3991     -- Get the status_type of the new phase
3992     SELECT status_type
3993       INTO l_new_status_type
3994       FROM eng_change_statuses
3995       WHERE status_code = p_status_code
3996         AND rownum = 1;
3997 
3998     -- Get the max sequence number in the lifecycle
3999     SELECT max(sequence_number)
4000       INTO l_max_sn
4001       FROM eng_lifecycle_statuses
4002       WHERE entity_name = G_ENG_CHANGE
4003         AND entity_id1 = p_change_id
4004         AND active_flag = 'Y';
4005 
4006     IF g_debug_flag THEN
4007        Write_Debug('Before comparing l_new_phase_sn = l_ri_phase_sn');
4008        Write_Debug('l_new_phase_sn      : ' || l_new_phase_sn );
4009        Write_Debug('l_ri_phase_sn       : ' || l_ri_phase_sn );
4010     END IF;
4011 
4012     -- Sanity check to make sure the new phase is after the current phase
4013     IF l_new_phase_sn <= l_ri_phase_sn THEN
4014       FND_MESSAGE.Set_Name('ENG','ENG_OBJ_STATE_CHANGED');
4015       FND_MSG_PUB.Add;
4016       RAISE FND_API.G_EXC_ERROR;
4017     END IF;
4018 
4019     IF g_debug_flag THEN
4020        Write_Debug('Before comparing l_new_phase_sn = l_max_sn');
4021     END IF;
4022 
4023     -- Check if the new phase is the last in the lifecycle definition
4024     IF (l_new_phase_sn = l_max_sn) THEN
4025       -- New phase is the last lifecycle phase
4026       IF g_debug_flag THEN
4027          Write_Debug('Branch: New phase is the last lifecycle phase');
4028       END IF;
4029 
4030       -- Sanity check: the new phase must be of status_type = 'IMPLEMENTED'
4031       IF (l_new_status_type <> G_ENG_IMPLEMENTED) THEN
4032         FND_MESSAGE.Set_Name('ENG','ENG_LAST_PHASE_NOT_IMP');
4033         FND_MSG_PUB.Add;
4034         RAISE FND_API.G_EXC_ERROR;
4035       END IF;
4036 
4037       -- Set the flag
4038       l_last_imp_flag := 'Y';
4039 
4040     ELSE
4041       -- New phase is not the last lifecycle phase
4042       IF g_debug_flag THEN
4043          Write_Debug('Branch: New phase is not the last lifecycle phase');
4044       END IF;
4045     END IF;
4046 
4047     -- Make sure the revised item is not implemented or cancelled
4048     -- Get the status_type of the revised item phase
4049     SELECT status_type
4050       INTO l_ri_status_type
4051       FROM eng_change_statuses
4052       WHERE status_code = l_ri_status_code
4053         AND rownum = 1;
4054 
4055     -- Update only those which are still active
4056     IF (l_ri_status_type = G_ENG_IMPLEMENTED
4057         OR l_ri_status_type = G_ENG_CANCELLED)
4058     THEN
4059       FND_MESSAGE.Set_Name('ENG','ENG_REVITEM_IMP_OR_CNCL');
4060       FND_MSG_PUB.Add;
4061       RAISE FND_API.G_EXC_ERROR;
4062     ELSE
4063       -- Case: promoting revised item to the last implement phase
4064       IF ( l_last_imp_flag = 'Y' ) THEN
4065 
4066 
4067         SELECT change_notice, organization_id
4068           INTO l_chg_notice, l_org_id
4069           FROM eng_engineering_changes
4070           WHERE change_id = p_change_id;
4071         -- If so, submit concurrent program to implement the eco and all its revised items
4072         -- as the lifecycle has already reach the last phase for implementation
4073         IF g_debug_flag THEN
4074           Write_Debug('Before: calling ENG_ECO_UTIL.Implement_ECO (for revised item)');
4075           Write_Debug('  l_chg_notice = ' || l_chg_notice);
4076           Write_Debug('  l_org_id     = ' || l_org_id);
4077         END IF;
4078 
4079         -- Call concurrent program to implement revised item
4080         ENG_ECO_UTIL.Implement_ECO
4081         ( p_api_version          =>    1.0
4082          ,p_init_msg_list        =>    FND_API.G_FALSE
4083          ,p_commit               =>    FND_API.G_FALSE
4084          ,p_validation_level     =>    p_validation_level
4085          ,p_debug                =>    p_debug --FND_API.G_FALSE
4086          ,p_output_dir           =>    p_output_dir
4087          ,p_debug_filename       =>    NULL --p_debug_filename
4088          ,x_return_status        =>    l_return_status
4089          ,x_msg_count            =>    l_msg_count
4090          ,x_msg_data             =>    l_msg_data
4091          ,p_change_id            =>    p_change_id
4092          ,p_change_notice        =>    l_chg_notice
4093          ,p_rev_item_seq_id      =>    p_object_id2
4094          ,p_org_id               =>    l_org_id
4095          ,x_request_id           =>    l_request_id
4096         );
4097 
4098         IF g_debug_flag THEN
4099           Write_Debug('After: calling ENG_ECO_UTIL.Implement_ECO (for revised item): ' || l_return_status);
4100         END IF;
4101 
4102         IF (l_return_status <>  FND_API.G_RET_STS_SUCCESS) THEN
4103           x_return_status := l_return_status;
4104           x_msg_count := l_msg_count;
4105           x_msg_data := l_msg_data;
4106           --#FND_MESSAGE.Set_Name('ENG','ENG_ERROR_CALLING_IMP_ECO');
4107           --#FND_MSG_PUB.Add;
4108           RAISE FND_API.G_EXC_ERROR;
4109 
4110         ELSIF (l_request_id = 0) THEN
4111           x_return_status := l_return_status;
4112           x_msg_count := l_msg_count;
4113           x_msg_data := l_msg_data;
4114           FND_MESSAGE.Set_Name('ENG','ENG_ERROR_CONCURRENT_PRGM');
4115           FND_MESSAGE.Set_Token('OBJECT_NAME', 'ENG_ECO_UTIL.Implement_ECO(for revised item)');
4116           FND_MSG_PUB.Add;
4117           RAISE FND_API.G_EXC_ERROR;
4118         END IF;
4119 
4120         IF g_debug_flag THEN
4121           Write_Debug('Successful: calling ENG_ECO_UTIL.Implement_ECO (for revised item)');
4122           Write_Debug('l_request_id       : ' || l_request_id );
4123         END IF;
4124 
4125         -- update parent revised item
4126         UPDATE eng_revised_items
4127           SET status_type = G_ENG_IMP_IN_PROGRESS,
4128               last_update_date = sysdate,
4129               last_updated_by = l_fnd_user_id,
4130               last_update_login = l_fnd_login_id,
4131               Implementation_req_id = l_request_id
4132           WHERE revised_item_sequence_id = p_object_id2;
4133         IF g_debug_flag THEN
4134           Write_Debug('After updating eng_revised_items (parent level).');
4135           Write_Debug('  Row count = ' || SQL%ROWCOUNT);
4136         END IF;
4137 
4138         -- update active children revised items
4139         UPDATE eng_revised_items
4140           SET status_type = G_ENG_IMP_IN_PROGRESS,
4141               last_update_date = sysdate,
4142               last_updated_by = l_fnd_user_id,
4143               last_update_login = l_fnd_login_id,
4144               Implementation_req_id = l_request_id
4145           WHERE parent_revised_item_seq_id = p_object_id2
4146             AND status_type NOT IN (G_ENG_IMPLEMENTED, G_ENG_CANCELLED);
4147         IF g_debug_flag THEN
4148           Write_Debug('After updating eng_revised_items (child level).');
4149           Write_Debug('  Row count = ' || SQL%ROWCOUNT);
4150         END IF;
4151 
4152       -- Case: promoting revised item to a phase that's not the last implement phase
4153       ELSE
4154         -- update parent revised item
4155         UPDATE eng_revised_items
4156           SET status_code = p_status_code,
4157               status_type = l_new_status_type,
4158               last_update_date = sysdate,
4159               last_updated_by = l_fnd_user_id,
4160               last_update_login = l_fnd_login_id
4161           WHERE revised_item_sequence_id = p_object_id2;
4162         IF g_debug_flag THEN
4163           Write_Debug('After updating eng_revised_items (parent level).');
4164           Write_Debug('  Row count = ' || SQL%ROWCOUNT);
4165         END IF;
4166 
4167         -- update active children revised items
4168      /*   UPDATE eng_revised_items
4169           SET status_code = p_status_code,
4170               status_type = l_new_status_type,
4171               last_update_date = sysdate,
4172               last_updated_by = l_fnd_user_id,
4173               last_update_login = l_fnd_login_id
4174           WHERE parent_revised_item_seq_id = p_object_id2
4175             AND status_type NOT IN (G_ENG_IMPLEMENTED, G_ENG_CANCELLED);*/
4176         IF g_debug_flag THEN
4177           Write_Debug('After updating eng_revised_items (child level).');
4178           Write_Debug('  Row count = ' || SQL%ROWCOUNT);
4179         END IF;
4180       END IF;
4181 
4182     END IF;
4183 
4184     IF g_debug_flag THEN
4185        Write_Debug('Done: Updating revised items to the new phase');
4186     END IF;
4187 
4188 
4189     -- Standard ending code ------------------------------------------------
4190     IF FND_API.To_Boolean ( p_commit ) THEN
4191       COMMIT WORK;
4192     END IF;
4193 
4194     FND_MSG_PUB.Count_And_Get
4195     ( p_count        =>      x_msg_count,
4196       p_data         =>      x_msg_data );
4197 
4198     IF g_debug_flag THEN
4199       Write_Debug('Finish. End Of procedure: Promote_Revised_Item');
4200     END IF;
4201 
4202     IF FND_API.to_Boolean( p_debug ) THEN
4203       Close_Debug_Session;
4204     END IF;
4205 
4206   EXCEPTION
4207     WHEN FND_API.G_EXC_ERROR THEN
4208       --ROLLBACK TO Promote_Revised_Item;
4209       x_return_status := FND_API.G_RET_STS_ERROR;
4210       FND_MSG_PUB.Count_And_Get
4211       ( p_count        =>      x_msg_count
4212        ,p_data         =>      x_msg_data );
4213       IF g_debug_flag THEN
4214         Write_Debug('Rollback and Finish with expected error.') ;
4215       END IF;
4216       IF FND_API.to_Boolean( p_debug ) THEN
4217         Close_Debug_Session;
4218       END IF;
4219     WHEN FND_API.G_EXC_UNEXPECTED_ERROR THEN
4220       --ROLLBACK TO Promote_Revised_Item;
4221       x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
4222       FND_MSG_PUB.Count_And_Get
4223       ( p_count        =>      x_msg_count
4224        ,p_data         =>      x_msg_data );
4225       IF g_debug_flag THEN
4226         Write_Debug('Rollback and Finish with unexpected error.') ;
4227       END IF;
4228       IF FND_API.to_Boolean( p_debug ) THEN
4229         Close_Debug_Session;
4230       END IF;
4231     WHEN OTHERS THEN
4232       --ROLLBACK TO Promote_Revised_Item;
4233       x_return_status := FND_API.G_RET_STS_UNEXP_ERROR ;
4234       IF FND_MSG_PUB.Check_Msg_Level ( FND_MSG_PUB.G_MSG_LVL_UNEXP_ERROR )
4235       THEN
4236         FND_MSG_PUB.Add_Exc_Msg ( G_PKG_NAME, l_api_name );
4237       END IF;
4238       FND_MSG_PUB.Count_And_Get
4239       ( p_count        =>      x_msg_count
4240        ,p_data         =>      x_msg_data );
4241       IF g_debug_flag THEN
4242         Write_Debug('Rollback and Finish with other error.') ;
4243       END IF;
4244       IF FND_API.to_Boolean( p_debug ) THEN
4245         Close_Debug_Session;
4246       END IF;
4247   END Promote_Revised_Item;
4248 
4249 
4250   -- Internal procedure for demotion of change header (inc. revItems)
4251   PROCEDURE Demote_Revised_Item
4252   (
4253     p_api_version               IN   NUMBER                             --
4254    ,p_init_msg_list             IN   VARCHAR2 := FND_API.G_FALSE        --
4255    ,p_commit                    IN   VARCHAR2 := FND_API.G_FALSE        --
4256    ,p_validation_level          IN   NUMBER   := FND_API.G_VALID_LEVEL_FULL
4257    ,p_debug                     IN   VARCHAR2 := FND_API.G_FALSE        --
4258    ,p_output_dir                IN   VARCHAR2 := NULL
4259    ,p_debug_filename            IN   VARCHAR2 := NULL
4260    ,x_return_status             OUT  NOCOPY  VARCHAR2                   --
4261    ,x_msg_count                 OUT  NOCOPY  NUMBER                     --
4262    ,x_msg_data                  OUT  NOCOPY  VARCHAR2                   --
4263    ,p_change_id                 IN   NUMBER                             -- header's change_id
4264    ,p_object_id2                IN   NUMBER                             -- revised item sequence id
4265    ,p_status_code               IN   NUMBER                             -- new phase
4266    ,p_api_caller                IN   VARCHAR2 := NULL                   -- can also be 'WF'
4267   )
4268   IS
4269     l_api_name           CONSTANT VARCHAR2(30)  := 'Demote_Revised_Item';
4270     l_api_version        CONSTANT NUMBER := 1.0;
4271 
4272     l_fnd_user_id        NUMBER := TO_NUMBER(FND_PROFILE.VALUE('USER_ID'));
4273     l_fnd_login_id       NUMBER := TO_NUMBER(FND_PROFILE.VALUE('LOGIN_ID'));
4274 
4275     l_api_caller         VARCHAR2(2) := NULL;
4276 
4277     l_return_status      VARCHAR2(1);
4278     l_msg_count          NUMBER;
4279     l_msg_data           VARCHAR2(2000);
4280 
4281     l_new_phase_sn       eng_lifecycle_statuses.sequence_number%TYPE;
4282 
4283     l_new_status_type    eng_change_statuses.status_type%TYPE;
4284 
4285     l_ri_status_code      eng_change_lines.status_code%TYPE;
4286     -- revItem's status_code's sequence_number
4287     l_ri_phase_sn         eng_lifecycle_statuses.sequence_number%TYPE;
4288     l_ri_status_type     eng_change_statuses.status_type%TYPE;
4289 
4290     l_curr_phase_sn      eng_lifecycle_statuses.sequence_number%TYPE;
4291 
4292   BEGIN
4293     -- Standard Start of API savepoint
4294     SAVEPOINT Demote_Revised_Item;
4295     -- Standard call to check for call compatibility
4296     IF NOT FND_API.Compatible_API_Call ( l_api_version
4297                                         ,p_api_version
4298                                         ,l_api_name
4299                                         ,G_PKG_NAME )
4300     THEN
4301       RAISE FND_API.G_EXC_UNEXPECTED_ERROR;
4302     END IF;
4303     -- Initialize message list if p_init_msg_list is set to TRUE.
4304     IF FND_API.to_Boolean( p_init_msg_list ) THEN
4305        FND_MSG_PUB.initialize;
4306     END IF;
4307 
4308 
4309     -- For Test/Debug
4310     Check_And_Open_Debug_Session(p_debug, p_output_dir, p_debug_filename) ;
4311     -- R12 Comment out
4312     -- IF FND_API.to_Boolean( p_debug ) THEN
4313     --     Open_Debug_Session(p_output_dir, p_debug_filename ) ;
4314     -- END IF;
4315 
4316     -- Write debug message if debug mode is on
4317     IF g_debug_flag THEN
4318        Write_Debug('ENG_CHANGE_LIFECYCLE_UTIL.Demote_Revised_Item log');
4319        Write_Debug('-----------------------------------------------------');
4320        Write_Debug('p_change_id         : ' || p_change_id );
4321        Write_Debug('p_object_id2        : ' || p_object_id2 );
4322        Write_Debug('p_status_code       : ' || p_status_code );
4323        Write_Debug('p_api_caller        : ' || p_api_caller );
4324        Write_Debug('-----------------------------------------------------');
4325        Write_Debug('Initializing return status... ' );
4326     END IF;
4327 
4328     -- Initialize API return status to success
4329     x_return_status := FND_API.G_RET_STS_SUCCESS;
4330 
4331     -- FND_PROFILE package is not available for workflow (WF),
4332     -- therefore manually set WHO column values
4333     IF p_api_caller = 'WF' THEN
4334       l_fnd_user_id := G_ENG_WF_USER_ID;
4335       l_fnd_login_id := G_ENG_WF_LOGIN_ID;
4336     ELSIF p_api_caller = 'CP' THEN
4337       l_fnd_user_id := G_ENG_CP_USER_ID;
4338       l_fnd_login_id := G_ENG_CP_LOGIN_ID;
4339     END IF;
4340 
4341     -- Real code starts here -----------------------------------------------
4342     -- Get the sequence number for the current phase of the change header
4343     SELECT sequence_number, status_code
4344       INTO l_ri_phase_sn, l_ri_status_code
4345       FROM eng_lifecycle_statuses
4346       WHERE entity_name = G_ENG_CHANGE
4347         AND entity_id1 = p_change_id
4348         AND active_flag = 'Y'
4349         AND status_code = ( SELECT status_code
4350                               FROM eng_revised_items
4351                               WHERE revised_item_sequence_id = p_object_id2)
4352         AND rownum = 1;
4353 
4354     -- Get the sequence number for the new phase of the change header
4355     SELECT sequence_number
4356       INTO l_new_phase_sn
4357       FROM eng_lifecycle_statuses
4358       WHERE entity_name = G_ENG_CHANGE
4359         AND entity_id1 = p_change_id
4360         AND status_code = p_status_code
4361         AND active_flag = 'Y'
4362         AND rownum = 1;
4363 
4364     IF g_debug_flag THEN
4365        Write_Debug('Before comparing l_new_phase_sn >= l_ri_phase_sn');
4366     END IF;
4367 
4368     -- Sanity check to make sure the new phase is after the current phase
4369     IF l_new_phase_sn >= l_ri_phase_sn THEN
4370       FND_MESSAGE.Set_Name('ENG','ENG_OBJ_STATE_CHANGED');
4371       FND_MSG_PUB.Add;
4372       RAISE FND_API.G_EXC_ERROR;
4373     END IF;
4374 
4375     -- Get the status_type of the new phase
4376     SELECT status_type
4377       INTO l_new_status_type
4378       FROM eng_change_statuses
4379       WHERE status_code = p_status_code;
4380 
4381     -- Make sure the revised item is not implemented or cancelled
4382     -- Get the status_type of the revised item phase
4383     SELECT status_type
4384       INTO l_ri_status_type
4385       FROM eng_change_statuses
4386       WHERE status_code = l_ri_status_code
4387         AND rownum = 1;
4388 
4389     -- Update only those which are still active
4390     IF (l_ri_status_type = G_ENG_IMPLEMENTED
4391         OR l_ri_status_type = G_ENG_CANCELLED)
4392     THEN
4393       FND_MESSAGE.Set_Name('ENG','ENG_REVITEM_IMP_OR_CNCL');
4394       FND_MSG_PUB.Add;
4395       RAISE FND_API.G_EXC_ERROR;
4396     ELSE
4397       -- update parent revised item
4398       UPDATE eng_revised_items
4399         SET status_code = p_status_code,
4400             status_type = l_new_status_type,
4401             last_update_date = sysdate,
4402             last_updated_by = l_fnd_user_id,
4403             last_update_login = l_fnd_login_id
4404         WHERE revised_item_sequence_id = p_object_id2;
4405       IF g_debug_flag THEN
4406         Write_Debug('After updating eng_revised_items (parent level).');
4407         Write_Debug('  Row count = ' || SQL%ROWCOUNT);
4408       END IF;
4409 
4410       -- update active children revised items
4411       UPDATE eng_revised_items
4412         SET status_code = p_status_code,
4413             status_type = l_new_status_type,
4414             last_update_date = sysdate,
4415             last_updated_by = l_fnd_user_id,
4416             last_update_login = l_fnd_login_id
4417         WHERE parent_revised_item_seq_id = p_object_id2
4418           AND status_type NOT IN (G_ENG_IMPLEMENTED, G_ENG_CANCELLED);
4419       IF g_debug_flag THEN
4420         Write_Debug('After updating eng_revised_items (child level).');
4421         Write_Debug('  Row count = ' || SQL%ROWCOUNT);
4422       END IF;
4423 
4424 
4425       -- Get the sequence number for the current phase of the change header
4426       SELECT sequence_number
4427         INTO l_curr_phase_sn
4428         FROM eng_lifecycle_statuses
4429         WHERE entity_name = G_ENG_CHANGE
4430           AND entity_id1 = p_change_id
4431           AND active_flag = 'Y'
4432           AND status_code = ( SELECT status_code
4433                                 FROM eng_engineering_changes
4434                                 WHERE change_id = p_change_id)
4435           AND rownum = 1;
4436 
4437       IF g_debug_flag THEN
4438          Write_Debug('After: getting header phase sequence number');
4439          Write_Debug('l_curr_phase_sn       : ' || l_curr_phase_sn );
4440       END IF;
4441       -- if the header's current phase is higher than the revised item's new phase
4442       -- demotion of revised item will also trigger demotion of header
4443       IF ( l_new_phase_sn < l_curr_phase_sn ) THEN
4444         IF g_debug_flag THEN
4445            Write_Debug('Demoting header is needed ');
4446            Write_Debug('Before: calling Demote_Header procedure');
4447         END IF;
4448 
4449         -- determine API caller - 'UI' should be used only once
4450         IF (p_api_caller = 'WF' OR p_api_caller = 'CP') THEN
4451           l_api_caller := p_api_caller;
4452         ELSE
4453           l_api_caller := NULL;
4454         END IF;
4455 
4456         Demote_Header
4457         ( p_api_version        => 1.0
4458          ,p_init_msg_list      => FND_API.G_FALSE
4459          ,p_commit             => FND_API.G_FALSE
4460          ,p_validation_level   => p_validation_level
4461          ,p_debug              => FND_API.G_FALSE
4462          ,p_output_dir         => p_output_dir
4463          ,p_debug_filename     => p_debug_filename
4464          ,x_return_status      => l_return_status
4465          ,x_msg_count          => l_msg_count
4466          ,x_msg_data           => l_msg_data
4467          ,p_change_id          => p_change_id
4468          ,p_status_code        => p_status_code
4469          ,p_update_ri_flag     => 'N'
4470          ,p_api_caller         => l_api_caller
4471         );
4472 
4473         IF g_debug_flag THEN
4474            Write_Debug('After: calling Demote_Header procedure: ' || l_return_status);
4475         END IF;
4476 
4477         IF ( l_return_status <>  FND_API.G_RET_STS_SUCCESS ) THEN
4478           x_return_status := l_return_status;
4479           x_msg_count := l_msg_count;
4480           x_msg_data := l_msg_data;
4481           --#FND_MESSAGE.Set_Name('ENG','ENG_ERROR_CALLING_PS_API');
4482           --#FND_MESSAGE.Set_Token('OBJECT_NAME', 'Demote_Header');
4483           --#FND_MSG_PUB.Add;
4484           RAISE FND_API.G_EXC_ERROR;
4485         END IF;
4486 
4487         IF g_debug_flag THEN
4488            Write_Debug('Successful: calling Demote_Header procedure');
4489         END IF;
4490       END IF;
4491 
4492     END IF;
4493 
4494     IF g_debug_flag THEN
4495        Write_Debug('Done: Updating revised items to the new phase');
4496     END IF;
4497 
4498     -- Standard ending code ------------------------------------------------
4499     IF FND_API.To_Boolean ( p_commit ) THEN
4500       COMMIT WORK;
4501     END IF;
4502 
4503     FND_MSG_PUB.Count_And_Get
4504     ( p_count        =>      x_msg_count,
4505       p_data         =>      x_msg_data );
4506 
4507     IF g_debug_flag THEN
4508       Write_Debug('Finish. End Of procedure: Demote_Revised_Item');
4509     END IF;
4510 
4511     IF FND_API.to_Boolean( p_debug ) THEN
4512       Close_Debug_Session;
4513     END IF;
4514 
4515   EXCEPTION
4516     WHEN FND_API.G_EXC_ERROR THEN
4517       --ROLLBACK TO Demote_Revised_Item;
4518       x_return_status := FND_API.G_RET_STS_ERROR;
4519       FND_MSG_PUB.Count_And_Get
4520       ( p_count        =>      x_msg_count
4521        ,p_data         =>      x_msg_data );
4522       IF g_debug_flag THEN
4523         Write_Debug('Rollback and Finish with expected error.') ;
4524       END IF;
4525       IF FND_API.to_Boolean( p_debug ) THEN
4526         Close_Debug_Session;
4527       END IF;
4528     WHEN FND_API.G_EXC_UNEXPECTED_ERROR THEN
4529       --ROLLBACK TO Demote_Revised_Item;
4530       x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
4531       FND_MSG_PUB.Count_And_Get
4532       ( p_count        =>      x_msg_count
4533        ,p_data         =>      x_msg_data );
4534       IF g_debug_flag THEN
4535         Write_Debug('Rollback and Finish with unexpected error.') ;
4536       END IF;
4537       IF FND_API.to_Boolean( p_debug ) THEN
4538         Close_Debug_Session;
4539       END IF;
4540     WHEN OTHERS THEN
4541       --ROLLBACK TO Demote_Revised_Item;
4542       x_return_status := FND_API.G_RET_STS_UNEXP_ERROR ;
4543       IF FND_MSG_PUB.Check_Msg_Level ( FND_MSG_PUB.G_MSG_LVL_UNEXP_ERROR )
4544       THEN
4545         FND_MSG_PUB.Add_Exc_Msg ( G_PKG_NAME, l_api_name );
4546       END IF;
4547       FND_MSG_PUB.Count_And_Get
4548       ( p_count        =>      x_msg_count
4549        ,p_data         =>      x_msg_data );
4550       IF g_debug_flag THEN
4551         Write_Debug('Rollback and Finish with other error.') ;
4552       END IF;
4553       IF FND_API.to_Boolean( p_debug ) THEN
4554         Close_Debug_Session;
4555       END IF;
4556   END Demote_Revised_Item;
4557 
4558 
4559   -- Interface procedure for combining promotion/demotion procedures
4560   -- Note that this procedure can ONLY be called directly from UI
4561   PROCEDURE Change_Phase
4562   (
4563     p_api_version               IN   NUMBER                             --
4564    ,p_init_msg_list             IN   VARCHAR2 := FND_API.G_FALSE        --
4565    ,p_commit                    IN   VARCHAR2 := FND_API.G_FALSE        --
4566    ,p_validation_level          IN   NUMBER   := FND_API.G_VALID_LEVEL_FULL
4567    ,p_debug                     IN   VARCHAR2 := FND_API.G_FALSE        --
4568    ,p_output_dir                IN   VARCHAR2 := NULL
4569    ,p_debug_filename            IN   VARCHAR2 := NULL
4570    ,x_return_status             OUT  NOCOPY  VARCHAR2                   --
4571    ,x_msg_count                 OUT  NOCOPY  NUMBER                     --
4572    ,x_msg_data                  OUT  NOCOPY  VARCHAR2                   --
4573    ,p_object_name               IN   VARCHAR2 := 'ENG_CHANGE'
4574    ,p_change_id                 IN   NUMBER                             -- header's change_id
4575    ,p_object_id2                IN   NUMBER   := NULL                   -- revised item seq id
4576    ,p_status_code               IN   NUMBER                             -- new phase
4577    ,p_update_ri_flag            IN   VARCHAR2 := 'Y'                    -- can also be 'N'
4578    ,p_api_caller                IN   VARCHAR2 := 'UI'
4579    ,p_action_type               IN   VARCHAR2 := G_ENG_PROMOTE          -- promote/demote
4580    ,p_comment                   IN   VARCHAR2 := NULL                   -- only used for co promote-to-implement action
4581    ,x_sfa_line_items_exists     OUT NOCOPY VARCHAR2
4582   )
4583   IS
4584     l_api_name           CONSTANT VARCHAR2(30)  := 'Change_Phase';
4585     l_api_version        CONSTANT NUMBER := 1.0;
4586 
4587     l_return_status      VARCHAR2(1);
4588     l_msg_count          NUMBER;
4589     l_msg_data           VARCHAR2(2000);
4590 
4591     l_curr_status_code   eng_engineering_changes.status_code%TYPE;
4592     l_curr_status_type   eng_engineering_changes.status_type%TYPE;
4593     l_wf_route_id        eng_lifecycle_statuses.change_wf_route_id%TYPE;
4594     l_wf_status          eng_lifecycle_statuses.workflow_status%TYPE;
4595   BEGIN
4596     -- Standard Start of API savepoint
4597     SAVEPOINT Change_Phase;
4598     -- Standard call to check for call compatibility
4599     IF NOT FND_API.Compatible_API_Call ( l_api_version
4600                                         ,p_api_version
4601                                         ,l_api_name
4602                                         ,G_PKG_NAME )
4603     THEN
4604       RAISE FND_API.G_EXC_UNEXPECTED_ERROR;
4605     END IF;
4606     -- Initialize message list if p_init_msg_list is set to TRUE.
4607     IF FND_API.to_Boolean( p_init_msg_list ) THEN
4608        FND_MSG_PUB.initialize;
4609     END IF;
4610 
4611 
4612     -- For Test/Debug
4613     Check_And_Open_Debug_Session(p_debug, p_output_dir, p_debug_filename) ;
4614     -- R12 Comment out
4615     -- IF FND_API.to_Boolean( p_debug ) THEN
4616     --     Open_Debug_Session(p_output_dir, p_debug_filename ) ;
4617     -- END IF;
4618 
4619     -- Write debug message if debug mode is on
4620     IF g_debug_flag THEN
4621        Write_Debug('ENG_CHANGE_LIFECYCLE_UTIL.Change_Phase log');
4622        Write_Debug('-----------------------------------------------------');
4623        Write_Debug('p_object_name       : ' || p_object_name );
4624        Write_Debug('p_change_id         : ' || p_change_id );
4625        Write_Debug('p_object_id2        : ' || p_object_id2 );
4626        Write_Debug('p_status_code       : ' || p_status_code );
4627        Write_Debug('p_api_caller        : ' || p_api_caller );
4628        Write_Debug('p_action_type       : ' || p_action_type );
4629        Write_Debug('-----------------------------------------------------');
4630        Write_Debug('Initializing return status... ' );
4631     END IF;
4632 
4633     -- Initialize API return status to success
4634     x_return_status := FND_API.G_RET_STS_SUCCESS;
4635 
4636 
4637     -- Real code starts here -----------------------------------------------
4638     IF (p_object_name = G_ENG_CHANGE) THEN
4639       -- Get the current phase of the change header
4640       SELECT status_code, status_type
4641         INTO l_curr_status_code, l_curr_status_type
4642         FROM eng_engineering_changes
4643         WHERE change_id = p_change_id;
4644 
4645       -- Get the workflow route id and status for the current phase
4646       SELECT change_wf_route_id, workflow_status
4647         INTO l_wf_route_id, l_wf_status
4648         FROM eng_lifecycle_statuses
4649         WHERE entity_name = G_ENG_CHANGE
4650           AND entity_id1 = p_change_id
4651           AND status_code = l_curr_status_code
4652           AND active_flag = 'Y'
4653           AND rownum = 1;
4654 
4655       -- (x If the current phase is of type APPROVAL x), and the
4656       -- workflow is available on the current phase but it is still running,
4657       -- raise error message.
4658       IF (--l_curr_status_type = G_ENG_APPROVED AND
4659           l_wf_route_id IS NOT NULL
4660           AND l_wf_status = Eng_Workflow_Util.G_RT_IN_PROGRESS)
4661       THEN
4662         FND_MESSAGE.Set_Name('ENG','ENG_OBJ_STATE_CHANGED');
4663         FND_MSG_PUB.Add;
4664         RAISE FND_API.G_EXC_ERROR;
4665       END IF;
4666 
4667       IF ( p_action_type = G_ENG_PROMOTE ) THEN
4668         Promote_Header
4669         ( p_api_version        => 1.0
4670          ,p_init_msg_list      => FND_API.G_FALSE
4671          ,p_commit             => FND_API.G_FALSE
4672          ,p_validation_level   => p_validation_level
4673          ,p_debug              => FND_API.G_FALSE
4674          ,p_output_dir         => p_output_dir
4675          ,p_debug_filename     => p_debug_filename
4676          ,x_return_status      => l_return_status
4677          ,x_msg_count          => l_msg_count
4678          ,x_msg_data           => l_msg_data
4679          ,p_change_id          => p_change_id
4680          ,p_status_code        => p_status_code
4681          ,p_update_ri_flag     => p_update_ri_flag
4682          ,p_api_caller         => p_api_caller
4683          ,p_comment            => p_comment
4684         );
4685 
4686         IF g_debug_flag THEN
4687            Write_Debug('After: calling Promote_Header procedure: ' || l_return_status);
4688         END IF;
4689 
4690 
4691 
4692         IF ( l_return_status <>  FND_API.G_RET_STS_SUCCESS ) THEN
4693           x_return_status := l_return_status;
4694           x_msg_count := l_msg_count;
4695           x_msg_data := l_msg_data;
4696           --#FND_MESSAGE.Set_Name('ENG','ENG_ERROR_CALLING_PS_API');
4697           --#FND_MESSAGE.Set_Token('OBJECT_NAME', 'Promote_Header');
4698           --#FND_MSG_PUB.Add;
4699           RAISE FND_API.G_EXC_ERROR;
4700         END IF;
4701       ELSIF ( p_action_type = G_ENG_DEMOTE ) THEN
4702 
4703         Demote_Header
4704         ( p_api_version        => 1.0
4705          ,p_init_msg_list      => FND_API.G_FALSE
4706          ,p_commit             => FND_API.G_FALSE
4707          ,p_validation_level   => p_validation_level
4708          ,p_debug              => FND_API.G_FALSE
4709          ,p_output_dir         => p_output_dir
4710          ,p_debug_filename     => p_debug_filename
4711          ,x_return_status      => l_return_status
4712          ,x_msg_count          => l_msg_count
4713          ,x_msg_data           => l_msg_data
4714          ,p_change_id          => p_change_id
4715          ,p_status_code        => p_status_code
4716          ,p_api_caller         => p_api_caller
4717          ,x_sfa_line_items_exists => x_sfa_line_items_exists
4718         );
4719 
4720 
4721         IF g_debug_flag THEN
4722            Write_Debug('After: calling Demote_Header procedure: ' || l_return_status);
4723         END IF;
4724 
4725 
4726         IF ( l_return_status <>  FND_API.G_RET_STS_SUCCESS ) THEN
4727           x_return_status := l_return_status;
4728           x_msg_count := l_msg_count;
4729           x_msg_data := l_msg_data;
4730           --#FND_MESSAGE.Set_Name('ENG','ENG_ERROR_CALLING_PS_API');
4731           --#FND_MESSAGE.Set_Token('OBJECT_NAME', 'Demote_Header');
4732           --#FND_MSG_PUB.Add;
4733           RAISE FND_API.G_EXC_ERROR;
4734         END IF;
4735       ELSE
4736         IF g_debug_flag THEN
4737           Write_Debug('Error: action is neither promotion nor demotion') ;
4738         END IF;
4739       END IF;
4740     -- revised item
4741     ELSIF (p_object_name = G_ENG_REVISED_ITEM) THEN
4742 
4743       IF ( p_action_type = G_ENG_PROMOTE ) THEN
4744         Promote_Revised_Item
4745         ( p_api_version        => 1.0
4746          ,p_init_msg_list      => FND_API.G_FALSE
4747          ,p_commit             => FND_API.G_FALSE
4748          ,p_validation_level   => p_validation_level
4749          ,p_debug              => FND_API.G_FALSE
4750          ,p_output_dir         => p_output_dir
4751          ,p_debug_filename     => p_debug_filename
4752          ,x_return_status      => l_return_status
4753          ,x_msg_count          => l_msg_count
4754          ,x_msg_data           => l_msg_data
4755          ,p_change_id          => p_change_id
4756          ,p_object_id2         => p_object_id2
4757          ,p_status_code        => p_status_code
4758          ,p_api_caller         => p_api_caller
4759         );
4760 
4761 
4762         IF g_debug_flag THEN
4763            Write_Debug('After: calling Promote_Revised_Item procedure: ' || l_return_status);
4764         END IF;
4765 
4766 
4767 
4768         IF ( l_return_status <>  FND_API.G_RET_STS_SUCCESS ) THEN
4769           x_return_status := l_return_status;
4770           x_msg_count := l_msg_count;
4771           x_msg_data := l_msg_data;
4772           --#FND_MESSAGE.Set_Name('ENG','ENG_ERROR_CALLING_PS_API');
4773           --#FND_MESSAGE.Set_Token('OBJECT_NAME', 'Promote_Revised_Item');
4774           --#FND_MSG_PUB.Add;
4775           RAISE FND_API.G_EXC_ERROR;
4776         END IF;
4777 
4778       ELSIF ( p_action_type = G_ENG_DEMOTE ) THEN
4779         Demote_Revised_Item
4780         ( p_api_version        => 1.0
4781          ,p_init_msg_list      => FND_API.G_FALSE
4782          ,p_commit             => FND_API.G_FALSE
4783          ,p_validation_level   => p_validation_level
4784          ,p_debug              => FND_API.G_FALSE
4785          ,p_output_dir         => p_output_dir
4786          ,p_debug_filename     => p_debug_filename
4787          ,x_return_status      => l_return_status
4788          ,x_msg_count          => l_msg_count
4789          ,x_msg_data           => l_msg_data
4790          ,p_change_id          => p_change_id
4791          ,p_object_id2         => p_object_id2
4792          ,p_status_code        => p_status_code
4793          ,p_api_caller         => p_api_caller
4794         );
4795 
4796         IF g_debug_flag THEN
4797            Write_Debug('After: calling Demote_Revised_Item procedure: ' || l_return_status);
4798         END IF;
4799 
4800 
4801         IF ( l_return_status <>  FND_API.G_RET_STS_SUCCESS ) THEN
4802           x_return_status := l_return_status;
4803           x_msg_count := l_msg_count;
4804           x_msg_data := l_msg_data;
4805           --#FND_MESSAGE.Set_Name('ENG','ENG_ERROR_CALLING_PS_API');
4806           --#FND_MESSAGE.Set_Token('OBJECT_NAME', 'Demote_Revised_Item');
4807           --#FND_MSG_PUB.Add;
4808           RAISE FND_API.G_EXC_ERROR;
4809         END IF;
4810       ELSE
4811         IF g_debug_flag THEN
4812           Write_Debug('Error: action is neither promotion nor demotion') ;
4813         END IF;
4814       END IF;
4815     ELSE
4816       IF g_debug_flag THEN
4817         Write_Debug('Error: p_object_name is neither ENG_CHANGE nor ENG_REVISED_ITEM') ;
4818       END IF;
4819     END IF;
4820 
4821     -- Standard ending code ------------------------------------------------
4822     IF FND_API.To_Boolean ( p_commit ) THEN
4823       COMMIT WORK;
4824     END IF;
4825 
4826     FND_MSG_PUB.Count_And_Get
4827     ( p_count        =>      x_msg_count,
4828       p_data         =>      x_msg_data );
4829 
4830     IF g_debug_flag THEN
4831       Write_Debug('Finish. End Of procedure: Change_Phase');
4832     END IF;
4833 
4834     IF FND_API.to_Boolean( p_debug ) THEN
4835       Close_Debug_Session;
4836     END IF;
4837 
4838   EXCEPTION
4839     WHEN FND_API.G_EXC_ERROR THEN
4840       --ROLLBACK TO Change_Phase;
4841       x_return_status := FND_API.G_RET_STS_ERROR;
4842       FND_MSG_PUB.Count_And_Get
4843       ( p_count        =>      x_msg_count
4844        ,p_data         =>      x_msg_data );
4845       IF g_debug_flag THEN
4846         Write_Debug('Rollback and Finish with expected error.') ;
4847       END IF;
4848       IF FND_API.to_Boolean( p_debug ) THEN
4849         Close_Debug_Session;
4850       END IF;
4851     WHEN FND_API.G_EXC_UNEXPECTED_ERROR THEN
4852       --ROLLBACK TO Change_Phase;
4853       x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
4854       FND_MSG_PUB.Count_And_Get
4855       ( p_count        =>      x_msg_count
4856        ,p_data         =>      x_msg_data );
4857       IF g_debug_flag THEN
4858         Write_Debug('Rollback and Finish with unexpected error.') ;
4859       END IF;
4860       IF FND_API.to_Boolean( p_debug ) THEN
4861         Close_Debug_Session;
4862       END IF;
4863     WHEN OTHERS THEN
4864       --ROLLBACK TO Change_Phase;
4865       x_return_status := FND_API.G_RET_STS_UNEXP_ERROR ;
4866       IF FND_MSG_PUB.Check_Msg_Level ( FND_MSG_PUB.G_MSG_LVL_UNEXP_ERROR )
4867       THEN
4868         FND_MSG_PUB.Add_Exc_Msg ( G_PKG_NAME, l_api_name );
4869       END IF;
4870       FND_MSG_PUB.Count_And_Get
4871       ( p_count        =>      x_msg_count
4872        ,p_data         =>      x_msg_data );
4873       IF g_debug_flag THEN
4874         Write_Debug('Rollback and Finish with other error.') ;
4875       END IF;
4876       IF FND_API.to_Boolean( p_debug ) THEN
4877         Close_Debug_Session;
4878       END IF;
4879 
4880   END Change_Phase;
4881 
4882   PROCEDURE Change_Phase
4883   (
4884     p_api_version               IN   NUMBER                             --
4885    ,p_init_msg_list             IN   VARCHAR2 := FND_API.G_FALSE        --
4886    ,p_commit                    IN   VARCHAR2 := FND_API.G_FALSE        --
4887    ,p_validation_level          IN   NUMBER   := FND_API.G_VALID_LEVEL_FULL
4888    ,p_debug                     IN   VARCHAR2 := FND_API.G_FALSE        --
4889    ,p_output_dir                IN   VARCHAR2 := NULL
4890    ,p_debug_filename            IN   VARCHAR2 := NULL
4891    ,x_return_status             OUT  NOCOPY  VARCHAR2                   --
4892    ,x_msg_count                 OUT  NOCOPY  NUMBER                     --
4893    ,x_msg_data                  OUT  NOCOPY  VARCHAR2                   --
4894    ,p_object_name               IN   VARCHAR2 := 'ENG_CHANGE'
4895    ,p_change_id                 IN   NUMBER                             -- header's change_id
4896    ,p_object_id2                IN   NUMBER   := NULL                   -- revised item seq id
4897    ,p_status_code               IN   NUMBER                             -- new phase
4898    ,p_update_ri_flag            IN   VARCHAR2 := 'Y'                    -- can also be 'N'
4899    ,p_api_caller                IN   VARCHAR2 := 'UI'
4900    ,p_action_type               IN   VARCHAR2 := G_ENG_PROMOTE          -- promote/demote
4901    ,p_comment                   IN   VARCHAR2 := NULL                   -- only used for co promote-to-implement action
4902   )
4903   IS
4904      l_sfa_line_items_exists VARCHAR2(1);
4905   BEGIN
4906           Change_Phase
4907           (
4908             p_api_version       => p_api_version
4909             ,p_init_msg_list     => p_init_msg_list
4910             ,p_commit            => p_commit
4911             ,p_validation_level  => p_validation_level
4912             ,p_debug             => p_debug
4913             ,p_output_dir        => p_output_dir
4914             ,p_debug_filename    => p_debug_filename
4915             ,x_return_status     => x_return_status
4916             ,x_msg_count         => x_msg_count
4917             ,x_msg_data          => x_msg_data
4918             ,p_object_name       => p_object_name
4919             ,p_change_id         => p_change_id
4920             ,p_object_id2        => p_object_id2
4921             ,p_status_code       => p_status_code
4922             ,p_update_ri_flag    => p_update_ri_flag
4923             ,p_api_caller        => p_api_caller
4924             ,p_action_type       => p_action_type
4925             ,p_comment           => p_comment
4926             ,x_sfa_line_items_exists => l_sfa_line_items_exists
4927           );
4928   END Change_Phase;
4929 
4930 
4931 
4932 
4933   -- Procedure to be called by WF to update lifecycle states of the change header,
4934   -- revised items, tasks and lines lifecycle states
4935   PROCEDURE Update_Lifecycle_States
4936   (
4937     p_api_version               IN   NUMBER                             --
4938    ,p_init_msg_list             IN   VARCHAR2 := FND_API.G_FALSE        --
4939    ,p_commit                    IN   VARCHAR2 := FND_API.G_FALSE        --
4940    ,p_validation_level          IN   NUMBER   := FND_API.G_VALID_LEVEL_FULL
4941    ,p_debug                     IN   VARCHAR2 := FND_API.G_FALSE        --
4942    ,p_output_dir                IN   VARCHAR2 := NULL
4943    ,p_debug_filename            IN   VARCHAR2 := NULL
4944    ,x_return_status             OUT  NOCOPY  VARCHAR2                   --
4945    ,x_msg_count                 OUT  NOCOPY  NUMBER                     --
4946    ,x_msg_data                  OUT  NOCOPY  VARCHAR2                   --
4947    ,p_change_id                 IN   NUMBER
4948    ,p_status_code               IN   NUMBER   := NULL -- passed only by WF call for p_route_status = IN_PROGRESS or CP for imp failure
4949    ,p_api_caller                IN   VARCHAR2 := NULL                   -- or 'WF'
4950    ,p_wf_route_id               IN   NUMBER
4951    ,p_route_status              IN   VARCHAR2
4952    ,p_comment                   IN   VARCHAR2 := NULL                   -- only used for co promote-to-implement action
4953   )
4954   IS
4955     l_api_name           CONSTANT VARCHAR2(30)  := 'Update_Lifecycle_States';
4956     l_api_version        CONSTANT NUMBER := 1.0;
4957 
4958     l_return_status      VARCHAR2(1);
4959     l_msg_count          NUMBER;
4960     l_msg_data           VARCHAR2(2000);
4961 
4962     l_fnd_user_id        NUMBER := TO_NUMBER(FND_PROFILE.VALUE('USER_ID'));
4963     l_fnd_login_id       NUMBER := TO_NUMBER(FND_PROFILE.VALUE('LOGIN_ID'));
4964 
4965     l_api_caller         VARCHAR2(2) := NULL;
4966 
4967     l_action_id          eng_change_actions.action_id%TYPE;
4968 
4969     l_chg_appr_status    eng_engineering_changes.approval_status_type%TYPE;
4970     l_curr_appr_status   eng_engineering_changes.approval_status_type%TYPE;
4971 
4972     l_cm_type_code       eng_engineering_changes.change_mgmt_type_code%TYPE;
4973     l_base_cm_type_code   eng_change_order_types.BASE_CHANGE_MGMT_TYPE_CODE%TYPE;
4974 
4975     l_curr_status_code   NUMBER;
4976     l_curr_status_type   NUMBER;
4977     l_next_status_code   NUMBER;
4978     l_last_status_code   NUMBER;
4979 
4980     l_status_type        NUMBER; -- status_type for p_status_code as incoming parameter
4981     l_min_appr_sn        eng_lifecycle_statuses.sequence_number%TYPE;
4982 
4983     l_last_wf_route_id   eng_lifecycle_statuses.change_wf_route_id%TYPE;
4984 
4985     l_curr_phase_sn      eng_lifecycle_statuses.sequence_number%TYPE;
4986     l_max_appr_phase_sn  eng_lifecycle_statuses.sequence_number%TYPE;
4987     l_max_phase_sn       eng_lifecycle_statuses.sequence_number%TYPE;
4988 
4989     l_nir_update_flag    VARCHAR2(1) := 'F';
4990 
4991     CURSOR c_lines IS
4992       SELECT s.status_type
4993         FROM eng_change_lines l,
4994              eng_change_statuses s
4995         WHERE l.change_id = p_change_id
4996           AND s.status_code = l.status_code;
4997     l_line_status_type   eng_change_statuses.status_type%TYPE;
4998 
4999     l_chg_notice         eng_engineering_changes.change_notice%TYPE;
5000     l_org_id             eng_engineering_changes.organization_id%TYPE;
5001     l_request_id         NUMBER;
5002 
5003     l_imp_eco_flag       VARCHAR2(1) := 'N';
5004 
5005     l_is_co_last_phase   VARCHAR2(1);
5006     l_auto_demote_status eng_lifecycle_statuses.status_code%TYPE;
5007 
5008     l_flag_imp_failed    VARCHAR2(1) := 'N';
5009 
5010   BEGIN
5011 
5012     -- Standard Start of API savepoint
5013     SAVEPOINT Update_Lifecycle_States;
5014     -- Standard call to check for call compatibility
5015     IF NOT FND_API.Compatible_API_Call ( l_api_version
5016                                         ,p_api_version
5017                                         ,l_api_name
5018                                         ,G_PKG_NAME )
5019     THEN
5020       RAISE FND_API.G_EXC_UNEXPECTED_ERROR;
5021     END IF;
5022     -- Initialize message list if p_init_msg_list is set to TRUE.
5023     IF FND_API.to_Boolean( p_init_msg_list ) THEN
5024       FND_MSG_PUB.initialize;
5025     END IF;
5026 
5027 
5028     -- For Test/Debug
5029     Check_And_Open_Debug_Session(p_debug, p_output_dir, p_debug_filename) ;
5030     -- R12 Comment out
5031     -- IF FND_API.to_Boolean( p_debug ) THEN
5032     --     Open_Debug_Session(p_output_dir, p_debug_filename ) ;
5033     -- END IF;
5034 
5035     -- Write debug message if debug mode is on
5036     IF g_debug_flag THEN
5037        Write_Debug('ENG_CHANGE_LIFECYCLE_UTIL.Update_Lifecycle_States log');
5038        Write_Debug('-----------------------------------------------------');
5039        Write_Debug('p_change_id         : ' || p_change_id );
5040        Write_Debug('p_status_code       : ' || p_status_code );
5041        Write_Debug('p_api_caller        : ' || p_api_caller );
5042        Write_Debug('p_wf_route_id       : ' || p_wf_route_id );
5043        Write_Debug('p_route_status      : ' || p_route_status );
5044        Write_Debug('l_fnd_user_id       : ' || l_fnd_user_id );
5045        Write_Debug('l_fnd_login_id      : ' || l_fnd_login_id );
5046        Write_Debug('-----------------------------------------------------');
5047        Write_Debug('Initializing return status... ' );
5048     END IF;
5049 
5050     -- Initialize API return status to success
5051     x_return_status := FND_API.G_RET_STS_SUCCESS;
5052 
5053     -- FND_PROFILE package is not available for workflow (WF),
5054     -- therefore manually set WHO column values
5055     IF p_api_caller = 'WF' THEN
5056       l_fnd_user_id := G_ENG_WF_USER_ID;
5057       l_fnd_login_id := G_ENG_WF_LOGIN_ID;
5058     /* bug 13042932
5059       ELSIF p_api_caller = 'CP' THEN
5060       l_fnd_user_id := G_ENG_CP_USER_ID;
5061       l_fnd_login_id := G_ENG_CP_LOGIN_ID;
5062     */
5063     END IF;
5064 
5065     -- Real code starts here -----------------------------------------------
5066 
5067     -- Translate workflow route statuses to change workflow status types
5068     IF (   p_route_status = Eng_Workflow_Util.G_RT_APPROVED
5069         OR p_route_status = Eng_Workflow_Util.G_RT_COMPLETED
5070         OR p_route_status = Eng_Workflow_Util.G_RT_REPLIED)
5071     THEN
5072       l_chg_appr_status := G_ENG_APPR_APPROVED;
5073     ELSIF (p_route_status = Eng_Workflow_Util.G_RT_REJECTED)
5074     THEN
5075       l_chg_appr_status := G_ENG_APPR_REJECTED;
5076     ELSIF (p_route_status = Eng_Workflow_Util.G_RT_TIME_OUT)
5077     THEN
5078       l_chg_appr_status := G_ENG_APPR_TIME_OUT;
5079     ELSIF (   p_route_status = Eng_Workflow_Util.G_RT_ABORTED
5080            OR p_route_status = Eng_Workflow_Util.G_RT_NOT_STARTED)
5081     THEN
5082       l_chg_appr_status := G_ENG_NOT_SUBMITTED;
5083     ELSIF (p_route_status = Eng_Workflow_Util.G_RT_IN_PROGRESS)
5084     THEN
5085       l_chg_appr_status := G_ENG_APPR_REQUESTED;
5086     END IF;
5087     IF g_debug_flag THEN
5088        Write_Debug('After: workflow status >> header approval status translation');
5089        Write_Debug('l_chg_appr_status   : ' || l_chg_appr_status );
5090     END IF;
5091 
5092 
5093     -- Query the required parameters
5094     -- Get the current phase, promote_phase and cm type of the change header
5095     SELECT eec.status_code, eec.promote_status_code, eec.change_mgmt_type_code,
5096            ecot.base_change_mgmt_type_code
5097       INTO l_curr_status_code, l_next_status_code, l_cm_type_code,
5098            l_base_cm_type_code
5099       FROM eng_engineering_changes eec,
5100            eng_change_order_types ecot
5101       WHERE eec.change_id = p_change_id
5102         AND ecot.change_order_type_id = eec.change_order_type_id;
5103 
5104     -- Get the current phase status_type
5105     SELECT status_type
5106       INTO l_curr_status_type
5107       FROM eng_change_statuses
5108       WHERE status_code = l_curr_status_code;
5109 
5110     -- Get the current phase's sequence number
5111     SELECT sequence_number
5112       INTO l_curr_phase_sn
5113       FROM eng_lifecycle_statuses
5114       WHERE entity_name = G_ENG_CHANGE
5115         AND entity_id1 = p_change_id
5116         AND status_code = l_curr_status_code
5117         AND active_flag = 'Y'
5118         AND rownum = 1;
5119 
5120     -- Get the sequence_number of the last phase
5121     -- Note that only phase of IMPLEMENT type can be the last phase
5122     SELECT max(sequence_number)
5123       INTO l_max_phase_sn
5124       FROM eng_lifecycle_statuses
5125       WHERE entity_name = G_ENG_CHANGE
5126         AND entity_id1 = p_change_id
5127         AND active_flag = 'Y';
5128 
5129     -- Get the sequence number of the last phase
5130     SELECT status_code, change_wf_route_id
5131       INTO l_last_status_code, l_last_wf_route_id
5132       FROM eng_lifecycle_statuses
5133       WHERE entity_name = G_ENG_CHANGE
5134         AND entity_id1 = p_change_id
5135         AND active_flag = 'Y'
5136         AND sequence_number = l_max_phase_sn;
5137 
5138 
5139     -- Case: (special 1) last implement phase of ECO: workflow completion
5140     -- Special branch of code to handle post <implement> promotion for ECO
5141     -- (invoked by eco last implement phase workflow call)
5142     IF (    (p_api_caller IS NULL OR p_api_caller <> 'CP')
5143          AND l_base_cm_type_code = G_ENG_ECO
5144          AND l_next_status_code = l_last_status_code
5145          AND p_wf_route_id = l_last_wf_route_id
5146         )
5147     THEN
5148       IF g_debug_flag THEN
5149         Write_Debug('In block: case (special) last implement phase of ECO: workflow completion.');
5150       END IF;
5151 
5152       -- Update the current phase's workflow status
5153       UPDATE eng_lifecycle_statuses
5154         SET workflow_status = p_route_status,
5155             completion_date = sysdate,    -- newly added for 3479509 fix (launch wf after implementation)
5156             last_update_date = sysdate,
5157             last_updated_by = l_fnd_user_id,
5158             last_update_login = l_fnd_login_id
5159         WHERE entity_name = G_ENG_CHANGE
5160           AND entity_id1 = p_change_id
5161           AND status_code = l_next_status_code
5162           AND active_flag = 'Y'
5163           AND rownum = 1;
5164       IF g_debug_flag THEN
5165         Write_Debug('After updating eng_lifecycle_statuses.workflow_status.');
5166         Write_Debug('  Row count = ' || SQL%ROWCOUNT);
5167       END IF;
5168 
5169 			-- Bug 5989058.
5170  	         -- Set the implementation date if the status is completed or implemented
5171  	         DECLARE
5172  	                 l_next_status_type eng_change_statuses.status_type%TYPE;
5173  	         BEGIN
5174 
5175  	                 SELECT status_type INTO l_next_status_type FROM eng_change_statuses WHERE status_code = l_next_status_code;
5176 
5177  	                 if( l_next_status_type = G_ENG_COMPLETED OR
5178  	                 l_next_status_type = G_ENG_IMPLEMENTED  ) THEN
5179  	                 UPDATE eng_engineering_changes SET
5180  	                         completion_date = SYSDATE
5181  	                 WHERE change_id = p_change_id;
5182  	                 END IF;
5183  	         EXCEPTION
5184  	                 WHEN OTHERS THEN
5185  	                         NULL;
5186  	         END;
5187 
5188     -- Case: (special 2) last implement phase of ECO direct promotion w/o wf
5189     -- Special branch of code to handle post <implement> promotion for ECO
5190     -- (invoked by Start_WF_OnlyIf_Necessary w/o wf or with p_skip_wf=Y, which
5191     --  can be recognized by the null p_wf_route_id)
5192     ELSIF (    (p_api_caller IS NULL OR p_api_caller <> 'CP')
5193             AND l_base_cm_type_code = G_ENG_ECO
5194             AND l_next_status_code = l_last_status_code
5195             AND p_wf_route_id IS NULL
5196            )
5197     THEN
5198       IF g_debug_flag THEN
5199         Write_Debug('In block: case (special) last implement phase of ECO');
5200       END IF;
5201 
5202       -- Get the required parameters before calling concurrent program for implementing ECO
5203       SELECT change_notice, organization_id
5204         INTO l_chg_notice, l_org_id
5205         FROM eng_engineering_changes
5206         WHERE change_id = p_change_id;
5207 
5208       -- If so, submit concurrent program to implement the eco and all its revised items
5209       -- as the lifecycle has already reach the last phase for implementation
5210       IF g_debug_flag THEN
5211         Write_Debug('Before: calling ENG_ECO_UTIL.Implement_ECO');
5212         Write_Debug('  l_chg_notice = ' || l_chg_notice);
5213         Write_Debug('  l_org_id     = ' || l_org_id);
5214       END IF;
5215       ENG_ECO_UTIL.Implement_ECO
5216       ( p_api_version          =>    1.0
5217        ,p_init_msg_list        =>    FND_API.G_FALSE
5218        ,p_commit               =>    FND_API.G_FALSE
5219        ,p_validation_level     =>    p_validation_level
5220        ,p_debug                =>    p_debug --FND_API.G_FALSE
5221        ,p_output_dir           =>    p_output_dir
5222        ,p_debug_filename       =>    'engact.impECO.log' --p_debug_filename
5223        ,x_return_status        =>    l_return_status
5224        ,x_msg_count            =>    l_msg_count
5225        ,x_msg_data             =>    l_msg_data
5226        ,p_change_id            =>    p_change_id
5227        ,p_change_notice        =>    l_chg_notice
5228        ,p_org_id               =>    l_org_id
5229        ,x_request_id           =>    l_request_id
5230       );
5231 
5232       IF g_debug_flag THEN
5233          Write_Debug('After: calling ENG_ECO_UTIL.Implement_ECO: ' || l_return_status);
5234       END IF;
5235 
5236 
5237       IF (l_request_id IS NULL) THEN
5238         IF g_debug_flag THEN
5239           Write_Debug('l_request_id = NULL');
5240         END IF;
5241       ELSE
5242         IF g_debug_flag THEN
5243           Write_Debug('l_request_id = ' || l_request_id);
5244         END IF;
5245 
5246         -- ATG Project
5247         -- Putting the request id flag in the implementation_req_id field
5248         UPDATE eng_engineering_changes
5249         SET implementation_req_id = l_request_id
5250         WHERE change_id = p_change_id;
5251       END IF;
5252 
5253       IF (l_return_status <>  FND_API.G_RET_STS_SUCCESS
5254           OR l_request_id IS NULL
5255           OR l_request_id = 0 )
5256       THEN
5257         l_flag_imp_failed := 'Y';
5258 
5259         IF (p_api_caller = 'WF') THEN
5260           -- Log implementation failure message
5261           UPDATE eng_engineering_changes
5262             SET status_type = G_ENG_IMP_FAILED,
5263                 last_update_date = sysdate,
5264                 last_updated_by = l_fnd_user_id,
5265                 last_update_login = l_fnd_login_id
5266             WHERE change_id = p_change_id;
5267 
5268           IF g_debug_flag THEN
5269              Write_Debug('Before: saving action log');
5270           END IF;
5271           l_action_id := 0;
5272           -- create new action log
5273           ENG_CHANGE_ACTIONS_UTIL.Create_Change_Action
5274           ( p_api_version           => 1.0
5275           , p_init_msg_list         => FND_API.G_FALSE        --
5276           , p_commit                => FND_API.G_FALSE        --
5277           , p_validation_level      => FND_API.G_VALID_LEVEL_FULL
5278           , p_debug                 => p_debug --FND_API.G_FALSE
5279           , p_output_dir            => p_output_dir
5280           , p_debug_filename        => NULL
5281           , x_return_status         => l_return_status
5282           , x_msg_count             => l_msg_count
5283           , x_msg_data              => l_msg_data
5284           , p_action_type           => ENG_CHANGE_ACTIONS_UTIL.G_ACT_IMP_FAILED
5285           , p_object_name           => G_ENG_CHANGE
5286           , p_object_id1            => p_change_id
5287           , p_object_id2            => NULL
5288           , p_object_id3            => NULL
5289           , p_object_id4            => NULL
5290           , p_object_id5            => NULL
5291           , p_parent_action_id      => -1
5292           , p_status_code           => NULL
5293           , p_action_date           => SYSDATE
5294           , p_change_description    => NULL
5295           , p_user_id               => l_fnd_user_id
5296           , p_api_caller            => p_api_caller
5297           , x_change_action_id      => l_action_id
5298           );
5299 
5300           IF g_debug_flag THEN
5301              Write_Debug('After: saving action log: ' || l_return_status);
5302              Write_Debug('l_action_id       : ' || l_action_id );
5303           END IF;
5304 
5305 
5306           IF ( l_return_status <>  FND_API.G_RET_STS_SUCCESS )
5307           THEN
5308             x_return_status := l_return_status;
5309             x_msg_count := l_msg_count;
5310             x_msg_data := l_msg_data;
5311             --#FND_MESSAGE.Set_Name('ENG','ENG_ERROR_CALLING_PS_API');
5312             --#FND_MESSAGE.Set_Token('OBJECT_NAME', 'ENG_CHANGE_ACTIONS_UTIL.Create_Change_Action');
5313             --#FND_MSG_PUB.Add;
5314             RAISE FND_API.G_EXC_ERROR;
5315           END IF;
5316           IF g_debug_flag THEN
5317              Write_Debug('Successful: saving action log');
5318           END IF;
5319         ELSE -- otherwise generate and return error message to UI
5320           x_return_status := l_return_status;
5321           x_msg_count := l_msg_count;
5322           x_msg_data := l_msg_data;
5323           FND_MESSAGE.Set_Name('ENG','ENG_ERROR_CONCURRENT_PRGM');
5324           FND_MESSAGE.Set_Token('OBJECT_NAME', 'ENG_ECO_UTIL.Implement_ECO');
5325           FND_MSG_PUB.Add;
5326           RAISE FND_API.G_EXC_ERROR;
5327         END IF;
5328       END IF;
5329 
5330       IF (l_flag_imp_failed = 'N') THEN
5331         -- Concurrent program has been set successfully, Set the flag
5332         -- for later code NOT to call PROMOTE_HEADER procedure in order to
5333         -- prevent an infinite loop
5334         l_imp_eco_flag := 'Y';
5335         IF g_debug_flag THEN
5336           Write_Debug('Successful: calling ENG_ECO_UTIL.Implement_ECO');
5337           Write_Debug('l_request_id       : ' || l_request_id );
5338         END IF;
5339 
5340         -- Update change header status_type
5341         UPDATE eng_engineering_changes
5342           SET status_type = G_ENG_IMP_IN_PROGRESS,
5343               last_update_date = sysdate,
5344               last_updated_by = l_fnd_user_id,
5345               last_update_login = l_fnd_login_id
5346           WHERE change_id = p_change_id;
5347 
5348         -- Log action for implementation_in_progress
5349         IF g_debug_flag THEN
5350           Write_Debug('Before: saving action log');
5351         END IF;
5352         l_action_id := 0;
5353         -- create new action log
5354         ENG_CHANGE_ACTIONS_UTIL.Create_Change_Action
5355         ( p_api_version           => 1.0
5356         , p_init_msg_list         => FND_API.G_FALSE        --
5357         , p_commit                => FND_API.G_FALSE        --
5358         , p_validation_level      => FND_API.G_VALID_LEVEL_FULL
5359         , p_debug                 => p_debug --FND_API.G_FALSE
5360         , p_output_dir            => p_output_dir
5361         , p_debug_filename        => NULL
5362         , x_return_status         => l_return_status
5363         , x_msg_count             => l_msg_count
5364         , x_msg_data              => l_msg_data
5365         , p_action_type           => ENG_CHANGE_ACTIONS_UTIL.G_ACT_IMP_IN_PROGRESS
5366         , p_object_name           => G_ENG_CHANGE
5367         , p_object_id1            => p_change_id
5368         , p_object_id2            => NULL
5369         , p_object_id3            => NULL
5370         , p_object_id4            => NULL
5371         , p_object_id5            => NULL
5372         , p_parent_action_id      => -1
5373         , p_status_code           => NULL
5374         , p_action_date           => SYSDATE
5375         , p_change_description    => p_comment
5376         , p_user_id               => l_fnd_user_id
5377         , p_api_caller            => p_api_caller
5378         , x_change_action_id      => l_action_id
5379         );
5380 
5381         IF g_debug_flag THEN
5382            Write_Debug('After: saving action log: ' || l_return_status );
5383            Write_Debug('l_action_id       : ' || l_action_id );
5384         END IF;
5385 
5386         IF ( l_return_status <>  FND_API.G_RET_STS_SUCCESS )
5387         THEN
5388           x_return_status := l_return_status;
5389           x_msg_count := l_msg_count;
5390           x_msg_data := l_msg_data;
5391           --#FND_MESSAGE.Set_Name('ENG','ENG_ERROR_CALLING_PS_API');
5392           --#FND_MESSAGE.Set_Token('OBJECT_NAME', 'ENG_CHANGE_ACTIONS_UTIL.Create_Change_Action');
5393           --#FND_MSG_PUB.Add;
5394           RAISE FND_API.G_EXC_ERROR;
5395         END IF;
5396         IF g_debug_flag THEN
5397            Write_Debug('Successful: saving action log');
5398         END IF;
5399 
5400       END IF; -- if (l_flag_imp_failed)
5401 
5402       IF g_debug_flag THEN
5403         Write_Debug('End block: case (special) last implement phase of ECO');
5404       END IF;
5405 
5406     -- Case 1: no workflow associated with the current phase
5407     --         or the workflow is successfully approved
5408     ELSIF (   (   (p_api_caller IS NULL OR p_api_caller <> 'CP')
5409                AND p_route_status IS NULL )
5410            OR l_chg_appr_status = G_ENG_APPR_APPROVED )
5411     THEN
5412       IF g_debug_flag THEN
5413         Write_Debug('Case 1: no workflow or workflow is approved');
5414       END IF;
5415 
5416       -- Update the current phase's workflow status
5417       UPDATE eng_lifecycle_statuses
5418         SET workflow_status = p_route_status,
5419             last_update_date = sysdate,
5420             last_updated_by = l_fnd_user_id,
5421             last_update_login = l_fnd_login_id
5422         WHERE entity_name = G_ENG_CHANGE
5423           AND entity_id1 = p_change_id
5424           AND status_code = l_curr_status_code
5425           AND active_flag = 'Y'
5426           AND rownum = 1;
5427       IF g_debug_flag THEN
5428         Write_Debug('After updating eng_lifecycle_statuses.workflow_status.');
5429         Write_Debug('  Row count = ' || SQL%ROWCOUNT);
5430       END IF;
5431 
5432       -- IF the current phase is the last one, also update its completion date
5433       -- Otherwise leave it for promote_header and demote_header procedures
5434       -- to set the completion_date
5435       IF (l_curr_phase_sn = l_max_phase_sn) THEN
5436         UPDATE eng_lifecycle_statuses
5437           SET completion_date = sysdate,
5438               last_update_date = sysdate,
5439               last_updated_by = l_fnd_user_id,
5440               last_update_login = l_fnd_login_id
5441           WHERE entity_name = G_ENG_CHANGE
5442             AND entity_id1 = p_change_id
5443             AND status_code = l_curr_status_code
5444             AND active_flag = 'Y'
5445             AND rownum = 1;
5446 
5447       	   -- Bug 5989058.
5448  	         -- Set the implementation date if the status is completed or implemented
5449  	         DECLARE
5450  	                 l_next_status_type eng_change_statuses.status_type%TYPE;
5451  	         BEGIN
5452 
5453  	                 SELECT status_type INTO l_next_status_type FROM eng_change_statuses WHERE status_code = l_curr_status_code;
5454 
5455  	                 if( l_next_status_type = G_ENG_COMPLETED OR
5456  	                         l_next_status_type = G_ENG_IMPLEMENTED  ) THEN
5457  	                                 UPDATE eng_engineering_changes SET
5458  	                                                         completion_date = SYSDATE
5459  	                                                         WHERE change_id = p_change_id;
5460  	                 END IF;
5461  	         EXCEPTION
5462  	                 WHEN OTHERS THEN
5463  	                         NULL;
5464  	         END;
5465 
5466         IF g_debug_flag THEN
5467           Write_Debug('After updating eng_lifecycle_statuses.completion_date.');
5468           Write_Debug('  Row count = ' || SQL%ROWCOUNT);
5469         END IF;
5470       END IF;
5471 
5472       IF g_debug_flag THEN
5473         Write_Debug('Current phase row updated');
5474       END IF;
5475 
5476       -- Force commit to prevent stucking on a phase in case of auto-promotion
5477       -- or auto-demotion failure triggered by workflow background engine
5478       IF (p_api_caller = 'WF' AND l_chg_appr_status = G_ENG_APPR_APPROVED)
5479       THEN
5480         IF FND_API.To_Boolean ( p_commit ) THEN -- fix by 14018580, in PIP session, using XA Datsource and hard commits will cause this subordination session error.
5481           COMMIT WORK;
5482         END IF;
5483       END IF;
5484 
5485 
5486       -- Update header and NIR approval status if needed
5487 
5488       -- Check if the change category is NIR, phase is on last implement phase
5489       -- and header approval status has not been set to APPROVED
5490       SELECT approval_status_type
5491         INTO l_curr_appr_status
5492         FROM eng_engineering_changes
5493         where change_id = p_change_id;
5494 
5495       IF ( l_base_cm_type_code = G_ENG_NEW_ITEM_REQ
5496            AND l_curr_phase_sn = l_max_phase_sn
5497            AND l_curr_appr_status <> G_ENG_APPR_APPROVED
5498            )
5499       THEN
5500         l_nir_update_flag := 'Y';
5501         l_chg_appr_status := G_ENG_APPR_APPROVED;
5502         IF g_debug_flag THEN
5503           Write_Debug('Current phase is last phase of NIR, and force setting of header approval status is needed');
5504         END IF;
5505       END IF;
5506 
5507 
5508       -- Check if the current phase is of type REVIEW/APPROVAL,
5509       -- and if it is the last such phase in the lifecycle of the change header
5510       --
5511       IF (    (l_curr_status_type = G_ENG_APPROVED OR l_nir_update_flag = 'Y')
5512            AND l_chg_appr_status IS NOT NULL
5513           )
5514       THEN
5515         IF g_debug_flag THEN
5516           Write_Debug('Current phase is of type APPROVAL, or last NIR phase needs to force header approval status to APPROVED');
5517         END IF;
5518 
5519         -- Get the sequence number of the last phase of type REVIEW/APPROVAL
5520         SELECT max(lcs.sequence_number)
5521           INTO l_max_appr_phase_sn
5522           FROM eng_lifecycle_statuses lcs,
5523                eng_change_statuses chs
5524           WHERE lcs.entity_name = G_ENG_CHANGE
5525             AND lcs.entity_id1 = p_change_id
5526             AND lcs.active_flag = 'Y'
5527             AND chs.status_code = lcs.status_code
5528             AND chs.status_type = G_ENG_APPROVED;
5529 
5530 
5531         IF g_debug_flag THEN
5532           Write_Debug('Check if the current phase is the last phase of type APPROVAL');
5533         END IF;
5534 
5535 
5536         -- Check if the current phase is the last phase of type REVIEW/APPROVAL
5537         -- Update header approval status if so
5538         IF ( l_curr_phase_sn = l_max_appr_phase_sn
5539              OR (p_api_caller IS NULL)
5540              OR l_nir_update_flag = 'Y'
5541              )
5542         THEN
5543           IF g_debug_flag THEN
5544             Write_Debug('Current phase is the last of such type');
5545           END IF;
5546 
5547           IF g_debug_flag THEN
5548             Write_Debug('Before: calling Update_Header_Appr_Status');
5549           END IF;
5550 
5551 
5552           -- Update change header approval status
5553           -- Launch header approval status change workflow
5554           Update_Header_Appr_Status
5555           (
5556             p_api_version               =>  1.0
5557            ,p_init_msg_list             =>  FND_API.G_FALSE
5558            ,p_commit                    =>  FND_API.G_FALSE
5559            ,p_validation_level          =>  FND_API.G_VALID_LEVEL_FULL
5560            ,p_debug                     =>  FND_API.G_FALSE
5561            ,p_output_dir                =>  p_output_dir
5562            ,p_debug_filename            =>  p_debug_filename
5563            ,x_return_status             =>  l_return_status
5564            ,x_msg_count                 =>  l_msg_count
5565            ,x_msg_data                  =>  l_msg_data
5566            ,p_change_id                 =>  p_change_id
5567            ,p_status_code               =>  l_curr_status_code
5568            ,p_appr_status               =>  l_chg_appr_status
5569            ,p_route_status              =>  p_route_status
5570            ,p_api_caller                =>  p_api_caller
5571            ,p_bypass                    =>  l_nir_update_flag
5572           );
5573 
5574 
5575           IF g_debug_flag THEN
5576             Write_Debug('After: Update_Header_Appr_Status: ' || l_return_status );
5577           END IF;
5578 
5579 
5580           IF ( l_return_status <>  FND_API.G_RET_STS_SUCCESS )
5581           THEN
5582             x_return_status := l_return_status;
5583             x_msg_count := l_msg_count;
5584             x_msg_data := l_msg_data;
5585             RAISE FND_API.G_EXC_ERROR;
5586           END IF;
5587           IF g_debug_flag THEN
5588             Write_Debug('After: calling Update_Header_Appr_Status');
5589           END IF;
5590 
5591         END IF;
5592       END IF;
5593        IF ( l_base_cm_type_code = G_ENG_NEW_ITEM_REQ
5594            AND l_curr_phase_sn = l_max_phase_sn) then
5595 	ENG_NIR_UTIL_PKG.set_nir_item_approval_status
5596           ( p_change_id          => p_change_id
5597            ,p_approval_status    => G_ENG_APPR_APPROVED
5598            ,x_return_status      => l_return_status
5599            ,x_msg_count          => l_msg_count
5600            ,x_msg_data           => l_msg_data
5601            );
5602 	END IF;
5603 
5604       -- Check if the current phase is the last of type IMPLEMENT (COMPLETE)
5605       -- Note that this code block is only used by non CO header types
5606       IF ( l_curr_status_type = G_ENG_IMPLEMENTED AND l_curr_phase_sn = l_max_phase_sn )
5607       THEN
5608         IF g_debug_flag THEN
5609           Write_Debug('Current phase is the last of type IMPLEMENTED');
5610         END IF;
5611         -- If there are still active lines, raise error message
5612         OPEN c_lines;
5613           LOOP
5614             FETCH c_lines INTO l_line_status_type;
5615             EXIT WHEN c_lines%NOTFOUND;
5616             IF ( l_line_status_type <> G_ENG_COMPLETED
5617                  AND l_line_status_type <> G_ENG_IMPLEMENTED
5618                  AND l_line_status_type <> G_ENG_CANCELLED
5619                     --   R12.C Enhancement : Added following condition because NIRs can have different line statuses
5620                  AND l_base_cm_type_code <> G_ENG_NEW_ITEM_REQ) THEN
5621               -- Stop and return error message
5622               IF g_debug_flag THEN
5623                 Write_Debug('Branch: Exists non completed/implemented/cancelled lines');
5624               END IF;
5625               FND_MESSAGE.Set_Name('ENG','ENG_EXIST_ACTIVE_LINES');
5626               FND_MSG_PUB.Add;
5627               RAISE FND_API.G_EXC_ERROR;
5628             END IF;
5629           END LOOP;
5630         CLOSE c_lines;
5631 
5632         IF g_debug_flag THEN
5633           Write_Debug('Finished checking open lines');
5634         END IF;
5635 
5636         -- If we can reach this line, it means there are no active lines
5637         -- Get the cm type for the change header
5638         SELECT eec.change_mgmt_type_code, eec.change_notice, eec.organization_id,
5639                ecot.base_change_mgmt_type_code
5640           INTO l_cm_type_code, l_chg_notice, l_org_id,
5641                l_base_cm_type_code
5642           FROM eng_engineering_changes eec,
5643                eng_change_order_types ecot
5644           WHERE eec.change_id = p_change_id
5645             AND ecot.change_order_type_id = eec.change_order_type_id;
5646 
5647         -- Complete attachment approval if needed
5648         IF g_debug_flag THEN
5649           Write_Debug('Before: calling DM attachment approval API');
5650         END IF;
5651         IF (   l_base_cm_type_code = G_ENG_ATTACHMENT_APPR
5652             OR l_base_cm_type_code = G_ENG_ATTACHMENT_REVW )
5653         THEN
5654 
5655           IF g_debug_flag THEN
5656             Write_Debug('In: calling DM attachment approval/review API');
5657             Write_Debug('p_workflow_status : ' || p_status_code );
5658             Write_Debug('p_approval_status : ' || l_chg_appr_status );
5659           END IF;
5660 
5661           ENG_ATTACHMENT_IMPLEMENTATION.Update_Attachment_Status
5662           (
5663             p_api_version         => 1.0
5664            ,p_init_msg_list       => FND_API.G_FALSE
5665            ,p_commit              => FND_API.G_FALSE
5666            ,p_validation_level    => p_validation_level
5667            ,p_debug               => p_debug --FND_API.G_FALSE
5668            ,p_output_dir          => p_output_dir
5669            ,p_debug_filename      => NULL --p_debug_filename
5670            ,x_return_status       => l_return_status
5671            ,x_msg_count           => l_msg_count
5672            ,x_msg_data            => l_msg_data
5673            ,p_change_id           => p_change_id
5674            ,p_workflow_status     => p_status_code
5675            ,p_approval_status     => G_ENG_APPR_APPROVED --l_chg_appr_status
5676            ,p_api_caller          => p_api_caller
5677           );
5678 
5679           IF g_debug_flag THEN
5680             Write_Debug('After: ENG_ATTACHMENT_IMPLEMENTATION.Update_Attachment_Status: ' || l_return_status );
5681           END IF;
5682 
5683 
5684 
5685 
5686           IF ( l_return_status <>  FND_API.G_RET_STS_SUCCESS ) THEN
5687             x_return_status := l_return_status;
5688             x_msg_count := l_msg_count;
5689             x_msg_data := l_msg_data;
5690             --#FND_MESSAGE.Set_Name('ENG','ENG_ERROR_CALLING_PS_API');
5691             --#FND_MESSAGE.Set_Token('OBJECT_NAME', 'ENG_ATTACHMENT_IMPLEMENTATION.Update_Attachment_Status');
5692             --#FND_MSG_PUB.Add;
5693             RAISE FND_API.G_EXC_ERROR;
5694           END IF;
5695         END IF;
5696         IF g_debug_flag THEN
5697           Write_Debug('After: calling DM attachment approval/review API');
5698         END IF;
5699 
5700         -- moved impECO block to Update_Lifecycle_States procedure
5701       END IF;  -- current phase is the last of type IMPLEMENT?
5702 
5703 
5704       IF g_debug_flag THEN
5705         Write_Debug('Finished checking all conditions prior to promotion, ready to promote if needed');
5706       END IF;
5707       -- Finished checking all the conditions for promotion, ready to promote (if needed)
5708       -- Find the promotion phase in the order of the following priority
5709       -- 1. promote_status_code in the change header (saved by promote action)
5710       SELECT promote_status_code
5711         INTO l_next_status_code
5712         FROM eng_engineering_changes
5713         WHERE change_id = p_change_id;
5714 
5715       -- 2. auto_promote_status in the lifecycle table
5716       IF ( l_next_status_code IS NULL ) THEN
5717         IF g_debug_flag THEN
5718           Write_Debug('promote_status_code is NULL');
5719         END IF;
5720         SELECT auto_promote_status
5721           INTO l_next_status_code
5722           FROM eng_lifecycle_statuses
5723           WHERE entity_name = G_ENG_CHANGE
5724             AND entity_id1 = p_change_id
5725             AND status_code = l_curr_status_code
5726             AND active_flag = 'Y'
5727             AND rownum = 1;
5728       END IF;
5729 
5730       IF ( l_next_status_code IS NOT NULL AND l_imp_eco_flag = 'N' )
5731       THEN
5732         IF g_debug_flag THEN
5733           Write_Debug('l_next_status_code IS NOT NULL AND l_imp_eco_flag = N, call PROMOTE_HEADER');
5734         END IF;
5735 
5736         -- determine API caller
5737         IF (p_api_caller = 'WF' OR p_api_caller = 'CP') THEN
5738           l_api_caller := p_api_caller;
5739         ELSE
5740           l_api_caller := NULL;
5741         END IF;
5742 
5743         Promote_Header
5744         (
5745           p_api_version        => 1.0
5746          ,p_init_msg_list      => FND_API.G_FALSE
5747          ,p_commit             => FND_API.G_FALSE
5748          ,p_validation_level   => p_validation_level
5749          ,p_debug              => FND_API.G_FALSE
5750          ,p_output_dir         => p_output_dir
5751          ,p_debug_filename     => p_debug_filename
5752          ,x_return_status      => l_return_status
5753          ,x_msg_count          => l_msg_count
5754          ,x_msg_data           => l_msg_data
5755          ,p_change_id          => p_change_id
5756          ,p_status_code        => l_next_status_code
5757          ,p_api_caller         => l_api_caller
5758         );
5759 
5760         IF g_debug_flag THEN
5761           Write_Debug('After: Promote_Header: ' || l_return_status );
5762         END IF;
5763 
5764 
5765         IF ( l_return_status <>  FND_API.G_RET_STS_SUCCESS ) THEN
5766           x_return_status := l_return_status;
5767           x_msg_count := l_msg_count;
5768           x_msg_data := l_msg_data;
5769           --#FND_MESSAGE.Set_Name('ENG','ENG_ERROR_CALLING_PS_API');
5770           --#FND_MESSAGE.Set_Token('OBJECT_NAME', 'Promote_Header');
5771           --#FND_MSG_PUB.Add;
5772           RAISE FND_API.G_EXC_ERROR;
5773         END IF;
5774 
5775         IF g_debug_flag THEN
5776           Write_Debug('After: calling PROMOTE_HEADER');
5777         END IF;
5778 
5779       ELSE
5780         -- No manual or auto promotion is set, do nothing
5781         NULL;
5782         IF g_debug_flag THEN
5783           Write_Debug('No manual or auto promotion is set, do nothing');
5784         END IF;
5785 
5786       END IF;
5787 
5788 
5789     -- Case 2: workflow is rejected
5790     ELSIF ( p_route_status = Eng_Workflow_Util.G_RT_REJECTED )
5791     THEN
5792       IF g_debug_flag THEN
5793         Write_Debug('Case 2: workflow is rejected');
5794       END IF;
5795 
5796       -- Update lifecycle table
5797       UPDATE eng_lifecycle_statuses
5798         SET workflow_status = p_route_status,
5799             last_update_date = sysdate,
5800             last_updated_by = l_fnd_user_id,
5801             last_update_login = l_fnd_login_id
5802         WHERE entity_name = G_ENG_CHANGE
5803           AND entity_id1 = p_change_id
5804           AND status_code = l_curr_status_code
5805           AND active_flag = 'Y'
5806           AND rownum = 1;
5807       IF g_debug_flag THEN
5808         Write_Debug('After updating eng_lifecycle_statuses.workflow_status.');
5809         Write_Debug('  Row count = ' || SQL%ROWCOUNT);
5810       END IF;
5811 
5812       IF g_debug_flag THEN
5813         Write_Debug('After updating current phase row');
5814       END IF;
5815 
5816       -- Get the auto demotion phase for the current phase of the change header
5817       SELECT auto_demote_status
5818         INTO l_next_status_code
5819         FROM eng_lifecycle_statuses
5820         WHERE entity_name = G_ENG_CHANGE
5821           AND entity_id1 = p_change_id
5822           AND status_code = l_curr_status_code
5823           AND active_flag = 'Y'
5824           AND rownum = 1;
5825 
5826       -- Reset promotion_status_code for the change header
5827       UPDATE eng_engineering_changes
5828         SET promote_status_code = NULL,
5829             last_update_date = sysdate,
5830             last_updated_by = l_fnd_user_id,
5831             last_update_login = l_fnd_login_id
5832         WHERE change_id = p_change_id;
5833       IF g_debug_flag THEN
5834         Write_Debug('After updating eng_engineering_changes.');
5835         Write_Debug('  Row count = ' || SQL%ROWCOUNT);
5836       END IF;
5837 
5838       IF g_debug_flag THEN
5839         Write_Debug('After getting AUTO_PROMOTE_STATUS in phase table and resetting PROMOTE_STATUS_CODE in change header table');
5840       END IF;
5841 
5842       -- update header approval status to "rejected" if the p_status_code passed
5843       -- by workflow is phase of type "approval"
5844 
5845       -- get phase type
5846       SELECT status_type
5847         INTO l_status_type
5848         FROM eng_change_statuses
5849         WHERE status_code = p_status_code;
5850       -- check if the phase type is APPROVAL
5851       IF ( l_status_type = G_ENG_APPROVED ) THEN
5852         IF g_debug_flag THEN
5853            Write_Debug('Phase type is APPROVAL');
5854         END IF;
5855 
5856         -- Update change header approval status
5857         -- Launch header approval status change workflow
5858         IF g_debug_flag THEN
5859            Write_Debug('Before: calling Update_Header_Appr_Status');
5860         END IF;
5861         Update_Header_Appr_Status
5862         (
5863           p_api_version               =>  1.0
5864          ,p_init_msg_list             =>  FND_API.G_FALSE
5865          ,p_commit                    =>  FND_API.G_FALSE
5866          ,p_validation_level          =>  FND_API.G_VALID_LEVEL_FULL
5867          ,p_debug                     =>  FND_API.G_FALSE
5868          ,p_output_dir                =>  p_output_dir
5869          ,p_debug_filename            =>  p_debug_filename
5870          ,x_return_status             =>  l_return_status
5871          ,x_msg_count                 =>  l_msg_count
5872          ,x_msg_data                  =>  l_msg_data
5873          ,p_change_id                 =>  p_change_id
5874          ,p_status_code               =>  p_status_code
5875          ,p_appr_status               =>  l_chg_appr_status
5876          ,p_route_status              =>  p_route_status
5877          ,p_api_caller                =>  p_api_caller
5878         );
5879 
5880         IF g_debug_flag THEN
5881           Write_Debug('After: calling Update_Header_Appr_Status: ' || l_return_status);
5882         END IF;
5883 
5884         IF ( l_return_status <>  FND_API.G_RET_STS_SUCCESS )
5885         THEN
5886           x_return_status := l_return_status;
5887           x_msg_count := l_msg_count;
5888           x_msg_data := l_msg_data;
5889           RAISE FND_API.G_EXC_ERROR;
5890         ELSE
5891           IF g_debug_flag THEN
5892             Write_Debug('Successful: calling Update_Header_Appr_Status');
5893           END IF;
5894         END IF;
5895 
5896       END IF; -- IF ( p_status_type = G_ENG_APPROVED )
5897 
5898       IF g_debug_flag THEN
5899         Write_Debug('Before if condition for calling DEMOTE_HEADER procedure');
5900       END IF;
5901       -- Call demotion procedure if necessary
5902       IF ( l_next_status_code IS NOT NULL ) THEN
5903         IF g_debug_flag THEN
5904           Write_Debug('l_next_status_code IS NOT NULL.');
5905           Write_Debug('Before: calling DEMOTE_HEADER procedure');
5906         END IF;
5907 
5908         -- determine API caller - 'UI' should be used only once
5909         IF (p_api_caller = 'WF' OR p_api_caller = 'CP') THEN
5910           l_api_caller := p_api_caller;
5911         ELSE
5912           l_api_caller := NULL;
5913         END IF;
5914 
5915         Demote_Header
5916         (
5917           p_api_version        => 1.0
5918          ,p_init_msg_list      => FND_API.G_FALSE
5919          ,p_commit             => FND_API.G_FALSE
5920          ,p_validation_level   => p_validation_level
5921          ,p_debug              => FND_API.G_FALSE
5922          ,p_output_dir         => p_output_dir
5923          ,p_debug_filename     => p_debug_filename
5924          ,x_return_status      => l_return_status
5925          ,x_msg_count          => l_msg_count
5926          ,x_msg_data           => l_msg_data
5927          ,p_change_id          => p_change_id
5928          ,p_status_code        => l_next_status_code
5929          ,p_api_caller         => l_api_caller
5930         );
5931         IF g_debug_flag THEN
5932           Write_Debug('After: calling DEMOTE_HEADER procedure: ' || l_return_status);
5933         END IF;
5934         IF ( l_return_status <>  FND_API.G_RET_STS_SUCCESS ) THEN
5935           x_return_status := l_return_status;
5936           x_msg_count := l_msg_count;
5937           x_msg_data := l_msg_data;
5938           --#FND_MESSAGE.Set_Name('ENG','ENG_ERROR_CALLING_PS_API');
5939           --#FND_MESSAGE.Set_Token('OBJECT_NAME', 'Demote_Header');
5940           --#FND_MSG_PUB.Add;
5941           RAISE FND_API.G_EXC_ERROR;
5942         END IF;
5943         IF g_debug_flag THEN
5944            Write_Debug('Successful: calling Demote_Header procedure');
5945         END IF;
5946 
5947       END IF;  -- if (next status_code is null)
5948 
5949 
5950     -- Case 3: workflow fails due to unexpected problems
5951     ELSIF (    p_route_status = Eng_Workflow_Util.G_RT_ABORTED
5952             OR p_route_status = Eng_Workflow_Util.G_RT_TIME_OUT
5953             OR p_route_status = Eng_Workflow_Util.G_RT_NOT_STARTED )
5954     THEN
5955       IF g_debug_flag THEN
5956         Write_Debug('Case 3: workflow ends with unexpected status');
5957       END IF;
5958 
5959       -- Update lifecycle table
5960       UPDATE eng_lifecycle_statuses
5961         SET workflow_status = p_route_status,
5962             last_update_date = sysdate,
5963             last_updated_by = l_fnd_user_id,
5964             last_update_login = l_fnd_login_id
5965         WHERE entity_name = G_ENG_CHANGE
5966           AND entity_id1 = p_change_id
5967           AND status_code = l_curr_status_code
5968           AND active_flag = 'Y'
5969           AND rownum = 1;
5970       IF g_debug_flag THEN
5971         Write_Debug('After updating eng_lifecycle_statuses.workflow_status.');
5972         Write_Debug('  Row count = ' || SQL%ROWCOUNT);
5973       END IF;
5974 
5975 
5976       IF g_debug_flag THEN
5977         Write_Debug('After updating the current phase');
5978       END IF;
5979 
5980       -- Reset promotion_status_code for the change header
5981       UPDATE eng_engineering_changes
5982         SET promote_status_code = NULL,
5983             last_update_date = sysdate,
5984             last_updated_by = l_fnd_user_id,
5985             last_update_login = l_fnd_login_id
5986         WHERE change_id = p_change_id;
5987       IF g_debug_flag THEN
5988         Write_Debug('After updating eng_lifecycle_statuses.promote_status_code.');
5989         Write_Debug('  Row count = ' || SQL%ROWCOUNT);
5990       END IF;
5991 
5992       IF g_debug_flag THEN
5993         Write_Debug('After resetting promote_status_code in change header table');
5994       END IF;
5995 
5996 
5997       -- Update change header approval status
5998       -- Launch header approval status change workflow
5999       Update_Header_Appr_Status
6000       (
6001         p_api_version               =>  1.0
6002        ,p_init_msg_list             =>  FND_API.G_FALSE
6003        ,p_commit                    =>  FND_API.G_FALSE
6004        ,p_validation_level          =>  FND_API.G_VALID_LEVEL_FULL
6005        ,p_debug                     =>  FND_API.G_FALSE
6006        ,p_output_dir                =>  p_output_dir
6007        ,p_debug_filename            =>  p_debug_filename
6008        ,x_return_status             =>  l_return_status
6009        ,x_msg_count                 =>  l_msg_count
6010        ,x_msg_data                  =>  l_msg_data
6011        ,p_change_id                 =>  p_change_id
6012        ,p_status_code               =>  p_status_code
6013        ,p_appr_status               =>  l_chg_appr_status
6014        ,p_route_status              =>  p_route_status
6015        ,p_api_caller                =>  p_api_caller
6016       );
6017 
6018       IF g_debug_flag THEN
6019          Write_Debug('After: calling Update_Header_Appr_Status: ' || l_return_status);
6020       END IF;
6021 
6022       IF ( l_return_status <>  FND_API.G_RET_STS_SUCCESS )
6023       THEN
6024         x_return_status := l_return_status;
6025         x_msg_count := l_msg_count;
6026         x_msg_data := l_msg_data;
6027         RAISE FND_API.G_EXC_ERROR;
6028       END IF;
6029       IF g_debug_flag THEN
6030         Write_Debug('After: calling Update_Header_Appr_Status');
6031       END IF;
6032 
6033     -- Case 4: workflow calls to update phase of p_status_code
6034     -- (may not be current header status_code in case of last ECO implement phase)
6035     -- to IN_PROGRESS
6036     ELSIF (p_route_status = Eng_Workflow_Util.G_RT_IN_PROGRESS) THEN
6037       -- sanity check: workflow must pass p_status_code for the workflow p_route_id
6038       IF (p_status_code IS NULL) THEN
6039         FND_MESSAGE.Set_Name('ENG','ENG_OBJECT_CANT_BE_NULL');
6040         FND_MESSAGE.Set_Token('OBJECT_NAME', 'p_status_code passed by workflow');
6041         FND_MSG_PUB.Add;
6042         RAISE FND_API.G_EXC_ERROR;
6043       END IF;
6044       -- update phase workflow status
6045       UPDATE eng_lifecycle_statuses
6046         SET workflow_status = p_route_status,
6047             last_update_date = sysdate,
6048             last_updated_by = l_fnd_user_id,
6049             last_update_login = l_fnd_login_id
6050         WHERE entity_name = G_ENG_CHANGE
6051           AND entity_id1 = p_change_id
6052           AND status_code = p_status_code
6053           AND active_flag = 'Y';
6054       IF g_debug_flag THEN
6055          Write_Debug('After updating eng_lifecycle_statuses.workflow_status.');
6056          Write_Debug('  Row count = ' || SQL%ROWCOUNT);
6057       END IF;
6058 
6059       -- update header approval status to "submitted" if the p_status_code passed
6060       -- by workflow is phase of type "approval"
6061 
6062       -- get phase type
6063       SELECT status_type
6064         INTO l_status_type
6065         FROM eng_change_statuses
6066         WHERE status_code = p_status_code;
6067       -- check if the phase type is APPROVAL
6068       IF ( l_status_type = G_ENG_APPROVED ) THEN
6069         IF g_debug_flag THEN
6070            Write_Debug('Phase type is APPROVAL');
6071         END IF;
6072 
6073         -- Update change header approval status
6074         -- Launch header approval status change workflow
6075         IF g_debug_flag THEN
6076            Write_Debug('Before: calling Update_Header_Appr_Status');
6077         END IF;
6078         Update_Header_Appr_Status
6079         (
6080           p_api_version               =>  1.0
6081          ,p_init_msg_list             =>  FND_API.G_FALSE
6082          ,p_commit                    =>  FND_API.G_FALSE
6083          ,p_validation_level          =>  FND_API.G_VALID_LEVEL_FULL
6084          ,p_debug                     =>  FND_API.G_FALSE
6085          ,p_output_dir                =>  p_output_dir
6086          ,p_debug_filename            =>  p_debug_filename
6087          ,x_return_status             =>  l_return_status
6088          ,x_msg_count                 =>  l_msg_count
6089          ,x_msg_data                  =>  l_msg_data
6090          ,p_change_id                 =>  p_change_id
6091          ,p_status_code               =>  p_status_code
6092          ,p_appr_status               =>  G_ENG_APPR_REQUESTED
6093          ,p_route_status              =>  p_route_status
6094          ,p_api_caller                =>  p_api_caller
6095         );
6096 
6097         IF g_debug_flag THEN
6098           Write_Debug('After: calling Update_Header_Appr_Status: ' || l_return_status);
6099         END IF;
6100 
6101 
6102         IF ( l_return_status <>  FND_API.G_RET_STS_SUCCESS )
6103         THEN
6104           x_return_status := l_return_status;
6105           x_msg_count := l_msg_count;
6106           x_msg_data := l_msg_data;
6107           RAISE FND_API.G_EXC_ERROR;
6108         ELSE
6109           IF g_debug_flag THEN
6110             Write_Debug('Successful: calling Update_Header_Appr_Status');
6111           END IF;
6112         END IF;
6113 
6114       END IF; -- IF ( p_status_type = G_ENG_APPROVED )
6115 
6116     -- Case 6: concurrent program for implementation failure
6117     ELSIF ( p_api_caller = 'CP' AND p_status_code = G_ENG_IMP_FAILED )
6118     THEN
6119       IF g_debug_flag THEN
6120         Write_Debug('Case 6: Concurrent Program Failure');
6121       END IF;
6122 
6123       -- Log implementation failure message
6124       UPDATE eng_engineering_changes
6125         SET status_type = G_ENG_IMP_FAILED,
6126             promote_status_code = NULL,
6127             last_update_date = sysdate,
6128             last_updated_by = l_fnd_user_id,
6129             last_update_login = l_fnd_login_id
6130         WHERE change_id = p_change_id;
6131 
6132       IF g_debug_flag THEN
6133          Write_Debug('Before: saving action log');
6134       END IF;
6135       l_action_id := 0;
6136       -- create new action log
6137       ENG_CHANGE_ACTIONS_UTIL.Create_Change_Action
6138       ( p_api_version           => 1.0
6139       , p_init_msg_list         => FND_API.G_FALSE        --
6140       , p_commit                => FND_API.G_FALSE        --
6141       , p_validation_level      => FND_API.G_VALID_LEVEL_FULL
6142       , p_debug                 => p_debug --FND_API.G_FALSE
6143       , p_output_dir            => p_output_dir
6144       , p_debug_filename        => NULL
6145       , x_return_status         => l_return_status
6146       , x_msg_count             => l_msg_count
6147       , x_msg_data              => l_msg_data
6148       , p_action_type           => ENG_CHANGE_ACTIONS_UTIL.G_ACT_IMP_FAILED
6149       , p_object_name           => G_ENG_CHANGE
6150       , p_object_id1            => p_change_id
6151       , p_object_id2            => NULL
6152       , p_object_id3            => NULL
6153       , p_object_id4            => NULL
6154       , p_object_id5            => NULL
6155       , p_parent_action_id      => -1
6156       , p_status_code           => NULL
6157       , p_action_date           => SYSDATE
6158       , p_change_description    => NULL
6159       , p_user_id               => l_fnd_user_id
6160       , p_api_caller            => p_api_caller
6161       , x_change_action_id      => l_action_id
6162       );
6163 
6164       IF g_debug_flag THEN
6165          Write_Debug('After: saving action log: ' || l_return_status);
6166          Write_Debug('l_action_id       : ' || l_action_id );
6167       END IF;
6168       IF ( l_return_status <>  FND_API.G_RET_STS_SUCCESS )
6169       THEN
6170         x_return_status := l_return_status;
6171         x_msg_count := l_msg_count;
6172         x_msg_data := l_msg_data;
6173         --#FND_MESSAGE.Set_Name('ENG','ENG_ERROR_CALLING_PS_API');
6174         --#FND_MESSAGE.Set_Token('OBJECT_NAME', 'ENG_CHANGE_ACTIONS_UTIL.Create_Change_Action');
6175         --#FND_MSG_PUB.Add;
6176         RAISE FND_API.G_EXC_ERROR;
6177       END IF;
6178       IF g_debug_flag THEN
6179          Write_Debug('Successful: saving action log');
6180       END IF;
6181 
6182       -- Commit anyway to make sure implementation failure action message is logged
6183       -- Note that since this branch is not invoked by workflow, no addtional check
6184       -- on p_api_caller = WF is needed, and commit is allowed
6185       IF FND_API.To_Boolean ( p_commit ) THEN -- fix by 14018580, in PIP session, using XA Datsource and hard commits will cause this subordination session error.
6186           COMMIT WORK;
6187       END IF;
6188 
6189       -- Check whether the header category is CO and it's on last implement phase
6190       Is_CO_On_Last_Imp_Phase
6191       (
6192         p_change_id                 => p_change_id
6193        ,p_api_caller                => p_api_caller
6194        ,x_is_co_last_phase          => l_is_co_last_phase
6195        ,x_auto_demote_status        => l_auto_demote_status
6196       );
6197       IF g_debug_flag THEN
6198         Write_Debug('After: calling procedure Is_CO_On_Last_Imp_Phase.');
6199         Write_Debug('  l_is_co_last_phase =   ' || l_is_co_last_phase);
6200         Write_Debug('  l_auto_demote_status = ' || l_auto_demote_status);
6201         Write_Debug('  l_last_status_code =   ' || l_last_status_code);
6202         Write_Debug('  l_auto_demote_status = ' || l_auto_demote_status);
6203       END IF;
6204 
6205 
6206       -- If header is CO and is on last phase,
6207       -- set header phase to last phase before demotion
6208 
6209       -- If auto demotion phase is defined, set demotion status
6210       -- If auto demotion phase is not defined, demote to the previous phase
6211       IF ( l_auto_demote_status IS NOT NULL) THEN
6212         l_next_status_code := l_auto_demote_status;
6213 
6214         -- must set header phase to last implement phase before demotion
6215         -- just to make the CO implement phase demotion as a normal demotion
6216         UPDATE eng_engineering_changes
6217           SET status_type = G_ENG_IMPLEMENTED,
6218               status_code = l_last_status_code,
6219               last_update_date = sysdate,
6220               last_updated_by = l_fnd_user_id,
6221               last_update_login = l_fnd_login_id
6222           WHERE change_id = p_change_id;
6223         l_curr_status_code := l_last_status_code;
6224 
6225         -- demote
6226         IF g_debug_flag THEN
6227            Write_Debug('Demoting header is needed ');
6228            Write_Debug('Before: calling Demote_Header procedure');
6229         END IF;
6230 
6231         Demote_Header
6232         ( p_api_version        => 1.0
6233          ,p_init_msg_list      => FND_API.G_FALSE
6234          ,p_commit             => FND_API.G_FALSE
6235          ,p_validation_level   => p_validation_level
6236          ,p_debug              => FND_API.G_FALSE
6237          ,p_output_dir         => p_output_dir
6238          ,p_debug_filename     => p_debug_filename
6239          ,x_return_status      => l_return_status
6240          ,x_msg_count          => l_msg_count
6241          ,x_msg_data           => l_msg_data
6242          ,p_change_id          => p_change_id
6243          ,p_status_code        => l_auto_demote_status
6244          ,p_api_caller         => p_api_caller
6245         );
6246         IF g_debug_flag THEN
6247            Write_Debug('After: calling Demote_Header procedure: ' || l_return_status);
6248         END IF;
6249         IF ( l_return_status <>  FND_API.G_RET_STS_SUCCESS ) THEN
6250           x_return_status := l_return_status;
6251           x_msg_count := l_msg_count;
6252           x_msg_data := l_msg_data;
6253           --#FND_MESSAGE.Set_Name('ENG','ENG_ERROR_CALLING_PS_API');
6254           --#FND_MESSAGE.Set_Token('OBJECT_NAME', 'Demote_Header');
6255           --#FND_MSG_PUB.Add;
6256           RAISE FND_API.G_EXC_ERROR;
6257         END IF;
6258         IF g_debug_flag THEN
6259           Write_Debug('Successful: calling DEMOTE_HEADER procedure ');
6260         END IF;
6261 
6262       ELSE -- no auto demotion for implement phase, set to previous phase
6263 
6264         NULL;
6265         /*
6266         UPDATE eng_engineering_changes
6267           SET status_type = p_status_code, --G_ENG_IMP_FAILED
6268               promote_status_code = NULL,
6269               last_update_date = sysdate,
6270               last_updated_by = l_fnd_user_id,
6271               last_update_login = l_fnd_login_id
6272           WHERE change_id = p_change_id;
6273         l_curr_status_code := l_last_status_code;
6274 
6275         -- no demotion, but refresh the implement phase workflow route if needed
6276         IF g_debug_flag THEN
6277           Write_Debug('Before: calling Refresh_WF_Route procedure ');
6278         END IF;
6279         Refresh_WF_Route
6280         ( p_api_version         => 1.0
6281          ,p_init_msg_list       => FND_API.G_FALSE
6282          ,p_commit              => FND_API.G_FALSE        --
6283          ,p_validation_level    => p_validation_level
6284          ,p_debug               => FND_API.G_FALSE
6285          ,p_output_dir          => p_output_dir
6286          ,p_debug_filename      => p_debug_filename
6287          ,x_return_status       => l_return_status
6288          ,x_msg_count           => l_msg_count
6289          ,x_msg_data            => l_msg_data
6290          ,p_change_id           => p_change_id
6291          ,p_status_code         => l_last_status_code
6292          ,p_wf_route_id         => NULL
6293          ,p_api_caller          => p_api_caller
6294          );
6295         IF g_debug_flag THEN
6296           Write_Debug('After: calling Refresh_WF_Route procedure: ' || l_return_status);
6297         END IF;
6298         */
6299 
6300       END IF;
6301 
6302     ELSE
6303       NULL; -- IMPOSSIBLE TO REACH THIS BLOCK, THEORETICALLY SPEAKING
6304       IF g_debug_flag THEN
6305         Write_Debug('Case x: this branch should never be reached! ') ;
6306       END IF;
6307     END IF;
6308      IF (      (p_api_caller IS NULL OR p_api_caller <> 'CP')
6309                AND p_route_status IS NOT NULL
6310                AND l_curr_status_type =12)
6311      THEN
6312           ENG_DOCUMENT_UTIL.Update_Approval_Status
6313             ( p_api_version         => 1.0
6314              ,p_init_msg_list       => FND_API.G_FALSE
6315              ,p_commit              => FND_API.G_FALSE
6316              ,p_validation_level    => p_validation_level
6317              ,p_debug               => FND_API.G_FALSE
6318              ,p_output_dir          => p_output_dir
6319              ,p_debug_filename      => p_debug_filename
6320              ,x_return_status       => l_return_status     --
6321              ,x_msg_count           => l_msg_count         --
6322              ,x_msg_data            => l_msg_data          --
6323              ,p_change_id           => p_change_id         -- header's change_id
6324              ,p_approval_status     => l_chg_appr_status       -- header approval status
6325              ,p_wf_route_status     => p_route_status      -- workflow routing status (for document types)
6326              ,p_api_caller          => p_api_caller        -- Optionnal for future use
6327             );
6328 
6329 elsif ( l_curr_status_type = 12 AND  p_route_status IS null)
6330     then
6331 
6332 
6333         ENG_DOCUMENT_UTIL.Update_Approval_Status
6334             ( p_api_version         => 1.0
6335              ,p_init_msg_list       => FND_API.G_FALSE
6336              ,p_commit              => FND_API.G_FALSE
6337              ,p_validation_level    => p_validation_level
6338              ,p_debug               => FND_API.G_FALSE
6339              ,p_output_dir          => p_output_dir
6340              ,p_debug_filename      => p_debug_filename
6341              ,x_return_status       => l_return_status     --
6342              ,x_msg_count           => l_msg_count         --
6343              ,x_msg_data            => l_msg_data          --
6344              ,p_change_id           => p_change_id         -- header's change_id
6345              ,p_approval_status     => l_chg_appr_status       -- header approval status
6346              ,p_wf_route_status     => p_route_status      -- workflow routing status (for document types)
6347              ,p_api_caller          => p_api_caller        -- Optionnal for future use
6348             );
6349   END IF;
6350        -- Standard ending code ------------------------------------------------
6351     IF FND_API.To_Boolean ( p_commit ) THEN
6352       COMMIT WORK;
6353     END IF;
6354 
6355     FND_MSG_PUB.Count_And_Get
6356     ( p_count        =>      x_msg_count,
6357       p_data         =>      x_msg_data );
6358 
6359     IF g_debug_flag THEN
6360       Write_Debug('Finish. End Of procedure: Update_Lifecycle_States');
6361     END IF;
6362 
6363     IF FND_API.to_Boolean( p_debug ) THEN
6364       Close_Debug_Session;
6365     END IF;
6366 
6367   EXCEPTION
6368     WHEN FND_API.G_EXC_ERROR THEN
6369       --ROLLBACK TO Update_Lifecycle_States;
6370       x_return_status := FND_API.G_RET_STS_ERROR;
6371       FND_MSG_PUB.Count_And_Get
6372       ( p_count        =>      x_msg_count
6373        ,p_data         =>      x_msg_data );
6374       IF g_debug_flag THEN
6375         Write_Debug('Rollback and Finish with expected error.') ;
6376       END IF;
6377       IF FND_API.to_Boolean( p_debug ) THEN
6378         Close_Debug_Session;
6379       END IF;
6380     WHEN FND_API.G_EXC_UNEXPECTED_ERROR THEN
6381       --ROLLBACK TO Update_Lifecycle_States;
6382       x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
6383       FND_MSG_PUB.Count_And_Get
6384       ( p_count        =>      x_msg_count
6385        ,p_data         =>      x_msg_data );
6386       IF g_debug_flag THEN
6387         Write_Debug('Rollback and Finish with unexpected error.') ;
6388       END IF;
6389       IF FND_API.to_Boolean( p_debug ) THEN
6390         Close_Debug_Session;
6391       END IF;
6392     WHEN OTHERS THEN
6393       --ROLLBACK TO Update_Lifecycle_States;
6394       x_return_status := FND_API.G_RET_STS_UNEXP_ERROR ;
6395       IF FND_MSG_PUB.Check_Msg_Level ( FND_MSG_PUB.G_MSG_LVL_UNEXP_ERROR )
6396       THEN
6397         FND_MSG_PUB.Add_Exc_Msg ( G_PKG_NAME, l_api_name );
6398       END IF;
6399       FND_MSG_PUB.Count_And_Get
6400       ( p_count        =>      x_msg_count
6401        ,p_data         =>      x_msg_data );
6402       IF g_debug_flag THEN
6403         Write_Debug('Rollback and Finish with other error.') ;
6404       END IF;
6405       IF FND_API.to_Boolean( p_debug ) THEN
6406         Close_Debug_Session;
6407       END IF;
6408   END Update_Lifecycle_States;
6409 
6410 
6411   -- Procedure to refresh the route_id of the currently active phase of a particular
6412   -- change header, called by WF only
6413   PROCEDURE Refresh_WF_Route
6414   (
6415     p_api_version               IN   NUMBER                             --
6416    ,p_init_msg_list             IN   VARCHAR2 := FND_API.G_FALSE        --
6417    ,p_commit                    IN   VARCHAR2 := FND_API.G_FALSE        --
6418    ,p_validation_level          IN   NUMBER   := FND_API.G_VALID_LEVEL_FULL
6419    ,p_debug                     IN   VARCHAR2 := FND_API.G_FALSE        --
6420    ,p_output_dir                IN   VARCHAR2 := NULL
6421    ,p_debug_filename            IN   VARCHAR2 := NULL
6422    ,x_return_status             OUT  NOCOPY  VARCHAR2                   --
6423    ,x_msg_count                 OUT  NOCOPY  NUMBER                     --
6424    ,x_msg_data                  OUT  NOCOPY  VARCHAR2                   --
6425    ,p_change_id                 IN   NUMBER
6426    ,p_status_code               IN   NUMBER
6427    ,p_wf_route_id               IN   NUMBER
6428    ,p_api_caller                IN   VARCHAR2 := NULL                   -- or 'WF'
6429   )
6430   IS
6431     l_api_name           CONSTANT VARCHAR2(30)  := 'Refresh_WF_Route';
6432     l_api_version        CONSTANT NUMBER := 1.0;
6433 
6434     l_return_status      VARCHAR2(1);
6435     l_msg_count          NUMBER;
6436     l_msg_data           VARCHAR2(2000);
6437 
6438     l_fnd_user_id        NUMBER := TO_NUMBER(FND_PROFILE.VALUE('USER_ID'));
6439     l_fnd_login_id       NUMBER := TO_NUMBER(FND_PROFILE.VALUE('LOGIN_ID'));
6440 
6441     CURSOR c_currPhase IS
6442       SELECT *
6443         FROM eng_lifecycle_statuses
6444         WHERE entity_name = G_ENG_CHANGE
6445           AND entity_id1 = p_change_id
6446           AND status_code = p_status_code
6447           AND active_flag = 'Y'
6448       FOR UPDATE;
6449     l_row_counter        NUMBER := 0;
6450     l_phase_row          eng_lifecycle_statuses%ROWTYPE;
6451     l_wf_route_id        eng_lifecycle_statuses.change_wf_route_id%TYPE;
6452     l_wf_route_id_new    eng_lifecycle_statuses.change_wf_route_id%TYPE;
6453     l_wf_status          eng_lifecycle_statuses.workflow_status%TYPE;
6454 
6455   BEGIN
6456     -- Standard Start of API savepoint
6457     SAVEPOINT Refresh_WF_Route;
6458     -- Standard call to check for call compatibility
6459     IF NOT FND_API.Compatible_API_Call ( l_api_version
6460                                         ,p_api_version
6461                                         ,l_api_name
6462                                         ,G_PKG_NAME )
6463     THEN
6464       RAISE FND_API.G_EXC_UNEXPECTED_ERROR;
6465     END IF;
6466     -- Initialize message list if p_init_msg_list is set to TRUE.
6467     IF FND_API.to_Boolean( p_init_msg_list ) THEN
6468        FND_MSG_PUB.initialize;
6469     END IF;
6470 
6471 
6472     -- For Test/Debug
6473     Check_And_Open_Debug_Session(p_debug, p_output_dir, p_debug_filename) ;
6474     -- R12 Comment out
6475     -- IF FND_API.to_Boolean( p_debug ) THEN
6476     --     Open_Debug_Session(p_output_dir, p_debug_filename ) ;
6477     -- END IF;
6478 
6479     -- Write debug message if debug mode is on
6480     IF g_debug_flag THEN
6481       Write_Debug('ENG_CHANGE_LIFECYCLE_UTIL.Refresh_WF_Route log');
6482       Write_Debug('-----------------------------------------------------');
6483       Write_Debug('p_change_id         : ' || p_change_id );
6484       Write_Debug('p_status_code       : ' || p_status_code );
6485       IF (p_wf_route_id IS NULL)
6486       THEN
6487         Write_Debug('p_wf_route_id       : null' );
6488       ELSE
6489         Write_Debug('p_wf_route_id       : ' || p_wf_route_id );
6490       END IF;
6491       Write_Debug('p_api_caller        : ' || p_api_caller );
6492       Write_Debug('-----------------------------------------------------');
6493       Write_Debug('Initializing return status... ' );
6494     END IF;
6495 
6496     -- Initialize API return status to success
6497     x_return_status := FND_API.G_RET_STS_SUCCESS;
6498 
6499     -- FND_PROFILE package is not available for workflow (WF),
6500     -- therefore manually set WHO column values
6501     IF p_api_caller = 'WF' THEN
6502       l_fnd_user_id := G_ENG_WF_USER_ID;
6503       l_fnd_login_id := G_ENG_WF_LOGIN_ID;
6504     ELSIF p_api_caller = 'CP' THEN
6505       l_fnd_user_id := G_ENG_CP_USER_ID;
6506       l_fnd_login_id := G_ENG_CP_LOGIN_ID;
6507     END IF;
6508 
6509     -- Real code starts here -----------------------------------------------
6510     OPEN c_currPhase;
6511       LOOP
6512         FETCH c_currPhase
6513           INTO l_phase_row;
6514         EXIT WHEN c_currPhase%NOTFOUND;
6515         l_row_counter := l_row_counter + 1;
6516 
6517         l_wf_route_id := l_phase_row.change_wf_route_id;
6518         l_wf_status   := l_phase_row.workflow_status;
6519 
6520         /*
6521         -- Make sure a workflow is already associated with the current phase
6522         IF (l_wf_route_id IS NULL) THEN
6523           FND_MESSAGE.Set_Name('ENG','ENG_WF_NOT_DEFINED_ON_PHASE');
6524           FND_MSG_PUB.Add;
6525           RAISE FND_API.G_EXC_ERROR;
6526         END IF;
6527         */
6528 
6529         -- if passed wf route id is null, it means to generate new id
6530         -- from the old id that's stored in the table, so we need to make sure
6531         -- first that the old id is not null
6532         IF (p_wf_route_id IS NULL)
6533         THEN
6534           IF g_debug_flag THEN
6535             Write_Debug('Branch: p_route_id is null') ;
6536           END IF;
6537           -- if the old wf route id doesn't exist then do nothing; otherwise refresh it
6538           IF (l_wf_route_id IS NOT NULL) THEN
6539             -- Get a new workflow route_id
6540             Eng_Change_Route_Util.REFRESH_ROUTE
6541             ( X_NEW_ROUTE_ID   => l_wf_route_id_new,
6542               P_ROUTE_ID       => l_wf_route_id,
6543               P_USER_ID        => l_fnd_user_id,
6544               P_API_CALLER     => p_api_caller
6545             );
6546             -- Replace the old id with the new id
6547             UPDATE eng_lifecycle_statuses
6548               SET change_wf_route_id = l_wf_route_id_new,
6549                   workflow_status = ENG_WORKFLOW_UTIL.G_RT_NOT_STARTED,
6550                   last_update_date = sysdate,
6551                   last_updated_by = l_fnd_user_id,
6552                   last_update_login = l_fnd_login_id
6553               WHERE CURRENT OF c_currPhase;
6554             IF g_debug_flag THEN
6555               Write_Debug('Updated route_id') ;
6556             END IF;
6557           END IF;
6558 
6559         -- else it is the regular case where wf route id is passed as not null
6560         ELSE
6561           IF g_debug_flag THEN
6562             Write_Debug('Branch: p_route_id is not null') ;
6563           END IF;
6564           UPDATE eng_lifecycle_statuses
6565             SET change_wf_route_id = p_wf_route_id,
6566                 workflow_status = ENG_WORKFLOW_UTIL.G_RT_NOT_STARTED,
6567                 last_update_date = sysdate,
6568                 last_updated_by = l_fnd_user_id,
6569                 last_update_login = l_fnd_login_id
6570             WHERE CURRENT OF c_currPhase;
6571           IF g_debug_flag THEN
6572             Write_Debug('Updated route_id') ;
6573           END IF;
6574         END IF;
6575 
6576     END LOOP;
6577     CLOSE c_currPhase;
6578 
6579     -- One and only one record should be found with the cursor
6580     IF (l_row_counter <> 1) THEN
6581       FND_MESSAGE.Set_Name('ENG','ENG_NOT_EXACTLY_ONE_RECORD');
6582       FND_MSG_PUB.Add;
6583       RAISE FND_API.G_EXC_ERROR;
6584     END IF;
6585 
6586     -- Standard ending code ------------------------------------------------
6587     IF FND_API.To_Boolean ( p_commit ) THEN
6588       COMMIT WORK;
6589     END IF;
6590 
6591     FND_MSG_PUB.Count_And_Get
6592     ( p_count        =>      x_msg_count,
6593       p_data         =>      x_msg_data );
6594 
6595     IF g_debug_flag THEN
6596       Write_Debug('Finish. End Of procedure: Refresh_WF_Route') ;
6597     END IF;
6598 
6599     IF FND_API.to_Boolean( p_debug ) THEN
6600       Close_Debug_Session;
6601     END IF;
6602 
6603   EXCEPTION
6604     WHEN FND_API.G_EXC_ERROR THEN
6605       --ROLLBACK TO Refresh_WF_Route;
6606       x_return_status := FND_API.G_RET_STS_ERROR;
6607       FND_MSG_PUB.Count_And_Get
6608       ( p_count        =>      x_msg_count
6609        ,p_data         =>      x_msg_data );
6610       IF g_debug_flag THEN
6611         Write_Debug('Rollback and Finish with expected error.') ;
6612       END IF;
6613       IF FND_API.to_Boolean( p_debug ) THEN
6614         Close_Debug_Session;
6615       END IF;
6616     WHEN FND_API.G_EXC_UNEXPECTED_ERROR THEN
6617       --ROLLBACK TO Refresh_WF_Route;
6618       x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
6619       FND_MSG_PUB.Count_And_Get
6620       ( p_count        =>      x_msg_count
6621        ,p_data         =>      x_msg_data );
6622       IF g_debug_flag THEN
6623         Write_Debug('Rollback and Finish with unexpected error.') ;
6624       END IF;
6625       IF FND_API.to_Boolean( p_debug ) THEN
6626         Close_Debug_Session;
6627       END IF;
6628     WHEN OTHERS THEN
6629       --ROLLBACK TO Refresh_WF_Route;
6630       x_return_status := FND_API.G_RET_STS_UNEXP_ERROR ;
6631       IF FND_MSG_PUB.Check_Msg_Level ( FND_MSG_PUB.G_MSG_LVL_UNEXP_ERROR )
6632       THEN
6633         FND_MSG_PUB.Add_Exc_Msg ( G_PKG_NAME, l_api_name );
6634       END IF;
6635       FND_MSG_PUB.Count_And_Get
6636       ( p_count        =>      x_msg_count
6637        ,p_data         =>      x_msg_data );
6638       IF g_debug_flag THEN
6639         Write_Debug('Rollback and Finish with other error.') ;
6640       END IF;
6641       IF FND_API.to_Boolean( p_debug ) THEN
6642         Close_Debug_Session;
6643       END IF;
6644 
6645   END Refresh_WF_Route;
6646 
6647 
6648 
6649   -- Procedure to automatically initialize lifecycles for a new change header
6650   -- It also takes care of automatically launching the workflow if needed
6651   -- Note that this procedure can ONLY be called directly from UI
6652   -- In R12, Added p_init_status_code to speicify the initialized status code
6653   -- In R12, Added p_init_option  'WF_ONLY'  Start Only WF
6654   PROCEDURE Init_Lifecycle
6655   (
6656     p_api_version               IN   NUMBER                             --
6657    ,p_init_msg_list             IN   VARCHAR2 := FND_API.G_FALSE        --
6658    ,p_commit                    IN   VARCHAR2 := FND_API.G_FALSE        --
6659    ,p_validation_level          IN   NUMBER   := FND_API.G_VALID_LEVEL_FULL
6660    ,p_debug                     IN   VARCHAR2 := FND_API.G_FALSE        --
6661    ,p_output_dir                IN   VARCHAR2 := NULL
6662    ,p_debug_filename            IN   VARCHAR2 := NULL
6663    ,x_return_status             OUT  NOCOPY  VARCHAR2                   --
6664    ,x_msg_count                 OUT  NOCOPY  NUMBER                     --
6665    ,x_msg_data                  OUT  NOCOPY  VARCHAR2                   --
6666    ,p_change_id                 IN   NUMBER                             -- header's change_id
6667    ,p_api_caller                IN   VARCHAR2 := 'UI'
6668    ,p_init_status_code          IN   NUMBER   := NULL                   -- R12
6669    ,p_init_option               IN   VARCHAR2 := NULL                   -- R12
6670   )
6671   IS
6672 
6673     l_api_name           CONSTANT VARCHAR2(30)  := 'Init_Lifecycle';
6674     l_api_version        CONSTANT NUMBER := 1.0;
6675 
6676     l_return_status      VARCHAR2(1);
6677     l_msg_count          NUMBER;
6678     l_msg_data           VARCHAR2(2000);
6679 
6680     l_fnd_user_id        NUMBER := TO_NUMBER(FND_PROFILE.VALUE('USER_ID'));
6681     l_fnd_login_id       NUMBER := TO_NUMBER(FND_PROFILE.VALUE('LOGIN_ID'));
6682 
6683     l_cm_type_code       eng_engineering_changes.change_mgmt_type_code%TYPE;
6684     l_base_cm_type_code  eng_change_order_types.BASE_CHANGE_MGMT_TYPE_CODE%TYPE;
6685     l_bug_number         NUMBER := 0;
6686 
6687     l_initial_phase_sn   eng_lifecycle_statuses.sequence_number%TYPE;
6688 
6689     l_status_code        eng_lifecycle_statuses.status_code%TYPE;
6690     l_status_type        eng_engineering_changes.status_type%TYPE;
6691     l_sequence_number    eng_lifecycle_statuses.sequence_number%TYPE;
6692     l_wf_route_id        eng_lifecycle_statuses.change_wf_route_id%TYPE;
6693     -- bug 9577905
6694     l_next_status_code   eng_lifecycle_statuses.auto_promote_status%TYPE;
6695     l_workflow_status    eng_lifecycle_statuses.workflow_status%TYPE;
6696     l_next_status        eng_lifecycle_statuses.workflow_status%TYPE;
6697     -- bug 9577905, end
6698 
6699     l_pls_block          VARCHAR2(5000);
6700     l_message_list Error_Handler.Error_Tbl_Type;  --Bug 11825003
6701 
6702     -- for auto-propagation if it's defined for first phase
6703     l_auto_prop_flag     eng_type_org_properties.AUTO_PROPAGATE_FLAG%TYPE;
6704     l_change_notice      eng_engineering_changes.change_notice%TYPE;
6705     l_hierarchy_name     per_organization_structures.name%TYPE;
6706     l_org_name           org_organization_definitions.organization_name%TYPE;
6707     l_row_cnt            NUMBER := 0;
6708     CURSOR c_orgProp IS
6709       SELECT op.auto_propagate_flag,
6710              ec.change_notice,
6711              pos.name,
6712              ood.name organization_name
6713         FROM eng_type_org_properties op,
6714              eng_engineering_changes ec,
6715              per_organization_structures pos,
6716              hr_all_organization_units_tl ood
6717         WHERE ec.change_id = p_change_id
6718           --AND ec.PLM_OR_ERP_CHANGE = 'PLM'
6719           AND op.change_type_id = ec.change_order_type_id
6720           AND op.organization_id = ec.organization_id
6721           AND op.propagation_status_code = l_status_code
6722           AND ec.hierarchy_id IS NOT NULL
6723           AND ec.organization_id IS NOT NULL
6724           AND pos.organization_structure_id(+) = ec.hierarchy_id
6725           AND ood.organization_id(+) = ec.organization_id
6726           AND ood.LANGUAGE = USERENV('LANG');
6727 
6728     l_request_id         NUMBER := 0;
6729 
6730     l_action_id          eng_change_actions.action_id%TYPE;
6731     l_param_list         WF_PARAMETER_LIST_T := WF_PARAMETER_LIST_T();
6732     l_wf_only_flag       BOOLEAN ;
6733 
6734   BEGIN
6735     -- Standard Start of API savepoint
6736     SAVEPOINT Init_Lifecycle;
6737     --Error_Handler.Initialize;    --Bug 11825003
6738     -- Standard call to check for call compatibility
6739     IF NOT FND_API.Compatible_API_Call ( l_api_version
6740                                         ,p_api_version
6741                                         ,l_api_name
6742                                         ,G_PKG_NAME )
6743     THEN
6744       RAISE FND_API.G_EXC_UNEXPECTED_ERROR;
6745     END IF;
6746     -- Initialize message list if p_init_msg_list is set to TRUE.
6747     IF FND_API.to_Boolean( p_init_msg_list ) THEN
6748        FND_MSG_PUB.initialize;
6749     END IF;
6750 
6751     -- For Test/Debug
6752     Check_And_Open_Debug_Session(p_debug, p_output_dir, p_debug_filename) ;
6753     -- R12 Comment out
6754     -- IF FND_API.to_Boolean( p_debug ) THEN
6755     --     Open_Debug_Session(p_output_dir, p_debug_filename ) ;
6756     -- END IF;
6757 
6758     -- Write debug message if debug mode is on
6759     IF g_debug_flag THEN
6760        Write_Debug('ENG_CHANGE_LIFECYCLE_UTIL.Init_Lifecycle log');
6761        Write_Debug('-----------------------------------------------------');
6762        Write_Debug('p_change_id         : ' || p_change_id );
6763        Write_Debug('p_init_status_code  : ' || p_init_status_code );
6764        Write_Debug('p_init_option       : ' || p_init_option );
6765        Write_Debug('-----------------------------------------------------');
6766        Write_Debug('Initializing return status... ' );
6767     END IF;
6768 
6769     -- Initialize API return status to success
6770     x_return_status := FND_API.G_RET_STS_SUCCESS;
6771 
6772     -- FND_PROFILE package is not available for workflow (WF),
6773     -- therefore manually set WHO column values
6774     IF p_api_caller = 'WF' THEN
6775       l_fnd_user_id := G_ENG_WF_USER_ID;
6776       l_fnd_login_id := G_ENG_WF_LOGIN_ID;
6777     ELSIF p_api_caller = 'CP' THEN
6778       l_fnd_user_id := G_ENG_CP_USER_ID;
6779       l_fnd_login_id := G_ENG_CP_LOGIN_ID;
6780     END IF;
6781 
6782     -- Real code starts here -----------------------------------------------
6783 
6784 
6785     -- Get the first phase from the change header's lifecycle definition
6786     -- In R12, added p_init_status_code condition here
6787     SELECT min(sequence_number)
6788       INTO l_initial_phase_sn
6789       FROM eng_lifecycle_statuses
6790       WHERE entity_name = G_ENG_CHANGE
6791         AND entity_id1 = p_change_id
6792         AND active_flag = 'Y'
6793         AND (status_code = p_init_status_code  OR p_init_status_code IS NULL) ;
6794 
6795     -- bug 9036674, add the filter for status to avoid promote the completed
6796     -- initial stage, it can avoid the later check throw exception
6797     begin
6798       -- bug 9577905, add l_workflow_status, l_next_status_code
6799       SELECT lcs.status_code, ecs.status_type, lcs.workflow_status,lcs.auto_promote_status
6800         INTO l_status_code, l_status_type, l_workflow_status, l_next_status_code
6801         FROM eng_lifecycle_statuses lcs,
6802              eng_change_statuses ecs
6803         WHERE lcs.entity_name = G_ENG_CHANGE
6804           AND lcs.entity_id1 = p_change_id
6805           AND lcs.active_flag = 'Y'
6806           AND lcs.sequence_number = l_initial_phase_sn
6807           AND ecs.status_code = lcs.status_code
6808           AND (NVL(lcs.workflow_status, 'xxx') <> Eng_Workflow_Util.G_RT_COMPLETED -- for 9036674
6809             OR lcs.auto_promote_status is not null) -- bug 9577905
6810           AND rownum = 1;
6811     exception
6812       when NO_DATA_FOUND then
6813         IF g_debug_flag THEN
6814            Write_Debug('The initial stage was promoted and Auto Promote disabled, exit Init_Lifecycle');
6815         END IF;
6816         return ;
6817     end;
6818     -- bug 12875329
6819     IF g_debug_flag THEN
6820        Write_Debug('l_initial_phase_sn  : ' || l_initial_phase_sn );
6821        Write_Debug('l_status_code       : ' || l_status_code );
6822        Write_Debug('l_status_type       : ' || l_status_type );
6823        Write_Debug('l_workflow_status   : ' || l_workflow_status );
6824        WRITE_DEBUG('l_next_status_code  : ' || L_NEXT_STATUS_CODE );
6825     END IF;
6826 
6827     -- bug 9577905, branch for first phase be completed and and Auto Promote enabled
6828 
6829 --Bug 13810488 For Approval type (status_type: 8), if it is finished, status is APPROVED instead of COMPLETED
6830     IF ( (l_workflow_status = Eng_Workflow_Util.G_RT_COMPLETED
6831             or ( l_status_type = 8 and l_workflow_status = Eng_Workflow_Util.G_RT_APPROVED) )
6832       and l_next_status_code is not null) THEN
6833       IF g_debug_flag THEN
6834         Write_Debug('The initial status is completed or approved, the second phase not started.');
6835         Write_Debug('start second phase, l_workflow_status : ' || l_workflow_status);
6836         Write_Debug('start second phase, l_next_status_code : ' || to_char(l_next_status_code));
6837       END IF;
6838 
6839       SELECT lcs.workflow_status
6840         INTO l_next_status
6841         FROM eng_lifecycle_statuses lcs
6842         WHERE lcs.entity_name = G_ENG_CHANGE
6843           AND lcs.entity_id1 = p_change_id
6844           AND lcs.active_flag = 'Y'
6845           AND lcs.status_code = l_next_status_code;
6846 
6847       IF (NVL(l_next_status, 'xxx') <> Eng_Workflow_Util.G_RT_COMPLETED) THEN
6848 
6849         IF g_debug_flag THEN
6850 	  Write_Debug('In Init_Lifecyle, l_next_status_code IS NOT NULL AND first phase be completed, call PROMOTE_HEADER');
6851 	END IF;
6852 
6853 	Promote_Header
6854 	(
6855 	  p_api_version        => 1.0
6856 	 ,p_init_msg_list      => FND_API.G_FALSE
6857 	 ,p_commit             => FND_API.G_FALSE
6858 	 ,p_validation_level   => FND_API.G_VALID_LEVEL_FULL
6859 	 ,p_debug              => FND_API.G_FALSE
6860 	 ,p_output_dir         => p_output_dir
6861 	 ,p_debug_filename     => p_debug_filename
6862 	 ,x_return_status      => l_return_status
6863 	 ,x_msg_count          => l_msg_count
6864 	 ,x_msg_data           => l_msg_data
6865 	 ,p_change_id          => p_change_id
6866 	 ,p_status_code        => l_next_status_code
6867 	 ,p_api_caller         => 'WF'
6868 	);
6869 
6870 	IF g_debug_flag THEN
6871 	  Write_Debug('After: Promote_Header: ' || l_return_status );
6872 	END IF;
6873 
6874 	IF ( l_return_status <>  FND_API.G_RET_STS_SUCCESS ) THEN
6875 	  x_return_status := l_return_status;
6876 	  x_msg_count := l_msg_count;
6877 	  x_msg_data := l_msg_data;
6878 	  --#FND_MESSAGE.Set_Name('ENG','ENG_ERROR_CALLING_PS_API');
6879 	  --#FND_MESSAGE.Set_Token('OBJECT_NAME', 'Promote_Header');
6880 	  --#FND_MSG_PUB.Add;
6881 	  RAISE FND_API.G_EXC_ERROR;
6882 	END IF;
6883 
6884 	IF g_debug_flag THEN
6885 	  Write_Debug('After: calling PROMOTE_HEADER');
6886 	END IF;
6887       END IF;
6888 
6889       return ;
6890     END IF;
6891     -- bug 9577905, end of branch for first phase be completed and and Auto Promote enabled
6892 
6893     -- bug 12875329
6894     IF (l_workflow_status = Eng_Workflow_Util.G_RT_IN_PROGRESS) THEN
6895       IF g_debug_flag THEN
6896       Write_Debug('The status is started, exit...');
6897       END IF;
6898       return ;  -- return to avoid the exception in Eng_Workflow_Util.CheckRouteStatus
6899     END IF;
6900 
6901     IF g_debug_flag THEN
6902        Write_Debug('After: getting first phase from lifecycle definitions');
6903     END IF;
6904 
6905     -- and set it in the eng_engineering_changes table
6906     UPDATE eng_engineering_changes
6907       SET status_code = l_status_code,
6908           status_type = l_status_type,
6909           initiation_date = sysdate
6910       WHERE change_id = p_change_id;
6911 
6912     IF g_debug_flag THEN
6913        Write_Debug('After: settting status_type and status_code of header to first phase');
6914     END IF;
6915 
6916     /*
6917     -- Get the current phase from change header
6918     SELECT status_code, status_type
6919       INTO l_status_code, l_status_type
6920       FROM eng_engineering_changes
6921       WHERE change_id = p_change_id;
6922 
6923     IF g_debug_flag THEN
6924        Write_Debug('After: getting current phase from change header');
6925     END IF;
6926     */
6927 
6928     -- Get the sequence number for the current phase
6929     SELECT sequence_number, change_wf_route_id
6930       INTO l_sequence_number, l_wf_route_id
6931       FROM eng_lifecycle_statuses
6932       WHERE entity_name = G_ENG_CHANGE
6933         AND entity_id1 = p_change_id
6934         AND active_flag = 'Y'
6935         AND status_code = l_status_code;
6936 
6937     IF g_debug_flag THEN
6938        Write_Debug('After: getting lifecycle definitions for the current phase');
6939     END IF;
6940 
6941     /*
6942     -- Sanity check
6943     IF (l_sequence_number <> l_initial_phase_sn) THEN
6944       FND_MESSAGE.Set_Name('ENG','ENG_CURR_PHASE_NOT_FIRST');
6945       FND_MSG_PUB.Add;
6946       RAISE FND_API.G_EXC_ERROR;
6947     END IF;
6948     IF g_debug_flag THEN
6949       Write_Debug('After: sanity check of the current phase as the first phase');
6950     END IF;
6951     */
6952 
6953     -- Sanity check on workflow
6954     IF (l_wf_route_id IS NOT NULL) THEN
6955       IF g_debug_flag THEN
6956         Write_Debug('Initial phase has workflow.');
6957       END IF;
6958     END IF;
6959 
6960     -- Initialize workflow_status for all phases that have workflows
6961     UPDATE eng_lifecycle_statuses
6962       SET workflow_status = Eng_Workflow_Util.G_RT_NOT_STARTED,
6963           last_update_date = sysdate,
6964           last_updated_by = l_fnd_user_id,
6965           last_update_login = l_fnd_login_id
6966       WHERE entity_name = G_ENG_CHANGE
6967         AND entity_id1 = p_change_id
6968         AND active_flag = 'Y'
6969         AND change_wf_route_id IS NOT NULL;
6970     IF g_debug_flag THEN
6971       Write_Debug('After updating eng_lifecycle_statuses.workflow_status.');
6972       Write_Debug('  Row count = ' || SQL%ROWCOUNT);
6973     END IF;
6974 
6975     IF g_debug_flag THEN
6976       Write_Debug('After: Initialize workflow_status for all phases that have workflows');
6977     END IF;
6978 
6979     -- Update current phase row
6980     UPDATE eng_lifecycle_statuses
6981       SET start_date = sysdate,
6982           last_update_date = sysdate,
6983           last_updated_by = l_fnd_user_id,
6984           last_update_login = l_fnd_login_id
6985       WHERE entity_name = G_ENG_CHANGE
6986         AND entity_id1 = p_change_id
6987         AND status_code = l_status_code
6988         AND active_flag = 'Y';
6989 
6990     IF g_debug_flag THEN
6991       Write_Debug('After updating eng_lifecycle_statuses.start_date.');
6992       Write_Debug('  Row count = ' || SQL%ROWCOUNT);
6993     END IF;
6994 
6995     IF g_debug_flag THEN
6996       Write_Debug('After: updating the current phase row');
6997     END IF;
6998 
6999 
7000     l_wf_only_flag := FALSE ;
7001     IF (p_init_option = 'WF_ONLY')
7002     THEN
7003 
7004 IF g_debug_flag THEN
7005     Write_Debug('WF Only Flag is TRUE. . .');
7006 END IF;
7007 
7008         l_wf_only_flag := TRUE ;
7009 
7010     END IF ;
7011 
7012     IF (NOT l_wf_only_flag)
7013     THEN
7014 
7015 
7016 IF g_debug_flag THEN
7017     Write_Debug('Before: saving action log');
7018 END IF;
7019         -- Record SUBMIT action log and raise submit business event
7020         l_action_id := 0;
7021         -- create new action log
7022         ENG_CHANGE_ACTIONS_UTIL.Create_Change_Action
7023         ( p_api_version           => 1.0
7024         , p_init_msg_list         => FND_API.G_FALSE        --
7025         , p_commit                => FND_API.G_FALSE        --
7026         , p_validation_level      => FND_API.G_VALID_LEVEL_FULL
7027         , p_debug                 => p_debug --FND_API.G_FALSE
7028         , p_output_dir            => p_output_dir
7029         , p_debug_filename        => 'engact.CreateAction.log'
7030         , x_return_status         => l_return_status
7031         , x_msg_count             => l_msg_count
7032         , x_msg_data              => l_msg_data
7033         , p_action_type           => ENG_CHANGE_ACTIONS_UTIL.G_ACT_SUBMIT
7034         , p_object_name           => G_ENG_CHANGE
7035         , p_object_id1            => p_change_id
7036         , p_object_id2            => NULL
7037         , p_object_id3            => NULL
7038         , p_object_id4            => NULL
7039         , p_object_id5            => NULL
7040         , p_parent_action_id      => -1
7041         , p_status_code           => NULL
7042         , p_action_date           => SYSDATE
7043         , p_change_description    => NULL
7044         , p_user_id               => l_fnd_user_id
7045         , p_api_caller            => p_api_caller
7046         , x_change_action_id      => l_action_id
7047         );
7048         IF g_debug_flag THEN
7049            Write_Debug('After: saving action log: ' || l_return_status);
7050            Write_Debug('l_action_id       : ' || l_action_id );
7051         END IF;
7052         IF ( l_return_status <>  FND_API.G_RET_STS_SUCCESS )
7053         THEN
7054           x_return_status := l_return_status;
7055           x_msg_count := l_msg_count;
7056           x_msg_data := l_msg_data;
7057           --#FND_MESSAGE.Set_Name('ENG','ENG_ERROR_CALLING_PS_API');
7058           --#FND_MESSAGE.Set_Token('OBJECT_NAME', 'ENG_CHANGE_ACTIONS_UTIL.Create_Change_Action');
7059           --#FND_MSG_PUB.Add;
7060           RAISE FND_API.G_EXC_ERROR;
7061         END IF;
7062         IF g_debug_flag THEN
7063            Write_Debug('Successful: saving action log');
7064         END IF;
7065 
7066         -- raise business event for SUBMIT action
7067         -- Select cm type and base type code for upcoming API calls
7068         SELECT eec.change_mgmt_type_code, ecot.base_change_mgmt_type_code
7069           INTO l_cm_type_code, l_base_cm_type_code
7070           FROM eng_engineering_changes eec,
7071                eng_change_order_types ecot
7072           WHERE eec.change_id = p_change_id
7073             AND ecot.change_order_type_id = eec.change_order_type_id;
7074 
7075      -- for nir set all included item approval status to submitted for approval
7076 	IF (l_base_cm_type_code = 'NEW_ITEM_REQUEST') THEN
7077 	   ENG_NIR_UTIL_PKG.set_nir_item_approval_status (p_change_id,
7078 							  Eng_Workflow_Util.G_REQUESTED,
7079 							  x_return_status => l_return_status,
7080 							  x_msg_count => l_msg_count,
7081 							  x_msg_data => l_msg_data);
7082 	END IF;
7083 
7084         -- Raise the approval status change business event
7085         -- Adding event parameters to the list
7086         WF_EVENT.AddParameterToList
7087         ( p_name          => ENG_CHANGE_BES_UTIL.G_BES_PARAM_CHANGE_ID
7088          ,p_value         => to_char(p_change_id)
7089          ,p_parameterList => l_param_list
7090          );
7091         WF_EVENT.AddParameterToList
7092         ( p_name          => ENG_CHANGE_BES_UTIL.G_BES_PARAM_BASE_CM_TYPE_CODE
7093          ,p_value         => l_base_cm_type_code
7094          ,p_parameterList => l_param_list
7095          );
7096 
7097 			--Bug 11825003
7098 			BEGIN
7099     	  -- Raise event
7100         WF_EVENT.RAISE
7101         ( p_event_name    => ENG_CHANGE_BES_UTIL.G_CMBE_HEADER_SUBMIT
7102          ,p_event_key     => p_change_id
7103          ,p_parameters    => l_param_list
7104          );
7105         l_param_list.DELETE;
7106       EXCEPTION
7107              --Added for bug 10128347
7108        WHEN OTHERS THEN
7109           ERROR_HANDLER.Add_Error_Message(
7110              p_message_name              => 'EGO_EVENT_SUBSCR'
7111             ,p_application_id            => 'EGO'
7112             ,p_message_type              => FND_API.G_RET_STS_ERROR
7113             ,p_addto_fnd_stack           => 'Y');
7114           raise EGO_USER_ATTRS_COMMON_PVT.G_SUBSCRIPTION_EXC;
7115    		End;
7116 
7117 
7118         -- auto propagate if necessary
7119         l_row_cnt := 0;
7120         OPEN c_orgProp;
7121           LOOP
7122             FETCH c_orgProp
7123               INTO l_auto_prop_flag,
7124                    l_change_notice,
7125                    l_hierarchy_name,
7126                    l_org_name;
7127             EXIT WHEN c_orgProp%NOTFOUND;
7128 
7129             l_row_cnt := l_row_cnt + 1;
7130             -- verify the uniqueness of the record
7131             IF (l_row_cnt > 1) THEN
7132               IF g_debug_flag THEN
7133                 Write_Debug('Error: more than one propagation policy is found');
7134               END IF;
7135             END IF;
7136 
7137             IF g_debug_flag THEN
7138               Write_Debug('one record for propagation policy is found');
7139               Write_Debug('l_auto_prop_flag         : ' || l_auto_prop_flag );
7140               Write_Debug('l_change_notice          : ' || l_change_notice );
7141               Write_Debug('l_hierarchy_name         : ' || l_hierarchy_name );
7142               Write_Debug('l_org_name               : ' || l_org_name );
7143             END IF;
7144 
7145             IF ( l_auto_prop_flag = 'Y') THEN
7146               IF g_debug_flag THEN
7147                 Write_Debug('which needs auto propagation');
7148               END IF;
7149 
7150               ENG_ECO_UTIL.Propagate_ECO
7151               (
7152                 p_api_version          =>    1.0
7153                ,p_init_msg_list        =>    FND_API.G_FALSE
7154                ,p_commit               =>    FND_API.G_FALSE
7155                ,p_validation_level     =>    FND_API.G_VALID_LEVEL_FULL
7156                ,p_debug                =>    p_debug --FND_API.G_FALSE
7157                ,p_output_dir           =>    p_output_dir
7158                ,p_debug_filename       =>    NULL --p_debug_filename
7159                ,x_return_status        =>    l_return_status
7160                ,x_msg_count            =>    l_msg_count
7161                ,x_msg_data             =>    l_msg_data
7162                ,p_change_id            =>    p_change_id
7163                ,p_change_notice        =>    l_change_notice
7164                ,p_hierarchy_name       =>    l_hierarchy_name
7165                ,p_org_name             =>    l_org_name
7166                ,x_request_id           =>    l_request_id
7167               );
7168 
7169               IF g_debug_flag THEN
7170                 Write_Debug('After: calling propagate_eco API: ' || l_return_status);
7171               END IF;
7172 
7173               IF ( l_return_status <>  FND_API.G_RET_STS_SUCCESS ) THEN
7174                 x_return_status := l_return_status;
7175                 x_msg_count := l_msg_count;
7176                 x_msg_data := l_msg_data;
7177                 --#FND_MESSAGE.Set_Name('ENG','ENG_ERROR_CALLING_PS_API');
7178                 --#FND_MESSAGE.Set_Token('OBJECT_NAME', 'ENG_ECO_UTIL.Propagate_ECO');
7179                 --#FND_MSG_PUB.Add;
7180                 RAISE FND_API.G_EXC_ERROR;
7181               END IF;
7182 
7183               IF g_debug_flag THEN
7184                 Write_Debug('Successful: calling propagate_eco API');
7185                 Write_Debug('l_request_id       : ' || l_request_id );
7186               END IF;
7187 
7188               IF g_debug_flag THEN
7189                  Write_Debug('Before: saving action log');
7190               END IF;
7191               l_action_id := 0;
7192               -- create new action log
7193               -- Bug Fix: 3547844
7194               -- In case of Auto-Propgation Action Log
7195               -- Who column is Workflow
7196               ENG_CHANGE_ACTIONS_UTIL.Create_Change_Action
7197               ( p_api_version           => 1.0
7198               , p_init_msg_list         => FND_API.G_FALSE        --
7199               , p_commit                => FND_API.G_FALSE        --
7200               , p_validation_level      => FND_API.G_VALID_LEVEL_FULL
7201               , p_debug                 => p_debug --FND_API.G_FALSE
7202               , p_output_dir            => p_output_dir
7203               , p_debug_filename        => NULL
7204               , x_return_status         => l_return_status
7205               , x_msg_count             => l_msg_count
7206               , x_msg_data              => l_msg_data
7207               , p_action_type           => ENG_CHANGE_ACTIONS_UTIL.G_ACT_PROPAGATE
7208               , p_object_name           => G_ENG_CHANGE
7209               , p_object_id1            => p_change_id
7210               , p_object_id2            => NULL
7211               , p_object_id3            => NULL
7212               , p_object_id4            => NULL
7213               , p_object_id5            => NULL
7214               , p_parent_action_id      => -1
7215               , p_status_code           => NULL
7216               , p_action_date           => SYSDATE
7217               , p_change_description    => NULL
7218               , p_user_id               => G_ENG_WF_USER_ID
7219               , p_api_caller            => 'WF'
7220               , x_change_action_id      => l_action_id
7221               );
7222 
7223               IF g_debug_flag THEN
7224                  Write_Debug('After: saving action log: ' || l_return_status);
7225                  Write_Debug('l_action_id       : ' || l_action_id );
7226               END IF;
7227 
7228               IF ( l_return_status <>  FND_API.G_RET_STS_SUCCESS )
7229               THEN
7230                 x_return_status := l_return_status;
7231                 x_msg_count := l_msg_count;
7232                 x_msg_data := l_msg_data;
7233                 --#FND_MESSAGE.Set_Name('ENG','ENG_ERROR_CALLING_PS_API');
7234                 --#FND_MESSAGE.Set_Token('OBJECT_NAME', 'ENG_CHANGE_ACTIONS_UTIL.Create_Change_Action');
7235                 --#FND_MSG_PUB.Add;
7236                 RAISE FND_API.G_EXC_ERROR;
7237               END IF;
7238               IF g_debug_flag THEN
7239                  Write_Debug('Successful: saving action log');
7240               END IF;
7241 
7242             ELSE
7243               IF g_debug_flag THEN
7244                 Write_Debug('which does not need auto propagation');
7245               END IF;
7246             END IF;
7247 
7248           END LOOP;
7249         CLOSE c_orgProp;
7250         IF g_debug_flag THEN
7251            Write_Debug('After checking propagation policy');
7252         END IF;
7253 
7254     END IF ; -- (NOT l_wf_only_flag)
7255 
7256 
7257     -- Start workflow for new phase if necessary
7258     Start_WF_OnlyIf_Necessary
7259     ( p_api_version       => 1.0
7260      ,p_init_msg_list     => FND_API.G_FALSE
7261      ,p_commit            => FND_API.G_FALSE
7262      ,p_validation_level  => p_validation_level
7263      ,p_debug             => FND_API.G_FALSE
7264      ,p_output_dir        => p_output_dir
7265      ,p_debug_filename    => p_debug_filename
7266      ,x_return_status     => l_return_status
7267      ,x_msg_count         => l_msg_count
7268      ,x_msg_data          => l_msg_data
7269      ,p_change_id         => p_change_id
7270      ,p_status_code       => l_status_code
7271      ,p_status_type       => l_status_type
7272      ,p_sequence_number   => l_sequence_number
7273      --,p_imp_eco_flag      => 'N'
7274      ,p_api_caller        => p_api_caller
7275      ,p_action_type       => NULL
7276     );
7277 
7278     IF g_debug_flag THEN
7279        Write_Debug('After call to procedure Start_WF_OnlyIf_Necessary: ' || l_return_status);
7280     END IF;
7281 
7282     IF ( l_return_status <>  FND_API.G_RET_STS_SUCCESS ) THEN
7283       x_return_status := l_return_status;
7284       x_msg_count := l_msg_count;
7285       x_msg_data := l_msg_data;
7286       --#FND_MESSAGE.Set_Name('ENG','ENG_ERROR_CALLING_WF_API');
7287       --#FND_MSG_PUB.Add;
7288       RAISE FND_API.G_EXC_ERROR;
7289     END IF;
7290 
7291     -- Standard ending code ------------------------------------------------
7292     IF FND_API.To_Boolean ( p_commit ) THEN
7293       COMMIT WORK;
7294     END IF;
7295 
7296     FND_MSG_PUB.Count_And_Get
7297     ( p_count        =>      x_msg_count,
7298       p_data         =>      x_msg_data );
7299 
7300     IF g_debug_flag THEN
7301       Write_Debug('Finish. End Of procedure: Init_Lifecycle') ;
7302     END IF;
7303 
7304     IF FND_API.to_Boolean( p_debug ) THEN
7305       Close_Debug_Session;
7306     END IF;
7307 
7308   EXCEPTION
7309     WHEN EGO_USER_ATTRS_COMMON_PVT.G_SUBSCRIPTION_EXC then  --Bug 11825003
7310      --ROLLBACK WORK;
7311      x_return_status := FND_API.G_RET_STS_ERROR;
7312      ERROR_HANDLER.Get_Message_List(l_message_list);
7313      			FOR i IN l_message_list.FIRST..l_message_list.LAST
7314      					LOOP
7315     					x_msg_data := x_msg_data || l_message_list(i).message_text;
7316     			END LOOP;
7317      IF g_debug_flag THEN
7318         Write_Debug('Rollback and Finish with expected error.') ;
7319       END IF;
7320       IF FND_API.to_Boolean( p_debug ) THEN
7321         Close_Debug_Session;
7322       END IF;
7323     WHEN FND_API.G_EXC_ERROR THEN
7324      --ROLLBACK TO Init_Lifecycle;
7325       x_return_status := FND_API.G_RET_STS_ERROR;
7326       FND_MSG_PUB.Count_And_Get
7327       ( p_count        =>      x_msg_count
7328        ,p_data         =>      x_msg_data );
7329       IF g_debug_flag THEN
7330         Write_Debug('Rollback and Finish with expected error.') ;
7331       END IF;
7332       IF FND_API.to_Boolean( p_debug ) THEN
7333         Close_Debug_Session;
7334       END IF;
7335     WHEN FND_API.G_EXC_UNEXPECTED_ERROR THEN
7336       --ROLLBACK TO Init_Lifecycle;
7337       x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
7338       FND_MSG_PUB.Count_And_Get
7339       ( p_count        =>      x_msg_count
7340        ,p_data         =>      x_msg_data );
7341       IF g_debug_flag THEN
7342         Write_Debug('Rollback and Finish with unexpected error.') ;
7343       END IF;
7344       IF FND_API.to_Boolean( p_debug ) THEN
7345         Close_Debug_Session;
7346       END IF;
7347     WHEN OTHERS THEN
7348       --ROLLBACK TO Init_Lifecycle;
7349       x_return_status := FND_API.G_RET_STS_UNEXP_ERROR ;
7350       IF FND_MSG_PUB.Check_Msg_Level ( FND_MSG_PUB.G_MSG_LVL_UNEXP_ERROR )
7351       THEN
7352         FND_MSG_PUB.Add_Exc_Msg (  G_PKG_NAME, l_api_name );
7353       END IF;
7354       FND_MSG_PUB.Count_And_Get
7355       ( p_count        =>      x_msg_count
7356        ,p_data         =>      x_msg_data );
7357       IF g_debug_flag THEN
7358         Write_Debug('Rollback and Finish with other error.') ;
7359       END IF;
7360       IF FND_API.to_Boolean( p_debug ) THEN
7361         Close_Debug_Session;
7362       END IF;
7363 
7364   END Init_Lifecycle;
7365 
7366 
7367 
7368 
7369   -- Procedure to be called by revised item implementation concurrent
7370   -- program to set its status_type
7371   PROCEDURE Update_RevItem_Lifecycle
7372   (
7373     p_api_version               IN   NUMBER                             --
7374    ,p_init_msg_list             IN   VARCHAR2 := FND_API.G_FALSE        --
7375    ,p_commit                    IN   VARCHAR2 := FND_API.G_FALSE        --
7376    ,p_validation_level          IN   NUMBER   := FND_API.G_VALID_LEVEL_FULL
7377    ,p_debug                     IN   VARCHAR2 := FND_API.G_FALSE        --
7378    ,p_output_dir                IN   VARCHAR2 := NULL
7379    ,p_debug_filename            IN   VARCHAR2 := NULL
7380    ,x_return_status             OUT  NOCOPY  VARCHAR2                   --
7381    ,x_msg_count                 OUT  NOCOPY  NUMBER                     --
7382    ,x_msg_data                  OUT  NOCOPY  VARCHAR2                   --
7383    ,p_rev_item_seq_id           IN   NUMBER
7384    ,p_status_type               IN   NUMBER                             -- say 10 for imp_failed
7385    ,p_api_caller                IN   VARCHAR2 := NULL                   -- 'CP'
7386   )
7387   IS
7388     l_api_name           CONSTANT VARCHAR2(30)  := 'Update_RevItem_Lifecycle';
7389     l_api_version        CONSTANT NUMBER := 1.0;
7390 
7391     l_return_status      VARCHAR2(1);
7392     l_msg_count          NUMBER;
7393     l_msg_data           VARCHAR2(2000);
7394 
7395     l_fnd_user_id        NUMBER := TO_NUMBER(FND_PROFILE.VALUE('USER_ID'));
7396     l_fnd_login_id       NUMBER := TO_NUMBER(FND_PROFILE.VALUE('LOGIN_ID'));
7397 
7398   BEGIN
7399     -- Standard Start of API savepoint
7400     --SAVEPOINT  Update_RevItem_Lifecycle;
7401     -- Standard call to check for call compatibility
7402     IF NOT FND_API.Compatible_API_Call ( l_api_version
7403                                         ,p_api_version
7404                                         ,l_api_name
7405                                         ,G_PKG_NAME )
7406     THEN
7407       RAISE FND_API.G_EXC_UNEXPECTED_ERROR;
7408     END IF;
7409     -- Initialize message list if p_init_msg_list is set to TRUE.
7410     IF FND_API.to_Boolean( p_init_msg_list ) THEN
7411        FND_MSG_PUB.initialize;
7412     END IF;
7413 
7414 
7415     -- For Test/Debug
7416     Check_And_Open_Debug_Session(p_debug, p_output_dir, p_debug_filename) ;
7417     -- R12 Comment out
7418     -- IF FND_API.to_Boolean( p_debug ) THEN
7419     --     Open_Debug_Session(p_output_dir, p_debug_filename ) ;
7420     -- END IF;
7421 
7422     -- Write debug message if debug mode is on
7423     IF g_debug_flag THEN
7424        Write_Debug('ENG_CHANGE_LIFECYCLE_UTIL.Update_RevItem_Lifecycle log');
7425        Write_Debug('-----------------------------------------------------');
7426        Write_Debug('p_rev_item_seq_id   : ' || p_rev_item_seq_id );
7427        Write_Debug('p_status_type       : ' || p_status_type );
7428        Write_Debug('-----------------------------------------------------');
7429        Write_Debug('Initializing return status... ' );
7430     END IF;
7431 
7432     -- Initialize API return status to success
7433     x_return_status := FND_API.G_RET_STS_SUCCESS;
7434 
7435     -- FND_PROFILE package is not available for workflow (WF),
7436     -- therefore manually set WHO column values
7437     IF p_api_caller = 'WF' THEN
7438       l_fnd_user_id := G_ENG_WF_USER_ID;
7439       l_fnd_login_id := G_ENG_WF_LOGIN_ID;
7440     ELSIF p_api_caller = 'CP' THEN
7441       l_fnd_user_id := G_ENG_CP_USER_ID;
7442       l_fnd_login_id := G_ENG_CP_LOGIN_ID;
7443     END IF;
7444 
7445 
7446     -- Real code starts here -----------------------------------------------
7447     UPDATE eng_revised_items
7448       SET status_type = p_status_type,
7449           last_update_date = sysdate,
7450           last_updated_by = l_fnd_user_id,
7451           last_update_login = l_fnd_login_id
7452       WHERE revised_item_sequence_id = p_rev_item_seq_id;
7453 
7454 
7455     -- Standard ending code ------------------------------------------------
7456     IF FND_API.To_Boolean ( p_commit ) THEN
7457       COMMIT WORK;
7458     END IF;
7459 
7460     FND_MSG_PUB.Count_And_Get
7461     ( p_count        =>      x_msg_count,
7462       p_data         =>      x_msg_data );
7463 
7464     IF g_debug_flag THEN
7465       Write_Debug('Finish. End Of procedure: Update_RevItem_Lifecycle') ;
7466     END IF;
7467 
7468     IF FND_API.to_Boolean( p_debug ) THEN
7469       Close_Debug_Session;
7470     END IF;
7471 
7472   EXCEPTION
7473     WHEN FND_API.G_EXC_ERROR THEN
7474       --ROLLBACK TO Update_RevItem_Lifecycle;
7475       x_return_status := FND_API.G_RET_STS_ERROR;
7476       FND_MSG_PUB.Count_And_Get
7477       ( p_count        =>      x_msg_count
7478        ,p_data         =>      x_msg_data );
7479       IF g_debug_flag THEN
7480         Write_Debug('Rollback and Finish with expected error.') ;
7481       END IF;
7482       IF FND_API.to_Boolean( p_debug ) THEN
7483         Close_Debug_Session;
7484       END IF;
7485     WHEN FND_API.G_EXC_UNEXPECTED_ERROR THEN
7486       --ROLLBACK TO Update_RevItem_Lifecycle;
7487       x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
7488       FND_MSG_PUB.Count_And_Get
7489       ( p_count        =>      x_msg_count
7490        ,p_data         =>      x_msg_data );
7491       IF g_debug_flag THEN
7492         Write_Debug('Rollback and Finish with unexpected error.') ;
7493       END IF;
7494       IF FND_API.to_Boolean( p_debug ) THEN
7495         Close_Debug_Session;
7496       END IF;
7497     WHEN OTHERS THEN
7498       --ROLLBACK TO Update_RevItem_Lifecycle;
7499       x_return_status := FND_API.G_RET_STS_UNEXP_ERROR ;
7500       IF FND_MSG_PUB.Check_Msg_Level ( FND_MSG_PUB.G_MSG_LVL_UNEXP_ERROR )
7501       THEN
7502         FND_MSG_PUB.Add_Exc_Msg (  G_PKG_NAME, l_api_name );
7503       END IF;
7504       FND_MSG_PUB.Count_And_Get
7505       ( p_count        =>      x_msg_count
7506        ,p_data         =>      x_msg_data );
7507       IF g_debug_flag THEN
7508         Write_Debug('Rollback and Finish with other error.') ;
7509       END IF;
7510       IF FND_API.to_Boolean( p_debug ) THEN
7511         Close_Debug_Session;
7512       END IF;
7513 
7514   END Update_RevItem_Lifecycle;
7515 
7516 
7517 
7518   -- R12B Reset Phase
7519   -- Reset Phase
7520   -- R12B
7521   -- Called when Reset Workflow button pressed in Workflow UI
7522   -- to reset Dcoument Status
7523   -- If Change Object is Document LC Object, Call Document API to reset the phase
7524   PROCEDURE Reset_Phase
7525   (
7526     p_api_version               IN   NUMBER                             --
7527    ,p_init_msg_list             IN   VARCHAR2 := FND_API.G_FALSE        --
7528    ,p_commit                    IN   VARCHAR2 := FND_API.G_FALSE        --
7529    ,p_validation_level          IN   NUMBER   := FND_API.G_VALID_LEVEL_FULL
7530    ,p_debug                     IN   VARCHAR2 := FND_API.G_FALSE        --
7531    ,p_output_dir                IN   VARCHAR2 := NULL
7532    ,p_debug_filename            IN   VARCHAR2 := NULL
7533    ,x_return_status             OUT  NOCOPY  VARCHAR2                   --
7534    ,x_msg_count                 OUT  NOCOPY  NUMBER                     --
7535    ,x_msg_data                  OUT  NOCOPY  VARCHAR2                   --
7536    ,p_change_id                 IN   NUMBER                             -- header's change_id
7537    ,p_status_code               IN   NUMBER   := NULL                   -- reset phase/status code
7538    ,p_api_caller                IN   VARCHAR2 := NULL                   -- can also be 'WF'
7539   )
7540   IS
7541 
7542     l_api_name           CONSTANT VARCHAR2(30)  := 'Reset_Phase';
7543     l_api_version        CONSTANT NUMBER := 1.0;
7544 
7545     l_fnd_user_id        NUMBER := TO_NUMBER(FND_PROFILE.VALUE('USER_ID'));
7546     l_fnd_login_id       NUMBER := TO_NUMBER(FND_PROFILE.VALUE('LOGIN_ID'));
7547 
7548     l_return_status      VARCHAR2(1);
7549     l_msg_count          NUMBER;
7550     l_msg_data           VARCHAR2(2000);
7551 
7552     l_doc_lc_object_flag  BOOLEAN := FALSE ;
7553 
7554     l_cm_type_code       eng_engineering_changes.CHANGE_MGMT_TYPE_CODE%TYPE;
7555     l_base_cm_type_code  eng_change_order_types.BASE_CHANGE_MGMT_TYPE_CODE%TYPE;
7556 
7557     l_next_status_code   NUMBER;
7558     l_reset_status_code  NUMBER;
7559     l_last_status_code   NUMBER;
7560     l_max_phase_sn       eng_lifecycle_statuses.sequence_number%TYPE;
7561     l_curr_status_type   eng_engineering_changes.status_type%TYPE;
7562 
7563     -- l_last_imp_flag      VARCHAR2(1) := 'N';
7564 
7565 
7566     -- Query the required parameters for current status
7567     -- Get the current phase, promote_phase and cm type of the change header
7568     CURSOR  c_cur_status (c_change_id NUMBER )
7569     IS
7570         SELECT eec.status_code
7571              , eec.promote_status_code
7572              , eec.change_mgmt_type_code
7573              , ecot.base_change_mgmt_type_code
7574           FROM eng_engineering_changes eec,
7575                eng_change_order_types ecot
7576           WHERE eec.change_id = c_change_id
7577             AND ecot.change_order_type_id = eec.change_order_type_id ;
7578 
7579 
7580     recinfo c_cur_status%rowtype;
7581 
7582 
7583   BEGIN
7584 
7585     -- Standard Start of API savepoint
7586     SAVEPOINT Reset_Phase ;
7587     -- Standard call to check for call compatibility
7588     IF NOT FND_API.Compatible_API_Call ( l_api_version
7589                                         ,p_api_version
7590                                         ,l_api_name
7591                                         ,G_PKG_NAME )
7592     THEN
7593       RAISE FND_API.G_EXC_UNEXPECTED_ERROR;
7594     END IF;
7595 
7596     -- Initialize message list if p_init_msg_list is set to TRUE.
7597     IF FND_API.to_Boolean( p_init_msg_list ) THEN
7598        FND_MSG_PUB.initialize;
7599     END IF;
7600 
7601 
7602     -- For Test/Debug
7603     Check_And_Open_Debug_Session(p_debug, p_output_dir, p_debug_filename) ;
7604 
7605 
7606     -- Write debug message if debug mode is on
7607     IF g_debug_flag THEN
7608        Write_Debug('ENG_CHANGE_LIFECYCLE_UTIL.Reset_Phase log');
7609        Write_Debug('-----------------------------------------------------');
7610        Write_Debug('p_change_id         : ' || to_char(p_change_id) );
7611        Write_Debug('p_status_code       : ' || to_char(p_status_code) );
7612        Write_Debug('p_api_caller        : ' || p_api_caller );
7613        Write_Debug('-----------------------------------------------------');
7614        Write_Debug('Initializing return status... ' );
7615     END IF;
7616 
7617     -- Initialize API return status to success
7618     x_return_status := FND_API.G_RET_STS_SUCCESS;
7619 
7620     -- FND_PROFILE package is not available for workflow (WF),
7621     -- therefore manually set WHO column values
7622     IF p_api_caller = 'WF' THEN
7623       l_fnd_user_id := G_ENG_WF_USER_ID;
7624       l_fnd_login_id := G_ENG_WF_LOGIN_ID;
7625     ELSIF p_api_caller = 'CP' THEN
7626       l_fnd_user_id := G_ENG_CP_USER_ID;
7627       l_fnd_login_id := G_ENG_CP_LOGIN_ID;
7628     END IF;
7629 
7630     -- Real code starts here -----------------------------------------------
7631 
7632 
7633 IF g_debug_flag THEN
7634     Write_Debug('Get the current status code to be reset ');
7635 END IF;
7636 
7637     OPEN c_cur_status(c_change_id => p_change_id) ;
7638     FETCH c_cur_status into recinfo ;
7639     IF (c_cur_status%notfound) THEN
7640        CLOSE c_cur_status;
7641        RAISE no_data_found;
7642     END IF;
7643 
7644     IF (c_cur_status%ISOPEN) THEN
7645        CLOSE c_cur_status ;
7646     END IF ;
7647 
7648     l_reset_status_code := recinfo.status_code ;
7649     l_next_status_code  := recinfo.promote_status_code ;
7650     l_cm_type_code      := recinfo.change_mgmt_type_code ;
7651     l_base_cm_type_code := recinfo.base_change_mgmt_type_code ;
7652 
7653     IF g_debug_flag THEN
7654         Write_Debug('Got current status code : ' || to_char(l_reset_status_code) );
7655     END IF;
7656 
7657     IF l_reset_status_code IS NULL THEN
7658         -- This should not happen
7659         FND_MESSAGE.SET_NAME('ENG', 'ENG_STATUS_CODE_NULL') ;
7660         FND_MSG_PUB.Add ;
7661         RAISE FND_API.G_EXC_ERROR ;
7662     END IF ;
7663 
7664     IF (p_status_code IS NOT NULL AND l_reset_status_code <> p_status_code )
7665     THEN
7666 
7667         -- This should not happen
7668         FND_MESSAGE.SET_NAME('ENG', 'ENG_RESET_STATUS_NOT_CUR') ;
7669         FND_MSG_PUB.Add ;
7670         RAISE FND_API.G_EXC_ERROR ;
7671 
7672     END IF ;
7673 
7674     -- Get the current phase status_type
7675     SELECT status_type
7676       INTO l_curr_status_type
7677       FROM eng_change_statuses
7678       WHERE status_code = l_reset_status_code;
7679 
7680     --
7681     -- Get the current phase's sequence number
7682     -- SELECT sequence_number
7683     --   INTO l_curr_phase_sn
7684     --   FROM eng_lifecycle_statuses
7685     --   WHERE entity_name = G_ENG_CHANGE
7686     --     AND entity_id1 = p_change_id
7687     --     AND status_code = l_reset_status_code
7688     --     AND active_flag = 'Y'
7689     --     AND rownum = 1;
7690     --
7691 
7692     -- Check if the current phase is of type APPROVAL,
7693     -- and if it is the last such phase in the lifecycle of the change header
7694     --
7695     IF (l_curr_status_type in (G_ENG_APPROVED ,G_ENG_REVIEWED))
7696     THEN
7697 
7698 IF g_debug_flag THEN
7699     Write_Debug('Current phase is of type APPROVAL...');
7700 END IF;
7701         -- if l_curr_status_type <> 12
7702          --THEN
7703           -- Update change header approval status
7704           -- Launch header approval status change workflow
7705           Update_Header_Appr_Status
7706           (
7707             p_api_version               =>  1.0
7708            ,p_init_msg_list             =>  FND_API.G_FALSE
7709            ,p_commit                    =>  FND_API.G_FALSE
7710            ,p_validation_level          =>  FND_API.G_VALID_LEVEL_FULL
7711            ,p_debug                     =>  FND_API.G_FALSE
7712            ,p_output_dir                =>  p_output_dir
7713            ,p_debug_filename            =>  p_debug_filename
7714            ,x_return_status             =>  l_return_status
7715            ,x_msg_count                 =>  l_msg_count
7716            ,x_msg_data                  =>  l_msg_data
7717            ,p_change_id                 =>  p_change_id
7718            ,p_status_code               =>  l_reset_status_code
7719            ,p_appr_status               =>  G_ENG_APPR_REQUESTED
7720            ,p_route_status              =>  Eng_Workflow_Util.G_RT_NOT_STARTED
7721            ,p_api_caller                =>  p_api_caller
7722            ,p_bypass                    =>  'N'
7723           );
7724       /* ELSE
7725 
7726 
7727         ENG_DOCUMENT_UTIL.Update_Approval_Status
7728             ( p_api_version         => 1.0
7729              ,p_init_msg_list       => FND_API.G_FALSE
7730              ,p_commit              => FND_API.G_FALSE
7731              ,p_validation_level    => p_validation_level
7732              ,p_debug               => FND_API.G_FALSE
7733              ,p_output_dir          => p_output_dir
7734              ,p_debug_filename      => p_debug_filename
7735              ,x_return_status       => l_return_status     --
7736              ,x_msg_count           => l_msg_count         --
7737              ,x_msg_data            => l_msg_data          --
7738              ,p_change_id           => p_change_id         -- header's change_id
7739              ,p_approval_status     => G_ENG_APPR_REQUESTED-- header approval status
7740              ,p_wf_route_status     => Eng_Workflow_Util.G_RT_NOT_STARTED      -- workflow routing status (for document types)
7741              ,p_api_caller          => p_api_caller        -- Optionnal for future use
7742             );
7743       END IF;*/
7744 
7745 
7746 IF g_debug_flag THEN
7747     Write_Debug('After: Update_Header_Appr_Status: ' || l_return_status );
7748 END IF;
7749 
7750 
7751           IF ( l_return_status <>  FND_API.G_RET_STS_SUCCESS )
7752           THEN
7753             x_return_status := l_return_status;
7754             x_msg_count := l_msg_count;
7755             x_msg_data := l_msg_data;
7756             RAISE FND_API.G_EXC_ERROR;
7757           END IF;
7758 
7759           IF g_debug_flag THEN
7760             Write_Debug('After: calling Update_Header_Appr_Status');
7761           END IF;
7762 
7763     END IF; -- current status type is  G_ENG_APPROVED
7764 
7765     -- R12B
7766     -- In case of Document LC Change Object, call ENG_DOCUMENT_UTIL.Change_Doc_LC_Phase
7767     -- to validate and sync Document LC Phase
7768     l_doc_lc_object_flag := ENG_DOCUMENT_UTIL.Is_Dom_Document_Lifecycle
7769                                ( p_change_id => p_change_id
7770                                , p_base_change_mgmt_type_code => l_base_cm_type_code
7771                                )  ;
7772 
7773     IF (l_doc_lc_object_flag)
7774     THEN
7775         IF l_reset_status_code IS NULL
7776         THEN
7777 
7778             IF g_debug_flag THEN
7779                  Write_Debug('param p_status_code is null, get the current status code to be reset ');
7780             END IF;
7781 
7782             OPEN c_cur_status(c_change_id => p_change_id) ;
7783             FETCH c_cur_status into recinfo;
7784             IF (c_cur_status%notfound) THEN
7785                 CLOSE c_cur_status;
7786                 RAISE no_data_found;
7787 
7788             END IF;
7789 
7790             IF (c_cur_status%ISOPEN) THEN
7791                 CLOSE c_cur_status ;
7792             END IF ;
7793 
7794             l_reset_status_code := recinfo.status_code ;
7795 
7796             IF g_debug_flag THEN
7797                  Write_Debug('Got current status code : ' || to_char(l_reset_status_code) );
7798             END IF;
7799 
7800             IF l_reset_status_code IS NULL THEN
7801                 -- This should not happen
7802                 FND_MESSAGE.SET_NAME('ENG', 'ENG_STATUS_CODE_NULL') ;
7803                 FND_MSG_PUB.Add ;
7804                 RAISE FND_API.G_EXC_ERROR ;
7805             END IF ;
7806 
7807         END IF ;
7808 
7809         IF g_debug_flag THEN
7810              Write_Debug('Before: calling ENG_DOCUMENT_UTIL.Change_Doc_LC_Phase');
7811              Write_Debug('  Status Code= ' || to_char(l_reset_status_code));
7812         END IF;
7813 
7814         ENG_DOCUMENT_UTIL.Change_Doc_LC_Phase
7815         ( p_api_version         => 1.0
7816          ,p_init_msg_list       => FND_API.G_FALSE
7817          ,p_commit              => FND_API.G_FALSE
7818          ,p_validation_level    => p_validation_level
7819          ,p_debug               => FND_API.G_FALSE
7820          ,p_output_dir          => p_output_dir
7821          ,p_debug_filename      => p_debug_filename
7822          ,x_return_status       => l_return_status
7823          ,x_msg_count           => l_msg_count
7824          ,x_msg_data            => l_msg_data
7825          ,p_change_id           => p_change_id
7826          ,p_lc_phase_code       => l_reset_status_code
7827          ,p_action_type         => G_ENG_PROMOTE
7828          ,p_api_caller          => p_api_caller
7829         ) ;
7830 
7831         IF g_debug_flag THEN
7832             Write_Debug('After: calling ENG_DOCUMENT_UTIL.Change_Doc_LC_Phase: ' || l_return_status) ;
7833         END IF;
7834 
7835         IF ( l_return_status <>  FND_API.G_RET_STS_SUCCESS )
7836         THEN
7837             x_return_status := l_return_status;
7838             x_msg_count := l_msg_count;
7839             x_msg_data := l_msg_data;
7840             RAISE FND_API.G_EXC_ERROR;
7841         END IF;
7842 
7843         IF g_debug_flag THEN
7844              Write_Debug('Successful: ENG_DOCUMENT_UTIL.Change_Doc_LC_Phase');
7845         END IF;
7846 
7847     END IF ; -- if ( Change Object is Documet LC Object)
7848 
7849 
7850     -- Standard ending code ------------------------------------------------
7851     IF FND_API.To_Boolean ( p_commit ) THEN
7852       COMMIT WORK;
7853     END IF;
7854 
7855     FND_MSG_PUB.Count_And_Get
7856     ( p_count        =>      x_msg_count,
7857       p_data         =>      x_msg_data );
7858 
7859     IF g_debug_flag THEN
7860       Write_Debug('Finish. End Of procedure: Promote_Header');
7861     END IF;
7862 
7863     IF FND_API.to_Boolean( p_debug ) THEN
7864       Close_Debug_Session;
7865     END IF;
7866 
7867   EXCEPTION
7868     WHEN FND_API.G_EXC_ERROR THEN
7869       -- Standard check of p_commit.
7870       IF FND_API.To_Boolean( p_commit ) THEN
7871 IF g_debug_flag THEN
7872    Write_Debug('Rollback . . .') ;
7873 END IF ;
7874           ROLLBACK TO Reset_Phase ;
7875       END IF;
7876 
7877       x_return_status := FND_API.G_RET_STS_ERROR;
7878 
7879       FND_MSG_PUB.Count_And_Get
7880       ( p_count        =>      x_msg_count
7881        ,p_data         =>      x_msg_data );
7882 
7883       IF g_debug_flag THEN
7884         Write_Debug('Finish with expected error.') ;
7885       END IF;
7886 
7887       IF FND_API.to_Boolean( p_debug ) THEN
7888         Close_Debug_Session;
7889       END IF;
7890 
7891     WHEN FND_API.G_EXC_UNEXPECTED_ERROR THEN
7892 
7893       -- Standard check of p_commit.
7894       IF FND_API.To_Boolean( p_commit ) THEN
7895 IF g_debug_flag THEN
7896    Write_Debug('Rollback . . .') ;
7897 END IF ;
7898           ROLLBACK TO Reset_Phase ;
7899       END IF;
7900 
7901       x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
7902 
7903       FND_MSG_PUB.Count_And_Get
7904       ( p_count        =>      x_msg_count
7905        ,p_data         =>      x_msg_data );
7906 
7907       IF g_debug_flag THEN
7908         Write_Debug('Rollback and Finish with unexpected error.') ;
7909       END IF;
7910 
7911 
7912       IF FND_API.to_Boolean( p_debug ) THEN
7913         Close_Debug_Session;
7914       END IF;
7915 
7916 
7917     WHEN OTHERS THEN
7918 
7919       -- Standard check of p_commit.
7920       IF FND_API.To_Boolean( p_commit ) THEN
7921 IF g_debug_flag THEN
7922    Write_Debug('Rollback . . .') ;
7923 END IF ;
7924           ROLLBACK TO Reset_Phase ;
7925       END IF;
7926 
7927       x_return_status := FND_API.G_RET_STS_UNEXP_ERROR ;
7928 
7929       IF FND_MSG_PUB.Check_Msg_Level ( FND_MSG_PUB.G_MSG_LVL_UNEXP_ERROR )
7930       THEN
7931         FND_MSG_PUB.Add_Exc_Msg ( G_PKG_NAME, l_api_name );
7932       END IF;
7933 
7934       FND_MSG_PUB.Count_And_Get
7935       ( p_count        =>      x_msg_count
7936        ,p_data         =>      x_msg_data );
7937 
7938 
7939       IF g_debug_flag THEN
7940         Write_Debug('Finish with other error.') ;
7941       END IF;
7942 
7943       IF FND_API.to_Boolean( p_debug ) THEN
7944         Close_Debug_Session;
7945       END IF;
7946 
7947   END Reset_Phase ;
7948 
7949 
7950   --
7951   -- R12B Sync Workflow Statuses/Lifecycle Phases
7952   -- If a phase is added or removed in an existing lifecycle setup which is already being used by
7953   -- some change objects including document lc change objects  then the lifecycles of the change object
7954   --  would be affected as below:
7955   --
7956   --   1. Adding a Phase: For all Change Objects the lifecycle that is being updated,
7957   --      would get this newly added Phase, if they have not already gone past that phase.
7958   --      For Change Objects that are already past the phase, these will not be affected.
7959   --
7960   --   2. Removing a Phase: Similar to the addition, the removal of the phase would also happen only for those
7961   --      change objects that have not reached the Phase being removed.
7962   --      For Change Objects already past the Phase, will not be affected for history purposes.
7963   --      If a Change Object is in a Phase that is being removed, then it should not be affected.
7964   --
7965   --   3. Updating a Phase Property: Phase Property update will not be affected.
7966   --
7967   -- This API will support the above syncronization and be called when the user update the LC Phase Setup and
7968   -- confirm to go ahead with  reflecting the changes to existing lifecycles of the change object.
7969   --
7970   PROCEDURE Sync_LC_Phase_Setup
7971   (
7972     p_api_version               IN   NUMBER                             --
7973    ,p_init_msg_list             IN   VARCHAR2 := FND_API.G_FALSE        --
7974    ,p_commit                    IN   VARCHAR2 := FND_API.G_FALSE        --
7975    ,p_validation_level          IN   NUMBER   := FND_API.G_VALID_LEVEL_FULL
7976    ,p_debug                     IN   VARCHAR2 := FND_API.G_FALSE        --
7977    ,p_output_dir                IN   VARCHAR2 := NULL
7978    ,p_debug_filename            IN   VARCHAR2 := NULL
7979    ,x_return_status             OUT  NOCOPY  VARCHAR2                   --
7980    ,x_msg_count                 OUT  NOCOPY  NUMBER                     --
7981    ,x_msg_data                  OUT  NOCOPY  VARCHAR2                   --
7982    ,p_change_type_id            IN   NUMBER                             -- header's change_type_id
7983    ,p_api_caller                IN   VARCHAR2 := NULL                   -- Future Use
7984   )
7985   IS
7986 
7987     l_api_name           CONSTANT VARCHAR2(30)  := 'Sync_LC_Phase_Setup';
7988     l_api_version        CONSTANT NUMBER := 1.0;
7989 
7990     l_fnd_user_id        NUMBER := TO_NUMBER(FND_PROFILE.VALUE('USER_ID'));
7991     l_fnd_login_id       NUMBER := TO_NUMBER(FND_PROFILE.VALUE('LOGIN_ID'));
7992 
7993     l_return_status      VARCHAR2(1);
7994     l_msg_count          NUMBER;
7995     l_msg_data           VARCHAR2(2000);
7996 
7997     -- Cursor to Fetch all the life cycle Statuses for corresponding Type.
7998     CURSOR  c_lc_phase_setup (c_change_type_id NUMBER )
7999     IS
8000        SELECT CHANGE_LIFECYCLE_STATUS_ID
8001             , SEQUENCE_NUMBER
8002             , STATUS_CODE
8003             , AUTO_PROMOTE_STATUS
8004             , AUTO_DEMOTE_STATUS
8005             , CHANGE_EDITABLE_FLAG
8006             , CHANGE_WF_ROUTE_ID
8007             , ENTITY_ID1 CHANGE_TYPE_ID
8008       FROM eng_lifecycle_statuses
8009       WHERE entity_name = 'ENG_CHANGE_TYPE'
8010       AND entity_id1 = c_change_type_id
8011       ORDER BY SEQUENCE_NUMBER ASC ;
8012 
8013     l_return_status       VARCHAR2(1);
8014     l_err_text            VARCHAR2(2000) ;
8015     l_Mesg_Token_Tbl      Error_Handler.Mesg_Token_Tbl_Type ;
8016 
8017 
8018   BEGIN
8019 
8020     -- Standard Start of API savepoint
8021     SAVEPOINT Sync_LC_Phase_Setup ;
8022     -- Standard call to check for call compatibility
8023     IF NOT FND_API.Compatible_API_Call ( l_api_version
8024                                         ,p_api_version
8025                                         ,l_api_name
8026                                         ,G_PKG_NAME )
8027     THEN
8028       RAISE FND_API.G_EXC_UNEXPECTED_ERROR;
8029     END IF;
8030 
8031     -- Initialize message list if p_init_msg_list is set to TRUE.
8032     IF FND_API.to_Boolean( p_init_msg_list ) THEN
8033        FND_MSG_PUB.initialize;
8034     END IF;
8035 
8036 
8037     -- For Test/Debug
8038     Check_And_Open_Debug_Session(p_debug, p_output_dir, p_debug_filename) ;
8039 
8040     -- Write debug message if debug mode is on
8041     IF g_debug_flag THEN
8042        Write_Debug('ENG_CHANGE_LIFECYCLE_UTIL.Sync_LC_Phase_Setup log');
8043        Write_Debug('-----------------------------------------------------');
8044        Write_Debug('p_change_type_id    : ' || to_char(p_change_type_id));
8045        Write_Debug('p_api_caller        : ' || p_api_caller );
8046        Write_Debug('-----------------------------------------------------');
8047        Write_Debug('Initializing return status... ' );
8048     END IF;
8049 
8050     -- Initialize API return status to success
8051     x_return_status := FND_API.G_RET_STS_SUCCESS;
8052 
8053     -- FND_PROFILE package is not available for workflow (WF),
8054     -- therefore manually set WHO column values
8055     IF p_api_caller = 'WF' THEN
8056       l_fnd_user_id := G_ENG_WF_USER_ID;
8057       l_fnd_login_id := G_ENG_WF_LOGIN_ID;
8058     ELSIF p_api_caller = 'CP' THEN
8059       l_fnd_user_id := G_ENG_CP_USER_ID;
8060       l_fnd_login_id := G_ENG_CP_LOGIN_ID;
8061     END IF;
8062 
8063     -- Real code starts here -----------------------------------------------
8064 
8065     -------------------------------------------------------------------------------------------
8066     --   1. Adding a Phase: For all Change Objects the lifecycle that is being updated,
8067     --      would get this newly added Phase, if they have not already gone past that phase.
8068     --      For Change Objects that are already past the phase, these will not be affected.
8069     -------------------------------------------------------------------------------------------
8070 
8071 
8072 IF g_debug_flag THEN
8073    Write_Debug(' Add LC Phase for submitted Change Objects . . .') ;
8074 END IF ;
8075 
8076         -- Insert the statuses data if it does not exists in change objects that have not gone past the phase
8077         -- and the phase does not exist in lifecycle of the change objects
8078         INSERT INTO ENG_LIFECYCLE_STATUSES
8079         (   CHANGE_LIFECYCLE_STATUS_ID
8080           , ENTITY_NAME
8081           , ENTITY_ID1
8082           , ENTITY_ID2
8083           , ENTITY_ID3
8084           , ENTITY_ID4
8085           , ENTITY_ID5
8086           , SEQUENCE_NUMBER
8087           , STATUS_CODE
8088           , START_DATE
8089           , COMPLETION_DATE
8090           , CHANGE_WF_ROUTE_ID
8091           , AUTO_PROMOTE_STATUS
8092           , AUTO_DEMOTE_STATUS
8093           , WORKFLOW_STATUS
8094           , CHANGE_EDITABLE_FLAG
8095           , CREATION_DATE
8096           , CREATED_BY
8097           , LAST_UPDATE_DATE
8098           , LAST_UPDATED_BY
8099           , LAST_UPDATE_LOGIN
8100           , ITERATION_NUMBER
8101           , ACTIVE_FLAG
8102           , CHANGE_WF_ROUTE_TEMPLATE_ID
8103         )
8104         SELECT
8105             ENG_LIFECYCLE_STATUSES_S.NEXTVAL
8106           , G_ENG_CHANGE
8107           , ch.CHANGE_ID
8108           , NULL -- ENTITY_ID2
8109           , NULL -- ENTITY_ID3
8110           , NULL -- ENTITY_ID4
8111           , NULL -- ENTITY_ID5
8112           , change_type.SEQUENCE_NUMBER
8113           , change_type.STATUS_CODE
8114           , NULL -- START_DATE
8115           , NULL -- COMPLETION_DATE
8116           , NULL -- CHANGE_WF_ROUTE_ID
8117           , change_type.AUTO_PROMOTE_STATUS
8118           , change_type.AUTO_DEMOTE_STATUS
8119           , NULL -- WORKFLOW_STATUS
8120           , change_type.CHANGE_EDITABLE_FLAG
8121           , SYSDATE
8122           , l_fnd_user_id
8123           , SYSDATE
8124           , l_fnd_user_id
8125           , l_fnd_login_id
8126           , cur_phase.ITERATION_NUMBER
8127           , 'S'
8128           , change_type.CHANGE_WF_ROUTE_ID
8129         FROM ENG_ENGINEERING_CHANGES ch
8130            , ENG_LIFECYCLE_STATUSES cur_phase
8131            , ENG_LIFECYCLE_STATUSES change_type
8132         WHERE change_type.entity_id1 = p_change_type_id
8133          AND change_type.entity_name = 'ENG_CHANGE_TYPE'
8134          AND ch.CHANGE_ORDER_TYPE_ID = change_type.entity_id1
8135          AND ch.STATUS_TYPE NOT IN (0, 5, 6, 11) -- exclude draft, cancel, implemented, completed
8136          AND ch.plm_or_erp_change = 'PLM'
8137          AND cur_phase.entity_name  = G_ENG_CHANGE
8138          AND cur_phase.entity_id1   = ch.CHANGE_ID
8139          AND cur_phase.active_flag  = 'Y'
8140          AND cur_phase.status_code  = ch.STATUS_CODE
8141          AND cur_phase.SEQUENCE_NUMBER < change_type.SEQUENCE_NUMBER
8142          AND NOT EXISTS ( SELECT 'exists'
8143                           FROM  ENG_LIFECYCLE_STATUSES change_lc_phase
8144                           WHERE change_lc_phase.entity_name  = G_ENG_CHANGE
8145                           AND   change_lc_phase.entity_id1   = ch.CHANGE_ID
8146                           AND   change_lc_phase.active_flag  = 'Y'
8147                           AND   change_lc_phase.status_code  = change_type.STATUS_CODE
8148                           AND   change_lc_phase.SEQUENCE_NUMBER = change_type.SEQUENCE_NUMBER
8149                         ) ;
8150 
8151 
8152 
8153 IF g_debug_flag THEN
8154    IF SQL%FOUND THEN
8155       Write_Debug(' Add LC Phase for Submitted Change Object:' || to_char(SQL%ROWCOUNT)) ;
8156    END IF ;
8157 END IF ;
8158 
8159 IF g_debug_flag THEN
8160    Write_Debug(' Add LC Phase for Draft Change Objects. . .') ;
8161 END IF ;
8162 
8163         -- Add LC Phase for Draft Change Objects
8164         INSERT INTO ENG_LIFECYCLE_STATUSES
8165         (   CHANGE_LIFECYCLE_STATUS_ID
8166           , ENTITY_NAME
8167           , ENTITY_ID1
8168           , ENTITY_ID2
8169           , ENTITY_ID3
8170           , ENTITY_ID4
8171           , ENTITY_ID5
8172           , SEQUENCE_NUMBER
8173           , STATUS_CODE
8174           , START_DATE
8175           , COMPLETION_DATE
8176           , CHANGE_WF_ROUTE_ID
8177           , AUTO_PROMOTE_STATUS
8178           , AUTO_DEMOTE_STATUS
8179           , WORKFLOW_STATUS
8180           , CHANGE_EDITABLE_FLAG
8181           , CREATION_DATE
8182           , CREATED_BY
8183           , LAST_UPDATE_DATE
8184           , LAST_UPDATED_BY
8185           , LAST_UPDATE_LOGIN
8186           , ITERATION_NUMBER
8187           , ACTIVE_FLAG
8188           , CHANGE_WF_ROUTE_TEMPLATE_ID
8189         )
8190         SELECT
8191             ENG_LIFECYCLE_STATUSES_S.NEXTVAL
8192           , G_ENG_CHANGE
8193           , ch.CHANGE_ID
8194           , NULL -- ENTITY_ID2
8195           , NULL -- ENTITY_ID3
8196           , NULL -- ENTITY_ID4
8197           , NULL -- ENTITY_ID5
8198           , change_type.SEQUENCE_NUMBER
8199           , change_type.STATUS_CODE
8200           , NULL -- START_DATE
8201           , NULL -- COMPLETION_DATE
8202           , NULL -- CHANGE_WF_ROUTE_ID
8203           , change_type.AUTO_PROMOTE_STATUS
8204           , change_type.AUTO_DEMOTE_STATUS
8205           , NULL -- WORKFLOW_STATUS
8206           , change_type.CHANGE_EDITABLE_FLAG
8207           , SYSDATE
8208           , l_fnd_user_id
8209           , SYSDATE
8210           , l_fnd_user_id
8211           , l_fnd_login_id
8212           , 0   -- ITERATION_NUMBER
8213           , 'S' -- ACTIVE_FLAG
8214           , change_type.CHANGE_WF_ROUTE_ID
8215         FROM ENG_ENGINEERING_CHANGES ch
8216            , ENG_LIFECYCLE_STATUSES change_type
8217         WHERE change_type.entity_id1 = p_change_type_id
8218          AND change_type.entity_name = 'ENG_CHANGE_TYPE'
8219          AND ch.CHANGE_ORDER_TYPE_ID = change_type.entity_id1
8220          AND ch.STATUS_CODE = 0 -- DRAFT
8221          AND NOT EXISTS ( SELECT 'exists'
8222                            FROM  ENG_LIFECYCLE_STATUSES change_lc_phase
8223                            WHERE change_lc_phase.entity_name  = G_ENG_CHANGE
8224                            AND   change_lc_phase.entity_id1   = ch.CHANGE_ID
8225                            AND   change_lc_phase.active_flag  = 'Y'
8226                            AND   change_lc_phase.status_code  = change_type.STATUS_CODE
8227                            AND   change_lc_phase.SEQUENCE_NUMBER = change_type.SEQUENCE_NUMBER
8228                          ) ;
8229 
8230 
8231 IF g_debug_flag THEN
8232    IF SQL%FOUND THEN
8233       Write_Debug(' Added LC Phase for Draft Change Objects:' || to_char(SQL%ROWCOUNT)) ;
8234    END IF ;
8235 END IF ;
8236 
8237 
8238 IF g_debug_flag THEN
8239    Write_Debug(' Add LC Phase Properties for reocrds for active_flag S. . .') ;
8240 END IF ;
8241 
8242         -- Add LC Phase Properties for reocrds for active_flag S
8243         -- Inserting the status properties
8244         INSERT INTO  ENG_STATUS_PROPERTIES
8245         (
8246             CHANGE_LIFECYCLE_STATUS_ID
8247           , STATUS_CODE
8248           , PROMOTION_STATUS_FLAG
8249           , CREATION_DATE
8250           , CREATED_BY
8251           , LAST_UPDATE_DATE
8252           , LAST_UPDATED_BY
8253           , LAST_UPDATE_LOGIN
8254         )
8255         SELECT
8256             lc_phase.CHANGE_LIFECYCLE_STATUS_ID
8257           , phase_prop_setup.STATUS_CODE
8258           , phase_prop_setup.PROMOTION_STATUS_FLAG
8259           , SYSDATE
8260           , l_fnd_user_id
8261           , SYSDATE
8262           , l_fnd_user_id
8263           , l_fnd_login_id
8264         FROM ENG_STATUS_PROPERTIES  phase_prop_setup
8265            , ENG_LIFECYCLE_STATUSES lc_phase_setup
8266            , ENG_LIFECYCLE_STATUSES lc_phase
8267            , ENG_ENGINEERING_CHANGES ch
8268         WHERE lc_phase_setup.entity_id1   = p_change_type_id
8269           AND lc_phase_setup.entity_name = 'ENG_CHANGE_TYPE'
8270           AND phase_prop_setup.CHANGE_LIFECYCLE_STATUS_ID = lc_phase_setup.CHANGE_LIFECYCLE_STATUS_ID
8271           AND ch.CHANGE_ORDER_TYPE_ID = lc_phase_setup.ENTITY_ID1
8272           AND ch.STATUS_TYPE NOT IN (5, 6, 11) -- exclude cancel, implemented, completed
8273           AND lc_phase.entity_name  = G_ENG_CHANGE
8274           AND lc_phase.entity_id1   = ch.CHANGE_ID
8275           AND lc_phase.SEQUENCE_NUMBER = lc_phase_setup.SEQUENCE_NUMBER
8276           AND lc_phase.STATUS_CODE = lc_phase_setup.STATUS_CODE
8277           AND lc_phase.ACTIVE_FLAG = 'S' ;
8278 
8279 
8280 IF g_debug_flag THEN
8281    IF SQL%FOUND THEN
8282       Write_Debug(' Added LC Phase Properties: ' || to_char(SQL%ROWCOUNT)) ;
8283    END IF ;
8284 END IF ;
8285 
8286 
8287 
8288 IF g_debug_flag THEN
8289    Write_Debug(' -------------------------------------------') ;
8290 END IF ;
8291 
8292     --
8293     --   2. Removing a Phase: Similar to the addition, the removal of the phase would also happen only for those
8294     --      change objects that have not reached the Phase being removed.
8295     --      For Change Objects already past the Phase, will not be affected for history purposes.
8296     --      If a Change Object is in a Phase that is being removed, then it should not be affected.
8297     --
8298     --   NOTE: Internally we hide the phase by changing active flag  to 'D'
8299     --
8300 
8301 IF g_debug_flag THEN
8302    Write_Debug(' Removing a Phase. . .') ;
8303 END IF ;
8304 
8305 
8306     UPDATE ENG_LIFECYCLE_STATUSES
8307     SET  ACTIVE_FLAG  = 'D'
8308     WHERE CHANGE_LIFECYCLE_STATUS_ID IN (
8309                                           SELECT change_phase.CHANGE_LIFECYCLE_STATUS_ID
8310                                           FROM ENG_ENGINEERING_CHANGES ch
8311                                              , ENG_LIFECYCLE_STATUSES cur_phase
8312                                              , ENG_LIFECYCLE_STATUSES change_phase
8313                                           WHERE ch.CHANGE_ORDER_TYPE_ID = p_change_type_id
8314                                           AND ch.STATUS_TYPE NOT IN (5, 6, 11) -- exclude cancel, implemented, completed
8315                                           AND cur_phase.entity_name  = G_ENG_CHANGE
8316                                           AND cur_phase.entity_id1   = ch.CHANGE_ID
8317                                           AND cur_phase.active_flag  = 'Y'
8318                                           AND cur_phase.status_code  = ch.STATUS_CODE
8319                                           AND cur_phase.SEQUENCE_NUMBER < change_phase.SEQUENCE_NUMBER
8320                                           AND change_phase.entity_name  = 'ENG_CHANGE'
8321                                           AND change_phase.entity_id1   = ch.CHANGE_ID
8322                                           AND change_phase.active_flag  = 'Y'
8323                                           AND NOT EXISTS ( SELECT 'exists'
8324                                                            FROM  eng_lifecycle_statuses lc_phase_setup
8325                                                            WHERE lc_phase_setup.entity_name  = 'ENG_CHANGE_TYPE'
8326                                                            AND   lc_phase_setup.entity_id1   = ch.CHANGE_ORDER_TYPE_ID
8327                                                            AND   lc_phase_setup.SEQUENCE_NUMBER = change_phase.SEQUENCE_NUMBER
8328                                                            AND   lc_phase_setup.STATUS_CODE = change_phase.STATUS_CODE
8329                                                           )
8330                                           UNION ALL
8331                                           SELECT change_phase.CHANGE_LIFECYCLE_STATUS_ID
8332                                           FROM   ENG_ENGINEERING_CHANGES ch
8333                                                , ENG_LIFECYCLE_STATUSES change_phase
8334                                           WHERE ch.CHANGE_ORDER_TYPE_ID = p_change_type_id
8335                                           AND ch.STATUS_CODE = 0 -- DRAFT
8336                                           AND ch.STATUS_TYPE NOT IN (5, 6, 11) -- exclude cancel, implemented, completed
8337                                           AND change_phase.entity_name  = G_ENG_CHANGE
8338                                           AND change_phase.entity_id1   = ch.CHANGE_ID
8339                                           AND change_phase.active_flag  = 'Y'
8340                                           AND NOT EXISTS ( SELECT 'exists'
8341                                                            FROM  eng_lifecycle_statuses lc_phase_setup
8342                                                            WHERE lc_phase_setup.entity_name  = 'ENG_CHANGE_TYPE'
8343                                                            AND   lc_phase_setup.entity_id1   = ch.CHANGE_ORDER_TYPE_ID
8344                                                            AND   lc_phase_setup.SEQUENCE_NUMBER = change_phase.SEQUENCE_NUMBER
8345                                                            AND   lc_phase_setup.STATUS_CODE = change_phase.STATUS_CODE
8346                                                          )
8347                                          ) ;
8348 
8349 
8350 
8351 IF g_debug_flag THEN
8352    IF SQL%FOUND THEN
8353       Write_Debug(' Removed Phases. . .' || to_char(SQL%ROWCOUNT)) ;
8354    END IF ;
8355 END IF ;
8356 
8357 
8358 IF g_debug_flag THEN
8359    Write_Debug(' Mass Update Change LC Phases marked as S to make them Activie. . .') ;
8360 END IF ;
8361 
8362     -- 3. Mass Update Change LC Phases marked as 'S' in the above process of syncronization of newly added phase.
8363     --  to make them Activie
8364     UPDATE ENG_LIFECYCLE_STATUSES lc_phase
8365     SET  lc_phase.ACTIVE_FLAG  = 'Y'
8366     WHERE lc_phase.CHANGE_LIFECYCLE_STATUS_ID IN (
8367                                           SELECT added_change_phase.CHANGE_LIFECYCLE_STATUS_ID
8368                                           FROM ENG_ENGINEERING_CHANGES ch
8369                                              , ENG_LIFECYCLE_STATUSES added_change_phase
8370                                           WHERE ch.CHANGE_ORDER_TYPE_ID = p_change_type_id
8371                                           AND ch.STATUS_TYPE NOT IN (5, 6, 11) -- exclude cancel, implemented, completed
8372                                           AND added_change_phase.entity_name  = G_ENG_CHANGE
8373                                           AND added_change_phase.entity_id1   = ch.CHANGE_ID
8374                                           AND added_change_phase.active_flag  = 'S'
8375                                          ) ;
8376 
8377 
8378 IF g_debug_flag THEN
8379    IF SQL%FOUND THEN
8380       Write_Debug(' Mass Update Change to make added phase active: ' || to_char(SQL%ROWCOUNT)) ;
8381    END IF ;
8382 END IF ;
8383 
8384 
8385 
8386     -- Standard ending code ------------------------------------------------
8387     IF FND_API.To_Boolean ( p_commit ) THEN
8388       COMMIT WORK;
8389     END IF;
8390 
8391     FND_MSG_PUB.Count_And_Get
8392     ( p_count        =>      x_msg_count,
8393       p_data         =>      x_msg_data );
8394 
8395     IF g_debug_flag THEN
8396       Write_Debug('Finish. End Of procedure: ' || l_api_name);
8397     END IF;
8398 
8399     IF FND_API.to_Boolean( p_debug ) THEN
8400       Close_Debug_Session;
8401     END IF;
8402 
8403   EXCEPTION
8404     WHEN FND_API.G_EXC_ERROR THEN
8405       -- Standard check of p_commit.
8406       IF FND_API.To_Boolean( p_commit ) THEN
8407 IF g_debug_flag THEN
8408    Write_Debug('Rollback . . .') ;
8409 END IF ;
8410           ROLLBACK TO Sync_LC_Phase_Setup ;
8411       END IF;
8412 
8413       x_return_status := FND_API.G_RET_STS_ERROR;
8414 
8415       FND_MSG_PUB.Count_And_Get
8416       ( p_count        =>      x_msg_count
8417        ,p_data         =>      x_msg_data );
8418 
8419       IF g_debug_flag THEN
8420         Write_Debug('Finish with expected error.') ;
8421       END IF;
8422 
8423       IF FND_API.to_Boolean( p_debug ) THEN
8424         Close_Debug_Session;
8425       END IF;
8426 
8427     WHEN FND_API.G_EXC_UNEXPECTED_ERROR THEN
8428 
8429       -- Standard check of p_commit.
8430       IF FND_API.To_Boolean( p_commit ) THEN
8431 IF g_debug_flag THEN
8432    Write_Debug('Rollback . . .') ;
8433 END IF ;
8434           ROLLBACK TO Sync_LC_Phase_Setup ;
8435       END IF;
8436 
8437       x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
8438 
8439       FND_MSG_PUB.Count_And_Get
8440       ( p_count        =>      x_msg_count
8441        ,p_data         =>      x_msg_data );
8442 
8443       IF g_debug_flag THEN
8444         Write_Debug('Rollback and Finish with unexpected error.') ;
8445       END IF;
8446 
8447 
8448       IF FND_API.to_Boolean( p_debug ) THEN
8449         Close_Debug_Session;
8450       END IF;
8451 
8452 
8453     WHEN OTHERS THEN
8454 
8455       -- Standard check of p_commit.
8456       IF FND_API.To_Boolean( p_commit ) THEN
8457 IF g_debug_flag THEN
8458    Write_Debug('Rollback . . .') ;
8459 END IF ;
8460           ROLLBACK TO Sync_LC_Phase_Setup ;
8461       END IF;
8462 
8463       x_return_status := FND_API.G_RET_STS_UNEXP_ERROR ;
8464 
8465       IF FND_MSG_PUB.Check_Msg_Level ( FND_MSG_PUB.G_MSG_LVL_UNEXP_ERROR )
8466       THEN
8467         FND_MSG_PUB.Add_Exc_Msg ( G_PKG_NAME, l_api_name );
8468       END IF;
8469 
8470       FND_MSG_PUB.Count_And_Get
8471       ( p_count        =>      x_msg_count
8472        ,p_data         =>      x_msg_data );
8473 
8474 
8475       IF g_debug_flag THEN
8476         Write_Debug('Finish with other error.') ;
8477       END IF;
8478 
8479       IF FND_API.to_Boolean( p_debug ) THEN
8480         Close_Debug_Session;
8481       END IF;
8482 
8483   END Sync_LC_Phase_Setup ;
8484 
8485 
8486 END ENG_CHANGE_LIFECYCLE_UTIL;
8487