DBA Data[Home] [Help]

PACKAGE BODY: APPS.MSC_CL_GMP_UTILITY

Source


1 PACKAGE BODY MSC_CL_GMP_UTILITY as --body
2  /* $Header: MSCCLGMB.pls 120.4.12020000.3 2013/04/05 09:33:52 vkinduri ship $ */
3 
4           /*======== GLOBAL OPM Data Collection Declaration =========*/
5 
6 TYPE  ref_cursor_typ is REF CURSOR;
7 
8 routing_dtl_cursor      VARCHAR2(32700) := NULL;
9 validation_statement    VARCHAR2(32700) := NULL;
10 invalid_string_value      EXCEPTION;
11 invalid_gmp_uom_profile   EXCEPTION;
12 stmt_no                   NUMBER := 0;
13 s		                  INTEGER := 1;
14 p_location                VARCHAR2(300) := NULL;
15 g_aps_eff_id              NUMBER     := 0;  /* Global Aps Effectivity ID */
16 aps_fmeff_id              NUMBER     := 0 ; /* Generated effectivity Id */
17 x_aps_fmeff_id            NUMBER     := 0 ; /* encoded effectivity Id */
18 g_fm_dtl_start_loc        INTEGER := 0; /* Start detail location */
19 g_fm_dtl_end_loc          INTEGER := 0;  /* End detail location */
20 g_fm_hdr_loc              INTEGER := 1;  /* Starting for formula header */
21 g_formula_orgn_count_tab  INTEGER := 1;  /* Starting for formula orgn detail */
22 g_rstep_loc	 	  INTEGER := 1 ;  /* global rtg offset location */
23 g_curr_rstep_loc	  NUMBER  := -1 ; /* current r step offsetp locn */
24 g_prev_formula_id 	  NUMBER := -1 ;
25 g_prev_locn 		  NUMBER := 1;
26 g_dep_index               NUMBER := 1;
27 alt_rsrc_size             INTEGER;  /* Number of Alternate resources for BOM */
28 formula_headers_size      INTEGER;  /* Number of rows in formula_headers */
29 fd_size      INTEGER;  /* Number of rows in formula_details */
30 formula_orgn_size  	  INTEGER;  /* Number of detail rows for formula */
31 routing_headers_size      INTEGER;  /* Number of rows in routing_headers */
32 rtg_org_dtl_size      	  INTEGER;  /* Number of rows in routing_org_details */
33 rtg_gen_dtl_size          INTEGER;  /* Number of rows in generic routing_det */
34 material_assocs_size      INTEGER;  /* Number of rows in material_assocs */
35 setup_size                INTEGER;  /* Number of rows in Seq Dep Cursor */
36 opr_stpdep_size           INTEGER := 1;  /* Number of rows in step dependency */
37 recipe_orgn_over_size     INTEGER;  /* No. of rows in recipe orgn override */
38 recipe_override_size      INTEGER;  /* Number of rows in recipe override */
39 rtg_offsets_size 	  INTEGER := 1;  /* Number of rows in rtg offsets tbl */
40 current_date_time         DATE;	    /* For consistency writes */
41 b_instance_id             INTEGER;
42 delimiter                 VARCHAR2(1);  /* Used when filling in comment columns on BOM and ROUTING Tables */
43 l_in_str_org              VARCHAR2(32767) := null ;   /* B3491625 */
44 at_apps_link              VARCHAR2(31); /* Database link to APPS server from Planning server  */
45 g_instance_id             NUMBER;       /* Instance Id from Planning server  */
46 g_mat_assoc               INTEGER;  /* Glabal counter for materail assiciation */
47 g_gmp_uom_class           VARCHAR2(10); /* UOM Class */
48 g_setup_id                NUMBER; /* hold he last setup_id */
49 sd_index                  INTEGER := 0 ;
50 /* These variables store the MTQ related values that is last inserted. */
51 g_old_formula_id          NUMBER ; /* B3970993 */
52 g_old_recipe_id           NUMBER ; /* B3970993 */
53 g_old_rtg_id              NUMBER ; /* B3970993 */
54 g_old_rtgstep_id          NUMBER ; /* B3970993 */
55 g_old_aps_item_id         NUMBER ; /* B3970993 */
56 g_mtq_loc                 NUMBER ; /* B3970993 */
57 g_min_mtq                 NUMBER ; /* B3970993 */
58 
59 desig_count		  NUMBER  := 0;
60 gfcst_cnt		  NUMBER  := 0;
61 gso_cnt		          NUMBER  := 0;
62 gschd_fcst_cnt	          NUMBER  := 0;
63 gitem_size		  NUMBER  := 0;
64 gfcst_size		  NUMBER  := 0;
65 gso_size		  NUMBER  := 0;
66 gschd_fcst_size	          NUMBER  := 0;
67 g_item_tbl_position	  NUMBER  := 0;
68 gcurrent_designator	  VARCHAR2(10) := NULL;
69 g_delimiter               VARCHAR2(4) := '/' ;
70 gprod_size                NUMBER  := 0;
71 grsrc_size                NUMBER  := 0;
72 gonhand_balance_size      NUMBER  := 0; -- akaruppa B4287033
73 g_rsrc_cnt                INTEGER ;
74 stp_chg_num               NUMBER  ;
75 stp_chg_cursor            VARCHAR2(32700);
76 statement_alt_resource    VARCHAR2(32700):= NULL;
77 alt_prod_size             INTEGER;  /* NAVIN :- : Number of rows in Alternate Resource */
78 /* Sowmya - As per the latest FDD changes */
79 l_res_inst_process        NUMBER;
80 /*-------------------------- Operation Charges-----------------------------*/
81 v_orgn_id                      NUMBER;
82 r                              NUMBER;
83 p                              NUMBER ;
84 chg_res_index                  NUMBER; /* NAVIN :- Resource Charges */
85 resource_usage_flag            NUMBER;
86 resource_instance_usage_flag   NUMBER;
87 old_rsrc_batch_id              NUMBER;
88 old_rsrc_resources             VARCHAR2(16);
89 old_rsrc_original_seq_num      NUMBER;
90 old_instance_number            NUMBER;
91 old_rsrc_inst_batch_id         NUMBER;
92 old_rsrc_inst_resources        VARCHAR2(16);
93 old_rsrc_inst_original_seq_num NUMBER;
94 V_FROM_RSRC                    VARCHAR2(16) ;
95 V_TO_RSRC                      VARCHAR2(16) ;
96 
97 TYPE gmp_buffer_typ IS RECORD
98 (
99   fmeff_id            PLS_INTEGER,  /* OPM Effectivity ID         */
100   aps_fmeff_id        PLS_INTEGER,  /* APS Effectivity ID - B2989806  */
101   item_id             PLS_INTEGER,  /* OPM Effectivity Item ID    */
102   formula_id          PLS_INTEGER,  /* Formula ID                 */
103   plant_code          VARCHAR2(4), /* Effectivity Orgn code      */
104   organization_id     PLS_INTEGER    ,  /* ID for the Plant           */
105   start_date          DATE,        /* Effectivity Start Date     */
106   end_date            DATE,        /* Effectivity End Date       */
107   inv_min_qty         NUMBER,      /* Effectivity Minimum Qty    */
108   inv_max_qty         NUMBER,      /* Effectivity Maximum Qty    */
109   preference          PLS_INTEGER,      /* Effectivity Preference     B3437281 */
110   primary_um          VARCHAR2(4), /* Primary UOM of the Item    */
111   whse_code           VARCHAR2(4), /* Resource or Material Whse  */
112   routing_id          PLS_INTEGER    ,  /* Routing ID. Could be NULL  */
113   routing_no          VARCHAR2(32),/* Associated Routing No      */
114   routing_vers        PLS_INTEGER   ,   /* Associated Routing Version */
115   routing_desc        VARCHAR2(70),/* Associated Routing DEsc'n  */
116   routing_um          VARCHAR2(4), /* UOM from the Routing       */
117   routing_qty         NUMBER,      /* Qty from the Routing       */
118   prod_factor         NUMBER, /*B2870041 factor to convert prod to rout um */
119   product_index       PLS_INTEGER, /*B2870041 index of the product line */
120   aps_item_id         PLS_INTEGER    ,  /* OPM Effective Aps Item ID    */
121   recipe_id           PLS_INTEGER,  /* 1830940 New GMD Changes Recipe ID */
122   recipe_no           VARCHAR2(32),   -- Biogen
123   recipe_version      PLS_INTEGER,    -- Biogen
124   rtg_hdr_location    PLS_INTEGER,   /* index link to routing header */
125 /* NAMIT_CR */
126   calculate_step_quantity NUMBER ,
127   category_id         PLS_INTEGER,  /* SGIDUGU */
128   setup_id            PLS_INTEGER,   /* SGIDUGU */
129   seq_dpnd_class      VARCHAR2(8)   /* SGIDUGU */
130 );
131 effectivity           gmp_buffer_typ;
132 -- primary_bom_formulaline_id  NUMBER     ; -- Bug # 4879588
133 
134 TYPE gmp_formula_header_typ IS RECORD
135 (
136   formula_id          PLS_INTEGER    ,
137   valid_flag          PLS_INTEGER   ,
138   start_dtl_loc       PLS_INTEGER    ,
139   end_dtl_loc         PLS_INTEGER    ,
140   total_output        NUMBER, /* B2870041 total output for all prod/byp */
141   total_um            VARCHAR2(4) /*B2870041 um used to calculate qty */
142 );
143 TYPE gmp_formula_header_tbl IS TABLE OF gmp_formula_header_typ
144 INDEX BY BINARY_INTEGER;
145 formula_header_tab        gmp_formula_header_tbl;
146 
147 TYPE gmp_formula_detail_typ IS RECORD
148 (
149   formula_id          PLS_INTEGER,
150   formula_no          VARCHAR2(32),
151   formula_vers        PLS_INTEGER,
152   formula_desc1       VARCHAR2(100),
153   x_formulaline_id    PLS_INTEGER,
154   line_type           PLS_INTEGER,
155   opm_item_id         PLS_INTEGER,
156   formula_qty         NUMBER,
157   scrap_factor        NUMBER,
158   scale_type          PLS_INTEGER,
159   contribute_yield_ind VARCHAR2(1),      /* B2657068 Rajesh Patangya */
160   contribute_step_qty_ind PLS_INTEGER,      /* NAMIT_ASQC */
161   phantom_type        PLS_INTEGER,
162   aps_um              VARCHAR2(3),
163   orig_um             VARCHAR2(4), /*B2870041 formula um */
164   primary_um          VARCHAR2(4), /* B2870041 item primary um */
165   bom_scale_type      PLS_INTEGER,
166   primary_qty         NUMBER,
167   aps_item_id         PLS_INTEGER,
168   scale_multiple      PLS_INTEGER,        /* B2657068 Rajesh Patangya */
169   scale_rounding_variance PLS_INTEGER,    /* B2657068 Rajesh Patangya */
170   rounding_direction  PLS_INTEGER,          /* B2657068 Rajesh Patangya */
171   release_type        PLS_INTEGER,
172    -- Bug: 6030499 Vpedarla added a few columns for item substituion
173   original_item_id    PLS_INTEGER, --PK
174   start_date          DATE,
175   end_date            DATE,
176   formula_line_id     PLS_INTEGER, --PK
177   preference          PLS_INTEGER, --PK
178   actual_end_date     DATE,
179   actual_end_flag     PLS_INTEGER,
180   sub_original_qty 	NUMBER,
181  -- sub_replace_qty 	NUMBER,  venu
182  -- replacement_uom 	VARCHAR2(4),  venu
183   original_item_flag  PLS_INTEGER,
184   formulaline_id      PLS_INTEGER
185 );
186 
187 TYPE gmp_formula_detail_tbl IS TABLE OF gmp_formula_detail_typ
188 INDEX by BINARY_INTEGER;
189 formula_detail_tab   gmp_formula_detail_tbl ;
190 
191 /* Bug:5872693 Vpedarla start 12-Feb-2007 */
192 prev_detail_tab                   gmp_formula_detail_tbl ;
193 orig_detail_tab                   gmp_formula_detail_tbl ;
194 temp_detail_tab                   gmp_formula_detail_tbl ;
195 subst_tab                         gmp_formula_detail_tbl ;
196 /* Bug:5872693 Vpedarla end 12-Feb-2007 */
197 
198 TYPE gmp_formula_detail_count_typ IS RECORD
199 (
200   formula_id          PLS_INTEGER    ,
201   formula_dtl_count   PLS_INTEGER
202 );
203 TYPE gmp_formula_detail_count_tbl IS TABLE OF gmp_formula_detail_count_typ
204 INDEX BY BINARY_INTEGER;
205 formula_dtl_count_rec     gmp_formula_detail_count_typ ;
206 
207 TYPE gmp_formula_orgn_count_typ IS RECORD
208 (
209   formula_id          PLS_INTEGER    ,
210   plant_code          VARCHAR2(4),
211   organization_id     PLS_INTEGER    ,
212   orgn_count          PLS_INTEGER    ,  /* Count of formula details */
213   valid_flag          PLS_INTEGER
214 );
215 TYPE gmp_formula_orgn_count_tbl IS TABLE OF gmp_formula_orgn_count_typ
216 INDEX BY BINARY_INTEGER;
217 formula_orgn_count_tab  gmp_formula_orgn_count_tbl;
218 
219 TYPE gmp_routing_header_typ IS RECORD
220 (
221   routing_id          PLS_INTEGER    ,
222   plant_code          VARCHAR2(4),
223   valid_flag          PLS_INTEGER   ,
224   generic_start_loc   PLS_INTEGER    ,
225   generic_end_loc     PLS_INTEGER    ,
226   orgn_start_loc      PLS_INTEGER    ,
227   orgn_end_loc        PLS_INTEGER    ,
228   step_start_loc      PLS_INTEGER    ,
229   step_end_loc        PLS_INTEGER    ,
230   usage_start_loc     PLS_INTEGER    ,
231   usage_end_loc       PLS_INTEGER    ,
232   stpdep_start_loc    PLS_INTEGER    ,
233   stpdep_end_loc      PLS_INTEGER
234 );
235 TYPE gmp_routing_header_tbl IS TABLE OF gmp_routing_header_typ
236 INDEX BY BINARY_INTEGER;
237 rtg_org_hdr_tab      gmp_routing_header_tbl;
238 
239 TYPE gmp_routing_detail_typ IS RECORD
240 (
241   routing_id          PLS_INTEGER    ,
242   orgn_code           VARCHAR2(4),
243   routingstep_no      PLS_INTEGER   ,
244   seq_dep_ind         PLS_INTEGER, /*B2870041 sequence dependent indicator */
245   prim_rsrc_ind_order PLS_INTEGER,
246   resources           VARCHAR2(16),
247   prim_rsrc_ind       PLS_INTEGER,
248   capacity_constraint PLS_INTEGER,
249   min_capacity        NUMBER,
250   max_capacity        NUMBER,
251   schedule_ind        PLS_INTEGER,
252 
253   routingstep_id      PLS_INTEGER    ,
254   x_routingstep_id    PLS_INTEGER    ,
255 --  routingstep_no      NUMBER   ,
256   step_qty            NUMBER,
257   minimum_transfer_qty NUMBER,
258   oprn_desc           VARCHAR2(70),
259   oprn_id             PLS_INTEGER  ,   /* SGIDUGU - Seq Dep changes */
260   oprn_no             VARCHAR2(32),
261   process_qty_um      VARCHAR2(4),
262   activity            VARCHAR2(16),
263   oprn_line_id        PLS_INTEGER    ,
264 --  resources           VARCHAR2(16),
265   resource_count      PLS_INTEGER   ,
266   resource_usage      NUMBER,
267   usage_um            VARCHAR2(4),
268   scale_type          PLS_INTEGER,
269 --  prim_rsrc_ind       NUMBER   ,
270   offset_interval     NUMBER,
271   resource_id         PLS_INTEGER,
272   x_resource_id       PLS_INTEGER    ,   /* B1177070 added encoded key */
273   rtg_scale_type      PLS_INTEGER,
274   aps_usage_um        VARCHAR2(3),
275   activity_factor     NUMBER,       /* GMD New Additional Columns */
276   process_qty         NUMBER,       /* GMD New Additional Columns */
277 --  seq_dep_ind         NUMBER, /*B2870041 sequence dependent indicator */
278   material_ind        PLS_INTEGER, /*B2870041 material indicator for next/prior*/
279   schedule_flag       PLS_INTEGER, /*B2870041 default value for APS*/
280   mat_found           PLS_INTEGER, /* Indicator is any activity is scheduled in operation. */
281   include_rtg_row     PLS_INTEGER, /* Do Not Plan Resource rows will have value 0 */
282   break_ind           PLS_INTEGER, /* Flag denoting whether activity is breakable or not. */
283   o_min_capacity      NUMBER,  /* Overrides */
284   o_max_capacity      NUMBER,  /* Overrides */
285   o_resource_usage    NUMBER,  /* Overrides */
286   o_activity_factor   NUMBER,  /* Overrides */
287   o_process_qty       NUMBER,  /* Overrides */
288   o_step_qty          NUMBER,  /* Overrides */
289   is_sds_rout         PLS_INTEGER,   /* B4918786 SDS */
290   is_unique           PLS_INTEGER,   /* B4918786 SDS */
291   is_nonunique        PLS_INTEGER,   /* B4918786 SDS */
292   setup_id            PLS_INTEGER    /* B4918786 SDS */
293 );
294 TYPE gmp_routing_detail_tbl IS TABLE OF gmp_routing_detail_typ
295 INDEX BY BINARY_INTEGER;
296 rtg_org_dtl_tab    gmp_routing_detail_tbl;
297 
298 TYPE gen_routing_detail_typ IS RECORD
299 (
300   routing_id          PLS_INTEGER,
301   routingstep_no      PLS_INTEGER,
302   seq_dep_ind         PLS_INTEGER, /*B2870041 sequence dependent indicator */
303   prim_rsrc_ind_order PLS_INTEGER,
304   resources           VARCHAR2(16),
305   routingstep_id      PLS_INTEGER,
306   oprn_no             VARCHAR2(32),
307   oprn_line_id        PLS_INTEGER,
308   activity            VARCHAR2(16),
309   prim_rsrc_ind       PLS_INTEGER,
310 --  resources           VARCHAR2(16),
311 --  prim_rsrc_ind       NUMBER   ,
312 --  seq_dep_ind         NUMBER, /*B2870041 sequence dependent indicator */
313   offset_interval     NUMBER,
314   uom_code            VARCHAR2(3) /* NAMIT_RD */
315 );
316 TYPE gen_routing_detail_tbl IS TABLE OF gen_routing_detail_typ
317 INDEX BY BINARY_INTEGER;
318 rtg_gen_dtl_tab       gen_routing_detail_tbl;
319 
320 /* B4918786 SDS */
321 TYPE gmp_sds_typ IS RECORD
322 (
323   oprn_id             PLS_INTEGER,
324   category_id         PLS_INTEGER,
325   seq_dpnd_class      VARCHAR2(100),
326   resources           VARCHAR2(16),
327   resource_id         PLS_INTEGER,
328   setup_id            PLS_INTEGER
329 );
330 TYPE gmp_sds_tbl IS TABLE OF gmp_sds_typ INDEX BY BINARY_INTEGER;
331 sds_tab    gmp_sds_tbl;
332 sds_tab_init gmp_sds_tbl;
333 
334 TYPE gmp_alt_resource_typ IS RECORD
335 (
336   prim_resource_id    PLS_INTEGER    ,
337   alt_resource_id     PLS_INTEGER    ,
338   min_capacity        NUMBER,  /* SGIDUGU - min capacity for alternate rsrc */
339   max_capacity        NUMBER,  /* SGIDUGU - max capacity for alternate rsrc */
340   runtime_factor      NUMBER,  /* B2353759,alternate runtime_factor */
341   preference	        PLS_INTEGER, /* Prod spec alternates */
342   item_id 	          PLS_INTEGER  /* Prod spec alternates */
343 );
344 TYPE gmp_alt_resource_tbl IS TABLE OF gmp_alt_resource_typ
345 INDEX BY BINARY_INTEGER;
346 rtg_alt_rsrc_tab       gmp_alt_resource_tbl;
347 
348 TYPE gmp_material_assoc_typ IS RECORD
349 (
350   formula_id          PLS_INTEGER    ,
351   recipe_id           PLS_INTEGER    ,
352   line_type           PLS_INTEGER,
353   line_no             PLS_INTEGER,
354   x_formulaline_id    PLS_INTEGER    ,   /* B1177070 added encoded key */
355   x_routingstep_id    PLS_INTEGER    ,  /* B1177070 added encoded key */
356 /* NAMIT_MTQ */
357   item_id             PLS_INTEGER  ,
358   routingstep_no      PLS_INTEGER,
359   aps_item_id         PLS_INTEGER,
360   uom_conv_factor     NUMBER,
361   min_trans_qty       NUMBER,
362   min_delay           NUMBER,
363   max_delay           NUMBER
364 );
365 TYPE gmp_material_assoc_tbl IS TABLE OF gmp_material_assoc_typ
366 INDEX BY BINARY_INTEGER;
367 mat_assoc_tab    gmp_material_assoc_tbl;
368 
369 /* NAMIT_CR Define Step Dependency Record Type */
370 
371 TYPE gmp_opr_stpdep_typ IS RECORD
372 (
373   routing_id          PLS_INTEGER  ,
374   x_dep_routingstep_id PLS_INTEGER    ,
375   x_routingstep_id    PLS_INTEGER    ,
376   dep_type            PLS_INTEGER,
377   standard_delay      NUMBER,
378   max_delay           NUMBER,
379   transfer_pct        NUMBER,
380   dep_routingstep_no  PLS_INTEGER,
381   routingstep_no      PLS_INTEGER,
382   chargeable_ind      PLS_INTEGER
383 );
384  TYPE gmp_opr_stepdep_tab IS TABLE OF gmp_opr_stpdep_typ
385  INDEX BY BINARY_INTEGER;
386 gmp_opr_stpdep_tbl gmp_opr_stepdep_tab;
387 
388 /* GMD New Declaration of PL/SQL Tables for Activity and Resources Overrides */
389 TYPE recipe_orgn_override_typ IS RECORD
390 (
391   routing_id          PLS_INTEGER    ,
392   orgn_code           VARCHAR2(4),
393   routingstep_id      PLS_INTEGER    ,
394   oprn_line_id        PLS_INTEGER    ,
395   recipe_id           PLS_INTEGER    ,
396   activity_factor     NUMBER,
397   resources           VARCHAR2(16),
398   resource_usage      NUMBER,
399   process_qty         NUMBER,
400 /* NAMIT_OC */
401   min_capacity        NUMBER,
402   max_capacity        NUMBER
403 );
404 TYPE recipe_orgn_override_tbl IS TABLE OF recipe_orgn_override_typ
405 INDEX BY BINARY_INTEGER;
406 rcp_orgn_override    recipe_orgn_override_tbl;
407 
408 TYPE recipe_override_typ IS RECORD
409 (
410   routing_id          PLS_INTEGER    ,
411   routingstep_id      PLS_INTEGER    ,
412   recipe_id           PLS_INTEGER    ,
413   step_qty            NUMBER
414 );
415 TYPE recipe_override_tbl IS TABLE OF recipe_override_typ
416 INDEX BY BINARY_INTEGER;
417 recipe_override      recipe_override_tbl;
418 -- Routing steps offsets
419 TYPE gmp_routing_step_offsets_typ IS RECORD
420 (
421 plant_code 	VARCHAR2(4),
422 fmeff_id 	NUMBER,
423 formula_id	NUMBER,
424 routingstep_id	NUMBER,
425 start_offset	NUMBER,
426 end_offset	NUMBER,
427 formulaline_id	NUMBER
428 );
429 TYPE rtgstep_offsets_tbl IS TABLE OF gmp_routing_step_offsets_typ
430 INDEX BY BINARY_INTEGER ;
431 rstep_offsets	rtgstep_offsets_tbl;
432 --
433 /* SGIDUGU Seq Dep Table Definition */
434 TYPE gmp_sequence_typ IS RECORD
435 (
436   oprn_id      NUMBER,
437   category_id  NUMBER,
438   seq_dep_id   NUMBER
439 );
440 
441 seq_rec  gmp_sequence_typ;
442 
443 TYPE gmp_setup_tbl  IS TABLE OF gmp_sequence_typ INDEX BY BINARY_INTEGER;
444 setupid_tab   gmp_setup_tbl ;
445 
446 /* End of SGIDUGU Seq Dep Table Definition */
447 
448 /* === OPM PLD Declaraion =====*/
449 
450 /* Record definition for the a line in a production order. */
451   TYPE product_typ IS RECORD(
452     batch_no                    VARCHAR2(32),
453     plant_code                  VARCHAR2(4),
454     batch_id                    PLS_INTEGER,
455     x_batch_id                  PLS_INTEGER,  /* B1177070 added encoded key */
456     wip_whse_code               VARCHAR2(4),
457     mtl_org_id                  PLS_INTEGER,
458     routing_id                  PLS_INTEGER,
459     start_date                  DATE,
460     end_date                    DATE,
461     trans_date                  DATE,
462     batch_status                PLS_INTEGER,
463     batch_type                  PLS_INTEGER,
464     organization_id             PLS_INTEGER,
465     whse_code                   VARCHAR2(4),
466     item_id                     PLS_INTEGER,   /* Give a Unique Item Id Name */
467     line_id                     PLS_INTEGER,
468     line_no                     PLS_INTEGER,   /* B2919303 */
469     tline_no                    PLS_INTEGER,   /* B2953953 - CoProducts */
470     line_type                   PLS_INTEGER,
471     tline_type                  PLS_INTEGER,   /* B2953953 - CoProducts */
472     qty                         NUMBER,
473     matl_item_id                PLS_INTEGER,   /* B1992371 for GME Changes */
474     recipe_item_id              PLS_INTEGER,   /* B1992371 for GME Changes */
475     poc_ind                     VARCHAR2(1),   /* B1992371, B2239948 for GME Changes */
476     firmed_ind                  PLS_INTEGER,      /* B2821248 - Firmed Ind is added */
477     batchstep_no                PLS_INTEGER,     /* B2919303 StepNo */
478     matl_qty                    NUMBER,
479     uom_conv_factor             NUMBER,
480     requested_completion_date   DATE,
481     schedule_priority		PLS_INTEGER,
482     from_op_seq_id 		PLS_INTEGER,
483     Minimum_Transfer_Qty	NUMBER,
484     Minimum_Time_Offset	        NUMBER,
485     Maximum_Time_Offset	        NUMBER,
486     from_op_seq_num		PLS_INTEGER
487    );
488   TYPE product_tbl IS TABLE OF product_typ INDEX by BINARY_INTEGER;
489   prod_tab   product_tbl;
490 
491 /* definition for the resource data of a production order */
492   TYPE rsrc_rec IS RECORD(
493     batch_id                  PLS_INTEGER,
494     x_batch_id                PLS_INTEGER,  /* B1177070 added encoded key */
495     batchstep_no              PLS_INTEGER,  /* B1224660 added batchstep to record */
496     seq_dep_ind               PLS_INTEGER,
497     prim_rsrc_ind_order       PLS_INTEGER,
498     resources                 VARCHAR2(16),
499     instance_number           PLS_INTEGER,
500     tran_seq_dep              PLS_INTEGER,
501     plan_start_date           DATE,
502     plant_code                VARCHAR2(4),
503 --    activity                VARCHAR2(16),	/* NAVIN: Remove this column. */
504     prim_rsrc_ind             PLS_INTEGER,
505     resource_id               PLS_INTEGER,
506     x_resource_id             PLS_INTEGER,  /* B1177070 added encoded key */
507     plan_rsrc_count           PLS_INTEGER,
508     actual_rsrc_count         PLS_INTEGER,
509     actual_start_date         DATE,
510     plan_cmplt_date           DATE,
511     actual_cmplt_date         DATE,
512     step_status               PLS_INTEGER,
513     resource_usage            NUMBER,
514     resource_instance_usage   NUMBER,
515     eqp_serial_number         VARCHAR2(30),   -- Bug 5713355
516     scale_type                PLS_INTEGER,
517     capacity_constraint       PLS_INTEGER ,
518     plan_step_qty             NUMBER,
519     min_xfer_qty              NUMBER,
520     material_ind              PLS_INTEGER,
521     schedule_flag             PLS_INTEGER,
522 --    offset_interval         NUMBER,
523     act_start_date            DATE,
524     utl_eff                   NUMBER,
525     bs_activity_id            PLS_INTEGER,
526     --NAVIN: START new field (added for 11.1.1.3 of Process Execution APS Patchset J.1 TDD)
527     group_sequence_id	      PLS_INTEGER,
528     group_sequence_number     PLS_INTEGER,
529     firm_type	              PLS_INTEGER,
530     setup_id	              PLS_INTEGER,
531     minimum_capacity          NUMBER,
532     maximum_capacity          NUMBER,
533     sequence_dependent_usage  NUMBER,
534     original_seq_num          NUMBER,
535     org_step_status	      PLS_INTEGER,
536     plan_charges	      PLS_INTEGER,
537     plan_rsrc_usage	      NUMBER,
538     actual_rsrc_usage	      NUMBER,
539     batchstep_id              PLS_INTEGER,   /* Navin 6/23/2004 Added for resource charges*/
540     mat_found                 PLS_INTEGER,
541     breakable_activity_flag   PLS_INTEGER,
542     usage_uom                 VARCHAR2(4), /*Sowmya - As Per the latest FDD changes */
543     step_qty_uom              VARCHAR2(3),
544     equp_item_id              PLS_INTEGER ,
545     gmd_rsrc_count            PLS_INTEGER,
546     step_start_date           DATE, /* populate msc_st_job_operations.reco_start_date */
547     step_end_date             DATE  /* populate msc_st_job_operations.reco_completion_date */
548     );
549   TYPE rsrc_dtl_tbl IS TABLE OF rsrc_rec INDEX by BINARY_INTEGER;
550   rsrc_tab   rsrc_dtl_tbl;
551 
552 /* Record and table definition for the MPS schedule details and the items and
553    orgs that are associated by plant/whse eff. The schedule are used for MDS
554    demand
555 */
556   TYPE sched_dtl_rec IS RECORD(
557     schedule        	VARCHAR2(16),
558     schedule_id     	PLS_INTEGER,
559     order_ind       	PLS_INTEGER,
560     stock_ind       	PLS_INTEGER,
561     whse_code       	VARCHAR2(4),
562     orgn_code       	VARCHAR2(4),
563     organization_id 	PLS_INTEGER,
564     inventory_item_id	PLS_INTEGER);
565 
566   TYPE sched_dtl_tbl IS TABLE OF sched_dtl_rec INDEX by BINARY_INTEGER;
567   sched_dtl_tab     sched_dtl_tbl;
568 
569   /* Record and table definition for forecast detals */
570   TYPE fcst_dtl_rec IS RECORD(
571     inventory_item_id   PLS_INTEGER,
572     organization_id     PLS_INTEGER,
573     forecast_id         PLS_INTEGER,
574     forecast            VARCHAR2(17),
575     orgn_code           VARCHAR2(4),
576     trans_date          DATE,
577     trans_qty           NUMBER,
578     consumed_qty        NUMBER,
579     use_fcst_flag	NUMBER(1));
580 
581   TYPE fcst_dtl_tbl IS TABLE OF fcst_dtl_rec INDEX by BINARY_INTEGER;
582   fcst_dtl_tab      fcst_dtl_tbl;
583 
584   /* Record and table definition for sales order detals */
585   TYPE sales_dtl_rec IS RECORD(
586     inventory_item_id   PLS_INTEGER,
587     organization_id 	PLS_INTEGER,
588     orgn_code           VARCHAR2(4),
589     order_no            VARCHAR2(32),
590     line_id             PLS_INTEGER,
591     net_price           NUMBER,
592     sched_shipdate      DATE,
593     request_date        DATE,       /* B2971996 */
594     trans_qty           NUMBER);
595 
596   TYPE sales_dtl_tbl IS TABLE OF sales_dtl_rec INDEX by BINARY_INTEGER;
597   sales_dtl_tab     sales_dtl_tbl;
598 
599   /* Record and table definition for schedule forecast association */
600   TYPE fcst_assoc_rec IS RECORD(
601     schedule_id         PLS_INTEGER,
602     forecast_id         PLS_INTEGER);
603 
604   TYPE fcst_assoc_tbl IS TABLE OF fcst_assoc_rec INDEX by BINARY_INTEGER;
605   SCHD_FCST_DTL_TAB     fcst_assoc_tbl;
606 
607   /* Record and table definition for designators */
608   TYPE desig_rec IS RECORD(
609     designator      VARCHAR2(15),
610     schedule        VARCHAR2(17),
611     orgn_code       VARCHAR2(4),
612     whse_code       VARCHAR2(4),
613     organization_id PLS_INTEGER);
614 
615   TYPE desig_tbl IS TABLE OF desig_rec INDEX by BINARY_INTEGER;
616   desig_tab         desig_tbl;
617 
618 TYPE stp_chg_typ is RECORD(
619   wip_entity_id	        PLS_INTEGER,
620   operation_seq_id      PLS_INTEGER,
621   resource_id	        PLS_INTEGER,
622   charge_num	        PLS_INTEGER,
623   organization_id       PLS_INTEGER,
624   operation_seq_no      PLS_INTEGER,
625   resource_seq_num      PLS_INTEGER ,
626   charge_quantity       NUMBER,
627   charge_start_dt_time	DATE,
628   charge_end_dt_time    DATE
629   );
630 
631 TYPE stp_chg_tab IS TABLE OF stp_chg_typ INDEX by BINARY_INTEGER;
632 stp_chg_tbl stp_chg_tab;
633 
634 /* NAVIN :- Alternate Resource */
635 /* NAVIN: Alternate Resource selection   */
636 TYPE prod_alt_resource_typ IS RECORD
637 (
638      prim_resource_id    PLS_INTEGER,
639      alt_resource_id     PLS_INTEGER,
640      min_capacity        NUMBER,
641      max_capacity        NUMBER,
642      runtime_factor      NUMBER,  /* B2353759,alternate runtime_factor */
643      preference          PLS_INTEGER, /* B5688153 Prod spec alternates */
644      item_id             PLS_INTEGER  /* B5688153 Prod spec alternates */
645 );
646 TYPE prod_alt_resource_tbl IS TABLE OF prod_alt_resource_typ INDEX by BINARY_INTEGER;
647 prod_alt_rsrc_tab       prod_alt_resource_tbl;
648 
649 /* ---------------------------  Global declarations ------------------------ */
650 TYPE number_idx_tbl IS TABLE OF NUMBER INDEX BY BINARY_INTEGER;
651 TYPE pls_idx_tbl IS TABLE OF PLS_INTEGER INDEX BY BINARY_INTEGER;
652 TYPE date_idx_tbl IS TABLE OF DATE INDEX BY BINARY_INTEGER;
653 TYPE uom_code_tbl IS TABLE OF VARCHAR2(3) INDEX BY BINARY_INTEGER;
654 empty_number_table      number_idx_tbl;
655 empty_date_table       	date_idx_tbl ;
656 empty_uom_code_tbl	uom_code_tbl ;
657 
658 bom_sr_instance_id  	pls_idx_tbl;
659 bomc_sr_instance_id 	pls_idx_tbl;
660 pef_sr_instance_id 	pls_idx_tbl;
661 rtg_sr_instance_id 	pls_idx_tbl;
662 or_sr_instance_id 	pls_idx_tbl;
663 opr_sr_instance_id 	pls_idx_tbl;
664 rs_sr_instance_id 	pls_idx_tbl;
665 oc_sr_instance_id 	pls_idx_tbl;
666 /* NAMIT_MTQ */
667 itm_mtq_sr_instance_id 	number_idx_tbl;
668 /* NAMIT_CR */
669 opr_stpdep_sr_instance_id 	pls_idx_tbl;
670 
671 bom_organization_id  	pls_idx_tbl;
672 bomc_organization_id 	pls_idx_tbl;
673 pef_organization_id 	pls_idx_tbl;
674 rtg_organization_id 	pls_idx_tbl;
675 oc_organization_id 	pls_idx_tbl;
676 gt_organization_id 	pls_idx_tbl;
677 /* NAMIT_MTQ */
678 itm_mtq_organization_id       	pls_idx_tbl ;
679 opr_stpdep_organization_id    	pls_idx_tbl ;
680 opr_organization_id   		pls_idx_tbl ;
681 or_organization_id    		pls_idx_tbl ;
682 rs_organization_id    		pls_idx_tbl ;
683 
684 bom_bill_sequence_id 	pls_idx_tbl;
685 bomc_bill_sequence_id 	pls_idx_tbl;
686 pef_bill_sequence_id 	pls_idx_tbl;
687 oc_bill_sequence_id 	pls_idx_tbl;
688 
689 bom_last_update_date 	date_idx_tbl ;
690 bomc_last_update_date 	date_idx_tbl ;
691 pef_last_update_date 	date_idx_tbl ;
692 rtg_last_update_date 	date_idx_tbl ;
693 or_last_update_date 	date_idx_tbl ;
694 opr_last_update_date 	date_idx_tbl ;
695 rs_last_update_date 	date_idx_tbl ;
696 oc_last_update_date 	date_idx_tbl ;
697 
698 bom_creation_date 	date_idx_tbl ;
699 bomc_creation_date 	date_idx_tbl ;
700 pef_creation_date 	date_idx_tbl ;
701 rtg_creation_date 	date_idx_tbl ;
702 or_creation_date 	date_idx_tbl ;
703 opr_creation_date 	date_idx_tbl ;
704 rs_creation_date 	date_idx_tbl ;
705 oc_creation_date 	date_idx_tbl ;
706 
707 pef_effectivity_date 	date_idx_tbl   ;
708 bomc_effectivity_date 	date_idx_tbl   ;
709 opr_effectivity_date 	date_idx_tbl   ;
710 bomc_disable_date 	date_idx_tbl   ;
711 
712 rtg_routing_sequence_id 	pls_idx_tbl   ;
713 pef_routing_sequence_id 	pls_idx_tbl   ;
714 or_routing_sequence_id 		pls_idx_tbl   ;
715 opr_routing_sequence_id 	pls_idx_tbl   ;
716 rs_routing_sequence_id 		pls_idx_tbl   ;
717 oc_routing_sequence_id 		pls_idx_tbl   ;
718 /* NAMIT_MTQ */
719 itm_mtq_routing_sequence_id 	pls_idx_tbl   ;
720 /* NAMIT_CR */
721 opr_stpdep_routing_sequence_id 	pls_idx_tbl   ;
722 
723 bomc_uom_code  uom_code_tbl  ;
724 rtg_uom_code   uom_code_tbl ;
725 or_uom_code    uom_code_tbl ;
726 opr_uom_code   uom_code_tbl ;
727 
728 bom_assembly_item_id 	pls_idx_tbl ;
729 rtg_assembly_item_id 	pls_idx_tbl ;
730 
731 bomc_component_sequence_id 	pls_idx_tbl;
732 oc_component_sequence_id 	pls_idx_tbl;
733 
734 or_operation_sequence_id  	pls_idx_tbl   ;
735 opr_operation_sequence_id 	pls_idx_tbl   ;
736 rs_operation_sequence_id 	pls_idx_tbl   ;
737 oc_operation_sequence_id 	pls_idx_tbl   ;
738 
739 or_resource_seq_num 		number_idx_tbl   ;
740 rs_resource_seq_num 		number_idx_tbl   ;
741 /* SGIDUGU - Seq Dep */
742 or_setup_id     		pls_idx_tbl   ;
743 gt_setup_id     		pls_idx_tbl   ;
744 
745 -- Bug: 6030499 Vpedarla Added new variables
746   v_dummy                 NUMBER;  /* B8401372 */
747   collect_ps_data         BOOLEAN;
748 
749 -- venu added for item substituion
750 loop_ctr                PLS_INTEGER;
751 k                       PLS_INTEGER;
752 orig_start_date         DATE;
753 substcount              PLS_INTEGER;
754 enddatenull             BOOLEAN:=FALSE;
755 
756 -- Bug:6030499 end
757 
758 
759 
760 TYPE seq_dep_class_typ IS TABLE OF ic_item_mst.seq_dpnd_class%TYPE INDEX BY
761 BINARY_INTEGER;
762 gt_seq_dep_class     seq_dep_class_typ   ;
763 empty_seq_dep_class	seq_dep_class_typ ;
764 --
765 TYPE oprn_no_typ IS TABLE OF gmd_operations.oprn_no%TYPE INDEX BY
766 BINARY_INTEGER;
767 gt_oprn_no     oprn_no_typ ;
768 empty_oprn_no     oprn_no_typ ;
769 
770 /* End of changes SGIDUGU - Seq Dep */
771 
772 /* -------------------------------  BOM declarations --------------------------- */
773 TYPE alternate_bom_designator IS TABLE OF msc_st_boms.alternate_bom_designator%TYPE
774 INDEX BY BINARY_INTEGER;
775 bom_alternate_bom_designator alternate_bom_designator ;
776 empty_alternate_bom_designator alternate_bom_designator ;
777 
778 TYPE specific_assembly_comment IS TABLE OF msc_st_boms.specific_assembly_comment%TYPE
779 INDEX BY BINARY_INTEGER;
780 bom_specific_assembly_comment specific_assembly_comment ;
781 empty_bom_assembly_comment specific_assembly_comment ;
782 
783 bom_scaling_type 	number_idx_tbl ;
784 bom_assembly_quantity 	number_idx_tbl ;
785 
786 TYPE uom IS TABLE OF msc_st_boms.uom%TYPE INDEX BY BINARY_INTEGER;
787 bom_uom 	uom ;
788 empty_bom_uom 	uom ;
789 
790 /* NAMIT_CR For Step Material Assoc */
791 bom_op_seq_number 	number_idx_tbl;
792 
793 /* NAMIT_OC For ingredients contribute_to_step_qty will
794         store 1 for YES and 0 for NO */
795 bomc_contribute_to_step_qty 	number_idx_tbl;
796 
797 bom_index INTEGER := 0 ;   /* BOM Global counter */
798 
799 /* ---------------------------  BOM Components declarations ------------------------ */
800 bomc_Inventory_item_id 		pls_idx_tbl;
801 bomc_using_assembly_id 		pls_idx_tbl    ;
802 bomc_component_type 		pls_idx_tbl    ;
803 bomc_scaling_type  		pls_idx_tbl;
804 bomc_usage_quantity 		number_idx_tbl;
805 bomc_opr_offset_percent  	number_idx_tbl ;
806 bomc_optional_component  	number_idx_tbl ;
807 bomc_wip_supply_type 		number_idx_tbl ;
808 bomc_scale_multiple  		pls_idx_tbl;
809 bomc_scale_rounding_variance 	pls_idx_tbl ;
810 bomc_rounding_direction  	pls_idx_tbl ;
811 
812 bomc_index INTEGER := 0 ;   /* BOM component Global counter */
813 
814 /* ---------------------------  Effectivity declarations ------------------------ */
815 pef_process_sequence_id 	pls_idx_tbl   ;
816 pef_item_id             	pls_idx_tbl ;
817 pef_disable_date 		date_idx_tbl   ;
818 pef_minimum_quantity 		number_idx_tbl   ;
819 pef_maximum_quantity 		number_idx_tbl   ;
820 pef_preference 			pls_idx_tbl ;
821 
822 pef_index INTEGER := 0 ;   /* Process Effectivity Global counter */
823 
824 /* -------------------------------  Routng declarations  --------------------------- */
825 TYPE routing_comment IS TABLE OF msc_st_routings.routing_comment%TYPE
826 INDEX BY BINARY_INTEGER;
827 rtg_routing_comment routing_comment ;
828 empty_rtg_comment routing_comment ;
829 
830 
831 TYPE alt_routing_designator  IS TABLE OF msc_st_routings.alternate_routing_designator%TYPE
832 INDEX BY BINARY_INTEGER;
833 rtg_alt_routing_designator alt_routing_designator   ;
834 empty_rtg_designator alt_routing_designator   ;
835 l_1237_count number;  -- Biogen
836 l_1238_count number;  -- Biogen
837 TYPE routing_quantity IS TABLE OF msc_st_routings.routing_quantity%TYPE
838 INDEX BY BINARY_INTEGER;
839 rtg_routing_quantity 		routing_quantity   ;
840 /* Bug: 6522250 Vpedarla modfied the type frpm pls_idx_tbl to routing_quantity */
841 
842 /* NAMIT_CR For Calculate Step Dependency Flag */
843 rtg_auto_step_qty_flag 		pls_idx_tbl  ;
844 
845 rtg_index INTEGER := 0 ;   /* Routing Global counter */
846 
847 /* -------------------------- Routng operations declarations  ------------------------ */
848 or_resource_id 		pls_idx_tbl   ;
849 gt_resource_id 		pls_idx_tbl   ;
850 
851 or_alternate_number 		pls_idx_tbl   ;
852 or_principal_flag 		pls_idx_tbl   ;
853 or_basis_type 			pls_idx_tbl   ;
854 or_resource_usage 		number_idx_tbl   ;
855 or_max_resource_units 		pls_idx_tbl   ;
856 or_resource_units 		pls_idx_tbl   ;
857 or_orig_rs_seq_num 		pls_idx_tbl ;
858 or_break_ind 			pls_idx_tbl;
859 
860 or_index PLS_INTEGER := 0 ;   /* Operation Resource Global counter */
861 gt_index PLS_INTEGER := 0 ;   /* Operation Resource Global counter */
862 
863 /* -------------------------- Operations declarations  ------------------------ */
864 opr_operation_seq_num 		pls_idx_tbl   ;
865 opr_mtransfer_quantity 		number_idx_tbl   ;
866 opr_department_id 		pls_idx_tbl ;
867 rs_department_id 		pls_idx_tbl ;
868 rs_schedule_flag 	pls_idx_tbl ;
869 /* NAMIT_MTQ */
870 itm_mtq_from_op_seq_id 	pls_idx_tbl;
871 /* NAMIT_CR */
872 opr_stpdep_frm_seq_id 	pls_idx_tbl ;
873 opr_stpdep_to_seq_id 	pls_idx_tbl ;
874 opr_stpdep_dependency_type pls_idx_tbl ;
875 /* NAMIT_CR */
876 itm_mtq_min_time_offset 	number_idx_tbl ;
877 itm_mtq_max_time_offset 	number_idx_tbl ;
878 rs_activity_group_id 		pls_idx_tbl ;
879 opr_stpdep_min_time_offset 	number_idx_tbl ;
880 opr_stpdep_max_time_offset 	number_idx_tbl ;
881 opr_stpdep_trans_pct 		number_idx_tbl ;
882 itm_mtq_frm_op_seq_num 		pls_idx_tbl ;
883 opr_stpdep_frm_op_seq_num 	pls_idx_tbl ;
884 opr_stpdep_to_op_seq_num 	pls_idx_tbl ;
885 opr_stpdep_app_to_chrg 		number_idx_tbl ;
886 itm_mtq_from_item_id 		pls_idx_tbl ;
887 itm_mtq_min_tran_qty 		number_idx_tbl ;
888 or_minimum_capacity 		number_idx_tbl ;
889 or_maximum_capacity 		number_idx_tbl ;
890 opr_step_qty 			number_idx_tbl;
891 
892 opr_step_qty_uom 		uom_code_tbl;
893 
894 TYPE operation_description IS TABLE OF msc_st_routing_operations.operation_description%TYPE
895 INDEX BY BINARY_INTEGER;
896 opr_operation_description operation_description   ;
897 empty_opr_description operation_description   ;
898 TYPE department_code IS TABLE OF msc_st_routing_operations.department_code%TYPE
899 INDEX BY BINARY_INTEGER;
900 opr_department_code department_code ;
901 empty_opr_department_code department_code ;
902 
903 opr_index PLS_INTEGER := 0 ;   /* Operation Global counter */
904 rs_index  PLS_INTEGER := 0 ;   /* Operation Global counter */
905 oc_index  PLS_INTEGER := 0 ;   /* Operation component Global counter */
906 /* NAMIT_MTQ */
907 mtq_index PLS_INTEGER := 0 ;   /* MTQ Global counter */
908 v_gmd_seq 		varchar2(100);
909 v_gmd_formula_lineid 	PLS_INTEGER := 0;
910 gmd_formline_cnt  	PLS_INTEGER := 0 ;
911 op_formline_cnt 	PLS_INTEGER := 0 ;
912 cnt     		PLS_INTEGER ;
913 
914 /* ------------------- Requirement declaration ---------------------*/
915 
916 /* akaruppa B5007729 */
917 empty_num_table      number_idx_tbl;
918 rr_organization_id   pls_idx_tbl;
919 s_organization_id    pls_idx_tbl;
920 d_organization_id    pls_idx_tbl;
921 f_organization_id    pls_idx_tbl;
922 i_organization_id    pls_idx_tbl;
923 o_organization_id    pls_idx_tbl; -- akaruppa B4287033
924 arr_organization_id  pls_idx_tbl; /* alternate resource declaration */
925 rr_activity_group_id pls_idx_tbl; /* B3995361 rpatangy */
926 rr_unadjusted_resource_hrs  number_idx_tbl;
927 rr_touch_time        number_idx_tbl;
928 
929 empty_pls_table     pls_idx_tbl;
930 rr_sr_instance_id   pls_idx_tbl;
931 s_sr_instance_id    pls_idx_tbl;
932 d_sr_instance_id    pls_idx_tbl;
933 f_sr_instance_id    pls_idx_tbl;
934 i_sr_instance_id    pls_idx_tbl;
935 o_sr_instance_id    pls_idx_tbl; -- akaruppa B4287033
936 stp_instance_id     pls_idx_tbl;
937 arr_sr_instance_id  pls_idx_tbl; /* alternate resource declaration */
938 
939 rr_supply_id         pls_idx_tbl;
940 rr_resource_seq_num  pls_idx_tbl;
941 rr_resource_id       pls_idx_tbl;
942 
943 rr_opr_hours_required number_idx_tbl ;
944 rr_usage_rate         number_idx_tbl ;
945 rr_assigned_units     number_idx_tbl ;
946 rr_department_id      pls_idx_tbl ;
947 
948 rr_wip_entity_id pls_idx_tbl ;
949 d_wip_entity_id  pls_idx_tbl ;
950 f_wip_entity_id  pls_idx_tbl ;
951 
952 rr_operation_seq_num pls_idx_tbl;
953 s_operation_seq_num  pls_idx_tbl;
954 d_operation_seq_num  pls_idx_tbl;
955 
956 rr_firm_flag                 pls_idx_tbl ;
957 rr_minimum_transfer_quantity number_idx_tbl ;
958 rr_parent_seq_num            number_idx_tbl ;
959 rr_schedule_flag             pls_idx_tbl ;
960 /* akaruppa B5007729 End*/
961 
962 empty_dat_table  date_idx_tbl;
963 rr_start_date    date_idx_tbl;
964 rr_end_date      date_idx_tbl;
965 
966 rr_hours_expended          number_idx_tbl ;
967 rr_breakable_activity_flag pls_idx_tbl ;
968 rr_plan_step_qty           number_idx_tbl; /*Sowmya - As per latest FDD changes */
969 rr_operation_sequence_id   pls_idx_tbl ; /* BUg: 6030499 Vpedarla BP Bug:5461922 */
970 
971 TYPE res_step_qty_uom IS TABLE OF VARCHAR2(3)
972 INDEX BY BINARY_INTEGER;
973 rre_step_qty_uom       res_step_qty_uom;
974 rr_step_qty_uom        res_step_qty_uom;  /*Sowmya - As per latest FDD changes */
975 
976 rr_gmd_rsrc_cnt              pls_idx_tbl; /*Sowmya - As per latest FDD changes */
977 jo_wip_entity_id             pls_idx_tbl;
978 jo_instance_id               pls_idx_tbl;
979 jo_operation_seq_num         pls_idx_tbl;
980 jo_operation_sequence_id     pls_idx_tbl;
981 jo_organization_id           pls_idx_tbl;
982 jo_department_id             pls_idx_tbl;
983 jo_minimum_transfer_quantity number_idx_tbl;
984 
985 TYPE recommended_typ IS TABLE OF VARCHAR2(1) INDEX BY BINARY_INTEGER;
986 jo_recommended         recommended_typ;
987 jo_network_start_end   recommended_typ;
988 joe_recommended        recommended_typ;
989 joe_network_start_end  recommended_typ;
990 
991 jo_reco_start_date      date_idx_tbl ;
992 jo_reco_completion_date date_idx_tbl ;
993 
994 rr_index      NUMBER := 0 ;
995 arr_index     NUMBER := 0 ;
996 si_index      NUMBER := 0 ;
997 inst_indx     NUMBER := 0 ; /* NAVIN :- - For Resource Instance */
998 jo_index      NUMBER := 0; /* NAMIT :- For msc_st_job_operations */
999 
1000 /* ------------------- Supply declaration ---------------------*/
1001 
1002 /* akaruppa B5007729 */
1003 s_plan_id               pls_idx_tbl  ;
1004 o_plan_id               pls_idx_tbl  ; -- akaruppa B4287033
1005 s_inventory_item_id     pls_idx_tbl ;
1006 d_inventory_item_id     pls_idx_tbl ;
1007 f_inventory_item_id     pls_idx_tbl ;
1008 o_inventory_item_id     pls_idx_tbl ; -- akaruppa B4287033
1009 rr_inventory_item_id    pls_idx_tbl ; -- HW B4902328
1010 
1011 s_new_schedule_date     date_idx_tbl ;
1012 o_new_schedule_date     date_idx_tbl ; -- akaruppa B4287033
1013 s_old_schedule_date     date_idx_tbl ;
1014 s_new_wip_start_date    date_idx_tbl ;
1015 s_old_wip_start_date    date_idx_tbl ;
1016 s_lunit_completion_date date_idx_tbl ;
1017 s_disposition_id        pls_idx_tbl ;
1018 s_order_type            pls_idx_tbl ;
1019 o_order_type            pls_idx_tbl ; -- akaruppa B4287033
1020 /* akaruppa B5007729 End*/
1021 
1022 TYPE order_number IS TABLE OF msc_st_supplies.order_number%TYPE INDEX BY BINARY_INTEGER;
1023 s_order_number  order_number ;
1024 se_order_number order_number ;/* akaruppa B5007729 */
1025 
1026 /* akaruppa B5007729 */
1027 s_new_order_quantity number_idx_tbl ;
1028 o_new_order_quantity number_idx_tbl ; -- akaruppa B4287033
1029 s_old_order_quantity number_idx_tbl ;
1030 s_firm_planned_type  pls_idx_tbl ;
1031 o_firm_planned_type  pls_idx_tbl ; -- akaruppa B4287033
1032 s_process_seq_id     pls_idx_tbl ;   -- B6795244
1033 /* akaruppa B5007729 End*/
1034 
1035 TYPE wip_entity_name IS TABLE OF msc_st_supplies.wip_entity_name%TYPE INDEX BY BINARY_INTEGER;
1036 s_wip_entity_name  wip_entity_name   ;
1037 se_wip_entity_name wip_entity_name ;/* akaruppa B5007729 */
1038 
1039 TYPE lot_number IS TABLE OF msc_st_supplies.lot_number%TYPE INDEX BY BINARY_INTEGER;
1040 s_lot_number lot_number ;
1041 o_lot_number lot_number ; -- akaruppa B4287033
1042 e_lot_number lot_number ; /* akaruppa B5007729 */
1043 
1044 /* akaruppa B5007729 */
1045 s_expiration_date          date_idx_tbl ;
1046 o_expiration_date          date_idx_tbl ; -- akaruppa B4287033
1047 s_firm_quantity            number_idx_tbl ;
1048 s_firm_date                date_idx_tbl ;
1049 s_by_product_using_assy_id pls_idx_tbl ;
1050 /* akaruppa B5007729 End*/
1051 
1052 s_requested_completion_date     date_idx_tbl ;
1053 
1054 TYPE stp_schedule_priority IS TABLE OF msc_st_supplies.schedule_priority%TYPE
1055 INDEX BY BINARY_INTEGER;
1056 s_schedule_priority  stp_schedule_priority;
1057 
1058 /*B5100481 - 16 for pending, 3 for wip*/
1059 s_wip_status_code            number_idx_tbl;
1060 
1061 /* NAVIN: MTQ with Hardlinks */
1062 stp_var_itm_instance_id      pls_idx_tbl;
1063 stp_var_itm_from_op_seq_id   pls_idx_tbl;
1064 stp_var_itm_wip_entity_id    pls_idx_tbl;
1065 stp_var_itm_from_item_id     pls_idx_tbl;
1066 stp_var_min_tran_qty         number_idx_tbl;
1067 stp_var_itm_min_tm_off       number_idx_tbl;
1068 stp_var_itm_max_tm_off       number_idx_tbl;
1069 stp_var_itm_from_op_seq_num  pls_idx_tbl;
1070 stp_var_itm_organization_id  pls_idx_tbl;
1071 
1072 s_index      NUMBER := 0 ;
1073 
1074 /* ---------------- Demands declaration ----------------------*/
1075 
1076 /* akaruppa B5007729 */
1077 d_assembly_item_id pls_idx_tbl ;
1078 f_assembly_item_id pls_idx_tbl ;
1079 
1080 d_demand_date date_idx_tbl ;
1081 f_demand_date date_idx_tbl ;
1082 
1083 d_requirement_quantity number_idx_tbl;
1084 f_requirement_quantity number_idx_tbl;
1085 
1086 d_demand_type pls_idx_tbl ;
1087 f_demand_type pls_idx_tbl ;
1088 
1089 d_origination_type pls_idx_tbl ;
1090 f_origination_type pls_idx_tbl ;
1091 /* akaruppa B5007729 End*/
1092 
1093 TYPE demand_schedule IS TABLE OF msc_st_demands.demand_schedule_name%TYPE
1094 INDEX BY BINARY_INTEGER;
1095 d_demand_schedule demand_schedule;
1096 f_demand_schedule demand_schedule;
1097 e_demand_schedule demand_schedule;/* akaruppa B5007729 */
1098 
1099 TYPE dorder_number IS TABLE OF msc_st_demands.order_number%TYPE INDEX BY BINARY_INTEGER;
1100 d_order_number dorder_number ;
1101 f_order_number dorder_number ;
1102 e_order_number dorder_number ;/* akaruppa B5007729 */
1103 
1104 TYPE dwip_entity_name IS TABLE OF msc_st_demands.wip_entity_name%TYPE INDEX BY BINARY_INTEGER;
1105 d_wip_entity_name     dwip_entity_name   ;
1106 f_wip_entity_name     dwip_entity_name   ;
1107 e_wip_entity_name     dwip_entity_name   ;/* akaruppa B5007729 */
1108 
1109 /* akaruppa B5007729 */
1110 d_selling_price number_idx_tbl;
1111 f_selling_price number_idx_tbl;
1112 
1113 d_request_date date_idx_tbl ;
1114 f_request_date date_idx_tbl ;
1115 
1116 TYPE forecast_designator IS TABLE OF msc_st_demands.forecast_designator%TYPE
1117 INDEX BY BINARY_INTEGER;
1118 f_forecast_designator forecast_designator ;
1119 e_forecast_designator forecast_designator ;/* akaruppa B5007729 */
1120 
1121 f_sales_order_line_id pls_idx_tbl; /* akaruppa B5007729 */
1122 
1123 /*B5100481 - 16 for pending, 3 for wip*/
1124 d_wip_status_code     number_idx_tbl;
1125 
1126 d_index      NUMBER := 0 ;
1127 
1128 /* ---------------- Designator declaration ----------------------*/
1129 TYPE designator IS TABLE OF msc_st_designators.designator%TYPE INDEX BY BINARY_INTEGER;
1130 i_designator designator ;
1131 e_designator designator ;/* akaruppa B5007729 */
1132 
1133 TYPE forecast_set IS TABLE OF msc_st_designators.forecast_set%TYPE INDEX BY BINARY_INTEGER;
1134 i_forecast_set forecast_set;
1135 e_forecast_set forecast_set;/* akaruppa B5007729 */
1136 
1137 TYPE description IS TABLE OF msc_st_designators.description%TYPE INDEX BY BINARY_INTEGER;
1138 i_description description ;
1139 e_description description ;/* akaruppa B5007729 */
1140 
1141 i_disable_date               date_idx_tbl ;/* akaruppa B5007729 */
1142 i_consume_forecast           number_idx_tbl;/* akaruppa B5007729 */
1143 i_backward_update_time_fence number_idx_tbl;/* akaruppa B5007729 */
1144 i_forward_update_time_fence  number_idx_tbl;/* akaruppa B5007729 */
1145 
1146 i_index      NUMBER := 0 ;
1147 
1148 /* akaruppa B4287033  OnHand Declarations */
1149 o_new_dock_date date_idx_tbl ;/* akaruppa B5007729 */
1150 
1151 o_deleted_flag pls_idx_tbl;/* akaruppa B5007729 */
1152 
1153 TYPE subinventory_code IS TABLE OF msc_st_supplies.subinventory_code%TYPE
1154 INDEX BY BINARY_INTEGER;
1155 o_subinventory_code subinventory_code   ;
1156 e_subinventory_code subinventory_code   ;/* akaruppa B5007729 */
1157 
1158 o_non_nettable_qty number_idx_tbl;/* akaruppa B5007729 */
1159 
1160 -- Rajesh Patangya 02-MAY-2006 Starts
1161 
1162 stp_chg_department_id      pls_idx_tbl ;
1163 stp_chg_resource_id        pls_idx_tbl ;
1164 stp_chg_organization_id    pls_idx_tbl ;
1165 stp_chg_wip_entity_id      pls_idx_tbl ;
1166 stp_chg_operation_seq_id   pls_idx_tbl ;
1167 stp_chg_operation_seq_no   pls_idx_tbl ;
1168 stp_chg_resource_seq_num   pls_idx_tbl ;
1169 stp_chg_charge_num         number_idx_tbl ;
1170 stp_chg_charge_quanitity   number_idx_tbl ;
1171 
1172 -- Rajesh Patangya 02-MAY-2006 Ends
1173 
1174 TYPE stp_charge_start_dt_time IS TABLE OF msc_st_resource_charges.charge_start_datetime%TYPE
1175 INDEX BY BINARY_INTEGER;
1176 stpe_chg_charge_start_dt_time stp_charge_start_dt_time ;
1177 stp_chg_charge_start_dt_time  stp_charge_start_dt_time ;
1178 
1179 TYPE stp_charge_end_dt_time IS TABLE OF msc_st_resource_charges.charge_end_datetime%TYPE
1180 INDEX BY BINARY_INTEGER;
1181 stpe_chg_charge_end_dt_time stp_charge_end_dt_time ;
1182 stp_chg_charge_end_dt_time  stp_charge_end_dt_time ;
1183 
1184 --------------------------NAVIN: Sequence Dependencies--------------------------
1185 
1186 -- Rajesh Patangya 02-MAY-2006 Starts
1187 
1188 rr_sequence_id           pls_idx_tbl ;
1189 rr_sequence_number       pls_idx_tbl ;
1190 rr_setup_id              pls_idx_tbl ;
1191 
1192 TYPE rsrc_firm_type IS TABLE OF msc_st_resource_requirements.firm_flag %TYPE
1193 INDEX BY BINARY_INTEGER;
1194 rr_firm_type rsrc_firm_type;
1195 
1196 /* NAVIN: new column for Operation Charges*/
1197 rr_min_capacity               number_idx_tbl;
1198 rr_max_capacity               number_idx_tbl;
1199 rr_original_seq_num           number_idx_tbl;
1200 rr_sequence_dependent_usage   number_idx_tbl;
1201 rr_alternate_number           number_idx_tbl;
1202 rr_basis_type                 number_idx_tbl;
1203 
1204 /* NAVIN :- Resource Instances start */
1205 
1206 rec_inst_supply_id            pls_idx_tbl;
1207 rec_inst_organization_id      pls_idx_tbl;
1208 rec_inst_sr_instance_id       pls_idx_tbl;
1209 rec_inst_rec_resource_seq_num pls_idx_tbl;
1210 rec_inst_resource_id          pls_idx_tbl;
1211 rec_inst_instance_id          pls_idx_tbl;
1212 rec_inst_start_date           date_idx_tbl ;
1213 rec_inst_end_date             date_idx_tbl ;
1214 rec_inst_rsrc_instance_hours  number_idx_tbl;
1215 rec_inst_operation_seq_num    pls_idx_tbl;
1216 rec_inst_department_id        pls_idx_tbl;
1217 rec_inst_wip_entity_id        pls_idx_tbl;
1218 
1219 -- Begin Bug 5713355
1220 TYPE rec_serial_number IS TABLE OF msc_st_resource_instance_reqs.serial_number%TYPE
1221 INDEX BY BINARY_INTEGER;
1222 empty_inst_serial_number      rec_serial_number ;
1223 rec_inst_serial_number        rec_serial_number;
1224 -- End Bug 5713355
1225 rec_inst_parent_seq_num       number_idx_tbl;
1226 rec_inst_original_seq_num     number_idx_tbl;
1227 rec_inst_equp_item_id         pls_idx_tbl;
1228 
1229 /* NAVIN :- Resource Instances end */
1230 
1231 /*-------------------------- Alternate Resources -----------------------------*/
1232 
1233 /* Sowmya - As Per the latest FDD changes :- Alternate resources declaration Start */
1234 
1235 TYPE alt_resource_varchar_typ IS TABLE OF VARCHAR2(4)
1236 INDEX BY BINARY_INTEGER;
1237 arre_uom_code              alt_resource_varchar_typ;
1238 arr_uom_code               alt_resource_varchar_typ;
1239 
1240 arr_wip_entity_id          pls_idx_tbl;
1241 arr_operation_seq_num      pls_idx_tbl;
1242 arr_res_seq_num            number_idx_tbl;
1243 arr_resource_id            pls_idx_tbl;
1244 arr_alternate_num          number_idx_tbl;
1245 arr_usage_rate             number_idx_tbl;
1246 arr_assigned_units         number_idx_tbl;
1247 arr_department_id          pls_idx_tbl;
1248 arr_activity_group_id      pls_idx_tbl;
1249 arr_basis_type             pls_idx_tbl;
1250 arr_setup_id               pls_idx_tbl;
1251 arr_schedule_seq_num       pls_idx_tbl;
1252 arr_maximum_assigned_units pls_idx_tbl;
1253 
1254 /* Sowmya - As Per latest FDD changes :- Alternate resources declaration Ends */
1255 
1256 /*===== Calendar Declaration ===========*/
1257 
1258 TYPE cal_shift_typ is RECORD
1259 ( cal_date    DATE,
1260   shift_num   PLS_INTEGER,
1261   from_time   PLS_INTEGER,
1262   to_time     PLS_INTEGER
1263 );
1264 calendar_record  cal_shift_typ;
1265 TYPE cal_tab is table of cal_shift_typ index by BINARY_INTEGER;
1266 new_rec  cal_tab;
1267 
1268 TYPE cal_detail_typ is RECORD
1269 (calendar_id        PLS_INTEGER,
1270  calendar_no        VARCHAR2(16),
1271  calendar_desc      VARCHAR2(40),
1272  orgn_code          VARCHAR2(4),
1273  resource_whse_code VARCHAR2(4),
1274  organization_id    PLS_INTEGER,
1275  posted             PLS_INTEGER
1276 );
1277 cursor_rec  cal_detail_typ;
1278 TYPE tab_cal_typ is table of cal_detail_typ INDEX BY BINARY_INTEGER;
1279 plsqltbl_rec  tab_cal_typ;
1280 
1281 resource_count    pls_idx_tbl;
1282 resource_id       pls_idx_tbl;
1283 instance_id       pls_idx_tbl;
1284 x_resource_id     pls_idx_tbl;
1285 x_instance_id     pls_idx_tbl;
1286 instance_number   pls_idx_tbl;
1287 shift_num         pls_idx_tbl;
1288 equipment_item_id pls_idx_tbl;
1289 
1290 f_date            date_idx_tbl;
1291 t_date            date_idx_tbl;
1292 
1293 TYPE serial_number IS TABLE OF msc_st_net_res_inst_avail.serial_number%TYPE
1294 INDEX BY BINARY_INTEGER;
1295 emp_serial_number  serial_number;
1296 msc_serial_number  serial_number;
1297 
1298 /*
1299 REM+=========================================================================+
1300 REM| PROCEDURE NAME                                                          |
1301 REM|    retrieve_effectivities                                               |
1302 REM|                                                                         |
1303 REM| TYPE                                                                    |
1304 REM|    Private                                                              |
1305 REM|                                                                         |
1306 REM| DESCRIPTION                                                             |
1307 REM|    The majority of the logic in this procedure is contained in the four |
1308 REM|    cursors. There is one for each type of effectivity as follows:       |
1309 REM|      case 1: Effectivity has an organisation and a routing              |
1310 REM|      case 2: Effectivity has an organisation but no routing             |
1311 REM|      case 3: Effectivity has no organisation but has a routing          |
1312 REM|      case 4: Effectivity has no organisation and no routing             |
1313 REM|    Depending on each case above, the retrieval logic differs slightly   |
1314 REM|    as does the source of some the values which come back. To make it    |
1315 REM|    simpler to understand (and maintain) each case was dealt             |
1316 REM|    with on its own. By putting as much logic as possible in the SQL it  |
1317 REM|    was hoped to optimise the database accesses and make the code itself |
1318 REM|    simpler.                                                             |
1319 REM|                                                                         |
1320 REM| INPUT PARAMETERS                                                        |
1321 REM|    none                                                                 |
1322 REM|                                                                         |
1323 REM| OUTPUT PARAMETERS                                                       |
1324 REM|    return_status  TRUE=> OK                                             |
1325 REM|                                                                         |
1326 REM| INPUT/OUTPUT PARAMETERS                                                 |
1327 REM|    None                                                                 |
1328 REM|                                                                         |
1329 REM| HISTORY                                                                 |
1330 REM|    Created 12th July 1999 by P.J.Schofield (OPM Development Oracle UK)  |
1331 REM|    04/03/2000 - Using organization_id from gmp_item_aps , instead of    |
1332 REM|                 organization_id from sy_orgn_mst, Bug# 1252322          |
1333 REM| 07/14/2002   Rajesh Patangya - Reorgnized the complete code B2314052    |
1334 REM| 01/14/2003   Sridhar Gidugu  - Using gia.uom_code instead of gia.item_um|
1335 REM|                                Bug# 2739627                             |
1336 REM| 06/02/2003   Sridhar Gidugu  - B2989806 - Forward port fix for          |
1337 REM|                                Bug#2916619 - Rewrote Effectivity Cursor |
1338 REM+=========================================================================+
1339 */
1340 PROCEDURE retrieve_effectivities
1341 (
1342   return_status  OUT NOCOPY BOOLEAN
1343 )
1344 IS
1345   c_formula_effectivity   ref_cursor_typ;
1346   cur_routing_hdr     ref_cursor_typ;
1347   cur_routing_dtl     ref_cursor_typ;
1348   cur_formula_dtl     ref_cursor_typ;
1349   cur_formula_hdr     ref_cursor_typ;
1350   cur_mat_assoc       ref_cursor_typ;
1351   cur_alt_resource    ref_cursor_typ;
1352   c_recipe_override   ref_cursor_typ;
1353   c_recipe_orgn       ref_cursor_typ;
1354   c_uom_conv          ref_cursor_typ; /*B2870041 uom conversion cursor*/
1355   cur_rtg_offsets     ref_cursor_typ;
1356 /* NAMIT_CR */
1357   cur_opr_stpdep      ref_cursor_typ;
1358 /* SGIDUGU_Seq */
1359   seq_dep_dtl         ref_cursor_typ;
1360   setup_id_dtl        ref_cursor_typ;
1361   uom_code_ref        ref_cursor_typ;
1362   plant_code          ref_cursor_typ;  -- bug: 6156957 Vpedarla
1363 
1364   sql_stmt                VARCHAR2(1000)  ;  -- Bug:6156957
1365 
1366   retrieval_cursor        VARCHAR2(32700) ;
1367   effectivity_cursor      VARCHAR2(32700) ;
1368   formula_hdr_cursor      VARCHAR2(32700) ;
1369   formula_dtl_cursor      VARCHAR2(32700) ;
1370   routing_hdr_cursor      VARCHAR2(32700) ;
1371   mat_assoc_cursor        VARCHAR2(32700) ;
1372   recipe_orgn_statement   VARCHAR2(32700) ;
1373   recipe_statement        VARCHAR2(32700) ;
1374   uom_conv_cursor         VARCHAR2(32700) ; /*B2870041 hold sql for uom conv*/
1375   -- Routing offsets
1376   rtg_offset_cur_stmt     VARCHAR2(32700) ;
1377   valid                   BOOLEAN ;
1378   routing_valid           BOOLEAN ;
1379   opr_stpdep_cursor       VARCHAR2(32700) ;
1380   seq_dep_cursor          VARCHAR2(32700) ;
1381   setup_id_cursor         VARCHAR2(32700) ;
1382 
1383   old_fmeff_id            PLS_INTEGER ;
1384   old_organization_id     PLS_INTEGER ;
1385   old_formula_id          PLS_INTEGER ;
1386   mat_start_indx          PLS_INTEGER ;
1387   mat_end_indx            PLS_INTEGER ;
1388   statement_alt_resource  VARCHAR2(32700) ;
1389   eff_counter		  INTEGER ;
1390   old_plant_code          VARCHAR2(4) ;
1391   s INTEGER := 1 ;
1392   temp_total_qty          NUMBER ; /*B2870041 temp var to calculate total output*/
1393   v_matl_qty              NUMBER ; /*B2870041 cursor var to get uom conv qty */
1394   spl_cnt                 NUMBER ;
1395   j                       PLS_INTEGER ; /*B2870041 for loop index*/
1396   end_index               PLS_INTEGER ; /*B2870041 for loop index*/
1397   old_route               PLS_INTEGER ; /*B2870041 for loop index*/
1398   old_orgn                VARCHAR2(4) := NULL; /*B2870041 for loop index*/
1399   old_step                PLS_INTEGER ; /*B2870041 for loop index*/
1400   ri                      PLS_INTEGER; /*B2870041 for loop index*/
1401   found                   PLS_INTEGER; /*B2870041 for loop index*/
1402 /* NAMIT_OC */
1403   found_chrg_rsrc         PLS_INTEGER ;
1404   chrg_activity           VARCHAR2(16) ;
1405   first_step_row          PLS_INTEGER; /*B2870041 for loop index*/
1406   l_gmp_um_code           VARCHAR2(25) ;
1407   uom_code_cursor         VARCHAR2(500);
1408   dtl_i                   PLS_INTEGER;
1409 
1410   v_gmd_cursor 		ref_cursor_typ;
1411   v_dummy                 NUMBER;  /* B8401372 */
1412 
1413 nullenddatefound        BOOLEAN := FALSE;  -- Bug:6030499 Vpedarla for item_substituion
1414 
1415  l_plant_code            VARCHAR2(4);
1416  l_first_rec             BOOLEAN;            -- Bug: 6156957
1417  l_in_str_plant          VARCHAR2(32000) ;      -- Bug: 6156957
1418  l_eff_counter           NUMBER;
1419 
1420 BEGIN
1421 
1422 LOG_MESSAGE(' retrieve_effectivities started ');
1423 
1424 g_fm_dtl_start_loc        := 0; /* Start detail location */
1425 g_fm_dtl_end_loc          := 0; /* End detail location */
1426 g_fm_hdr_loc              := 1; /* Starting for formula header */
1427 g_formula_orgn_count_tab  := 1; /* Starting for formula orgn detail */
1428 
1429 g_rstep_loc               := 1 ;
1430 g_curr_rstep_loc	  := -1 ;
1431 g_prev_formula_id         := -1 ;
1432 g_prev_locn               := 1;
1433 
1434   retrieval_cursor        := NULL;
1435   effectivity_cursor      := NULL;
1436   formula_hdr_cursor      := NULL;
1437   formula_dtl_cursor      := NULL;
1438   routing_hdr_cursor      := NULL;
1439   mat_assoc_cursor        := NULL;
1440   recipe_orgn_statement   := NULL;
1441   recipe_statement        := NULL;
1442   uom_conv_cursor         := NULL;
1443   rtg_offset_cur_stmt     := NULL;
1444   opr_stpdep_cursor       := NULL ;
1445   seq_dep_cursor          := NULL ;
1446   setup_id_cursor         := NULL ;
1447   statement_alt_resource  := NULL ;
1448   old_plant_code          := NULL ;
1449   old_orgn                := NULL;
1450   chrg_activity           := NULL ;
1451   l_gmp_um_code           := NULL ;
1452   uom_code_cursor         := NULL ;
1453 
1454   valid                   := FALSE;
1455   routing_valid           := FALSE ;
1456 
1457   l_first_rec              := TRUE;
1458   l_in_str_plant          := NULL;
1459 
1460   old_fmeff_id            := 0  ;
1461   old_organization_id     := 0  ;
1462   old_formula_id          := 0  ;
1463   mat_start_indx          := 0  ;
1464   mat_end_indx            := 0  ;
1465   eff_counter		  := 0 ;
1466   s 			:= 1 ;
1467   temp_total_qty          := 0  ;
1468   v_matl_qty              := 0  ;
1469   spl_cnt                 := 0 ;
1470   j                       := 0 ;
1471   end_index               := 0 ;
1472   old_route               := 0 ;
1473   old_step                := 0 ;
1474   ri                      := 0 ;
1475   found                   := 0 ;
1476   found_chrg_rsrc         := 0 ;
1477   first_step_row          := 0 ;
1478   dtl_i                   := 0 ;
1479   v_dummy                 := 0 ;
1480 
1481 
1482 dbms_session.free_unused_user_memory;/* akaruppa B5007729 */
1483 
1484 /* populate the org_string    */
1485      IF MSC_CL_GMP_UTILITY.org_string(g_instance_id) THEN
1486         NULL ;
1487      ELSE
1488         log_message(MSC_CL_GMP_UTILITY.g_in_str_org);
1489         RAISE invalid_string_value  ;
1490      END IF;
1491 
1492 --       l_in_str_org := 'IN (1381,1382,1383,1383,5172)' ;
1493     l_in_str_org := MSC_CL_GMP_UTILITY.g_in_str_org ;  /* B3491625 */
1494      log_message(' retrieve_effectivities org string is : ' || l_in_str_org) ;
1495 
1496  /* Bug:6156957 Vpedarla select organisations to restrict the data collections */
1497 
1498    sql_stmt := 'select distinct plant_code from gmp_item_aps ' ||at_apps_link ;
1499 
1500 
1501    --bug 6902965 changes start l_in_str_plant built dynamically
1502    --bug 6924981 changes made as a result of changes made by bug 6902965 caused collections to fail
1503         l_in_str_plant := ' IN (''';
1504 
1505           OPEN plant_code for sql_stmt;
1506       LOOP
1507          FETCH plant_code INTO l_plant_code;  -- fetch next row
1508          EXIT WHEN plant_code%NOTFOUND;  -- exit loop when last row is fetched
1509 
1510         IF l_first_rec THEN
1511             l_in_str_plant:= l_in_str_plant || l_plant_code||'''';
1512             l_first_rec := FALSE;
1513          ELSE
1514             l_in_str_plant := l_in_str_plant||',' ||''''||l_plant_code||'''';
1515          END IF;
1516       END LOOP;
1517       CLOSE plant_code;
1518 
1519 --bug 6924981
1520        IF not l_first_rec THEN
1521          l_in_str_plant:= l_in_str_plant || ')';
1522        ELSE
1523         l_in_str_plant:= l_in_str_plant || ''')';
1524        END IF;
1525 --bug 6902965 changes end.
1526       LOG_MESSAGE('plant string is:'||l_in_str_plant);
1527 
1528       sql_stmt :=  NULL;
1529       l_plant_code := NULL;
1530 
1531 
1532 /*B2870041 changed cursor to retrieve the just the routing qty no uom conv,
1533 added uom conv of the product to the routing uom for a qty of 1 to get the
1534 factor. The factor will be used later. added product index to allow access
1535 when we are writing out the routing */
1536     /* The query is being modified to incorporate changes for 1830940 */
1537 /* B2989806 Added inline tables and outer joins to select aps_fmeff_id */
1538 
1539 /* NAMIT UOM Changes */
1540   --  l_gmp_um_code   := fnd_profile.VALUE('SY$UOM_HOURS'); /* OPM UOM */
1541     l_gmp_um_code   := get_profile_value('SY$UOM_HOURS', at_apps_link );
1542 
1543     IF l_gmp_um_code IS NOT NULL THEN
1544 /* Get the UOM code and UOM Class corresponding to "GMP: UOM for Hour" Profile */
1545        uom_code_cursor :=
1546                       ' select um_type '
1547                       ||' from sy_uoms_mst'||at_apps_link
1548                       ||' where um_code = :gmp_um_code ';
1549 /* mattt the comparison is done against um_code not unit_of_measure */
1550 -- ||' where unit_of_measure = :gmp_um_code ';
1551 
1552        OPEN uom_code_ref FOR uom_code_cursor USING l_gmp_um_code;
1553        FETCH uom_code_ref INTO g_gmp_uom_class;
1554        CLOSE uom_code_ref;
1555     ELSE
1556          RAISE invalid_gmp_uom_profile  ;
1557     END IF;
1558     IF (g_gmp_uom_class IS NULL) THEN
1559          RAISE invalid_gmp_uom_profile  ;
1560     END IF;
1561 
1562     effectivity_cursor :=
1563                    ' SELECT  eff.recipe_validity_rule_id, '
1564                    ||' nvl(gfe.aps_fmeff_id,-1),eff.item_id, '
1565                    ||' eff.formula_id,eff.lorgn_code, eff.organization_id, '
1566                    ||' eff.start_date, eff.end_date, eff.inv_min_qty, '
1567                    ||' eff.inv_max_qty, eff.preference, eff.uom_code, '
1568                    ||' eff.wcode, eff.routing_id, '
1569                    ||' eff.routing_no, eff.routing_vers, eff.routing_desc, '
1570                    ||' eff.item_um, eff.routing_qty, '
1571                    ||' eff.prd_fct  , eff.prd_ind, '
1572                    ||' eff.aps_item_id, eff.recipe_id, eff.recipe_no, eff.recipe_version, eff.rhdr_loc, '
1573                    ||' decode(eff.calculate_step_quantity,0,2,1) calculate_step_quantity, '
1574                    ||' eff.category_id,NULL , '
1575                    ||' eff.seq_dpnd_class '
1576                    ||' FROM (  '
1577                    ||' SELECT  /*+ DRIVING_SITE(grb) DRIVING_SITE(ffe) DRIVING_SITE(ffm) DRIVING_SITE(frh) DRIVING_SITE(som) DRIVING_SITE(gia)'
1578                    ||' DRIVING_SITE(gs1) DRIVING_SITE(gs2) DRIVING_SITE(gs3) DRIVING_SITE(gs4) */ ffe.recipe_validity_rule_id, ffe.item_id, '
1579                    ||' grb.formula_id, ffe.orgn_code lorgn_code, gia.organization_id, '
1580 		   ||' ffe.start_date, ffe.end_date, ffe.inv_min_qty, '
1581 		   ||' ffe.inv_max_qty, ffe.preference, gia.uom_code, '
1582                    ||' som.resource_whse_code wcode , grb.routing_id, '
1583 		   ||' frh.routing_no, frh.routing_vers, frh.routing_desc, '
1584                    ||' frh.item_um, frh.routing_qty, ' /*B2870041*/
1585                    ||' DECODE(frh.item_um,gia.item_um ,1, '
1586                    ||'        GMICUOM.uom_conversion'||at_apps_link
1587                    ||'                 (ffe.item_id, '
1588                    ||'                 0, '
1589                    ||'                 1, '
1590                    ||'                 gia.item_um , '   /* primary */
1591                    ||'                 frh.item_um , '   /* routing um */
1592                    ||'                 0 '
1593                    ||'                 ) '
1594                    ||'         ) prd_fct, -1 prd_ind, '
1595                    ||' gia.aps_item_id, grb.recipe_id, grb.recipe_no, grb.recipe_version, 0 rhdr_loc, '
1596                    ||' grb.calculate_step_quantity,'
1597 		   || ' gia.category_id,NULL, '
1598                    ||' gia.seq_dpnd_class '
1599 		   ||' FROM  gmd_recipes_b'||at_apps_link||' grb,'
1600 		   ||'       gmd_recipe_validity_rules'||at_apps_link||' ffe,'
1601 		   ||'       fm_form_mst'||at_apps_link||' ffm,'
1602 		   ||'       fm_rout_hdr'||at_apps_link||' frh,'
1603 		   ||'       sy_orgn_mst'||at_apps_link||' som,'
1604 		   ||'       gmp_item_aps'||at_apps_link||' gia,'
1605 		   ||'       gmd_status_b'||at_apps_link||' gs1,'
1606 		   ||'       gmd_status_b'||at_apps_link||' gs2,'
1607 		   ||'       gmd_status_b'||at_apps_link||' gs3,'
1608 		   ||'       gmd_status_b'||at_apps_link||' gs4 '
1609                    ||' WHERE grb.delete_mark = 0 '
1610                    ||'   AND grb.recipe_id = ffe.recipe_id '
1611                    ||'   AND grb.recipe_status = gs1.status_code '
1612                    ||'   AND gs1.status_type IN (' ||'''700'''|| ',' ||'''900'''|| ') '
1613                    ||'   AND gs1.delete_mark = 0 '
1614                    ||'   AND ffe.delete_mark = 0 '
1615                    ||'   AND ffe.validity_rule_status = gs2.status_code '
1616                    ||'   AND gs2.status_type IN (' ||'''700'''|| ',' ||'''900'''|| ') '
1617                    ||'   AND gs2.delete_mark = 0 '
1618                    ||'   AND frh.delete_mark = 0 '
1619                    ||'   AND ffm.delete_mark = 0 '
1620                    ||'   AND som.delete_mark = 0 '
1621                    ||'   AND frh.inactive_ind = 0 '
1622                    ||'   AND ffm.inactive_ind = 0 '
1623                    ||'   AND grb.routing_id IS NOT NULL '
1624                    ||'   AND ffe.orgn_code IS NOT NULL '
1625                    ||'   AND ffe.recipe_use IN (0,1) '
1626                    ||'   AND nvl(ffe.end_date,(SYSDATE + 1)) > SYSDATE '
1627                    ||'   AND ffe.orgn_code = som.orgn_code '
1628                    ||'   AND grb.formula_id = ffm.formula_id '
1629                    ||'   AND ffm.formula_status = gs3.status_code '
1630                    ||'   AND gs3.status_type IN (' ||'''700'''|| ',' ||'''900'''|| ') '
1631                    ||'   AND gs3.delete_mark = 0 '
1632                    ||'   AND grb.routing_id =  frh.routing_id '
1633                    ||'   AND frh.routing_status =  gs4.status_code '
1634                    ||'   AND gs4.status_type IN (' ||'''700'''|| ',' ||'''900'''|| ') '
1635                    ||'   AND gs4.delete_mark = 0 '
1636                    ||'   AND gia.plant_code =  ffe.orgn_code '
1637                    ||'   AND gia.item_id =  ffe.item_id '
1638                    ||'   AND gia.whse_code = som.resource_whse_code '
1639                    ||'   AND gia.replen_ind = 1 '
1640                    ||'   AND EXISTS ( SELECT /*+ DRIVING_SITE(fmdtl) */ 1 '
1641                    ||'          FROM  fm_matl_dtl'||at_apps_link||' fmdtl '
1642                    ||'          WHERE formula_id = grb.formula_id '
1643                    ||'            AND line_type = 1 '
1644                    ||'            AND item_id = ffe.item_id ) '
1645                    ||' UNION ALL '
1646                    ||' SELECT /*+ DRIVING_SITE(grb) DRIVING_SITE(ffe) DRIVING_SITE(ffm) DRIVING_SITE(som) DRIVING_SITE(gia)'
1647                    ||' DRIVING_SITE(gs1) DRIVING_SITE(gs2) DRIVING_SITE(gs3) */ ffe.recipe_validity_rule_id, ffe.item_id, '
1648                    ||' grb.formula_id, ffe.orgn_code lorgn_code, gia.organization_id, '
1649                    ||' ffe.start_date, ffe.end_date, ffe.inv_min_qty, '
1650                    ||' ffe.inv_max_qty, ffe.preference, gia.uom_code, '
1651                    ||' gia.whse_code wcode , to_number(null) , '
1652 		   ||' NULL, to_number(null), NULL, '
1653                    ||' NULL, to_number(null), to_number(null) prd_fct, -1 prd_ind, '
1654                    ||' gia.aps_item_id, grb.recipe_id, grb.recipe_no, grb.recipe_version , 0 rhdr_loc, '
1655 /* NAMIT_CR,SGIDUGU */
1656                    ||' 0 calculate_step_quantity, '
1657                    ||' gia.category_id,NULL, '
1658                    ||' gia.seq_dpnd_class '
1659 		   ||' FROM  gmd_recipes_b'||at_apps_link||' grb,'
1660 		   ||'       gmd_recipe_validity_rules'||at_apps_link||' ffe,'
1661 		   ||'       fm_form_mst'||at_apps_link||' ffm, '
1662 		   ||'       sy_orgn_mst'||at_apps_link||' som, '
1663 		   ||'       gmp_item_aps'||at_apps_link||' gia, '
1664 		   ||'       gmd_status_b'||at_apps_link||' gs1,'
1665 		   ||'       gmd_status_b'||at_apps_link||' gs2,'
1666 		   ||'       gmd_status_b'||at_apps_link||' gs3 '
1667                    ||' WHERE  grb.delete_mark = 0 '
1668                    ||'   AND grb.recipe_id = ffe.recipe_id '
1669                    ||'   AND grb.recipe_status = gs1.status_code '
1670                    ||'   AND gs1.status_type IN (' ||'''700'''|| ',' ||'''900'''|| ') '
1671                    ||'   AND gs1.delete_mark = 0 '
1672                    ||'   AND ffe.delete_mark = 0 '
1673                    ||'   AND ffe.validity_rule_status = gs2.status_code '
1674                    ||'   AND gs2.status_type IN (' ||'''700'''|| ',' ||'''900'''|| ') '
1675                    ||'   AND gs2.delete_mark = 0 '
1676                    ||'   AND ffm.delete_mark = 0 '
1677                    ||'   AND som.delete_mark = 0 '
1678                    ||'   AND ffm.inactive_ind = 0 '
1679                    ||'   AND grb.routing_id IS NULL '
1680                    ||'   AND ffe.orgn_code IS NOT NULL '
1681                    ||'   AND ffe.orgn_code = som.orgn_code '
1682                    ||'   AND ffe.recipe_use IN (0,1) '
1683                    ||'   AND nvl(ffe.end_date,(SYSDATE + 1)) > SYSDATE '
1684                    ||'   AND grb.formula_id = ffm.formula_id '
1685                    ||'   AND ffm.formula_status = gs3.status_code '
1686                    ||'   AND gs3.status_type IN (' ||'''700'''|| ',' ||'''900'''|| ') '
1687                    ||'   AND gs3.delete_mark = 0 '
1688                    ||'   AND gia.plant_code =  ffe.orgn_code '
1689                    ||'   AND gia.item_id =  ffe.item_id '
1690                    ||'   AND gia.whse_code = som.resource_whse_code '
1691                    ||'   AND gia.replen_ind = 1 '
1692                    ||'   AND EXISTS ( SELECT /*+ DRIVING_SITE(fmdtl) */ 1 '
1693                    ||'          FROM  fm_matl_dtl'||at_apps_link||' fmdtl '
1694                    ||'          WHERE formula_id = grb.formula_id '
1695                    ||'            AND line_type = 1 '
1696                    ||'            AND item_id = ffe.item_id ) '
1697                    ||' UNION ALL '
1698                    ||' SELECT /*+ DRIVING_SITE(grb) DRIVING_SITE(ffe) DRIVING_SITE(ffm) DRIVING_SITE(frh) DRIVING_SITE(som) DRIVING_SITE(gia)'
1699                    ||' DRIVING_SITE(gs1) DRIVING_SITE(gs2) DRIVING_SITE(gs3) DRIVING_SITE(gs4) */ ffe.recipe_validity_rule_id, ffe.item_id, '
1700                    ||' grb.formula_id, gia.plant_code lorgn_code, gia.organization_id, '
1701                    ||' ffe.start_date, ffe.end_date, ffe.inv_min_qty, '
1702                    ||' ffe.inv_max_qty, ffe.preference, gia.uom_code, '
1703                    ||' som.resource_whse_code wcode , grb.routing_id, '
1704                    ||' frh.routing_no, frh.routing_vers, frh.routing_desc, '
1705                    ||' frh.item_um, frh.routing_qty,' /*B2870041*/
1706                    ||' DECODE(frh.item_um,gia.item_um, 1, '
1707                    ||'        GMICUOM.uom_conversion'||at_apps_link
1708                    ||'                 (ffe.item_id, '
1709                    ||'                 0, '
1710                    ||'                 1, '
1711                    ||'                 gia.item_um , '   /* primary */
1712                    ||'                 frh.item_um , '   /* routing um */
1713                    ||'                 0 '
1714                    ||'                 ) '
1715                    ||'         ) prd_fct, -1 prd_ind, '
1716                    ||' gia.aps_item_id, grb.recipe_id, grb.recipe_no, grb.recipe_version , 0 rhdr_loc, '
1717 /* NAMIT_CR,SGIDUGU */
1718                    ||' grb.calculate_step_quantity, '
1719                    ||' gia.category_id,NULL, '
1720                    ||' gia.seq_dpnd_class '
1721 		   ||' FROM  gmd_recipes_b'||at_apps_link||' grb,'
1722 		   ||'       gmd_recipe_validity_rules'||at_apps_link||' ffe,'
1723 		   ||'       fm_form_mst'||at_apps_link||' ffm,'
1724 		   ||'       fm_rout_hdr'||at_apps_link||' frh,'
1725 		   ||'       sy_orgn_mst'||at_apps_link||' som,'
1726 		   ||'       gmp_item_aps'||at_apps_link||' gia,'
1727 		   ||'       gmd_status_b'||at_apps_link||' gs1,'
1728 		   ||'       gmd_status_b'||at_apps_link||' gs2,'
1729 		   ||'       gmd_status_b'||at_apps_link||' gs3,'
1730 		   ||'       gmd_status_b'||at_apps_link||' gs4 '
1731                    ||' WHERE grb.delete_mark = 0 '
1732                    ||'   AND grb.recipe_id = ffe.recipe_id '
1733                    ||'   AND grb.recipe_status = gs1.status_code '
1734                    ||'   AND gs1.status_type IN (' ||'''700'''|| ',' ||'''900'''|| ') '
1735                    ||'   AND gs1.delete_mark = 0 '
1736                    ||'   AND ffe.delete_mark = 0 '
1737                    ||'   AND ffe.validity_rule_status = gs2.status_code '
1738                    ||'   AND gs2.status_type IN (' ||'''700'''|| ',' ||'''900'''|| ') '
1739                    ||'   AND gs2.delete_mark = 0 '
1740                    ||'   AND frh.delete_mark = 0 '
1741                    ||'   AND ffm.delete_mark = 0 '
1742                    ||'   AND som.delete_mark = 0 '
1743                    ||'   AND frh.inactive_ind = 0 '
1744                    ||'   AND ffm.inactive_ind = 0 '
1745                    ||'   AND grb.routing_id IS NOT NULL '
1746                    ||'   AND ffe.orgn_code IS NULL '
1747                    ||'   AND ffe.recipe_use IN (0,1) '
1748                    ||'   AND nvl(ffe.end_date,(SYSDATE + 1)) > SYSDATE '
1749                    ||'   AND grb.formula_id = ffm.formula_id '
1750                    ||'   AND ffm.formula_status = gs3.status_code '
1751                    ||'   AND gs3.status_type IN (' ||'''700'''|| ',' ||'''900'''|| ') '
1752                    ||'   AND gs3.delete_mark = 0 '
1753                    ||'   AND grb.routing_id =  frh.routing_id '
1754                    ||'   AND frh.routing_status =  gs4.status_code '
1755                    ||'   AND gs4.status_type IN (' ||'''700'''|| ',' ||'''900'''|| ') '
1756                    ||'   AND gs4.delete_mark = 0 '
1757                    ||'   AND gia.plant_code =  som.orgn_code '
1758                    ||'   AND gia.item_id =  ffe.item_id '
1759                    ||'   AND gia.whse_code = som.resource_whse_code '
1760                    ||'   AND gia.replen_ind = 1 '
1761                    ||'   AND EXISTS ( SELECT /*+ DRIVING_SITE(fmdtl) */ 1 '
1762                    ||'          FROM  fm_matl_dtl'||at_apps_link||' fmdtl '
1763                    ||'          WHERE formula_id = grb.formula_id '
1764                    ||'            AND line_type = 1 '
1765                    ||'            AND item_id = ffe.item_id ) '
1766                    ||' UNION ALL '
1767                    ||' SELECT /*+ DRIVING_SITE(grb) DRIVING_SITE(ffe) DRIVING_SITE(som) DRIVING_SITE(ffm) DRIVING_SITE(gia)'
1768                    ||' DRIVING_SITE(gs1) DRIVING_SITE(gs2) DRIVING_SITE(gs3) */ ffe.recipe_validity_rule_id, ffe.item_id, '
1769                    ||' grb.formula_id, gia.plant_code lorgn_code, gia.organization_id, '
1770                    ||' ffe.start_date, ffe.end_date, ffe.inv_min_qty, '
1771                    ||' ffe.inv_max_qty, ffe.preference, gia.uom_code, '
1772                    ||' gia.whse_code wcode , to_number(null) , '
1773                    ||' NULL, to_number(null), NULL, '
1774                    ||' NULL, to_number(null), to_number(null) prd_fct, -1 prd_ind, ' /*B2870041*/
1775                    ||' gia.aps_item_id, grb.recipe_id, grb.recipe_no, grb.recipe_version , 0 rhdr_loc, '
1776 /* NAMIT_CR,SGIDUGU */
1777                    ||' 0 calculate_step_quantity, '
1778                    ||' gia.category_id,NULL, '
1779                    ||' gia.seq_dpnd_class '
1780 		   ||' FROM  gmd_recipes_b'||at_apps_link||' grb,'
1781 		   ||'       gmd_recipe_validity_rules'||at_apps_link||' ffe,'
1782                    ||'       sy_orgn_mst'||at_apps_link||' som, '
1783                    ||'       fm_form_mst'||at_apps_link||' ffm, '
1784                    ||'       gmp_item_aps'||at_apps_link||' gia,'
1785 		   ||'       gmd_status_b'||at_apps_link||' gs1,'
1786 		   ||'       gmd_status_b'||at_apps_link||' gs2,'
1787 		   ||'       gmd_status_b'||at_apps_link||' gs3 '
1788                    ||' WHERE grb.delete_mark = 0 '
1789                    ||'   AND grb.recipe_id = ffe.recipe_id '
1790                    ||'   AND grb.recipe_status = gs1.status_code '
1791                    ||'   AND gs1.status_type IN (' ||'''700'''|| ',' ||'''900'''|| ') '
1792                    ||'   AND gs1.delete_mark = 0 '
1793                    ||'   AND ffe.delete_mark = 0 '
1794                    ||'   AND ffe.validity_rule_status = gs2.status_code '
1795                    ||'   AND gs2.status_type IN (' ||'''700'''|| ',' ||'''900'''|| ') '
1796                    ||'   AND gs2.delete_mark = 0 '
1797                    ||'   AND ffm.delete_mark = 0 '
1798                    ||'   AND som.delete_mark = 0 '
1799                    ||'   AND ffm.inactive_ind = 0 '
1800                    ||'   AND grb.routing_id IS NULL '
1801                    ||'   AND ffe.orgn_code IS NULL '
1802                    ||'   AND ffe.recipe_use IN (0,1) '
1803                    ||'   AND nvl(ffe.end_date,(SYSDATE + 1)) > SYSDATE '
1804                    ||'   AND grb.formula_id = ffm.formula_id '
1805                    ||'   AND ffm.formula_status = gs3.status_code '
1806                    ||'   AND gs3.status_type IN (' ||'''700'''|| ',' ||'''900'''|| ') '
1807                    ||'   AND gs3.delete_mark = 0 '
1808 		   ||'   AND gia.plant_code = som.orgn_code '  ;
1809          IF l_in_str_org  IS NOT NULL THEN
1810          effectivity_cursor := effectivity_cursor
1811                    ||'   AND gia.organization_id ' || l_in_str_org
1812                    ||'   AND gia.whse_code = som.resource_whse_code ' ;
1813         END IF;
1814          /* B3837959 MMK Issue, Database link added for form_eff */
1815          effectivity_cursor := effectivity_cursor
1816 		   ||'   AND gia.item_id = ffe.item_id '
1817                    ||'   AND gia.replen_ind = 1 '
1818                    ||'   AND EXISTS ( SELECT /*+ DRIVING_SITE(fmdtl) */ 1 '
1819                    ||'          FROM  fm_matl_dtl'||at_apps_link||' fmdtl '
1820                    ||'          WHERE formula_id = grb.formula_id '
1821                    ||'            AND line_type = 1 '
1822                    ||'            AND item_id = ffe.item_id )  ) eff,'
1823                    ||'( SELECT /*+ DRIVING_SITE(gfrme) */ plant_code, whse_code, fmeff_id, '
1824                    ||'             max(aps_fmeff_id) aps_fmeff_id '
1825                    ||'             FROM gmp_form_eff'||at_apps_link||' gfrme'
1826                    ||'      GROUP BY plant_code, whse_code, fmeff_id '
1827                    ||'    ) gfe '
1828               -- Rajesh B8260178 code changes
1829                    ||'WHERE EXISTS ( select 1 from sy_orgn_mst'||at_apps_link||' som '
1830                    ||'  WHERE som.orgn_code ' || l_in_str_plant
1831                    ||'    AND som.orgn_code =  eff.lorgn_code )  '
1832                    ||' AND eff.lorgn_code = gfe.plant_code (+) '
1833                    ||' AND eff.wcode = gfe.whse_code (+) '
1834                    ||' AND eff.recipe_validity_rule_id = gfe.fmeff_id (+) '
1835 		   ||' ORDER BY 4,5,6  ' ;
1836 
1837     formula_hdr_cursor :=
1838                      ' SELECT /*+ DRIVING_SITE(ffm) DRIVING_SITE(grb) DRIVING_SITE(ffe) DRIVING_SITE(gs) */ unique ffm.formula_id, 0, 0, 0, -1, NULL '
1839                    ||' FROM fm_form_mst'||at_apps_link||' ffm, '
1840                    ||'      gmd_recipes_b'||at_apps_link||' grb, '
1841                    ||'      gmd_recipe_validity_rules'||at_apps_link||' ffe, '
1842                    ||'      gmd_status_b'||at_apps_link||' gs '
1843                    ||' WHERE grb.recipe_id = ffe.recipe_id '
1844                    ||'   AND ( ffe.orgn_code is NULL or ffe.orgn_code '|| l_in_str_plant || ')'  -- Bug:6156957 Vpedarla
1845                    ||'   AND ffe.validity_rule_status = gs.status_code '
1846                    ||'   AND gs.status_type IN (' ||'''700'''|| ',' ||'''900'''|| ') '
1847                    ||'   AND gs.delete_mark = 0 '
1848                    ||'   AND nvl(ffe.end_date,(SYSDATE + 1)) > SYSDATE '
1849                    ||'   AND ffm.formula_id = grb.formula_id '
1850                    ||'   AND ffe.delete_mark = 0 '
1851                    ||'   AND ffm.delete_mark = 0 '
1852                    ||' ORDER BY formula_id  ' ;
1853 
1854     -- gmp_putline('Started at '|| TO_CHAR(SYSDATE,'DD-MON-YYYY HH24:MI:SS'),'a');
1855     log_message('Formula Header Cursor  =  '||formula_hdr_cursor);
1856     OPEN cur_formula_hdr FOR formula_hdr_cursor;
1857     FETCH cur_formula_hdr BULK COLLECT INTO formula_header_tab;
1858     formula_headers_size := formula_header_tab.COUNT;
1859 
1860 /* PPG Bug: 13590192
1861     OPEN cur_formula_hdr FOR formula_hdr_cursor;
1862     LOOP
1863       FETCH cur_formula_hdr INTO formula_header_tab(formula_headers_size);
1864       EXIT WHEN cur_formula_hdr%NOTFOUND;
1865       formula_headers_size := formula_headers_size + 1;
1866     END LOOP;
1867 */
1868     CLOSE cur_formula_hdr;
1869    -- formula_headers_size := formula_headers_size -1 ;
1870     time_stamp;
1871     log_message('Formula Header size is = ' || to_char(formula_headers_size)) ;
1872 
1873      v_gmd_seq := 'SELECT MAX(formulaline_id) FROM fm_matl_dtl'||at_apps_link;
1874 
1875      OPEN v_gmd_cursor FOR v_gmd_seq;
1876      FETCH v_gmd_cursor INTO v_gmd_formula_lineid;
1877      CLOSE v_gmd_cursor;
1878 	v_gmd_formula_lineid := (v_gmd_formula_lineid * 2 ) + 1 ;
1879 
1880 /*B2870041 added the original um from the line and the primary um of the item
1881 but in the OPM uom format. We will use this later for conversions */
1882     /* B2657068 Rajesh Patangya */
1883     /* B2954076 Rajesh Patangya, cursor modified */
1884 
1885   -- Bug: 6030499 Vpedarla item substituion changes
1886 prev_detail_tab(1) := NULL;
1887 orig_detail_tab(1) := NULL;
1888 fd_size := 0;
1889 
1890 
1891 -- Bug: 6030499 Vpedarla changed item subsitution. Not using OLD CODE. Replaced the OLD CODE.
1892 
1893    formula_dtl_cursor :=
1894          '  SELECT /*+ DRIVING_SITE (fmd) DRIVING_SITE (ffm) DRIVING_SITE(a) */ ffm.formula_id, '
1895        ||'  ffm.formula_no, '
1896        ||'  ffm.formula_vers, '
1897        ||'  ffm.formula_desc1, '
1898        ||'  ((fmd.formulaline_id * 2) + 1) x_formulaline_id, '
1899        ||'  fmd.line_type, '
1900        ||'  fmd.item_id, '
1901        ||'  decode(fmd.original_item_flag,1,fmd.qty,(( fmd.sub_replace_qty / fmd.sub_original_qty) * fmd.line_item_qty)) qty, '
1902        /*B5176291 - for substitute items fmd.qty will be null, in those case subsittute qty should be used*/
1903        ||'  fmd.scrap_factor, '
1904        ||'  fmd.scale_type, '
1905        ||'  fmd.contribute_yield_ind, '
1906                    ||'  decode(fmd.line_type, -1, decode(nvl(fmd.contribute_step_qty_ind, '''||'N'||''''||'),'    -- venu
1907                    ||    ''''||'Y'||''''||',1,2), 1) contribute_step_qty_ind,'                                    -- venu
1908        ||'  DECODE(fmd.phantom_type,0,null,6) phantom_type, '
1909        ||'  gia.uom_code, ' --akaruppa changed gia.uom_code to msi.primary_uom_code
1910        ||'  fmd.item_um ,  ' /*B2870041*/ --akaruppa changed fmd.item_um to fmd.detail_uom and gia.item_um to msi.primary_uom_code
1911        /* bug: 6433328 vpedarla changed the primary_um from gia.uom_code to gia.item_um
1912        ||'  gia.uom_code, '  */
1913        ||'  gia.item_um, '
1914        ||'  DECODE(fmd.scale_type,0,0,1,2) bom_scale_type, '
1915        ||'  DECODE(fmd.item_um,gia.uom_code,decode(fmd.original_item_flag,1,fmd.qty,((fmd.sub_replace_qty / fmd.sub_original_qty) * fmd.line_item_qty)), '
1916        ||'        GMICUOM.uom_conversion'||at_apps_link
1917        ||'                  ( fmd.item_id, '
1918        ||'                   0, '
1919        ||'                   decode(fmd.original_item_flag,1,fmd.qty,((fmd.sub_replace_qty / fmd.sub_original_qty) * fmd.line_item_qty)), '
1920        ||'                   fmd.item_um , '
1921        ||'                   gia.item_um , '
1922        ||'                   0)) primary_qty, '
1923        ||'  gia.aps_item_id, '
1924        ||'  fmd.scale_multiple, '
1925        ||'  (fmd.scale_rounding_variance * 100) scale_rounding_variance, '   -- venu multipied it by 100
1926        ||'  decode(fmd.rounding_direction,1,2,2,1,fmd.rounding_direction) ,'
1927        ||'  fmd.release_type, '
1928        ||'  fmd.line_item_id, '
1929        ||'  fmd.start_date, '
1930        ||'  fmd.end_date, '
1931        ||'  fmd.formulaline_id formula_line_id , '
1932        ||'  fmd.preference , '
1933        ||'  null actual_end_date ,'
1934        ||'  0 actual_end_flag ,'
1935        ||'  fmd.sub_original_qty ,'   -- venu
1936    --    ||'  fmd.sub_replace_qty ,'    -- venu
1937    --    ||'  fmd.replacement_uom , '   -- venu
1938        ||'  fmd.original_item_flag , '
1939        ||'  fmd.formulaline_id formula_line_id '
1940        ||'  FROM  gmd_material_effectivities_vw'||at_apps_link||' fmd,'
1941        ||'        fm_form_mst'||at_apps_link||' ffm, '
1942        ||'        (SELECT  a.item_id, a.aps_item_id, a.item_um, a.uom_code '
1943        ||'            FROM (SELECT item_id, aps_item_id, item_um, uom_code, '
1944        ||'           ROW_NUMBER() OVER ( PARTITION BY item_id ORDER BY item_id,aps_item_id ) AS first_row '
1945        ||'           FROM gmp_item_aps ' ||at_apps_link || ' ) a where a.first_row = 1 ) gia '
1946        ||'  WHERE gia.item_id = fmd.item_id '
1947        ||'  AND ffm.formula_id = fmd.formula_id '
1948        ||'  AND ffm.formula_id  IN   ( select /*+ DRIVING_SITE(grb) DRIVING_SITE(ffe) DRIVING_SITE(gs) */ unique grb.formula_id   '             --  -- Bug:6156957 Vpedarla add this where condition
1949        ||'                  FROM  gmd_recipes_b '||at_apps_link ||' grb,  '
1950        ||'                      gmd_recipe_validity_rules  '||at_apps_link ||'  ffe, '
1951        ||'                      gmd_status_b  '||at_apps_link ||'                      gs '
1952        ||'                  WHERE grb.recipe_id = ffe.recipe_id    '
1953        ||'                  AND ( ffe.orgn_code is NULL or ffe.orgn_code '|| l_in_str_plant || ')'
1954        ||'                  AND ffe.validity_rule_status = gs.status_code    '
1955        ||'                  AND gs.status_type IN (' ||'''700'''|| ',' ||'''900'''|| ')   '
1956        ||'                  AND gs.delete_mark = 0   '
1957        ||'                  AND nvl(ffe.end_date,(SYSDATE + 1)) > SYSDATE   '
1958        ||'                  AND ffe.delete_mark = 0 )  '
1959        ||'  AND ffm.delete_mark = 0 '
1960        ||'  AND nvl(fmd.qty,fmd.sub_replace_qty)  <> 0'    -- venu added
1961        ||'  AND ( fmd.qty <> 0 OR (( fmd.sub_replace_qty / fmd.sub_original_qty) * fmd.line_item_qty) <> 0) '
1962        ||'  ORDER BY ffm.formula_id ,fmd.line_type, fmd.formulaline_id, '
1963        ||'  fmd.original_item_flag desc,fmd.start_date,fmd.preference ';
1964 
1965     LOG_MESSAGE('Formula Detail Cursor  = ' || formula_dtl_cursor );
1966 
1967 	OPEN cur_formula_dtl FOR formula_dtl_cursor;
1968 	-- { L1
1969 	LOOP
1970 	FETCH cur_formula_dtl INTO temp_detail_tab(1);
1971 	-- Bug 5955251 Vpedarla 29-Mar-2007  COLLECTION ISSUE CREATES DUMMY CO-PRODUCT CREATION IN ODS
1972 	EXIT WHEN cur_formula_dtl%NOTFOUND;
1973 	--end of bug 5955251
1974 	   -- { 1
1975 	   IF  (temp_detail_tab(1).original_item_flag = 1 ) THEN         /* If original item */
1976 	     -- { 2
1977 	     IF substcount <> 0 THEN              --processing the previous original item's substituion records
1978 	        FOR i in 1..substcount
1979 	        -- { L2
1980 	        loop
1981 	           -- { 3
1982 	           IF (subst_tab(i).start_date <= NVL(subst_tab(i).end_date,subst_tab(i).start_date)) THEN
1983 	              FOR j in 1..substcount
1984 	              -- { L3
1985 	              LOOP
1986 	                  -- { 4
1987 	                  IF ((I <> J) and
1988 	                      (subst_tab(j).start_date <= NVL(subst_tab(j).end_date,subst_tab(j).start_date))) THEN
1989 	                        -- { 5
1990 	                        IF (subst_tab(i).preference < subst_tab(j).preference) THEN
1991 	                             -- { 6
1992 	                             IF ((subst_tab(j).start_date >= subst_tab(i).start_date) and
1993 	                                  (subst_tab(i).end_date IS NULL)) THEN
1994 		       		                subst_tab(j).end_date := (subst_tab(j).start_date - 1/1440) ;
1995 
1996 	                             ELSIF ((subst_tab(j).start_date < subst_tab(i).start_date) and
1997 	                                      (subst_tab(i).end_date IS NULL) AND
1998 		                                ((subst_tab(j).end_date >= subst_tab(i).start_date) OR
1999 		                                (subst_tab(j).end_date IS NULL))) THEN
2000 	       		                     subst_tab(j).end_date := (subst_tab(i).start_date - 1/1440) ;
2001 
2002 	                             ELSIF ((subst_tab(j).start_date < subst_tab(i).end_date) and
2003 	                                    (subst_tab(j).end_date <= subst_tab(i).end_date) and
2004 	                                    (subst_tab(i).start_date <= subst_tab(j).start_date)) THEN
2005 	                                subst_tab(j).end_date := (subst_tab(j).start_date - 1/1440) ;
2006 
2007 	                             ELSIF (subst_tab(j).start_date > subst_tab(i).start_date)  and
2008 	                                  (subst_tab(j).start_date < subst_tab(i).end_date)  and
2009 	                                   (subst_tab(j).end_date > subst_tab(i).end_date) THEN
2010 		                         	   subst_tab(j).start_date := subst_tab(i).end_date + 1/1440 ;
2011 
2012 	                             ELSIF (subst_tab(i).start_date > subst_tab(j).start_date)  and
2013 	                                    (subst_tab(i).start_date < subst_tab(j).end_date)  and
2014 	                                    (subst_tab(i).end_date > subst_tab(j).end_date)  THEN
2015 	                        		 subst_tab(j).end_date := subst_tab(i).start_date - 1/1440 ;
2016                                 --Swapna Bug#5975883 below eslif condition was added
2017 	                             ELSIF(subst_tab(i).start_date <= subst_tab(j).start_date) and
2018                                       (subst_tab(i).end_date is NOT NULL) and (subst_tab(j).start_date < subst_tab(i).end_date) and
2019 	                	                 (subst_tab(j).end_date is NULL) THEN
2020 	                                 subst_tab(j).start_date := subst_tab(i).end_date + 1/1440;
2021 	                             ELSIF(subst_tab(i).start_date > subst_tab(j).start_date)  and
2022 	                	                 (subst_tab(j).end_date is NULL)
2023 	                	                 and (subst_tab(i).end_date is NOT NULL) THEN
2024 	                                 subst_tab(j).end_date := subst_tab(i).start_date - 1/1440;
2025 	                                 substcount := substcount + 1;	--Swapna Bug#5975883
2026 	                                 subst_tab(substcount) := subst_tab(j);
2027 	                           		 subst_tab(substcount).start_date := subst_tab(i).end_date +1/1440 ;
2028 	                                 subst_tab(substcount).end_date := NULL;
2029 
2030 	                             ELSIF (subst_tab(i).start_date > subst_tab(j).start_date) and
2031 		                               (subst_tab(i).end_date < subst_tab(j).end_date) THEN
2032 	                                 substcount := substcount + 1;
2033 	                                 subst_tab(substcount) := subst_tab(j);
2034 	                                 subst_tab(substcount).start_date := subst_tab(i).end_date +1/1440 ;
2035 	                                 subst_tab(substcount).end_date := subst_tab(j).end_date;
2036 	                                 subst_tab(j).end_date := subst_tab(i).start_date - 1/1440 ;
2037 
2038 	                            END IF;
2039 	                            -- } 6
2040 	                        END IF;
2041 	                        -- } 5
2042 	                   END IF;
2043 	                   -- } 4
2044 	                END LOOP;
2045 	                -- } L3
2046 	            END IF;
2047 	            -- } 3
2048 	        END LOOP;
2049 	        -- } L2
2050 	      /* insert processed substitutes now */
2051 	        FOR k in 1..substcount
2052 	        LOOP
2053 	           fd_size := fd_size + 1 ;
2054 	           formula_detail_tab(fd_size) := subst_tab(k) ;
2055 	           formula_detail_tab(fd_size).x_formulaline_id := NULL;
2056 	        END LOOP;
2057 	        /*insert trailing records if there is no substitue which has a null end date*/
2058 	        enddatenull := FALSE; -- Bug: 6030499 Vpedarla forward port of 11.5.9 bug 6047372.
2059                 FOR k in 1..substcount
2060 	        LOOP
2061 	        If subst_tab(k).end_date is null then
2062 	           enddatenull := TRUE;
2063 	        ELSIF subst_tab(k).end_date > NVL(orig_detail_tab(1).start_date,sysdate) THEN
2064 	           orig_detail_tab(1).start_date:= subst_tab(k).end_date + 1/1440 ;
2065 	        END IF;
2066 	     END LOOP;
2067 	     IF NOT(enddatenull) THEN
2068 	        fd_size := fd_size + 1 ;
2069 	        formula_detail_tab(fd_size) := orig_detail_tab(1) ;
2070 	        formula_detail_tab(fd_size).original_item_id := orig_detail_tab(1).opm_item_id;
2071 	        formula_detail_tab(fd_size).x_formulaline_id := NULL;
2072 	        formula_detail_tab(fd_size).end_date:=NULL;
2073 	     END IF;
2074 	  END IF; /* end of substitute record processing */
2075 	  -- } 2 substcount <> 0
2076 	     orig_detail_tab(1) := temp_detail_tab(1) ;
2077 		 prev_detail_tab(1) := temp_detail_tab(1) ;
2078 	        /* This is to insert original item */
2079 	     IF  nvl(temp_detail_tab(1).end_date,(SYSDATE +1)) > sysdate THEN
2080 	        fd_size := fd_size + 1 ;
2081 		    formula_detail_tab(fd_size) := temp_detail_tab (1) ;
2082 		    formula_detail_tab(fd_size).end_date := temp_detail_tab(1).end_date - 1/1440 ;
2083 	      END IF ;
2084 	        substcount := 0;
2085 	        orig_start_date:=orig_detail_tab(1).end_date;
2086 	   -- } IF of 1
2087 	   ELSE /* ELSE of original item - not an original item */
2088 	   -- { ELSE of 1
2089 	       IF substcount > 0 THEN /* from the second record onwards */
2090 	       /* comparing with prevoious record to check if there is any gap so that we insert
2091 	          the original item record in the gap. */
2092 	          IF ( temp_detail_tab(1).start_date > orig_start_date ) and NOT(nullenddatefound) THEN
2093 	         /* store the previous record' end date */
2094 	               substcount := substcount + 1 ;
2095 	               subst_tab(substcount) := orig_detail_tab(1) ;
2096 	               subst_tab(substcount).original_item_id := orig_detail_tab(1).opm_item_id;
2097 	               subst_tab(substcount).x_formulaline_id := NULL;
2098 	               subst_tab(substcount).start_date := orig_start_date;
2099 	               subst_tab(substcount).end_date := temp_detail_tab (1).start_date - 1/1440;
2100 	               subst_tab(substcount).preference:=99999;
2101 	           END IF;
2102 	       END IF;
2103 	       substcount := substcount + 1 ;
2104 	       subst_tab(substcount) := temp_detail_tab (1) ;
2105 	       IF (temp_detail_tab (1).end_date IS NULL) AND NOT (nullenddatefound)  THEN
2106 	          nullenddatefound := TRUE;
2107 	       ELSIF (temp_detail_tab(1).end_date > orig_start_date ) AND NOT (nullenddatefound) THEN
2108 	          orig_start_date := temp_detail_tab(1).end_date +1/1440;
2109 	       END IF;
2110 
2111 	   END IF;
2112 	   -- }  1
2113 	EXIT WHEN cur_formula_dtl%NOTFOUND;
2114 	END LOOP;
2115 	-- } L1
2116 CLOSE cur_formula_dtl;
2117 
2118 time_stamp ;
2119 log_message('Formula Detail size is = ' || to_char(fd_size)) ;
2120 
2121 subst_tab.delete;
2122 prev_detail_tab.delete;
2123 orig_detail_tab.delete;
2124 
2125 dbms_session.free_unused_user_memory;
2126 
2127 -- Bug: 6030499 VPedarla end of item substuition code
2128 
2129 
2130 -- =========== rtg offset data selection start ========================
2131    rtg_offset_cur_stmt := ' SELECT '||
2132 		' gro.plant_code, '||
2133 		' gro.fmeff_id, '||
2134 		' gro.formula_id, '||
2135 		' gro.routingstep_id, '||
2136 		' gro.start_offset, '||
2137 		' gro.end_offset, '||
2138 		' (rsm.formulaline_id *2 )+ 1'||
2139 		' from '||
2140 		' gmd_recipe_step_materials'||at_apps_link||' rsm, '||
2141 		' gmp_routing_offsets'||at_apps_link||' gro '||
2142 		' WHERE '||
2143 		' gro.recipe_id = rsm.recipe_id '||
2144 		' AND gro.routingstep_id = rsm.routingstep_id '||
2145 		' ORDER BY gro.formula_id,gro.plant_code, rsm.formulaline_id ' ;
2146 
2147     log_message('Routing offset Cursor  =  '||rtg_offset_cur_stmt);
2148 
2149     OPEN cur_rtg_offsets  FOR rtg_offset_cur_stmt ;
2150     FETCH cur_rtg_offsets BULK COLLECT INTO rstep_offsets;
2151 
2152     rtg_offsets_size := rstep_offsets.COUNT;
2153 
2154 /* PPG Bug: 13590192
2155     LOOP
2156       FETCH cur_rtg_offsets INTO rstep_offsets(rtg_offsets_size);
2157       EXIT WHEN cur_rtg_offsets%NOTFOUND;
2158 
2159       rtg_offsets_size := rtg_offsets_size + 1;
2160     END LOOP;
2161 */
2162 
2163     CLOSE cur_rtg_offsets;
2164 
2165  --   rtg_offsets_size := rtg_offsets_size -1 ;
2166     time_stamp ;
2167     log_message('Routing Offsets size is = ' || to_char(rtg_offsets_size)) ;
2168 
2169 -- =========== rtg offset data selection end ========================
2170 
2171     -- Validate formula for uom conversion, for planned items
2172     validate_formula ;
2173     -- PK Bug 6417932 Restored l_in_str_plant changes made for 6156957
2174     routing_hdr_cursor :=
2175                      ' SELECT /*+ DRIVING_SITE(som) DRIVING_SITE(frh) DRIVING_SITE(grb) DRIVING_SITE(ffe) DRIVING_SITE(gs) */ unique frh.routing_id, som.orgn_code, '
2176 /* NAMIT_CR 2 more zeros added for Linking Step Dependency to Routing Header */
2177                    ||'        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 '
2178                    ||' FROM sy_orgn_mst'||at_apps_link||' som, '
2179                    ||'      fm_rout_hdr'||at_apps_link||' frh, '
2180                    ||'      gmd_recipes_b'||at_apps_link||' grb, '
2181                    ||'      gmd_recipe_validity_rules'||at_apps_link||' ffe, '
2182                    ||'      gmd_status_b'||at_apps_link||' gs '
2183                    ||' WHERE grb.recipe_id = ffe.recipe_id '
2184                    ||'   AND som.orgn_code '|| l_in_str_plant            -- Bug:6156957 Vpedarla
2185                    ||'   AND ffe.validity_rule_status = gs.status_code '
2186                    ||'   AND gs.status_type IN (' ||'''700'''|| ',' ||'''900'''|| ') '
2187                    ||'   AND gs.delete_mark = 0 '
2188                    ||'   AND nvl(ffe.end_date,(SYSDATE + 1)) > SYSDATE '
2189                    ||'   AND frh.routing_id = grb.routing_id '
2190                    ||'   AND som.delete_mark = 0 '
2191                    ||'   AND som.resource_whse_code is NOT NULL '
2192                    ||'   AND nvl(ffe.orgn_code, som.orgn_code) = som.orgn_code' ;
2193             IF l_in_str_org  IS NOT NULL THEN
2194                routing_hdr_cursor := routing_hdr_cursor
2195                    ||'   AND EXISTS ( SELECT 1 FROM gmp_item_aps'||at_apps_link||' gia '
2196                    ||'   WHERE gia.whse_code = som.resource_whse_code )' ;
2197             END IF;
2198 
2199          routing_hdr_cursor := routing_hdr_cursor
2200                    ||'   AND ffe.delete_mark = 0 '
2201                    ||'   AND frh.delete_mark = 0 '
2202                    ||'   AND frh.inactive_ind = 0 '
2203                    ||' ORDER BY frh.routing_id, som.orgn_code ' ;
2204 
2205     log_message('Routing Header Cursor  =  '||routing_hdr_cursor);
2206     OPEN cur_routing_hdr FOR routing_hdr_cursor;
2207     LOOP
2208       FETCH cur_routing_hdr INTO rtg_org_hdr_tab(routing_headers_size);
2209       EXIT WHEN cur_routing_hdr%NOTFOUND;
2210       routing_headers_size := routing_headers_size + 1;
2211     END LOOP;
2212     CLOSE cur_routing_hdr;
2213     routing_headers_size := routing_headers_size -1 ;
2214     time_stamp ;
2215     log_message('Routing Header size is = ' || to_char(routing_headers_size)) ;
2216     /* 2582849 minimum_transfer_qty selected */
2217 
2218 
2219 -- Bug: 6030499 Vpedarla conditinalised the following code.
2220 
2221  IF collect_ps_data THEN
2222 
2223     /*  Select Seq Dep rows SGIDUGU
2224        Construct PL/Sql table used in bsearch
2225       Select Setup id rows for oprn_id <> -1 SGIDUGU */
2226    setup_id_cursor :=
2227           ' SELECT oprn_id, '
2228               ||'  category_id,   '
2229               ||'  seq_dep_id   '
2230               ||'  FROM  gmp_sequence_types'||at_apps_link||' gst  '
2231               ||'  WHERE oprn_id <> -1  '
2232               ||'  ORDER BY oprn_id,category_id  ' ;
2233 --
2234      setup_size := 1;
2235      OPEN setup_id_dtl FOR setup_id_cursor;
2236      LOOP
2237         FETCH setup_id_dtl INTO setupid_tab(setup_size);
2238         EXIT WHEN setup_id_dtl%NOTFOUND;
2239         setup_size := setup_size + 1;
2240      END LOOP;
2241      CLOSE setup_id_dtl;
2242      setup_size := setup_size - 1;
2243      time_stamp ;
2244      log_message('Setup id size is = ' || to_char(setup_size)) ;
2245 --
2246     /*  End of Select Seq Dep rows SGIDUGU */
2247 --
2248 
2249 END IF;  -- Bug: 6030499 Vpedarla end of condition code.
2250     -- PK Bug 6417932 Restored l_in_str_plant changes made for 6156957
2251     routing_dtl_cursor :=
2252           ' SELECT /*+ DRIVING_SITE(sou) DRIVING_SITE(sou2) DRIVING_SITE(crd) DRIVING_SITE(frd) DRIVING_SITE(fom) DRIVING_SITE(goa) DRIVING_SITE(gor) */ frd.routing_id, '
2253               ||'  crd.orgn_code, '
2254               ||'  frd.routingstep_no,  '
2255               ||'  NVL(goa.sequence_dependent_ind,0), '
2256               /* This will ensure that ordering will always have primary first */
2257               ||'  DECODE(gor.prim_rsrc_ind, 1,1,2,2,0,3), '
2258               ||'  gor.resources, '
2259               ||'  gor.prim_rsrc_ind, '
2260               ||'  decode(crd.capacity_constraint,1,1,2), '
2261               ||'  crd.min_capacity, '
2262               ||'  crd.max_capacity, '
2263               ||'  crd.schedule_ind, '
2264               ||'  frd.routingstep_id, '
2265               ||'  ((frd.routingstep_id * 2) + 1) x_routingstep_id,  '
2266               ||'  frd.step_qty, '
2267               ||'  NVL(frd.minimum_transfer_qty,0) minimum_transfer_qty, '
2268               ||'  fom.oprn_desc,  '
2269               ||'  fom.oprn_id,  '     /* SGIDUGU Seq Dep */
2270               ||'  fom.oprn_no,  '
2271               ||'  sou2.uom_code,'
2272               ||'  goa.activity, '
2273               ||'  goa.oprn_line_id, '
2274               ||'  gor.resource_count, '
2275               ||'  gor.resource_usage, '
2276               ||'  gor.usage_um, '
2277               ||'  gor.scale_type,'
2278               ||'  goa.offset_interval, '
2279               ||'  crd.resource_id, '
2280               ||'  ((crd.resource_id * 2) + 1) x_resource_id, '
2281 --              ||'  -- DECODE(gor.scale_type,0,2,1,1,2,1) , ' /* B2967464 */
2282               ||'  DECODE(gor.scale_type,0,2,1,1,2,3) , ' /* B2967464 */
2283               ||'  sou.uom_code, '
2284               ||'  goa.activity_factor, '
2285               ||'  gor.process_qty, '
2286 --              ||'  NVL(goa.sequence_dependent_ind,0), '
2287               ||'  NVL(goa.material_ind,0), '
2288               ||'  1 , '
2289               || '  SUM(NVL(goa.material_ind,0))  OVER (PARTITION BY '
2290               || '  frd.routing_id, crd.orgn_code, frd.routingstep_no) mat_found, '
2291               || '  1, ' /* flag for including rows */
2292               || '  decode(goa.break_ind,NULL,2,0,2,1,1) brk_ind'
2293               || ' ,-1, -1, -1, -1, -1, -1, '
2294               ||' (SUM(DECODE(NVL(goa.sequence_dependent_ind,0),1,1,0)) OVER '
2295               ||' (PARTITION BY '
2296               ||' frd.routing_id, crd.orgn_code)) is_sds_rout,'
2297               ||' DECODE(NVL(goa.sequence_dependent_ind,0),1,DECODE(gor.prim_rsrc_ind,1,1,0),0) is_unique, '
2298               ||' DECODE(NVL(goa.sequence_dependent_ind,0),1,0,DECODE(gor.prim_rsrc_ind,1,1,0)) is_nonunique, '
2299               ||' NULL setup_id '
2300               ||' FROM  sy_uoms_mst'||at_apps_link||' sou, '
2301               ||'       sy_uoms_mst'||at_apps_link||' sou2, '
2302               ||'       cr_rsrc_dtl'||at_apps_link||' crd, '
2303               ||'       fm_rout_dtl'||at_apps_link||' frd, '
2304               ||'       gmd_operations'||at_apps_link||' fom, '
2305               ||'       gmd_operation_activities'||at_apps_link||' goa, '
2306               ||'       gmd_operation_resources'||at_apps_link||' gor '
2307               ||'   WHERE frd.routing_id IN  ( select /*+ DRIVING_SITE(grb) DRIVING_SITE(ffe) DRIVING_SITE(gs) */ unique grb.routing_id    '   -- Bug:6156957 Vpedarla added this where condition
2308               ||'          FROM  gmd_recipes_b  '||at_apps_link||'  grb,  '
2309               ||'         gmd_recipe_validity_rules   '||at_apps_link||'   ffe,  '
2310               ||'         gmd_status_b  '||at_apps_link||'   gs  '
2311               ||'         WHERE grb.recipe_id = ffe.recipe_id '
2312               ||'         AND ( ffe.orgn_code is NULL or ffe.orgn_code '|| l_in_str_plant || ')'
2313               ||'         AND ffe.validity_rule_status = gs.status_code '
2314               ||'         AND gs.status_type IN (' ||'''700'''|| ',' ||'''900'''|| ')   '
2315               ||'         AND gs.delete_mark = 0    '
2316               ||'         AND nvl(ffe.end_date,(SYSDATE + 1)) > SYSDATE '
2317               ||'         AND ffe.delete_mark = 0  )  '
2318               ||'   AND frd.oprn_id = fom.oprn_id '
2319               ||'   AND fom.oprn_id = goa.oprn_id '
2320               ||'   AND goa.oprn_line_id = gor.oprn_line_id '
2321               ||'   AND crd.resources = gor.resources '
2322               ||'   AND sou.um_code = gor.usage_um '
2323               ||'   AND sou2.um_code = fom.process_qty_um '
2324               ||'   AND sou.delete_mark = 0 '
2325               ||'   AND fom.delete_mark = 0 '
2326               ||'   AND goa.activity_factor > 0 '
2327               ||'   AND sou.um_type = :gmp_uom_class '
2328               ||' ORDER BY  '
2329               ||'         1, 2, 3, 4, 5, 6 ';
2330 
2331     log_message('g_gmp_uom_class '||g_gmp_uom_class||' Routing Detail Cursor  =  '||routing_dtl_cursor);
2332     OPEN cur_routing_dtl FOR routing_dtl_cursor USING g_gmp_uom_class;
2333     LOOP
2334       FETCH cur_routing_dtl INTO rtg_org_dtl_tab(rtg_org_dtl_size);
2335       EXIT WHEN cur_routing_dtl%NOTFOUND;
2336       /*B2870041 The activities have to be properly marked for the schedule
2337          flag. This only needs to be done once for the route. The index is
2338          copied for ease of use. */
2339 
2340       ri := rtg_org_dtl_size;
2341 
2342       /* since the select includes orgn_code we need to track when the route
2343          org or step changes. If any of them change this means the step has
2344          changed. when there is a new step the process needs to reset. The
2345          new values are saved and the first row of the step is saved to be
2346          used to loop later. found will be used to indicate that an activity
2347          has the material ind set to 1 */
2348 
2349       IF old_route <> rtg_org_dtl_tab(ri).routing_id OR
2350          old_orgn <> rtg_org_dtl_tab(ri).orgn_code OR
2351          old_step <> rtg_org_dtl_tab(ri).routingstep_no THEN
2352 
2353         found := 0;
2354         /* NAMIT_OC */
2355         found_chrg_rsrc := 0;
2356         chrg_activity   := NULL;
2357         first_step_row := ri;
2358 
2359         old_route := rtg_org_dtl_tab(ri).routing_id;
2360         old_orgn := rtg_org_dtl_tab(ri).orgn_code;
2361         old_step := rtg_org_dtl_tab(ri).routingstep_no;
2362 
2363       END IF;
2364       /* if we found an activity with the material ind = 1 and one has not
2365          found yet we need to go back and set all the activities before this
2366          one in the step as PRIOR. the rows are looped though using the first
2367          step row index to the row before this current row. All rows with
2368          the material ind = 1 will have the schedule flag set to 1 as part
2369          of the query by default. If no activity has a material ind = 1
2370          all of the activities will be considered as schedule_flag=1
2371          by default in the query */
2372 
2373       IF rtg_org_dtl_tab(ri).material_ind = 1 AND found = 0 THEN
2374         found := 1;
2375         IF first_step_row < ri THEN
2376           end_index := ri -1;
2377           FOR j IN first_step_row..end_index
2378           LOOP
2379             rtg_org_dtl_tab(j).schedule_flag := 3;
2380           END LOOP;
2381         END IF;
2382 
2383       /* if the material ind is 0 but another activity was found with 1
2384          then this row will be considered as NEXT. */
2385       ELSIF rtg_org_dtl_tab(ri).material_ind = 0 AND found = 1 THEN
2386         rtg_org_dtl_tab(ri).schedule_flag := 4;
2387       END IF;
2388 
2389         /* NAMIT_OC */
2390 
2391         /* If an operation has been found to have more than one activity with chargeable resources the first
2392         activity will be used and all other activities will have the scale type changed to be linear. If any
2393         activity found with chargeable resource, other activities in the operation having resource with
2394         scale_type "By Charge", will be changed to scale_type "Proportional" */
2395 
2396       IF rtg_org_dtl_tab(ri).mat_found = 0 OR rtg_org_dtl_tab(ri).material_ind = 1
2397       THEN
2398 
2399         IF rtg_org_dtl_tab(ri).rtg_scale_type = 3
2400         AND rtg_org_dtl_tab(ri).capacity_constraint = 1
2401         AND found_chrg_rsrc = 0 THEN
2402           found_chrg_rsrc := 1;
2403           chrg_activity := rtg_org_dtl_tab(ri).activity;
2404         /* if the rtg_scale_type is 3 but another activity was found with 3
2405            then this row will be assigned scale_type = 1. */
2406         ELSIF rtg_org_dtl_tab(ri).rtg_scale_type = 3
2407         AND rtg_org_dtl_tab(ri).capacity_constraint = 1
2408         AND found_chrg_rsrc = 1
2409         AND chrg_activity <> rtg_org_dtl_tab(ri).activity THEN
2410           rtg_org_dtl_tab(ri).rtg_scale_type := 1;
2411           rtg_org_dtl_tab(ri).scale_type := 1;
2412         END IF;
2413       END IF;
2414 
2415       rtg_org_dtl_size := rtg_org_dtl_size + 1;
2416 
2417     END LOOP;
2418     CLOSE cur_routing_dtl;
2419     rtg_org_dtl_size := rtg_org_dtl_size -1 ;
2420     time_stamp ;
2421     log_message('Routing Org detail size is = ' || to_char(rtg_org_dtl_size)) ;
2422 
2423      /* New GMD Changes - B1830940 */
2424     -- PK Bug 6417932 Restored l_in_str_plant changes made for 6156957
2425     validation_statement := 'SELECT '
2426               ||' /*+ DRIVING_SITE(frd) DRIVING_SITE(fom) DRIVING_SITE(goa) DRIVING_SITE(gor) DRIVING_SITE(sou) */ '
2427               ||'  frd.routing_id, '
2428               ||'  frd.routingstep_no, '
2429 /* NAMIT_RD */
2430               ||'  NVL(goa.sequence_dependent_ind,0), '
2431               ||'  DECODE(gor.prim_rsrc_ind, 1,1,2,2,0,3), ' /* This will ensure that ordering will
2432                                                                 always have primary firsr*/
2433               ||'  gor.resources, '
2434               ||'  frd.routingstep_id, '
2435               ||'  fom.oprn_no, '
2436               ||'  goa.oprn_line_id, '
2437               ||'  goa.activity, '
2438               ||'  decode(gor.prim_rsrc_ind,1,1,2), ' --  Bug: 6030499 Vpedarla   ||'  gor.prim_rsrc_ind, '
2439 --              ||'  gor.resources, '
2440 --              ||'  decode(gor.prim_rsrc_ind,1,1,2) prim_rsrc_ind, '
2441 --              ||'  NVL(goa.sequence_dependent_ind,0), '
2442               ||'  goa.offset_interval, '
2443 /* NAMIT_RD */
2444               ||'  sou.uom_code '
2445               ||' FROM  fm_rout_dtl'||at_apps_link||' frd, '
2446               ||'       gmd_operations'||at_apps_link||' fom, '
2447               ||'       gmd_operation_activities'||at_apps_link||' goa, '
2448               ||'       gmd_operation_resources'||at_apps_link||' gor, '
2449 /* NAMIT_RD */
2450               ||'       sy_uoms_mst'||at_apps_link||' sou '
2451               ||' WHERE frd.routing_id IN ( select /*+ DRIVING_SITE(grb) DRIVING_SITE(ffe) DRIVING_SITE(gs) */ unique grb.routing_id    '  -- Bug:6156957 Vpedarla added this where condition
2452               ||'          FROM  gmd_recipes_b  '||at_apps_link||'  grb,  '
2453               ||'         gmd_recipe_validity_rules   '||at_apps_link||'       ffe,  '
2454               ||'         gmd_status_b  '||at_apps_link||'   gs  '
2455               ||'         WHERE grb.recipe_id = ffe.recipe_id '
2456               ||'         AND ( ffe.orgn_code is NULL or ffe.orgn_code '|| l_in_str_plant || ')'
2457               ||'         AND ffe.validity_rule_status = gs.status_code '
2458               ||'         AND gs.status_type IN (' ||'''700'''|| ',' ||'''900'''|| ')   '
2459               ||'         AND gs.delete_mark = 0    '
2460               ||'         AND nvl(ffe.end_date,(SYSDATE + 1)) > SYSDATE '
2461               ||'         AND ffe.delete_mark = 0  ) '
2462               ||'   AND frd.oprn_id = fom.oprn_id '
2463               ||'   AND fom.oprn_id = goa.oprn_id '
2464 /* NAMIT_RD */
2465 --              ||'   AND gor.prim_rsrc_ind in (1,2) '
2466               ||'   AND fom.delete_mark = 0'
2467               ||'   AND goa.oprn_line_id = gor.oprn_line_id '
2468 /* NAMIT_RD */
2469               ||'   AND sou.um_code = gor.usage_um '
2470               ||'   AND sou.delete_mark = 0 '
2471               ||'   AND sou.um_type = :gmp_uom_class '
2472 /* NAMIT_RD */
2473               ||' ORDER BY 1, 2, 3, 4, 5 ' ;
2474 /*              ||' ORDER BY frd.routing_id, '
2475               ||'          frd.routingstep_no, '
2476               ||'          fom.oprn_no, '
2477               ||'          NVL(goa.sequence_dependent_ind,0) DESC, '
2478               ||'          goa.offset_interval,'
2479               ||'          goa.activity,'
2480               ||'          goa.oprn_line_id,'
2481               ||'          decode(gor.prim_rsrc_ind,1,1,2), '
2482               ||'          gor.resources ' ;*/
2483 
2484     log_message('g_gmp_uom_class '||g_gmp_uom_class||' validation_statement  =  '||validation_statement);
2485     OPEN cur_routing_dtl FOR validation_statement USING g_gmp_uom_class;
2486     FETCH cur_routing_dtl BULK COLLECT INTO rtg_gen_dtl_tab;
2487     rtg_gen_dtl_size := rtg_gen_dtl_tab.count;
2488 /* PPG Bug: 13590192
2489     LOOP
2490       FETCH cur_routing_dtl INTO rtg_gen_dtl_tab(rtg_gen_dtl_size);
2491       EXIT WHEN cur_routing_dtl%NOTFOUND;
2492       rtg_gen_dtl_size := rtg_gen_dtl_size + 1;
2493     END LOOP;
2494 */
2495 
2496     CLOSE cur_routing_dtl;
2497 --    rtg_gen_dtl_size := rtg_gen_dtl_size -1 ;
2498     time_stamp ;
2499     log_message('Generic Routing size is = ' || to_char(rtg_gen_dtl_size)) ;
2500 
2501     --   B8333384 Rajesh Patangya, added gmd_status join
2502 
2503     recipe_orgn_statement := ' SELECT '
2504                ||'  grb.routing_id, gc.orgn_code, '
2505                ||'  gc.routingstep_id, gc.oprn_line_id, gc.recipe_id, '
2506                ||'  gc.activity_factor, '
2507                ||'  gc.resources, gc.resource_usage, gc.process_qty, '
2508                ||'  gc.min_capacity, gc.max_capacity  '
2509                ||' FROM gmd_recipes'||at_apps_link||' grb, '
2510                ||' ( '
2511                ||' SELECT /*+ DRIVING_SITE(goa) DRIVING_SITE(gor) */'
2512                ||'  gor.recipe_id, '
2513                ||'  gor.orgn_code, '
2514                ||'  gor.oprn_line_id, '
2515                ||'  gor.routingstep_id, '
2516                ||'  goa.activity_factor, '
2517                ||'  gor.resources, '
2518                ||'  gor.resource_usage , '
2519                ||'  gor.process_qty,  '
2520                ||'  gor.min_capacity, '
2521                ||'  gor.max_capacity  '
2522                ||' FROM  gmd_recipe_orgn_activities'||at_apps_link||' goa, '
2523                ||'       gmd_recipe_orgn_resources'||at_apps_link||' gor '
2524                ||' WHERE gor.recipe_id = goa.recipe_id '
2525                ||'   AND gor.orgn_code = goa.orgn_code '
2526                ||'   AND gor.oprn_line_id = goa.oprn_line_id '
2527                ||'   AND gor.routingstep_id = goa.routingstep_id '
2528                ||' UNION ALL '
2529                ||' SELECT /*+ DRIVING_SITE(goa) DRIVING_SITE(gor) */ goa.recipe_id, '
2530                ||'  goa.orgn_code, '
2531                ||'  goa.oprn_line_id, '
2532                ||'  goa.routingstep_id, '
2533                ||'  goa.activity_factor,  '
2534                ||'  NULL resources,  '
2535                ||'  -1 resource_usage, '
2536                ||'  -1 process_qty, '
2537                ||'  -1 min_capacity, '
2538                ||'  -1 max_capacity '
2539                ||' FROM  gmd_recipe_orgn_activities'||at_apps_link||' goa '
2540                ||' WHERE NOT EXISTS( SELECT 1 '
2541                ||'       FROM gmd_recipe_orgn_resources'||at_apps_link||' gor '
2542                ||'       WHERE gor.recipe_id = goa.recipe_id '
2543                ||'         AND gor.orgn_code = goa.orgn_code '
2544                ||'         AND gor.oprn_line_id = goa.oprn_line_id '
2545                ||'         AND gor.routingstep_id = goa.routingstep_id ) '
2546                ||' UNION ALL '
2547                ||' SELECT /*+ DRIVING_SITE(goa) DRIVING_SITE(gor) */ gor.recipe_id, '
2548                ||'  gor.orgn_code, '
2549                ||'  gor.oprn_line_id, '
2550                ||'  gor.routingstep_id, '
2551                ||'  -1 activity_factor, '
2552                ||'  gor.resources, '
2553                ||'  gor.resource_usage , '
2554                ||'  gor.process_qty,  '
2555                ||'  gor.min_capacity, '
2556                ||'  gor.max_capacity '
2557                ||' FROM  gmd_recipe_orgn_resources'||at_apps_link||' gor  '
2558                ||' WHERE NOT EXISTS( SELECT 1 '
2559                ||'       FROM gmd_recipe_orgn_activities'||at_apps_link||' goa'
2560                ||'       WHERE goa.recipe_id = gor.recipe_id '
2561                ||'         AND goa.orgn_code = gor.orgn_code '
2562                ||'         AND goa.oprn_line_id = gor.oprn_line_id '
2563                ||'         AND goa.routingstep_id = gor.routingstep_id ) '
2564                ||' ) gc, '
2565                ||' gmd_status_b'||at_apps_link||' gs1  '
2566                ||' WHERE grb.recipe_id = gc.recipe_id '
2567                ||'   AND grb.delete_mark = 0 '
2568                ||'   AND grb.recipe_status = gs1.status_code '
2569                ||'   AND gs1.status_type IN (' ||'''700''' || ',' || '''900''' || ') '
2570                ||'   AND gs1.delete_mark = 0 '
2571                ||' ORDER BY 1,2,3,4,5 ' ;
2572 
2573 
2574     LOG_MESSAGE('recipe_orgn_statement -'||recipe_orgn_statement);
2575     OPEN c_recipe_orgn FOR recipe_orgn_statement;
2576 /* PPG Bug: 13590192
2577     LOOP
2578       FETCH c_recipe_orgn INTO rcp_orgn_override(recipe_orgn_over_size);
2579       EXIT WHEN c_recipe_orgn%NOTFOUND;
2580       recipe_orgn_over_size := recipe_orgn_over_size + 1;
2581     END LOOP;
2582   */
2583    FETCH c_recipe_orgn BULK COLLECT INTO rcp_orgn_override;
2584    recipe_orgn_over_size := rcp_orgn_override.COUNT;
2585 
2586     CLOSE c_recipe_orgn;
2587 
2588     --recipe_orgn_over_size := recipe_orgn_over_size -1 ;
2589     time_stamp ;
2590     log_message('recipe_orgn_over_size is= '|| to_char(recipe_orgn_over_size));
2591 
2592     --   B8333384 Rajesh Patangya, added gmd_status join
2593 
2594     recipe_statement :=
2595                  ' SELECT /*+ DRIVING_SITE(grb) DRIVING_SITE(grs) DRIVING_SITE(gs1) */ '
2596                ||' grb.routing_id, grs.routingstep_id, grs.recipe_id, '
2597                ||'        grs.step_qty '
2598                ||' FROM gmd_recipes'||at_apps_link||' grb, '
2599                ||'      gmd_recipe_routing_steps'||at_apps_link||' grs, '
2600                ||'      gmd_status_b'||at_apps_link||' gs1  '
2601                ||' WHERE grb.recipe_id = grs.recipe_id '
2602                ||'   AND grb.delete_mark = 0 '
2603                ||'   AND grb.recipe_status = gs1.status_code '
2604                ||'   AND gs1.status_type IN (' ||'''700''' || ',' || '''900''' || ') '
2605                ||'   AND gs1.delete_mark = 0 '
2606                ||' ORDER BY 1,2,3 ' ;
2607 
2608     LOG_MESSAGE('recipe_statement is = '|| recipe_statement);
2609     OPEN c_recipe_override FOR recipe_statement ;
2610      FETCH c_recipe_override BULK COLLECT INTO recipe_override;
2611 /* PPG Bug: 13590192
2612     LOOP
2613       FETCH c_recipe_override INTO recipe_override(recipe_override_size);
2614       EXIT WHEN c_recipe_override%NOTFOUND;
2615       recipe_override_size := recipe_override_size + 1;
2616     END LOOP;
2617  */
2618     CLOSE c_recipe_override;
2619  --   recipe_override_size := recipe_override_size -1 ;
2620     recipe_override_size := recipe_override.COUNT;
2621     time_stamp ;
2622     log_message('recipe Override size is = '||to_char(recipe_override_size)) ;
2623 
2624 
2625      /* Alternate Resource selection   */
2626      /* B5688153, Rajesh Patangya prod spec alt*/
2627         statement_alt_resource :=
2628                      ' SELECT /*+ DRIVING_SITE(acrd) DRIVING_SITE(pcrd) DRIVING_SITE(cam) DRIVING_SITE(prod) */ '
2629                    ||' pcrd.resource_id, acrd.resource_id, '
2630                    ||' acrd.min_capacity, acrd.max_capacity, '
2631                    ||' cam.runtime_factor, '
2632 /*prod spec alt*/  ||' nvl(cam.preference,-1), nvl(prod.item_id,-1)   '
2633                    ||' FROM  cr_rsrc_dtl'||at_apps_link||' acrd, '
2634                    ||'       cr_rsrc_dtl'||at_apps_link||' pcrd, '
2635                    ||'       cr_ares_mst'||at_apps_link||' cam, '
2636 		               ||'       gmp_altresource_products'||at_apps_link||' prod'
2637                    ||' WHERE cam.alternate_resource = acrd.resources '
2638                    ||'   AND cam.primary_resource = pcrd.resources '
2639                    ||'   AND acrd.orgn_code = pcrd.orgn_code '
2640                    ||'   AND cam.primary_resource = prod.primary_resource(+) '
2641                    ||'   AND cam.alternate_resource = prod.alternate_resource(+)  '
2642                    ||'   AND acrd.delete_mark = 0  '
2643                    ||' ORDER BY pcrd.resource_id, '
2644                    ||'   DECODE(cam.preference,NULL,cam.runtime_factor,cam.preference),'
2645                    ||'   prod.item_id ' ;
2646 
2647 
2648     OPEN cur_alt_resource FOR statement_alt_resource ;
2649     LOOP
2650       FETCH cur_alt_resource INTO rtg_alt_rsrc_tab(alt_rsrc_size);
2651       EXIT WHEN cur_alt_resource%NOTFOUND;
2652       alt_rsrc_size := alt_rsrc_size + 1;
2653     END LOOP;
2654     CLOSE cur_alt_resource;
2655     alt_rsrc_size := alt_rsrc_size -1 ;
2656     time_stamp ;
2657     log_message('Alternate Routing size is = ' || to_char(alt_rsrc_size)) ;
2658 
2659 /* NAMIT_CR Get Step Dependency data */
2660 
2661  -- Bug:6030499  Vpedrla conditional code
2662 IF collect_ps_data THEN
2663 
2664    opr_stpdep_cursor := '    SELECT /*+ DRIVING_SITE(frd1) DRIVING_SITE(frd2) DRIVING_SITE(frdp) */ frdp.routing_id, '
2665               ||'          ((frd2.routingstep_id * 2) + 1) x_dep_routingstep_id, '
2666               ||'          ((frd1.routingstep_id * 2) + 1) x_routingstep_id, '
2667               ||'          decode(frdp.dep_type,0,1,2) dependency_type, '
2668               ||'          frdp.standard_delay, '
2669               ||'          frdp.max_delay, '
2670               ||'          frdp.transfer_pct, '
2671               ||'          frdp.dep_routingstep_no, '
2672               ||'          frdp.routingstep_no, '
2673               ||'          decode(nvl(frdp.chargeable_ind, 0),0,2,1,1) '
2674               ||'      FROM '
2675               ||'          fm_rout_dtl'||at_apps_link||' frd1, '
2676               ||'          fm_rout_dtl'||at_apps_link||' frd2, '
2677               ||'          fm_rout_dep'||at_apps_link||' frdp '
2678               ||'      WHERE '
2679               ||'          frd1.routing_id = frdp.routing_id '
2680               ||'          AND frd1.routingstep_no = frdp.routingstep_no '
2681               ||'          AND frd2.routing_id = frdp.routing_id '
2682               ||'          AND frd2.routingstep_no = frdp.dep_routingstep_no '
2683               ||'      ORDER BY 1,3,2 ' ;
2684 
2685     OPEN cur_opr_stpdep FOR opr_stpdep_cursor ;
2686     FETCH cur_opr_stpdep BULK COLLECT INTO gmp_opr_stpdep_tbl;
2687     opr_stpdep_size := gmp_opr_stpdep_tbl.COUNT;
2688 
2689 /* PPG Bug: 13590192
2690     LOOP
2691       FETCH cur_opr_stpdep INTO gmp_opr_stpdep_tbl(opr_stpdep_size);
2692       EXIT WHEN cur_opr_stpdep%NOTFOUND;
2693       opr_stpdep_size := opr_stpdep_size + 1;
2694     END LOOP;
2695 */
2696 
2697     CLOSE cur_opr_stpdep;
2698 --    opr_stpdep_size := opr_stpdep_size -1 ;
2699     time_stamp ;
2700     log_message('Operation Step Dependency size is = ' || to_char(opr_stpdep_size)) ;
2701 
2702 END IF;
2703 -- Bug:6030499 Vpedarla end of conditional code
2704 
2705     /* ------------------------------------------------------- */
2706     /* PROCESSING STARTS AFTER SELECTION OF THE DATA IN MEMORY */
2707     /* ------------------------------------------------------- */
2708 
2709     -- Link the routing header and detail
2710     log_message('before link_routing') ;
2711     time_stamp ;
2712     link_routing ;
2713     log_message('After link_routing') ;
2714     time_stamp ;
2715 /* Now spool the routing Header data for debugging */
2716 /*
2717   log_message ('Routing is ');
2718   log_message ('RTG_ID Plnt Valid GStart GEnd OStart OEnd StStart StEND UsgSt
2719   UsgEnd StpDepSt StpDepEnd  ');
2720   For spl_cnt in 1..rtg_org_hdr_tab.COUNT
2721   LOOP
2722      log_message ( rtg_org_hdr_tab(spl_cnt).routing_id ||'*'||
2723      rtg_org_hdr_tab(spl_cnt).plant_code         ||'*'||
2724      rtg_org_hdr_tab(spl_cnt).valid_flag         ||'*'||
2725      rtg_org_hdr_tab(spl_cnt).generic_start_loc  ||'*'||
2726      rtg_org_hdr_tab(spl_cnt).generic_end_loc    ||'*'||
2727      rtg_org_hdr_tab(spl_cnt).orgn_start_loc     ||'*'||
2728      rtg_org_hdr_tab(spl_cnt).orgn_end_loc       ||'*'||
2729      rtg_org_hdr_tab(spl_cnt).step_start_loc     ||'*'||
2730      rtg_org_hdr_tab(spl_cnt).step_end_loc       ||'*'||
2731      rtg_org_hdr_tab(spl_cnt).usage_start_loc    ||'*'||
2732      rtg_org_hdr_tab(spl_cnt).usage_end_loc      ||'*'||
2733      rtg_org_hdr_tab(spl_cnt).stpdep_start_loc   ||'*'||
2734      rtg_org_hdr_tab(spl_cnt).stpdep_end_loc );
2735   END LOOP ;
2736   */
2737 
2738     -- Link the routing header and detail overrides
2739     log_message('before link_override_routing') ;
2740     time_stamp ;
2741     link_override_routing ;
2742     log_message('After link_override_routing') ;
2743     time_stamp ;
2744 
2745 
2746     /*  New GMD Changes B1830940 */
2747     /*  B2800311, APS SHOULD SEE INGREDIENTS RELEASED AS AUTO-BY-STEP */
2748     /* B3054460 OPM/APS TO CATER FOR CHANGE TO TIME PHASED PLANNING OF
2749        MANUAL CONSUMPTION TYPE
2750     */
2751     /* Bug: 7286778 Vpedarla added index GMP_ITEM_APS_I2 usage hint for better performance */
2752 
2753     mat_assoc_cursor  :=
2754             ' SELECT formula_id, '
2755             ||' recipe_id,  '
2756             ||' line_type,  '
2757             ||' line_no,    '
2758             ||' x_formulaline_id, '
2759             ||' x_routingstep_id, '
2760             ||' item_id, '
2761             ||' routingstep_no, '
2762             ||' aps_item_id, '
2763             ||' DECODE(fmd_item_um, gia_item_um, 1, GMICUOM.uom_conversion'||at_apps_link||' (item_id, 0, 1, fmd_item_um, gia_item_um, 0)) uom_conv_factor, '
2764             ||' minimum_transfer_qty, '
2765             ||' minimum_delay, '
2766             ||' maximum_delay '
2767             ||' FROM ( '
2768             ||'  SELECT DISTINCT '
2769             ||'  /*+ DRIVING_SITE(r) DRIVING_SITE(frm) DRIVING_SITE(fmd) DRIVING_SITE(frd) DRIVING_SITE(gia)  */ '
2770 	    ||'  fmd.formula_id, '
2771 	    ||'  frm.recipe_id, '
2772             ||'  DECODE(fmd.line_type, 1,1,2,2,-1,3) line_type, '
2773 	    ||'  fmd.line_no, '
2774             ||'  ((frm.formulaline_id * 2) + 1) x_formulaline_id, '
2775             ||'  ((frm.routingstep_id * 2) + 1) x_routingstep_id, '
2776 	    ||'   fmd.item_id, '
2777 	    ||'   frd.routingstep_no, '
2778             ||'   gia.aps_item_id, '
2779             ||'   decode(fmd.line_type, 1, frm.minimum_transfer_qty, null) minimum_transfer_qty, '
2780             ||'   decode(fmd.line_type, 1, frm.minimum_delay, null) minimum_delay, '
2781             ||'   decode(fmd.line_type, 1, frm.maximum_delay, null) maximum_delay, '
2782             ||'  fmd.item_um fmd_item_um, '
2783             ||'  gia.item_um gia_item_um '
2784             ||' FROM gmd_recipes_b'||at_apps_link||' r ,'
2785 	    ||'      gmd_recipe_step_materials'||at_apps_link||' frm, '
2786             ||'      fm_matl_dtl'||at_apps_link||' fmd, '
2787             ||'      fm_rout_dtl'||at_apps_link||' frd,  '
2788 	    ||'      gmp_item_aps'||at_apps_link||' gia '
2789 
2790               ||' WHERE frm.formulaline_id = fmd.formulaline_id '
2791               ||'    AND frm.formulaline_id LIKE ''%'' '
2792               ||'   AND frm.recipe_id = r.recipe_id '
2793               ||'    AND frm.recipe_id LIKE ''%'' '
2794               ||'    AND EXISTS '
2795               ||'   ( SELECT /*+ DRIVING_SITE(ffe) DRIVING_SITE(gs) */ 1 '
2796               ||'     FROM gmd_recipe_validity_rules'||at_apps_link||' ffe,  '
2797 	      ||'       gmd_status_b'||at_apps_link||' gs '
2798 
2799               ||'   WHERE ffe.recipe_id = r.recipe_id '
2800               ||'   AND ( ffe.orgn_code is NULL or ffe.orgn_code '|| l_in_str_plant || ')'
2801               ||'   AND ffe.validity_rule_status = gs.status_code '
2802               ||'   AND gs.status_type IN (' ||'''700''' || ',' || '''900''' || ') '
2803               ||'   AND gs.delete_mark = 0 '
2804               ||'      AND ffe.recipe_use IN (0,1) '
2805               ||'   AND NVL(ffe.end_date,(SYSDATE + 1)) > SYSDATE '
2806               ||'   AND ffe.delete_mark = 0 '
2807               ||'    ) '
2808               ||'   AND (fmd.release_type in (1,2,3) '
2809 	      ||'   OR         NVL(r.calculate_step_quantity,0) = 1 ) '
2810 
2811               ||'   AND frd.routingstep_id = frm.routingstep_id '
2812               ||'   AND gia.item_id = fmd.item_id '
2813               ||' ) '
2814               ||' ORDER BY 1,2,3,6,7 ';
2815 
2816 --    mat_assoc_cursor  :=
2817 --                   ' SELECT /*+ DRIVING_SITE(r) DRIVING_SITE(frm) DRIVING_SITE(fmd) '
2818 --              ||' DRIVING_SITE(frd) DRIVING_SITE(a)  */
2819 --              ||'  fmd.formula_id, frm.recipe_id, '
2820 --              ||'  DECODE(fmd.line_type, 1,1,2,2,-1,3), fmd.line_no, '
2821 --              ||'  ((frm.formulaline_id * 2) + 1) x_formulaline_id, '
2822 --              ||'  ((frm.routingstep_id * 2) + 1) x_routingstep_id, '
2823 --              ||'   fmd.item_id, frd.routingstep_no, '
2824 --              ||'   gia.aps_item_id, '
2825 --              ||'   DECODE(fmd.item_um, gia.item_um, 1, '
2826 --              ||'     GMICUOM.uom_conversion'||At_Apps_Link
2827 --              ||'       (fmd.item_id, 0, 1, fmd.item_um, gia.item_um, 0)) uom_conv_factor, '
2828 --              /*Sowmya - As per Latest FDD changes - Changes as per Matt's review comments-
2829 --              Fetch the conversion factor for a unit item, needed for converting the MTQ.
2830 --              MTQ value to be passed as promary UOM.*/
2831 --              ||'   decode(fmd.line_type, 1, frm.minimum_transfer_qty, null) minimum_transfer_qty, '
2832 --              ||'   decode(fmd.line_type, 1, frm.minimum_delay, null) minimum_delay, '
2833 --              ||'   decode(fmd.line_type, 1, frm.maximum_delay, null) maximum_delay '
2834 --              ||' FROM gmd_recipes'||At_Apps_Link||' r ,' /* added for asqc flg*/
2835 --	            ||'      gmd_recipe_step_materials'||at_apps_link||' frm, '
2836 --              ||'      fm_matl_dtl'||at_apps_link||' fmd, '
2837 --              ||'      fm_rout_dtl'||at_apps_link||' frd,  '   /* NAMIT_MTQ */
2838 --              ||'      ( SELECT /*+ DRIVING_SITE(gmp_item_aps) INDEX(gia GMP_ITEM_APS_I2) */ item_id, aps_item_id, item_um, uom_code '
2839 --              ||'        FROM (SELECT item_id, aps_item_id, item_um, uom_code,'
2840 --              ||'  		ROW_NUMBER() OVER ( PARTITION BY item_id '
2841 --              ||'      		ORDER BY item_id,aps_item_id ) AS first_row '
2842 --              ||'              	FROM gmp_item_aps'||at_apps_link
2843 --              ||'               WHERE aps_item_id like  ''%'' '
2844 --              ||'       	) a '
2845 --              ||'        WHERE first_row = 1 '
2846 --              ||'       ) gia ' /*Sowmya - Added*/
2847 --              ||' WHERE fmd.formulaline_id = frm.formulaline_id '
2848 --              ||'   AND frm.recipe_id = r.recipe_id '  /* B3054460 */
2849 --              ||'   AND EXISTS ( SELECT /*+ DRIVING_SITE(ffe) DRIVING_SITE(gs) */ '
2850 --              ||'               1 FROM '
2851 --              ||'       gmd_status_b'||at_apps_link||' gs, '
2852 --              ||'       gmd_recipe_validity_rules'||at_apps_link||' ffe '
2853 --              ||'   WHERE ffe.recipe_id = r.recipe_id '
2854 --              ||'   AND ffe.validity_rule_status = gs.status_code '
2855 --              ||'   AND gs.status_type IN (' ||'''700''' || ',' || '''900''' || ') '
2856 --              ||'   AND gs.delete_mark = 0 '
2857 --              ||'   AND NVL(ffe.end_date,(SYSDATE + 1)) > SYSDATE '
2858 --              ||'   AND ffe.delete_mark = 0 '
2859 --              ||'   AND ffe.recipe_use IN (0,1)  ) '
2860 --              ||'   AND (fmd.release_type in (1,2,3) OR '  /* B3054460 */
2861 --              ||'        NVL(r.calculate_step_quantity,0) = 1 ) '  /* xfer for ASQC */
2862 --              ||'   AND frd.routingstep_id = frm.routingstep_id '  /* NAMIT_MTQ */
2863 --              ||'   AND gia.item_id = fmd.item_id '
2864 --              ||' ORDER BY 1,2,3,6,7 ';
2865 
2866 /* Bug: 7286778 Vpedarla added the below where clauses for better performance */
2867 /* B3970993 nsinghi. Changed order by clause from 1,2,3,4,5 to 1,2,3,6,7 */
2868 
2869   log_message('Material association cursor ' || mat_assoc_cursor) ;
2870 
2871     OPEN cur_mat_assoc FOR mat_assoc_cursor ;
2872     FETCH cur_mat_assoc BULK COLLECT INTO mat_assoc_tab;
2873     material_assocs_size := mat_assoc_tab.COUNT;
2874 /* PPG Bug: 13590192
2875     LOOP
2876       FETCH cur_mat_assoc INTO mat_assoc_tab(material_assocs_size);
2877       EXIT WHEN cur_mat_assoc%NOTFOUND;
2878       material_assocs_size := material_assocs_size + 1;
2879     END LOOP;
2880 */
2881     CLOSE cur_mat_assoc;
2882 --    material_assocs_size := material_assocs_size -1 ;
2883     time_stamp ;
2884     log_message('Material assoc size is = ' || to_char(material_assocs_size)) ;
2885 
2886  -- The cursor for effectivity opened and then the details processed
2887  l_eff_counter := 0;
2888  OPEN c_formula_effectivity FOR effectivity_cursor;
2889 
2890   LOOP
2891   FETCH c_formula_effectivity INTO effectivity;
2892   EXIT WHEN c_formula_effectivity%NOTFOUND;
2893   l_eff_counter := l_eff_counter + 1;
2894    IF ((effectivity.formula_id <> old_formula_id) OR
2895        (effectivity.plant_code <> old_plant_code) OR
2896        (effectivity.organization_id <> old_organization_id) OR
2897        (effectivity.fmeff_id <> old_fmeff_id)
2898       )  THEN   /* Old values */
2899 
2900     valid := check_formula(effectivity.plant_code,
2901                   effectivity.organization_id, effectivity.formula_id);
2902     -- PK
2903     IF not valid THEN
2904       log_message('check_formula returned Invalid for plant code ' || effectivity.plant_code||
2905                    ' Organization_id '||effectivity.organization_id||' formula_id '||effectivity.formula_id) ;
2906     END IF;
2907     /* routing check for effectivity */
2908     IF (valid) AND effectivity.routing_id IS NOT NULL THEN
2909         /* Locate_org_routing through Bsearch */
2910          valid := find_routing_header (effectivity.routing_id,
2911                                        effectivity.plant_code);
2912          --PK
2913          IF not valid THEN
2914             log_message('find_routing_header returned Invalid for plant code ' || effectivity.plant_code||
2915                    ' routing_id '||effectivity.routing_id) ;
2916          END IF;
2917 
2918        IF (valid) AND effectivity.rtg_hdr_location > 0 AND
2919                       effectivity.routing_qty >= 0 THEN
2920 
2921            g_setup_id  := NULL;
2922            sd_index    := 0 ;
2923            validate_routing( effectivity.routing_id,
2924                              effectivity.plant_code,
2925                              effectivity.rtg_hdr_location,
2926                              routing_valid);
2927 
2928             IF (routing_valid) THEN /* Valid routing  */
2929                   valid := TRUE ;
2930              ELSE
2931                     valid := FALSE ;
2932                  log_message('validate_routing returned Invalid for plant code ' || effectivity.plant_code||
2933                    ' routing_id '||effectivity.routing_id||' rtg_hdr_location '||effectivity.rtg_hdr_location||
2934                    effectivity.rtg_hdr_location) ;
2935              END IF;  /* Valid routing  */
2936 
2937        END IF ;   /* routing header location */
2938 
2939        /*B2870041 this logic will get the total output qty in the routing uom
2940           if the formula or route fails validation the effectivity is skipped*/
2941        IF (valid) THEN
2942 
2943          /* if the total output was already calculated for this formula in
2944             the routing um there is no need to do it again */
2945          IF formula_header_tab(g_fm_hdr_loc).total_um <>
2946               effectivity.routing_um  OR
2947             formula_header_tab(g_fm_hdr_loc).total_um IS NULL THEN
2948 
2949            /* if the factor was not calculated then the uom conversion failed
2950               and if it failed the effectivity can not be used */
2951            IF effectivity.prod_factor <= 0 THEN
2952              valid := FALSE;
2953              log_message(' Not valid because effectivity.prod_factor is '||effectivity.prod_factor);
2954            ELSE
2955              /* reset the total ouput accumulator and loop through all of the
2956                 material details to find all products and byproducts */
2957              temp_total_qty := 0;
2958 
2959              FOR j IN g_fm_dtl_start_loc..g_fm_dtl_end_loc
2960              LOOP
2961 
2962                /* if the line is either a product or byproduct then we need
2963                   to process it */
2964                IF formula_detail_tab(j).line_type > 0 THEN
2965 
2966                  /* if the item is the same as the item in the effectivity
2967                     we have the factor to get the item from base uom to the
2968                     route uom */
2969                  IF (formula_detail_tab(j).opm_item_id = effectivity.item_id)
2970                  THEN
2971                    temp_total_qty := temp_total_qty +
2972                      (effectivity.prod_factor *
2973                       formula_detail_tab(j).primary_qty);
2974                  /* if the item is different but the item base uom is the
2975                     same as the route the primary_qty will be used */
2976                  ELSIF
2977                    formula_detail_tab(j).opm_item_id <> effectivity.item_id AND
2978                    formula_detail_tab(j).primary_um = effectivity.routing_um
2979                  THEN
2980                    temp_total_qty := temp_total_qty +
2981                       formula_detail_tab(j).primary_qty;
2982                  /* if the item is different but the item base uom is the
2983                     same as the route the primary_qty will be used */
2984                  ELSIF
2985                    formula_detail_tab(j).opm_item_id <> effectivity.item_id AND
2986                    formula_detail_tab(j).orig_um = effectivity.routing_um
2987                  THEN
2988                    temp_total_qty := temp_total_qty +
2989                       formula_detail_tab(j).formula_qty;
2990                  /* no uom can be matched or the item is not the same as the
2991                     product thus a uom conversion will need to be done. If the
2992                     qty is 0 there is no need to do the conversion */
2993                  ELSIF formula_detail_tab(j).formula_qty > 0 THEN
2994                    uom_conv_cursor :=
2995                        'SELECT '
2996                      ||'  GMICUOM.uom_conversion'||at_apps_link
2997                      ||'  (:pitem, 0, :pqty, :pfrom_um, :pto_um, 0) '
2998                      ||'FROM dual';
2999                    v_matl_qty := -1;
3000                    OPEN c_uom_conv FOR uom_conv_cursor USING
3001                      formula_detail_tab(j).opm_item_id,
3002                      formula_detail_tab(j).primary_qty,
3003                      formula_detail_tab(j).primary_um,
3004                      effectivity.routing_um;
3005 
3006                    FETCH c_uom_conv INTO v_matl_qty;
3007                    CLOSE c_uom_conv;
3008 
3009                    /* as long as the qty is >0 then the uom conversion was
3010                       successful. If negative then it failed so reject the
3011                       effectivity and stop the current loop */
3012                    IF v_matl_qty > 0 THEN
3013                      temp_total_qty := temp_total_qty + v_matl_qty;
3014                    ELSE
3015                      valid := FALSE;
3016                      log_message(' Existing v_matl_qty = '||v_matl_qty);
3017                      EXIT;
3018                    END IF;
3019                  END IF;
3020                END IF;
3021              END LOOP;
3022              /* if there was no failure and the qty is >0 save the values in
3023                 the formula header */
3024              IF (valid) AND temp_total_qty > 0 THEN
3025                formula_header_tab(g_fm_hdr_loc).total_output :=
3026                  temp_total_qty;
3027                formula_header_tab(g_fm_hdr_loc).total_um :=
3028                  effectivity.routing_um;
3029              ELSE
3030                log_message(' Not updating formula_header_tab temp_total_qty = '||temp_total_qty);
3031              END IF;
3032            END IF;
3033          END IF;
3034        END IF;
3035 
3036 
3037     END IF;   /* routing check for effectivity */
3038 
3039     IF valid THEN
3040       g_curr_rstep_loc := find_routing_offsets(effectivity.formula_id,
3041                                effectivity.plant_code);
3042       export_effectivities (valid);
3043     END IF ;
3044 
3045    END IF ;   /* Old Values */
3046 
3047     old_formula_id      := effectivity.formula_id ;
3048     old_organization_id := effectivity.organization_id ;
3049     old_fmeff_id        := effectivity.fmeff_id ;
3050     old_plant_code      := effectivity.plant_code ;
3051     valid               := FALSE ;
3052     routing_valid       := FALSE ;
3053 
3054 
3055     /*  venu   added B3837959 MMK Issue, Bulk insert after every 1000 effectivities */
3056     eff_counter         := eff_counter + 1 ;
3057 
3058     IF (mod(eff_counter,1000) = 0)  THEN /* Every 1000 effectivity */
3059       /* If all is OK, Bulk Insert the data into MSC tables */
3060        log_message('Before MSC Inserts' ) ;
3061        time_stamp ;
3062        msc_inserts(valid);
3063           IF NOT (valid) THEN
3064              log_message('Error encountered in MSC_INSERTS');
3065           END IF;
3066     END IF ; /* Every 1000 effectivity */
3067 
3068 
3069   END LOOP;
3070   CLOSE c_formula_effectivity;
3071     log_message('Before MSC Inserts l_eff_counter = '||l_eff_counter ) ;
3072   time_stamp ;
3073   /* If all is OK, Bulk Insert the data into MSC tables */
3074    msc_inserts(valid);
3075        IF valid THEN
3076           COMMIT;
3077 	ELSE
3078 	log_message('Invalid after MSC Inserts' ) ;
3079 	NULL ;
3080        END IF;
3081    write_setups_and_transitions(at_apps_link, valid) ;  /* SGIDUGU - Seq Dependencies */
3082 
3083        IF valid THEN
3084           COMMIT;
3085 	ELSE
3086 	log_message('Invalid after write_setups_and_transitions' ) ;
3087 	NULL ;
3088        END IF;
3089 
3090   log_message('End of process' ) ;
3091   time_stamp ;
3092   -- gmp_putline('End at '|| TO_CHAR(SYSDATE,'DD-MON-YYYY HH24:MI:SS'),'a');
3093 /* akaruppa B5007729 Start*/
3094          /* Free memory used by PL/SQL tables used by program  */
3095            IF formula_header_tab.COUNT > 0 THEN
3096            formula_header_tab.delete ;
3097            END IF;
3098            IF formula_header_tab.COUNT > 0 THEN
3099            formula_header_tab.delete ;
3100            END IF;
3101            IF formula_detail_tab.COUNT > 0 THEN
3102            formula_detail_tab.delete ;
3103            END IF;
3104            IF formula_orgn_count_tab.COUNT > 0 THEN
3105            formula_orgn_count_tab.delete ;
3106            END IF;
3107            IF rtg_org_hdr_tab.COUNT > 0 THEN
3108            rtg_org_hdr_tab.delete ;
3109            END IF;
3110            IF rtg_org_dtl_tab.COUNT > 0 THEN
3111            rtg_org_dtl_tab.delete ;
3112            END IF;
3113            IF rtg_gen_dtl_tab.COUNT > 0 THEN
3114            rtg_gen_dtl_tab.delete ;
3115            END IF;
3116            IF rtg_alt_rsrc_tab.COUNT > 0 THEN
3117            rtg_alt_rsrc_tab.delete ;
3118            END IF;
3119            IF mat_assoc_tab.COUNT > 0 THEN
3120            mat_assoc_tab.delete;
3121            END IF;
3122            IF rcp_orgn_override.COUNT > 0 THEN
3123            rcp_orgn_override.delete ;
3124            END IF;
3125            IF recipe_override.COUNT > 0 THEN
3126            recipe_override.delete ;
3127            END IF;
3128            IF rstep_offsets.COUNT > 0 THEN
3129            rstep_offsets.delete ;
3130            END IF;
3131 
3132           dbms_session.free_unused_user_memory;
3133 
3134           SELECT st.VALUE INTO v_dummy from V$MYSTAT st, V$STATNAME sn
3135           WHERE st.STATISTIC# = sn.STATISTIC#
3136           AND sn.NAME in ('session pga memory max');
3137           log_message('Session pga memory max = ' || to_char(v_dummy) );
3138 
3139           SELECT st.VALUE INTO v_dummy from V$MYSTAT st, V$STATNAME sn
3140           where st.STATISTIC# = sn.STATISTIC#
3141           and sn.NAME in ('session pga memory');
3142           log_message('Session pga memory = ' || TO_CHAR(v_dummy) );
3143 
3144 	  /* akaruppa B5007729 End*/
3145 
3146   return_status := TRUE;
3147 
3148   EXCEPTION
3149     WHEN invalid_string_value  THEN
3150         log_message('Organization string is Invalid ' );
3151         return_status := FALSE;
3152     WHEN invalid_gmp_uom_profile THEN
3153         log_message('Profile "GMP: UOM for Hour" is Invalid ' );
3154         return_status := FALSE;
3155     WHEN OTHERS THEN
3156 	log_message('Error retrieving effectivities: '||sqlerrm);
3157 	return_status := FALSE;
3158 
3159 END retrieve_effectivities;
3160 
3161 /*
3162 REM+=========================================================================+
3163 REM| PROCEDURE NAME                                                          |
3164 REM|    link_override_routing                                                |
3165 REM| DESCRIPTION                                                             |
3166 REM|    Link the override based on routing and organization code             |
3167 REM|                                                                         |
3168 REM| HISTORY                                                                 |
3169 REM| 08/23/2002   Created Rajesh Patangya                                    |
3170 REM|                                                                         |
3171 REM+=========================================================================+
3172 */
3173 PROCEDURE link_override_routing IS
3174   i              PLS_INTEGER ;
3175   j              PLS_INTEGER ;
3176   k              PLS_INTEGER ;
3177   lgr_loc        PLS_INTEGER ;
3178   lgr_start_loc  PLS_INTEGER ;
3179   lgr_end_loc    PLS_INTEGER ;
3180   lorg_loc       PLS_INTEGER ;
3181   old_routing_id PLS_INTEGER ;
3182   gen_start_pos  PLS_INTEGER ;
3183   org_start_pos  PLS_INTEGER ;
3184   start_gen_pos_written PLS_INTEGER  ;
3185   start_org_pos_written PLS_INTEGER  ;
3186 
3187 BEGIN
3188   i              := 1 ;
3189   j              := 1 ;
3190   k              := 1 ;
3191   lgr_loc        := 0 ;
3192   lgr_start_loc  := 0 ;
3193   lgr_end_loc    := 0 ;
3194   lorg_loc       := 0 ;
3195   old_routing_id := 0 ;
3196   gen_start_pos  := 1  ;
3197   org_start_pos  := 1  ;
3198   start_gen_pos_written := 0 ;
3199   start_org_pos_written := 0 ;
3200 
3201 
3202   -- gmp_putline(' Begin Link Override Rtg ','a');
3203   FOR i IN 1..routing_headers_size
3204   LOOP
3205    IF rtg_org_hdr_tab(i).routing_id = old_routing_id THEN /* old rtg */
3206 
3207         rtg_org_hdr_tab(i).step_start_loc := lgr_start_loc ;
3208         rtg_org_hdr_tab(i).step_end_loc   := lgr_end_loc ;
3209    ELSE
3210         start_gen_pos_written := 0 ;
3211         FOR j IN gen_start_pos..recipe_override_size
3212         LOOP
3213         IF recipe_override(j).routing_id = rtg_org_hdr_tab(i).routing_id THEN
3214             IF start_gen_pos_written = 0 THEN
3215                 lgr_start_loc := j ;  /* Used for other org in org header */
3216                 rtg_org_hdr_tab(i).step_start_loc := j ;
3217                 start_gen_pos_written := 1 ;
3218             END IF ;
3219             IF j = recipe_override_size THEN
3220                 rtg_org_hdr_tab(i).step_end_loc := j ;
3221                 lgr_end_loc     := j ;
3222             END IF ;
3223 
3224         ELSIF recipe_override(j).routing_id > rtg_org_hdr_tab(i).routing_id
3225         THEN
3226 
3227             IF start_gen_pos_written <> 1 THEN
3228                 rtg_org_hdr_tab(i).step_start_loc := -1 ;
3229                 rtg_org_hdr_tab(i).step_end_loc   := -1 ;
3230                 lgr_start_loc   := - 1;
3231                 lgr_end_loc     := - 1;
3232             ELSE
3233                 lgr_end_loc   := j - 1;
3234                 rtg_org_hdr_tab(i).step_end_loc := lgr_end_loc ;
3235             END IF ;
3236             gen_start_pos := j ;
3237             EXIT ;
3238 
3239         /* ELSE - no need to write, continue looping. */
3240         END IF ;
3241      END LOOP ;   /* Generic loop */
3242    END IF ;   /* old rtg */
3243 
3244      --  For organization recipe
3245      start_org_pos_written := 0 ;
3246      FOR k IN org_start_pos..recipe_orgn_over_size
3247      LOOP
3248       IF rcp_orgn_override(k).routing_id = rtg_org_hdr_tab(i).routing_id AND
3249          rcp_orgn_override(k).orgn_code  = rtg_org_hdr_tab(i).plant_code THEN
3250 
3251           IF start_org_pos_written = 0 THEN
3252               rtg_org_hdr_tab(i).usage_start_loc := k ;
3253               start_org_pos_written := 1 ;
3254           END IF ;
3255           IF k = recipe_orgn_over_size THEN
3256               rtg_org_hdr_tab(i).usage_end_loc := k ;
3257           END IF ;
3258 
3259       ELSIF (rcp_orgn_override(k).routing_id>rtg_org_hdr_tab(i).routing_id) OR
3260           (
3261           (rcp_orgn_override(k).routing_id = rtg_org_hdr_tab(i).routing_id) AND
3262           (rcp_orgn_override(k).orgn_code  > rtg_org_hdr_tab(i).plant_code)
3263           )  THEN
3264 
3265             IF start_org_pos_written <> 1 THEN
3266               rtg_org_hdr_tab(i).usage_start_loc := -1 ;
3267               rtg_org_hdr_tab(i).usage_end_loc :=  -1 ;
3268             ELSE
3269               rtg_org_hdr_tab(i).usage_end_loc := k - 1 ;
3270             END IF ;
3271             org_start_pos := k ;
3272             EXIT ;
3273 
3274       /* ELSE - no need to write, continue looping. */
3275       END IF ;
3276      END LOOP ;   /* recipe organization loop */
3277 
3278      old_routing_id := rtg_org_hdr_tab(i).routing_id ;
3279   END LOOP ;  /* routing header loop */
3280 
3281   -- gmp_putline(' End Link Override Rtg ','a');
3282 END link_override_routing;
3283 
3284 /*
3285 REM+=========================================================================+
3286 REM| FUNCTION NAME                                                           |
3287 REM|    find_routing_header                                                  |
3288 REM| DESCRIPTION                                                             |
3289 REM|                                                                         |
3290 REM| HISTORY                                                                 |
3291 REM| 07/14/2002   Rajesh Patangya - Reorgnized the complete code B2314052    |
3292 REM+=========================================================================+
3293 */
3294 FUNCTION find_routing_header ( prouting_id   IN PLS_INTEGER,
3295                                pplant_code   IN VARCHAR2)
3296                                RETURN BOOLEAN IS
3297 
3298 routing_header_loc   PLS_INTEGER     ;
3299 BEGIN
3300 routing_header_loc   := 0 ;
3301       routing_header_loc := bsearch_routing (prouting_id,
3302                                              pplant_code);
3303 
3304        IF routing_header_loc > 0 THEN  /* routing header location */
3305 
3306           IF (rtg_org_hdr_tab(routing_header_loc).valid_flag < 0) OR
3307              (rtg_org_hdr_tab(routing_header_loc).generic_start_loc < 0) OR
3308              (rtg_org_hdr_tab(routing_header_loc).orgn_start_loc < 0)  THEN
3309                 log_message('Valid '||rtg_org_hdr_tab(routing_header_loc).valid_flag||' gen start loc '||
3310                 rtg_org_hdr_tab(routing_header_loc).generic_start_loc||' orgn start loc '||rtg_org_hdr_tab(routing_header_loc).orgn_start_loc);
3311                 effectivity.rtg_hdr_location :=  -1 ;
3312                 return FALSE ;
3313            ELSE
3314                 effectivity.rtg_hdr_location := routing_header_loc ;
3315                 return TRUE ;
3316           END IF ;
3317        ELSE
3318                 log_message('Bsearch returned negative for Routing Plant ');
3319                 effectivity.rtg_hdr_location :=  -1 ;
3320                 return FALSE ;
3321        END IF ; /* routing header location */
3322 
3323 END find_routing_header;
3324 
3325 /*
3326 REM+=========================================================================+
3327 REM| PROCEDURE NAME                                                          |
3328 REM|    link_routing                                                         |
3329 REM| DESCRIPTION                                                             |
3330 REM|                                                                         |
3331 REM| HISTORY                                                                 |
3332 REM| 07/14/2002   Rajesh Patangya - Reorgnized the complete code B2314052    |
3333 REM+=========================================================================+
3334 */
3335 PROCEDURE link_routing IS
3336   i              PLS_INTEGER ;
3337   j              PLS_INTEGER ;
3338   k              PLS_INTEGER ;
3339   lgr_loc        PLS_INTEGER ;
3340   lgr_start_loc  PLS_INTEGER ;
3341   lgr_end_loc    PLS_INTEGER ;
3342   lorg_loc       PLS_INTEGER ;
3343   old_routing_id PLS_INTEGER ;
3344   gen_start_pos  PLS_INTEGER ;
3345   org_start_pos  PLS_INTEGER ;
3346   start_gen_pos_written PLS_INTEGER  ;
3347   start_org_pos_written PLS_INTEGER  ;
3348 /* NAMIT_CR To link step dependency to routing header */
3349   lstpdep_start_loc  PLS_INTEGER ;
3350   lstpdep_end_loc    PLS_INTEGER ;
3351   stpdep_start_pos  PLS_INTEGER ;
3352   start_stpdep_pos_written PLS_INTEGER  ;
3353 
3354 BEGIN
3355   i              := 1 ;
3356   j              := 1 ;
3357   k              := 1 ;
3358   lgr_loc        := 0 ;
3359   lgr_start_loc  := 0 ;
3360   lgr_end_loc    := 0 ;
3361   lorg_loc       := 0 ;
3362   old_routing_id := 0 ;
3363   gen_start_pos  := 1  ;
3364   org_start_pos  := 1  ;
3365   start_gen_pos_written := 0 ;
3366   start_org_pos_written := 0 ;
3367   lstpdep_start_loc  := 0 ;
3368   lstpdep_end_loc    := 0 ;
3369   stpdep_start_pos  := 1  ;
3370   start_stpdep_pos_written := 0 ;
3371 
3372 
3373   -- gmp_putline(' Start Link Rtg ','a');
3374   FOR i IN 1..routing_headers_size
3375   LOOP
3376    IF rtg_org_hdr_tab(i).routing_id = old_routing_id THEN /* old rtg */
3377 
3378         rtg_org_hdr_tab(i).generic_start_loc := lgr_start_loc ;
3379         rtg_org_hdr_tab(i).generic_end_loc   := lgr_end_loc ;
3380 /* NAMIT_CR Link the Step Dependency to the routing header */
3381         rtg_org_hdr_tab(i).stpdep_start_loc := lstpdep_start_loc ;
3382         rtg_org_hdr_tab(i).stpdep_end_loc   := lstpdep_end_loc ;
3383 
3384    ELSE
3385 
3386         start_gen_pos_written := 0 ;
3387         FOR j IN gen_start_pos..rtg_gen_dtl_size
3388         LOOP
3389         IF rtg_gen_dtl_tab(j).routing_id = rtg_org_hdr_tab(i).routing_id THEN
3390             IF start_gen_pos_written = 0 THEN
3391                 lgr_start_loc := j ;  /* Used for other org in org header */
3392                 rtg_org_hdr_tab(i).generic_start_loc := j ;
3393                 start_gen_pos_written := 1 ;
3394             END IF ;
3395             IF j = rtg_gen_dtl_size THEN
3396                 rtg_org_hdr_tab(i).generic_end_loc := j ;
3397                 lgr_end_loc     := j ;
3398             END IF ;
3399 
3400         ELSIF rtg_gen_dtl_tab(j).routing_id > rtg_org_hdr_tab(i).routing_id
3401         THEN
3402 
3403             IF start_gen_pos_written <> 1 THEN
3404                 rtg_org_hdr_tab(i).generic_start_loc := -1 ;
3405                 rtg_org_hdr_tab(i).generic_end_loc   := -1 ;
3406                 lgr_start_loc   := - 1;
3407                 lgr_end_loc     := - 1;
3408             ELSE
3409                 lgr_end_loc   := j - 1;
3410                 rtg_org_hdr_tab(i).generic_end_loc := lgr_end_loc ;
3411             END IF ;
3412             gen_start_pos := j ;
3413             EXIT ;
3414 
3415         /* ELSE - no need to write, continue looping. */
3416         END IF ;
3417      END LOOP ;   /* Generic loop */
3418 /* NAMIT_CR Code To Link Step Dependency to Routing Header Start */
3419 
3420 
3421      start_stpdep_pos_written := 0 ;
3422      FOR j IN stpdep_start_pos..opr_stpdep_size
3423      LOOP
3424         IF gmp_opr_stpdep_tbl(j).routing_id = rtg_org_hdr_tab(i).routing_id THEN
3425             IF start_stpdep_pos_written = 0 THEN
3426                 lstpdep_start_loc := j ;  /* Used for other routes in route header */
3427                 rtg_org_hdr_tab(i).stpdep_start_loc := j ;
3428                 start_stpdep_pos_written := 1 ;
3429             END IF ;
3430             IF j = opr_stpdep_size THEN
3431                 rtg_org_hdr_tab(i).stpdep_end_loc := j ;
3432                 lstpdep_end_loc     := j ;
3433             END IF ;
3434 
3435         ELSIF gmp_opr_stpdep_tbl(j).routing_id > rtg_org_hdr_tab(i).routing_id
3436         THEN
3437 
3438             IF start_stpdep_pos_written <> 1 THEN
3439                 rtg_org_hdr_tab(i).stpdep_start_loc := -1 ;
3440                 rtg_org_hdr_tab(i).stpdep_end_loc   := -1 ;
3441                 lstpdep_start_loc   := - 1;
3442                 lstpdep_end_loc     := - 1;
3443             ELSE
3444                 lstpdep_end_loc   := j - 1;
3445                 rtg_org_hdr_tab(i).stpdep_end_loc := lstpdep_end_loc ;
3446             END IF ;
3447             stpdep_start_pos := j ;
3448             EXIT ;
3449 
3450         /* ELSE - no need to write, continue looping. */
3451         END IF ;
3452      END LOOP ;   /* Step Dependency loop */
3453 
3454 /* NAMIT_CR Code To Link Step Dependency to Routing Header End */
3455 
3456    END IF ;   /* old rtg */
3457 
3458      --  For organization routing
3459      start_org_pos_written := 0 ;
3460      For k IN org_start_pos..rtg_org_dtl_size
3461      LOOP
3462       IF rtg_org_dtl_tab(k).routing_id = rtg_org_hdr_tab(i).routing_id AND
3463          rtg_org_dtl_tab(k).orgn_code  = rtg_org_hdr_tab(i).plant_code THEN
3464 
3465           IF start_org_pos_written = 0 THEN
3466               rtg_org_hdr_tab(i).orgn_start_loc := k ;
3467               start_org_pos_written := 1 ;
3468           END IF ;
3469           IF k = rtg_org_dtl_size THEN
3470               rtg_org_hdr_tab(i).orgn_end_loc := k ;
3471           END IF ;
3472 
3473       ELSIF (rtg_org_dtl_tab(k).routing_id > rtg_org_hdr_tab(i).routing_id) OR
3474           (
3475           (rtg_org_dtl_tab(k).routing_id = rtg_org_hdr_tab(i).routing_id) AND
3476           (rtg_org_dtl_tab(k).orgn_code  > rtg_org_hdr_tab(i).plant_code)
3477           )  THEN
3478 
3479             IF start_org_pos_written <> 1 THEN
3480               rtg_org_hdr_tab(i).orgn_start_loc := -1 ;
3481               rtg_org_hdr_tab(i).orgn_end_loc :=  -1 ;
3482             ELSE
3483               rtg_org_hdr_tab(i).orgn_end_loc := k - 1 ;
3484             END IF ;
3485             org_start_pos := k ;
3486             EXIT ;
3487 
3488       /* ELSE - no need to write, continue looping. */
3489       END IF ;
3490      END LOOP ;   /* Organization loop */
3491 
3492      old_routing_id := rtg_org_hdr_tab(i).routing_id ;
3493 
3494   END LOOP ;  /* routing header loop */
3495 
3496   -- gmp_putline(' End Link Rtg ','a');
3497 END link_routing;
3498 
3499 /*
3500 REM+=========================================================================+
3501 REM| PROCEDURE NAME                                                          |
3502 REM|    validate_routing                                                     |
3503 REM| DESCRIPTION                                                             |
3504 REM|   1. ALL Items in effectivity needs to be convertible to Routing UOM    |
3505 REM|   2. ALL details are present in gmp_item_aps with appropriate flags     |
3506 REM|                                                                         |
3507 REM| HISTORY                                                                 |
3508 REM| 07/14/2002   Rajesh Patangya - Reorgnized the complete code B2314052    |
3509 REM+=========================================================================+
3510 */
3511 PROCEDURE validate_routing (prouting_id IN PLS_INTEGER ,
3512                            porgn_code   IN VARCHAR2,
3513                            pheader_loc  IN PLS_INTEGER,
3514                            prout_valid  OUT NOCOPY BOOLEAN)
3515 IS
3516 
3517   uom_statement           VARCHAR2(2000) ;
3518   old_routingstep_id      PLS_INTEGER   ;
3519   old_oprn_no             VARCHAR2(32)  ;
3520   old_activity            PLS_INTEGER ;
3521   i                       INTEGER ;
3522   j                       INTEGER ;
3523   start_genric_count      PLS_INTEGER ;
3524   end_genric_count        PLS_INTEGER ;
3525   start_orgn_count        PLS_INTEGER ;
3526   end_orgn_count          PLS_INTEGER ;
3527   rtg_org_loc             PLS_INTEGER ;
3528   prim_rsrc_cnt           PLS_INTEGER ;
3529   p_uom_qty               NUMBER ;
3530   rtg_valid               BOOLEAN ;
3531   rtg_recipe_valid        BOOLEAN ;  -- vpedarla
3532   found_match             BOOLEAN ;
3533 
3534 --
3535   k                       INTEGER;
3536   step_start_index        INTEGER;
3537   step_end_index          INTEGER;
3538   usage_start_index       INTEGER;
3539   usage_end_index         INTEGER;
3540   prev_routingstep_id     NUMBER;
3541   l_setup_id              NUMBER;
3542 
3543 BEGIN
3544   uom_statement           := NULL ;
3545   old_routingstep_id      := 0 ;
3546   old_oprn_no             := ' ' ;
3547   old_activity            := -1 ;
3548   i                       := 1 ;
3549   j                       := 1 ;
3550   start_genric_count      := 0 ;
3551   end_genric_count        := 0 ;
3552   start_orgn_count        := 0 ;
3553   end_orgn_count          := 0 ;
3554   rtg_org_loc             := 0 ;
3555   prim_rsrc_cnt           := 0 ;
3556   p_uom_qty               := -1 ;
3557   rtg_valid               := TRUE ;
3558   rtg_recipe_valid        := TRUE ;  -- bug:6825139 vpedarla
3559   found_match             := TRUE ;
3560   prim_rsrc_cnt      := 0 ;
3561   found_match        := TRUE ;
3562   prev_routingstep_id     := NULL ;
3563   l_setup_id              := NULL;
3564 
3565    rtg_org_loc        := pheader_loc;
3566    start_genric_count := rtg_org_hdr_tab(rtg_org_loc).generic_start_loc;
3567    end_genric_count   := rtg_org_hdr_tab(rtg_org_loc).generic_end_loc;
3568    start_orgn_count   := rtg_org_hdr_tab(rtg_org_loc).orgn_start_loc;
3569    end_orgn_count     := rtg_org_hdr_tab(rtg_org_loc).orgn_end_loc;
3570 
3571 -- Overrides Rajesh {
3572    rtg_valid                 := TRUE ;
3573    k                         := 1;
3574 
3575    step_start_index :=
3576       rtg_org_hdr_tab(effectivity.rtg_hdr_location).step_start_loc ;
3577    step_end_index :=
3578       rtg_org_hdr_tab(effectivity.rtg_hdr_location).step_end_loc ;
3579    usage_start_index :=
3580       rtg_org_hdr_tab(effectivity.rtg_hdr_location).usage_start_loc ;
3581    usage_end_index :=
3582       rtg_org_hdr_tab(effectivity.rtg_hdr_location).usage_end_loc ;
3583 
3584 -- Changes for Overrides Rajesh }
3585 
3586    /* Generic routing check */
3587    IF (start_genric_count > 0) AND (end_genric_count > 0 ) THEN
3588    FOR i IN start_genric_count..end_genric_count
3589    LOOP
3590      /* { */
3591       IF (rtg_gen_dtl_tab(i).routing_id = prouting_id) THEN
3592 
3593          /* If operation, activity, step change then */
3594          IF (i = start_genric_count) OR
3595             (rtg_gen_dtl_tab(i).routingstep_id <> old_routingstep_id) OR
3596             (rtg_gen_dtl_tab(i).oprn_no <> old_oprn_no) OR
3597             (rtg_gen_dtl_tab(i).oprn_line_id <>  old_activity)  THEN
3598               prim_rsrc_cnt := 0 ;
3599           END IF ;
3600 
3601           IF rtg_gen_dtl_tab(i).prim_rsrc_ind = 1 THEN
3602              prim_rsrc_cnt := prim_rsrc_cnt + 1 ;
3603           END IF ;
3604 
3605           /* If no primary/ multiple primary resource exit and invalidate
3606              the rtg_header for all the organization */
3607           IF prim_rsrc_cnt <> 1 THEN
3608               --  Routing INVALID We should not do any further processing
3609               prim_rsrc_cnt := 0 ;
3610               invalidate_rtg_all_org(prouting_id) ;
3611               rtg_valid := FALSE;
3612               EXIT ;
3613           END IF ;
3614 
3615           old_routingstep_id := rtg_gen_dtl_tab(i).routingstep_id ;
3616           old_oprn_no        := rtg_gen_dtl_tab(i).oprn_no ;
3617           old_activity       := rtg_gen_dtl_tab(i).oprn_line_id ;
3618 
3619        /* organization check */
3620        IF (start_orgn_count > 0) AND (end_orgn_count > 0 ) AND
3621              (start_orgn_count <= end_orgn_count)
3622        THEN
3623        FOR j IN start_orgn_count..end_orgn_count
3624        LOOP
3625         /* {{ */
3626          IF (rtg_org_dtl_tab(j).orgn_code = porgn_code)  AND
3627             (rtg_org_dtl_tab(j).routing_id = prouting_id) THEN
3628 
3629 -- ------------------
3630          IF (rtg_org_dtl_tab(j).routingstep_id <> nvl(prev_routingstep_id,-1)) THEN
3631 
3632            IF (rtg_org_dtl_tab(j).is_unique = 1) AND (effectivity.category_id > 0)
3633 	   THEN
3634                l_setup_id := bsearch_setupid(rtg_org_dtl_tab(j).oprn_id,
3635                                  effectivity.category_id);
3636                IF l_setup_id > 0 THEN
3637                   rtg_org_dtl_tab(j).setup_id := l_setup_id ;
3638                ELSE
3639                  /* The actual SDS changeover data is not established */
3640                  rtg_org_dtl_tab(j).setup_id := NULL ;
3641                END IF;
3642            END IF;
3643            prev_routingstep_id := rtg_org_dtl_tab(j).routingstep_id ;
3644          END IF;
3645          IF (rtg_org_dtl_tab(j).is_unique = 1) AND (effectivity.category_id > 0) THEN
3646             sd_index := sd_index + 1 ;
3647             sds_tab(sd_index).oprn_id        := rtg_org_dtl_tab(j).oprn_id ;
3648             sds_tab(sd_index).category_id    := effectivity.category_id    ;
3649             sds_tab(sd_index).seq_dpnd_class := effectivity.seq_dpnd_class ;
3650             sds_tab(sd_index).resources      := rtg_org_dtl_tab(j).resources ;
3651             sds_tab(sd_index).resource_id    := rtg_org_dtl_tab(j).resource_id ;
3652             sds_tab(sd_index).setup_id       := rtg_org_dtl_tab(j).setup_id ;
3653          END IF;
3654 -- ------------------
3655           /* -------- Get step qty override (RDP) ------------------*/
3656 
3657             rtg_org_dtl_tab(j).o_resource_usage  := -1 ;
3658             rtg_org_dtl_tab(j).o_activity_factor := -1 ;
3659             rtg_org_dtl_tab(j).o_step_qty        := -1 ;
3660             rtg_org_dtl_tab(j).o_process_qty     := -1 ;
3661             rtg_org_dtl_tab(j).o_max_capacity    := -1 ;
3662             rtg_org_dtl_tab(j).o_min_capacity    := -1 ;
3663 
3664             IF (step_start_index > 0) AND (step_end_index > 0) THEN
3665             k := 1 ;
3666             FOR k IN step_start_index..step_end_index
3667             LOOP
3668              IF (effectivity.recipe_id =
3669                    recipe_override(k).recipe_id) THEN
3670 
3671              IF (rtg_org_dtl_tab(j).routing_id =
3672                    recipe_override(k).routing_id) AND
3673                 (rtg_org_dtl_tab(j).routingstep_id =
3674                    recipe_override(k).routingstep_id) THEN
3675 
3676                  rtg_org_dtl_tab(j).o_step_qty :=
3677                     recipe_override(k).step_qty ;
3678                  EXIT ;
3679              END IF ;
3680             ELSE
3681                  rtg_org_dtl_tab(j).o_step_qty := -1 ;
3682                  EXIT ;
3683             END IF; /* Get step qty override */
3684 
3685             END LOOP ;   /* Step Qty Override */
3686             END IF; /* Get step qty override */
3687            /* -------- step qty override Ends (RDP) ------------------*/
3688 
3689             IF (rtg_gen_dtl_tab(i).routingstep_id =
3690                                rtg_org_dtl_tab(j).routingstep_id) AND
3691                (rtg_gen_dtl_tab(i).oprn_line_id =
3692                                rtg_org_dtl_tab(j).oprn_line_id) AND
3693                (rtg_gen_dtl_tab(i).resources =
3694                                 rtg_org_dtl_tab(j).resources) THEN
3695 
3696       /* ------------ Override Calculation Code start ----------------------*/
3697 
3698             IF ((usage_start_index > 0) AND (usage_end_index > 0)) THEN
3699             k := 1 ;
3700               FOR k IN usage_start_index..usage_end_index
3701               LOOP
3702                /* { */
3703                IF (rtg_org_dtl_tab(j).routing_id =
3704                       rcp_orgn_override(k).routing_id) AND
3705                      (rtg_org_dtl_tab(j).orgn_code =
3706                       rcp_orgn_override(k).orgn_code) AND
3707                      (rtg_org_dtl_tab(j).routingstep_id =
3708                       rcp_orgn_override(k).routingstep_id) AND
3709                      (rtg_org_dtl_tab(j).oprn_line_id =
3710                       rcp_orgn_override(k).oprn_line_id) AND
3711                      (effectivity.recipe_id =
3712                       rcp_orgn_override(k).recipe_id) THEN
3713 
3714                    -- Activity factor override
3715                      rtg_org_dtl_tab(j).o_activity_factor :=
3716                                rcp_orgn_override(k).activity_factor;
3717                    -- Resource Overrides
3718                  /* { */
3719                  IF (rtg_org_dtl_tab(j).resources =
3720                          rcp_orgn_override(k).resources) THEN
3721 
3722                      rtg_org_dtl_tab(j).o_resource_usage :=
3723                             rcp_orgn_override(k).resource_usage;
3724                    -- Process Qty override
3725                      rtg_org_dtl_tab(j).o_process_qty :=
3726                              rcp_orgn_override(k).process_qty ;
3727                    -- Min / Max Capacity Overrides
3728                      rtg_org_dtl_tab(j).o_min_capacity :=
3729                              rcp_orgn_override(k).min_capacity ;
3730                      rtg_org_dtl_tab(j).o_max_capacity :=
3731                              rcp_orgn_override(k).max_capacity ;
3732                  END IF ; /* } Resource Overrides */
3733 
3734                END IF ;  /* }check for routing/step/oprn/recipe */
3735 
3736               END LOOP;  /* Override Loop Ends here */
3737             END IF; /* } check for Override presence */
3738 
3739             IF (rtg_org_dtl_tab(j).prim_rsrc_ind = 1) THEN
3740 
3741                      IF (rtg_org_dtl_tab(j).o_resource_usage = -1 ) THEN
3742 
3743                        IF (rtg_org_dtl_tab(j).resource_usage = 0) THEN
3744                         rtg_valid := FALSE ;
3745         		rtg_org_hdr_tab(rtg_org_loc).valid_flag := -1 ;
3746                         log_message('Recipe ' || effectivity.recipe_id ||' '||
3747                                rtg_org_dtl_tab(j).resources|| ' has usage 0');
3748                         EXIT ;
3749                        END IF;
3750                      ELSIF (rtg_org_dtl_tab(j).o_resource_usage = 0) THEN
3751                      --   rtg_valid := FALSE ;    /* bug: 6825139 Vpedarla */
3752                           rtg_recipe_valid  := FALSE ;
3753                         log_message('Recipe ' || effectivity.recipe_id ||' '||
3754                                rtg_org_dtl_tab(j).resources|| ' has usage 0');
3755                         EXIT ;
3756                      END IF ;
3757 
3758                      IF (rtg_org_dtl_tab(j).o_activity_factor = -1 ) THEN
3759                        IF (rtg_org_dtl_tab(j).activity_factor = 0) THEN
3760                         rtg_valid := FALSE ;
3761         		rtg_org_hdr_tab(rtg_org_loc).valid_flag := -1 ;
3762                         log_message('Recipe ' || effectivity.recipe_id ||
3763                          ' has ZERO activity factor');
3764                         EXIT;
3765                        END IF;
3766                      ELSIF (rtg_org_dtl_tab(j).o_activity_factor = 0) THEN
3767                       --  rtg_valid := FALSE ;    /* bug: 6825139 Vpedarla */
3768                           rtg_recipe_valid  := FALSE;
3769                         log_message('Recipe ' || effectivity.recipe_id ||
3770                          ' has ZERO Override activity factor');
3771                         EXIT ;
3772                      END IF ;
3773 
3774                      IF (rtg_org_dtl_tab(j).o_step_qty = -1 ) THEN
3775                        IF (rtg_org_dtl_tab(j).step_qty = 0) THEN
3776                         rtg_valid := FALSE ;
3777         		rtg_org_hdr_tab(rtg_org_loc).valid_flag := -1 ;
3778                         log_message('Recipe ' || effectivity.recipe_id ||
3779                          ' has ZERO step qty');
3780                         EXIT ;
3781                        END IF;
3782                      ELSIF (rtg_org_dtl_tab(j).o_step_qty = 0) THEN
3783                       --  rtg_valid := FALSE ;    /* bug: 6825139 Vpedarla */
3784                           rtg_recipe_valid := FALSE ;
3785                         log_message('Recipe ' || effectivity.recipe_id ||
3786                          ' has ZERO override step qty');
3787                         EXIT ;
3788                      END IF ;
3789             END IF;  /* For primary resource chack */
3790 /*
3791     IF rtg_org_dtl_tab(j).routing_id = 58 THEN
3792      log_message (
3793      rtg_org_dtl_tab(j).routing_id ||'*'||
3794      effectivity.recipe_id ||'*'||
3795      rtg_org_dtl_tab(j).prim_rsrc_ind      ||'*'||
3796      rtg_org_dtl_tab(j).routingstep_id         ||' Us '||
3797      rtg_org_dtl_tab(j).resources     ||'* '||
3798      rtg_org_dtl_tab(j).resource_usage      ||' *'||
3799      rtg_org_dtl_tab(j).o_resource_usage      ||' AF '||
3800      rtg_org_dtl_tab(j).activity_factor      ||' *'||
3801      rtg_org_dtl_tab(j).o_activity_factor      ||' SQ '||
3802      rtg_org_dtl_tab(j).step_qty      ||' *'||
3803      rtg_org_dtl_tab(j).o_step_qty     ||' PQ '||
3804      rtg_org_dtl_tab(j).process_qty      ||' *'||
3805      rtg_org_dtl_tab(j).o_process_qty      ||' M '||
3806      rtg_org_dtl_tab(j).min_capacity   ||' *'||
3807      rtg_org_dtl_tab(j).o_min_capacity   ||' X '||
3808      rtg_org_dtl_tab(j).max_capacity   ||' *'||
3809      rtg_org_dtl_tab(j).o_max_capacity);
3810      END IF;
3811 */
3812       /* ------------ Override Calculation Code start ----------------------*/
3813 
3814                 IF (rtg_org_dtl_tab(j).prim_rsrc_ind = 1
3815                     AND rtg_org_dtl_tab(j).schedule_ind = 3) THEN
3816 
3817                     rtg_valid := FALSE;
3818         	    rtg_org_hdr_tab(rtg_org_loc).valid_flag := -1 ;
3819                     log_message('Primary Resource '||rtg_org_dtl_tab(j).resources||
3820                         ' is defined as Do Not Plan ');
3821                     EXIT;
3822                 ELSIF (rtg_org_dtl_tab(j).prim_rsrc_ind <> 1
3823                     AND rtg_org_dtl_tab(j).schedule_ind = 3) THEN
3824 
3825                     start_orgn_count := j + 1 ;
3826                     rtg_org_dtl_tab(j).include_rtg_row := 0;
3827                     EXIT;
3828                 ELSE
3829                     rtg_valid := TRUE ;
3830         	    rtg_org_hdr_tab(rtg_org_loc).valid_flag := 1 ;
3831                     start_orgn_count := j + 1 ;
3832                     EXIT ;
3833                 END IF;
3834 
3835             ELSE
3836               -- Make the rtg invalid ONLY if the Primary or Auxilary
3837               -- resources for any activity is missing
3838               IF rtg_gen_dtl_tab(i).prim_rsrc_ind <> 0 THEN
3839                  rtg_valid := FALSE ;
3840                 log_message('Missing Plant Resource '||rtg_org_dtl_tab(j).resources);
3841       -- gmp_putline('Missing resource ' || rtg_org_dtl_tab(j).resources,'a');
3842               END IF ;
3843               EXIT;
3844             END IF ;
3845 
3846          END IF;
3847          /* }} */
3848        END LOOP;   /* Orgnization  Loop */
3849        ELSE
3850           -- If there are no organization details , the rtg is invalid
3851           rtg_valid := FALSE ;
3852        END IF;  /* organization check */
3853 
3854            IF ( rtg_valid = FALSE or rtg_recipe_valid = FALSE ) THEN
3855        --  IF  rtg_valid = FALSE  THEN   /* bug: 6825139 Vpedarla */
3856             EXIT ;
3857          END IF ;
3858      END IF;
3859      /* } */
3860    END LOOP ;  /* Generic Loop */
3861    ELSE
3862         -- If no generic routing details present, make routing invalid
3863         rtg_valid := FALSE ;
3864         invalidate_rtg_all_org(prouting_id) ;
3865    END IF;  /* Generic routing check */
3866 
3867    IF rtg_valid THEN
3868         rtg_org_hdr_tab(rtg_org_loc).valid_flag := 1 ;
3869    ELSE
3870         rtg_org_hdr_tab(rtg_org_loc).valid_flag := -1 ;
3871    END IF ;
3872 
3873       --  bug:6825139 vpedarla
3874    IF rtg_recipe_valid THEN
3875         prout_valid := rtg_valid ;
3876    ELSE
3877         prout_valid := rtg_recipe_valid ;
3878    END IF ;
3879    --  prout_valid := rtg_valid ;
3880 
3881 END validate_routing ;
3882 
3883 /*
3884 REM+=========================================================================+
3885 REM| PROCEDURE NAME                                                          |
3886 REM|    invalidate_rtg_all_org                                               |
3887 REM| DESCRIPTION                                                             |
3888 REM|                                                                         |
3889 REM| HISTORY                                                                 |
3890 REM| 07/14/2002   Rajesh Patangya - Reorgnized the complete code B2314052    |
3891 REM+=========================================================================+
3892 */
3893 PROCEDURE invalidate_rtg_all_org (p_routing_id IN NUMBER) IS
3894 
3895   i INTEGER ;
3896 BEGIN
3897   i := 1  ;
3898    FOR i IN 1..routing_headers_size
3899    LOOP
3900      IF rtg_org_hdr_tab(i).routing_id = p_routing_id THEN
3901            rtg_org_hdr_tab(i).valid_flag := -1 ;
3902      ELSIF rtg_org_hdr_tab(i).routing_id > p_routing_id THEN
3903            EXIT ;
3904      /* ELSE
3905            NULL ;  */
3906      END IF;
3907    END LOOP ;
3908 END invalidate_rtg_all_org;
3909 
3910 /*
3911 REM+=========================================================================+
3912 REM| PROCEDURE NAME                                                          |
3913 REM|    validate_formula                                                     |
3914 REM| DESCRIPTION                                                             |
3915 REM|                                                                         |
3916 REM|   Note that we are going to structure the formula retrieval query       |
3917 REM|   so that only the formulae used in Effectivities are fetched           |
3918 REM|   so trying to validate all at once does not cause any extra work       |
3919 REM|  Summary : Two validations need to be performed                         |
3920 REM|    1. ALL details can be converted to primary UOM                       |
3921 REM|    2. ALL details are present in gmp_item_aps with appropriate flags    |
3922 REM|                                                                         |
3923 REM| It is now determined that the check for gmp_item_aps and flags therein  |
3924 REM| should NOT be done here , so would be made immediately before inserting |
3925 REM| rows. The same may also be achieved by joining to gmp_item_aps table    |
3926 REM| while getting formula details                                           |
3927 REM|                                                                         |
3928 REM| HISTORY                                                                 |
3929 REM| 07/14/2002   Rajesh Patangya - Reorgnized the complete code B2314052    |
3930 REM+=========================================================================+
3931 */
3932 PROCEDURE validate_formula IS
3933 
3934 i                  INTEGER ;
3935 j                  INTEGER ;
3936 current_dtl_cnt    INTEGER ;
3937 start_pos_written  PLS_INTEGER ;
3938 detail_found       PLS_INTEGER ;
3939 uom_success        BOOLEAN ;
3940 
3941 BEGIN
3942 i                  := 1 ;
3943 j                  := 1 ;
3944 current_dtl_cnt    := 1 ;
3945 start_pos_written  := 0 ;
3946 detail_found       := 0 ;
3947 uom_success        := FALSE ;
3948    --  gmp_putline(' Begin validate_formula ','a');
3949    FOR i IN 1..formula_headers_size
3950    LOOP
3951      uom_success       := TRUE ;
3952      start_pos_written := 0 ;
3953      detail_found      := 0 ;
3954 
3955      FOR j IN current_dtl_cnt..fd_size
3956      LOOP
3957        IF formula_detail_tab(j).formula_id = formula_header_tab(i).formula_id
3958        THEN
3959            detail_found  := 1 ;
3960            IF formula_detail_tab(j).primary_qty < 0  THEN
3961 		uom_success := FALSE ;
3962            ELSE
3963 		uom_success := TRUE ;
3964            END IF;
3965 
3966            --  store the starting detail position
3967            IF start_pos_written = 0 THEN
3968               formula_header_tab(i).start_dtl_loc := j ;
3969               start_pos_written := 1 ;
3970            END IF;
3971 
3972            --  store the ending detail position, if it is the last row
3973            IF j = fd_size THEN
3974               formula_header_tab(i).end_dtl_loc := j ;
3975            END IF ;
3976 
3977        ELSIF formula_detail_tab(j).formula_id >
3978                           formula_header_tab(i).formula_id THEN
3979 
3980            --  store the ending detail position
3981            IF start_pos_written <> 1 THEN
3982               formula_header_tab(i).start_dtl_loc := -1 ;
3983               formula_header_tab(i).end_dtl_loc := -1 ;
3984            ELSE
3985               formula_header_tab(i).end_dtl_loc := j - 1 ;
3986            END IF ;
3987            current_dtl_cnt := j ;
3988            EXIT ;
3989 
3990        /* ELSE - no need to write else as it simply has to continue looping. */
3991        END IF ;
3992 
3993      END LOOP ;   /* fd_size  */
3994 
3995      IF (detail_found = 1) THEN
3996          IF (uom_success) THEN
3997            formula_header_tab(i).valid_flag := 1 ;
3998          ELSE
3999            formula_header_tab(i).valid_flag := -1 ;
4000            formula_header_tab(i).start_dtl_loc := -1 ;
4001            formula_header_tab(i).end_dtl_loc := -1 ;
4002    	   log_message(
4003                   'UOM Conversion falied for formula ' ||
4004    		  to_char(formula_header_tab(i).formula_id)
4005                   );
4006           END IF ;
4007      ELSE
4008            formula_header_tab(i).valid_flag := -1 ;
4009            formula_header_tab(i).start_dtl_loc := -1 ;
4010            formula_header_tab(i).end_dtl_loc := -1 ;
4011 	/* B4625724
4012    	   log_message(
4013                   'Formula detail not found for formula ' ||
4014    		  to_char(formula_header_tab(i).formula_id)
4015                   );
4016 	*/
4017      END IF ;
4018 
4019    END LOOP ;   /* Formula header loop */
4020 
4021    /* Now validate the formula for all the organizations */
4022    validate_formula_for_orgn ;
4023 
4024    --  gmp_putline(' End validate_formula ','a');
4025 END validate_formula ;
4026 
4027 /*
4028 REM+=========================================================================+
4029 REM| PROCEDURE NAME                                                          |
4030 REM|    validate_formula_for_orgn                                            |
4031 REM| DESCRIPTION                                                             |
4032 REM|    This procedure contains SQL query, but getting executed only once.   |
4033 REM| HISTORY                                                                 |
4034 REM| 07/14/2002   Rajesh Patangya - Reorgnized the complete code B2314052    |
4035 REM| 08/27/2002   Rajesh Patangya - Voltek Customer Fix B2362810             |
4036 REM+=========================================================================+
4037 */
4038 PROCEDURE validate_formula_for_orgn IS
4039 
4040     cur_formula_orgn_count          ref_cursor_typ;
4041     c_formula_dtl_count             ref_cursor_typ;
4042     formula_orgn_count_cursor       VARCHAR2(32767) ;
4043     formula_dtl_count_cursor        VARCHAR2(32767) ;
4044     fm_dtl_orgn_cnt                 INTEGER ;
4045     i                               INTEGER ;
4046 
4047 BEGIN
4048     formula_orgn_count_cursor       := NULL ;
4049     formula_dtl_count_cursor        := NULL ;
4050     fm_dtl_orgn_cnt                 := 1 ;
4051     i                               := 1 ;
4052       --  gmp_putline(' start of validate_formula_for_org ','a');
4053 
4054    formula_orgn_count_cursor :=
4055                      ' SELECT /*+ DRIVING_SITE(fmd) DRIVING_SITE(ffm) DRIVING_SITE(gia) DRIVING_SITE(som) */ fmd.formula_id, gia.plant_code, '
4056                    ||'       gia.organization_id, count(*), 0 '
4057                    ||' FROM  fm_matl_dtl'||at_apps_link||' fmd, '
4058                    ||'       fm_form_mst'||at_apps_link||' ffm, '
4059                    ||'       gmp_item_aps'||at_apps_link||' gia, '
4060                    ||'       sy_orgn_mst'||at_apps_link||' som '
4061                    ||' WHERE ffm.formula_id = fmd.formula_id '
4062                    ||'   AND ffm.delete_mark = 0 '
4063                    ||'   AND fmd.qty <> 0 '  /* 2362810 Voltek Fix */
4064                    ||'   AND fmd.item_id = gia.item_id '
4065                    ||'   AND gia.plant_code = som.orgn_code ' ;
4066          IF l_in_str_org  IS NOT NULL THEN
4067             formula_orgn_count_cursor := formula_orgn_count_cursor
4068                    ||'   AND gia.whse_code = som.resource_whse_code ' ;
4069         END IF;
4070 
4071          formula_orgn_count_cursor := formula_orgn_count_cursor
4072                    ||'   AND ( '
4073                    ||'       ( fmd.line_type = -1 AND '
4074                    ||'         gia.consum_ind = 1 ) '
4075                    ||'     OR '
4076                    ||'       ( fmd.line_type IN (1,2) AND '
4077                    ||'         gia.replen_ind = 1 ) '
4078                    ||'       ) '
4079                    ||' GROUP BY fmd.formula_id, gia.plant_code, '
4080                    ||'          gia.organization_id, 0 '
4081                    ||' ORDER BY fmd.formula_id, gia.plant_code, '
4082                    ||'          gia.organization_id ' ;
4083 
4084        -- Get counts for the formulae
4085        formula_dtl_count_cursor :=
4086                      ' SELECT /*+ DRIVING_SITE(fmd) DRIVING_SITE(ffm) */ fmd.formula_id, count(*) '
4087                    ||' FROM  fm_matl_dtl'||at_apps_link||' fmd, '
4088                    ||'       fm_form_mst'||at_apps_link||' ffm '
4089                    ||' WHERE ffm.formula_id = fmd.formula_id '
4090                    ||'   AND ffm.delete_mark = 0 '
4091                    ||'   AND fmd.qty <> 0 '   /* 2362810 Voltek Fix */
4092                    ||' GROUP BY fmd.formula_id '
4093                    ||' ORDER BY fmd.formula_id ' ;
4094 
4095     OPEN cur_formula_orgn_count FOR formula_orgn_count_cursor;
4096     FETCH cur_formula_orgn_count BULK COLLECT INTO formula_orgn_count_tab;
4097     formula_orgn_size := formula_orgn_count_tab.count;
4098 /* PPG Bug: 13590192
4099     LOOP
4100     FETCH cur_formula_orgn_count INTO formula_orgn_count_tab(formula_orgn_size);
4101     EXIT WHEN cur_formula_orgn_count%NOTFOUND;
4102 
4103     formula_orgn_size := formula_orgn_size + 1 ;
4104     END LOOP;
4105     */
4106 
4107     CLOSE cur_formula_orgn_count;
4108     --formula_orgn_size := formula_orgn_size -1 ;
4109     time_stamp ;
4110     log_message('Formula Orgn size is = ' || to_char(formula_orgn_size)) ;
4111 
4112     OPEN c_formula_dtl_count FOR formula_dtl_count_cursor ;
4113     FETCH c_formula_dtl_count INTO formula_dtl_count_rec ;
4114      WHILE c_formula_dtl_count%FOUND
4115      LOOP
4116 
4117        FOR i IN fm_dtl_orgn_cnt..formula_orgn_size
4118        LOOP
4119         IF formula_dtl_count_rec.formula_id =
4120                       formula_orgn_count_tab(i).formula_id THEN
4121 
4122              IF formula_dtl_count_rec.formula_dtl_count =
4123                       formula_orgn_count_tab(i).orgn_count THEN
4124                  formula_orgn_count_tab(i).valid_flag := 1 ;
4125              ELSE
4126                  formula_orgn_count_tab(i).valid_flag := -1 ;
4127              END IF ;
4128 
4129         ELSIF formula_dtl_count_rec.formula_id <
4130                  formula_orgn_count_tab(i).formula_id THEN
4131                  fm_dtl_orgn_cnt := i ;
4132               EXIT ;
4133 
4134         /*  ELSE NULL ;  */
4135         END IF ;
4136        END LOOP ;
4137 
4138      /* Get the next record */
4139      FETCH c_formula_dtl_count INTO formula_dtl_count_rec ;
4140      END LOOP ;
4141      CLOSE c_formula_dtl_count ;
4142      --   gmp_putline(' End of validate_formula_for_org ','a');
4143 
4144 END validate_formula_for_orgn;
4145 
4146 /*
4147 REM+=========================================================================+
4148 REM| FUNCTION NAME                                                           |
4149 REM|    check_formula                                                        |
4150 REM| DESCRIPTION                                                             |
4151 REM|                                                                         |
4152 REM| HISTORY                                                                 |
4153 REM| 07/14/2002   Rajesh Patangya - Reorgnized the complete code B2314052    |
4154 REM+=========================================================================+
4155 */
4156 FUNCTION check_formula ( pplant_code IN VARCHAR2,
4157                          porganization_id IN NUMBER,
4158                          pformula_id IN NUMBER) return BOOLEAN IS
4159 
4160 i                 INTEGER ;
4161 p_plant_code      VARCHAR2(4) ;
4162 p_organization_id NUMBER ;
4163 p_formula_id      NUMBER ;
4164 
4165 BEGIN
4166 p_plant_code      := pplant_code;
4167 p_organization_id := porganization_id;
4168 p_formula_id      := pformula_id;
4169 
4170 FOR i in g_fm_hdr_loc..formula_headers_size
4171 LOOP
4172 	IF  formula_header_tab(i).formula_id = pformula_id THEN
4173 	    IF formula_header_tab(i).valid_flag = 1 THEN
4174 		-- Note down formula_header location to be used
4175 		-- while writing the bom
4176 		g_fm_dtl_start_loc := formula_header_tab(i).start_dtl_loc ;
4177 		g_fm_dtl_end_loc := formula_header_tab(i).end_dtl_loc ;
4178 	        IF check_formula_for_organization (p_plant_code ,
4179                                                    p_organization_id ,
4180                                                    p_formula_id) THEN
4181 		  g_fm_hdr_loc := i ;
4182                   return TRUE ;
4183                 ELSE
4184 		  g_fm_hdr_loc := i ;
4185                   return FALSE ;
4186                 END IF;
4187             ELSE
4188 		  g_fm_hdr_loc := i ;
4189 		  /* Bug 4625724-Relocated message here so we do not list
4190 			invalid formulas indep of organization*/
4191 		  log_message('Formula detail not found for formula id = ' ||
4192                  to_char(formula_header_tab(i).formula_id)||' in organization id = '||
4193               		to_char(p_organization_id));
4194                   return FALSE ;
4195 	    END IF ;  /* Header validation */
4196 	ELSIF formula_header_tab(i).formula_id > pformula_id THEN
4197 		g_fm_hdr_loc := i ;
4198 		return FALSE ;
4199         /* ELSE
4200              NULL ;   */
4201 	END IF ;
4202 END LOOP ;
4203 		return FALSE ;
4204 END check_formula ;
4205 
4206 /*
4207 REM+=========================================================================+
4208 REM| FUNCTION NAME                                                           |
4209 REM|    check_formula_for_organization                                       |
4210 REM| DESCRIPTION                                                             |
4211 REM|                                                                         |
4212 REM| HISTORY                                                                 |
4213 REM| 07/14/2002   Rajesh Patangya - Reorgnized the complete code B2314052    |
4214 REM+=========================================================================+
4215 */
4216 FUNCTION check_formula_for_organization (
4217                          pplant_code IN VARCHAR2,
4218                          porganization_id IN NUMBER,
4219                          pformula_id IN NUMBER) return BOOLEAN IS
4220 i            INTEGER ;
4221 BEGIN
4222 i            := 1  ;
4223 FOR i IN g_formula_orgn_count_tab..formula_orgn_count_tab.COUNT
4224 LOOP
4225   IF formula_orgn_count_tab(i).formula_id = pformula_id THEN
4226 
4227     IF formula_orgn_count_tab(i).plant_code = pplant_code THEN
4228         IF formula_orgn_count_tab(i).organization_id = porganization_id THEN
4229           IF formula_orgn_count_tab(i).valid_flag = 1 THEN
4230              g_formula_orgn_count_tab := i ;
4231              return TRUE ;
4232           ELSE
4233              g_formula_orgn_count_tab := i ;
4234              return FALSE ;
4235           END IF;
4236         ELSIF formula_orgn_count_tab(i).organization_id > porganization_id THEN
4237              g_formula_orgn_count_tab := i ;
4238              return FALSE ;
4239            /* ELSE
4240                  NULL ;  */
4241         END IF;  /* Organizatin ID */
4242     ELSIF formula_orgn_count_tab(i).plant_code >  pplant_code THEN
4243              g_formula_orgn_count_tab := i ;
4244              return FALSE ;
4245     /* ELSE
4246         NULL ;  */
4247     END IF ;   /* For Plant code  */
4248   ELSIF formula_orgn_count_tab(i).formula_id > pformula_id THEN
4249            g_formula_orgn_count_tab := i ;
4250            return FALSE ;
4251   /* ELSE
4252     NULL ;  */
4253   END IF;
4254 END LOOP ;
4255    return FALSE ;
4256 END check_formula_for_organization ;
4257 
4258 /*
4259 REM+=========================================================================+
4260 REM| FUNCTION NAME                                                           |
4261 REM|    bsearch_routing                                                      |
4262 REM| DESCRIPTION                                                             |
4263 REM|                                                                         |
4264 REM| HISTORY                                                                 |
4265 REM| 07/14/2002   Rajesh Patangya - Reorgnized the complete code B2314052    |
4266 REM+=========================================================================+
4267 */
4268 FUNCTION bsearch_routing (p_routing_id IN PLS_INTEGER ,
4269 			  p_plant_code IN VARCHAR2)
4270 			RETURN INTEGER IS
4271 
4272 top     INTEGER ;
4273 bottom  INTEGER ;
4274 mid     INTEGER ;
4275 
4276 BEGIN
4277      top    := 1;
4278      bottom := routing_headers_size ;
4279      mid    := -1 ;
4280    WHILE  (top <= bottom )
4281     LOOP
4282      mid := top + ( ( bottom - top ) / 2 );
4283 
4284      IF p_routing_id < rtg_org_hdr_tab(mid).routing_id OR
4285   	(p_routing_id = rtg_org_hdr_tab(mid).routing_id AND
4286 	 p_plant_code < rtg_org_hdr_tab(mid).plant_code ) THEN
4287 	bottom := mid -1 ;
4288      ELSIF
4289 	p_routing_id > rtg_org_hdr_tab(mid).routing_id OR
4290         (p_routing_id = rtg_org_hdr_tab(mid).routing_id AND
4291          p_plant_code > rtg_org_hdr_tab(mid).plant_code ) THEN
4292 	top := mid + 1 ;
4293      ELSE
4294 	-- We can do the checking for the validity etc here
4295 	-- OR just return the location to calling function and
4296 	-- let the calling function do rest of the work
4297 	RETURN mid ;
4298      END IF ;
4299     END LOOP;
4300     -- Not found
4301     Return -1 ;
4302 END bsearch_routing ;
4303 /*
4304 REM+=========================================================================+
4305 REM| FUNCTION NAME                                                           |
4306 REM|    bsearch_setupid  SGIDUGU                                             |
4307 REM| DESCRIPTION                                                             |
4308 REM|                                                                         |
4309 REM| HISTORY                                                                 |
4310 REM+=========================================================================+
4311 */
4312 FUNCTION bsearch_setupid (p_oprn_id       IN PLS_INTEGER ,
4313                           p_category_id   IN PLS_INTEGER
4314                          ) RETURN INTEGER IS
4315 --
4316 top     INTEGER ;
4317 bottom  INTEGER ;
4318 mid     INTEGER ;
4319 
4320 BEGIN
4321 --
4322      top    := 1;
4323      bottom := setup_size ;
4324      mid    := -1 ;
4325 --
4326    WHILE  (top <= bottom )
4327     LOOP
4328      mid := top + ( ( bottom - top ) / 2 );
4329 
4330      IF p_oprn_id < setupid_tab(mid).oprn_id OR
4331   	(p_oprn_id = setupid_tab(mid).oprn_id AND
4332 	 p_category_id < setupid_tab(mid).category_id ) THEN
4333 	bottom := mid -1 ;
4334      ELSIF
4335 	p_oprn_id > setupid_tab(mid).oprn_id OR
4336         (p_oprn_id = setupid_tab(mid).oprn_id AND
4337          p_category_id > setupid_tab(mid).category_id ) THEN
4338 	top := mid + 1 ;
4339      ELSE
4340 --	RETURN mid ;
4341 	RETURN setupid_tab(mid).seq_dep_id ;
4342      END IF ;
4343     END LOOP;
4344     -- Not found
4345     Return -1 ;
4346 END bsearch_setupid ;
4347 /*
4348 REM+=========================================================================+
4349 REM| PROCEDURE NAME                                                          |
4350 REM|    write_process_effectivities                                          |
4351 REM|                                                                         |
4352 REM| TYPE                                                                    |
4353 REM|    Private                                                              |
4354 REM|                                                                         |
4355 REM| USAGE                                                                   |
4356 REM|    This procedure creates the effectivty rows in gmp_form_eff and       |
4357 REM|    msc_process_effectivities                                            |
4358 REM|                                                                         |
4359 REM| DESCRIPTION                                                             |
4360 REM|                                                                         |
4361 REM|                                                                         |
4362 REM| INPUT PARAMETERS                                                        |
4363 REM|    None                                                                 |
4364 REM|                                                                         |
4365 REM| OUTPUT PARAMETERS                                                       |
4366 REM|    return_status    TRUE => OK                                          |
4367 REM|                                                                         |
4368 REM| INPUT/OUTPUT PARAMETERS                                                 |
4369 REM|    None                                                                 |
4370 REM|                                                                         |
4371 REM| HISTORY                                                                 |
4372 REM|  07/14/2002   Rajesh Patangya - Reorgnized the complete code B2314052   |
4373 REM|  06/02/2003   Sridhar Gidugu  Checked aps_fmeff_id before               |
4374 REM|                               inserts - B2989806                        |
4375 REM+=========================================================================+
4376 */
4377 PROCEDURE write_process_effectivity
4378 (
4379   p_x_aps_fmeff_id   IN NUMBER,
4380   p_aps_fmeff_id     IN NUMBER,
4381   return_status      OUT NOCOPY BOOLEAN
4382 )
4383 IS
4384   statement_form_eff     VARCHAR2(32700) ;
4385   loop_index       INTEGER;
4386   routing_id       NUMBER ;
4387 
4388 BEGIN
4389   statement_form_eff     := NULL ;
4390 
4391 /* B2989806  Added IF condition below */
4392 IF effectivity.aps_fmeff_id = -1 THEN
4393     statement_form_eff :=
4394 	          'INSERT INTO gmp_form_eff'||at_apps_link
4395 		   ||' ( '
4396 		   ||'  aps_fmeff_id,whse_code,plant_code,fmeff_id, '
4397                    ||'  formula_id, routing_id, '
4398 		   ||'  creation_date, created_by, last_update_date, '
4399                    ||'  last_updated_by '
4400 		   ||' ) '
4401 		   ||' VALUES '
4402 		   ||' ( :p1,:p2,:p3,:p4,:p5,:p6,:p7,:p8,:p9,:p10)';
4403 
4404              /* This aps_fmeff_id the next sequence ID, but not multiplied by
4405                 2 and added by 1 */
4406     EXECUTE IMMEDIATE statement_form_eff USING
4407 		   p_aps_fmeff_id,
4408 		   effectivity.whse_code,
4409 		   effectivity.plant_code,
4410 		   effectivity.fmeff_id,
4411 		   effectivity.formula_id,
4412 		   effectivity.routing_id,
4413 		   current_date_time,
4414 		   0,
4415 		   current_date_time,
4416 		   0;
4417 END IF ; /* New effectivity row to be created */
4418 
4419         /* Process Effectivity Bulk Insert assignment */
4420 
4421            pef_index := pef_index + 1 ;
4422            pef_process_sequence_id(pef_index) :=   p_x_aps_fmeff_id ;
4423            pef_item_id(pef_index) :=  effectivity.aps_item_id ;   /* aps_item_id */
4424            pef_organization_id(pef_index) :=  effectivity.organization_id ;
4425            pef_effectivity_date(pef_index) :=  effectivity.start_date ;
4426 
4427            IF effectivity.end_date IS NOT NULL THEN
4428                 pef_disable_date(pef_index) :=  effectivity.end_date ;
4429            ELSE
4430                 pef_disable_date(pef_index) := null_value ;
4431            END IF;
4432 
4433            pef_minimum_quantity(pef_index) :=  effectivity.inv_min_qty ;
4434            pef_maximum_quantity(pef_index) :=  effectivity.inv_max_qty ;
4435            pef_preference(pef_index)       :=  effectivity.preference ;
4436            pef_routing_sequence_id(pef_index) :=  p_x_aps_fmeff_id ;
4437            pef_bill_sequence_id(pef_index)    :=  p_x_aps_fmeff_id ;
4438            pef_sr_instance_id(pef_index) :=  b_instance_id ;
4439            -- pef_deleted_flag(pef_index)     := 2;
4440            pef_last_update_date(pef_index) := current_date_time ;
4441            -- bom_last_updated_by(pef_index)  := 0 ;
4442            pef_creation_date(pef_index)    := current_date_time ;
4443            -- pef_created_by(pef_index)       := 0;
4444 
4445   return_status := TRUE;
4446 
4447   EXCEPTION
4448     WHEN OTHERS THEN
4449        log_message('Write Process Effectivity Raised Exception: '||sqlerrm);
4450        log_message(to_char(effectivity.fmeff_id));
4451        return_status := FALSE;
4452 END write_process_effectivity;
4453 
4454 /*
4455 REM+=========================================================================+
4456 REM| PROCEDURE NAME                                                          |
4457 REM|    write_bom_components                                                 |
4458 REM|                                                                         |
4459 REM| TYPE                                                                    |
4460 REM|    Private                                                              |
4461 REM|                                                                         |
4462 REM| USAGE                                                                   |
4463 REM|    This procedure creates the bill of material components in msc_boms   |
4464 REM|                                                                         |
4465 REM| DESCRIPTION                                                             |
4466 REM|                                                                         |
4467 REM|                                                                         |
4468 REM| INPUT PARAMETERS                                                        |
4469 REM|    None                                                                 |
4470 REM|                                                                         |
4471 REM| OUTPUT PARAMETERS                                                       |
4472 REM|    return_status    TRUE => OK                                          |
4473 REM|                                                                         |
4474 REM| INPUT/OUTPUT PARAMETERS                                                 |
4475 REM|    None                                                                 |
4476 REM|                                                                         |
4477 REM| HISTORY                                                                 |
4478 REM|  07/14/2002   Rajesh Patangya - Reorgnized the complete code B2314052   |
4479 REM|  08/27/2002 - B2098058 Alternate_bomdesignator is being passed          |
4480 REM|               as the eff_id because 1. Alt_rtg_desgn is now required    |
4481 REM|               per explanation in the bug 2.alt_rtg_desgn should be same |
4482 REM|               alt_bom_desgn for the bom in the same eff 3.OPM has       |
4483 REM|               has no way to determine primary bom/rtg from alternate    |
4484 REM|                                                                         |
4485 REM+=========================================================================+
4486 */
4487 PROCEDURE write_bom_components
4488 (
4489   p_x_aps_fmeff_id   IN PLS_INTEGER,
4490   return_status      OUT NOCOPY BOOLEAN
4491 )
4492 IS
4493   temp_assembly_comment   VARCHAR2(240) ;
4494   primary_bom_written     PLS_INTEGER ;
4495   p_primary_qty           NUMBER ;
4496   loop_index              PLS_INTEGER;
4497   l_scale_type            INTEGER;
4498   l_offset_loc            NUMBER ;
4499   l_offset           	  NUMBER ;
4500   l_line_type 		  INTEGER;
4501   rtgstpno_loc            NUMBER;
4502 BEGIN
4503   temp_assembly_comment   := NULL ;
4504   p_primary_qty           := 0 ;
4505   l_offset_loc            := 0 ;
4506   l_offset           	  := 0 ;
4507   l_line_type 		  := 0 ;
4508 
4509 
4510   rtgstpno_loc := -1;
4511   primary_bom_written := 0 ;
4512 
4513   -- ABHAY write the code to get the offset percentages here.
4514   -- The code will loop through the formula_detail_tab  from
4515   -- g_fm_dtl_start_loc to g_fm_dtl_end_loc and update the field offset
4516   FOR loop_index IN g_fm_dtl_start_loc..g_fm_dtl_end_loc
4517   LOOP
4518 
4519      /* Do write a row for the primary produc */
4520 
4521    IF (effectivity.item_id = formula_detail_tab(loop_index).opm_item_id) AND
4522       (formula_detail_tab(loop_index).line_type = 1)  THEN
4523       IF primary_bom_written = 0 THEN
4524          /* WRITE_BOM : Do write a row for the primary product   */
4525         BEGIN
4526         /*B2870041 save the index of the product it will be used when writing
4527            the route and its details */
4528         effectivity.product_index := loop_index;
4529 
4530         temp_assembly_comment :=
4531 	 formula_detail_tab(loop_index).formula_no ||delimiter||
4532 	 to_char(formula_detail_tab(loop_index).formula_vers) ||delimiter||
4533 	 formula_detail_tab(loop_index).formula_desc1 ;
4534 
4535          /* BOM Bulk Insert assignments */
4536 
4537          bom_index := bom_index + 1 ;
4538          bom_bill_sequence_id(bom_index) := p_x_aps_fmeff_id ;
4539          bom_sr_instance_id(bom_index)   := b_instance_id ;
4540          bom_organization_id(bom_index)  := effectivity.organization_id ;
4541          bom_assembly_item_id(bom_index) := effectivity.aps_item_id ;
4542          -- bom_assembly_type(bom_index)    := 1 ;
4543          IF l_1237_count <> 0 OR l_1238_count <> 0 THEN  -- Biogen start
4544          bom_alternate_bom_designator(bom_index) := effectivity.recipe_no || delimiter || to_char(effectivity.recipe_version) || delimiter || formula_detail_tab(loop_index).formula_no
4545                                                 ||delimiter||  to_char(formula_detail_tab(loop_index).formula_vers);
4546          ELSE
4547          bom_alternate_bom_designator(bom_index)  := p_x_aps_fmeff_id ;
4548          END IF;  -- Biogen end
4549          bom_specific_assembly_comment(bom_index) :=  temp_assembly_comment ;
4550          bom_scaling_type(bom_index)    :=
4551                              formula_detail_tab(loop_index).bom_scale_type ;
4552          bom_assembly_quantity(bom_index)  :=
4553                             formula_detail_tab(loop_index).primary_qty ;
4554          bom_uom(bom_index)  := formula_detail_tab(loop_index).aps_um ;
4555 /* NAMIT_CR For Step Material Assoc */
4556 /* Used enhanced binary search to get the location for routing
4557     step number of product. */
4558 
4559             rtgstpno_loc :=
4560                enh_bsearch_stpno (effectivity.formula_id, effectivity.recipe_id,
4561                   effectivity.item_id);
4562 
4563 --
4564 
4565             IF(rtgstpno_loc > 0) THEN
4566                bom_op_seq_number(bom_index) := mat_assoc_tab(rtgstpno_loc).routingstep_no;
4567             ELSE
4568                 bom_op_seq_number(bom_index) := null_value ;
4569             END IF;
4570 
4571 --         bom_op_seq_number(bom_index) := formula_detail_tab(loop_index).routingstep_no;
4572 
4573          -- bom_deleted_flag(bom_index)     := 2;
4574          bom_last_update_date(bom_index) := current_date_time ;
4575          -- bom_last_updated_by(bom_index)  := 0 ;
4576          bom_creation_date(bom_index)    := current_date_time ;
4577          -- bom_created_by(bom_index)       := 0;
4578 
4579          EXCEPTION
4580               WHEN OTHERS THEN
4581               log_message('Error writing to msc_st_boms: '||sqlerrm);
4582               /* B3837959 MMK Issue, set return status to false */
4583               return_status := FALSE;
4584          END;
4585           primary_bom_written := 1 ;
4586 --          primary_bom_formulaline_id := formula_detail_tab(loop_index).x_formulaline_id; -- Bug # 4879588
4587       -- 01/17/2003 Rajesh Patangya B2740767
4588       ELSE      /* Primary BOM written */
4589            /* Primary product written and now co-prod is same as prod
4590               note that the co-products always contribute to yield and
4591               scale type can only be fixed or linear per restrictions in GMD
4592            */
4593 	-- Now get the offset percentage
4594 	-- -------------------------------
4595 	IF g_curr_rstep_loc > 0  AND
4596 	(formula_detail_tab(loop_index).release_type between  1 AND 3)
4597 	THEN
4598 	 l_offset_loc := get_offsets( effectivity.formula_id,
4599 				effectivity.plant_code,
4600 		formula_detail_tab(loop_index).x_formulaline_id ) ;
4601 	 IF l_offset_loc < 0 THEN
4602           IF formula_detail_tab(loop_index).line_type < 0 THEN
4603                 l_offset := 0 ;
4604           ELSE
4605                 l_offset := 100 ;
4606           END IF ;
4607 	 ELSE
4608           IF formula_detail_tab(loop_index).line_type < 0 THEN
4609                 l_offset := rstep_offsets(l_offset_loc).start_offset ;
4610           ELSE
4611                 l_offset := rstep_offsets(l_offset_loc).end_offset ;
4612           END IF ;
4613 
4614 	 END IF ;
4615 	ELSE
4616 	  IF formula_detail_tab(loop_index).line_type < 0 THEN
4617 		l_offset := 0 ;
4618 	  ELSE
4619 		l_offset := 100 ;
4620 	  END IF ;
4621 	END IF ;
4622 	-- -------------------------------
4623 
4624          BEGIN   /* co-product */
4625          /* BOM Component Bulk Insert assignments */
4626          bomc_index := bomc_index + 1 ;
4627          bomc_component_sequence_id(bomc_index) := formula_detail_tab(loop_index).x_formulaline_id ;
4628          bomc_sr_instance_id(bomc_index)   := b_instance_id ;
4629          bomc_organization_id(bomc_index)  := effectivity.organization_id ;
4630          bomc_Inventory_item_id(bomc_index) := formula_detail_tab(loop_index).aps_item_id ;
4631          bomc_using_assembly_id(bomc_index) := effectivity.aps_item_id ;
4632          bomc_bill_sequence_id(bomc_index) := p_x_aps_fmeff_id ;
4633          bomc_component_type(bomc_index) := 10 ;  /* for co-proudcts */
4634          bomc_scaling_type(bomc_index) := l_scale_type; /* Scailing type for APS */
4635            -- bomc_change_notice(i)  == null
4636            -- bomc_revision(i),  == null
4637          bomc_uom_code(bomc_index) := formula_detail_tab(loop_index).aps_um ;
4638          bomc_usage_quantity(bomc_index) :=  (-1 * formula_detail_tab(loop_index).primary_qty) ;
4639          bomc_effectivity_date(bomc_index) := current_date_time ;
4640          bomc_contribute_to_step_qty(bomc_index) := formula_detail_tab(loop_index).contribute_step_qty_ind;
4641          bomc_disable_date(bomc_index) := null_value ;
4642            -- bomc_from_unit_number := null_value,
4643            -- bomc_to_unit_number := null_value,
4644            -- bomc_use_up_code := null_value,
4645            -- bomc_suggested_effectivity_date := null_value,
4646            -- bomc_driving_item_id := null_value,
4647          IF l_offset IS NOT NULL THEN
4648            bomc_opr_offset_percent(bomc_index) := l_offset; /* offset percentage */
4649          ELSE
4650            bomc_opr_offset_percent(bomc_index) := null_value ;
4651          END IF;
4652 
4653          bomc_optional_component(bomc_index) := 2 ;
4654            -- bomc_old_effectivity_date := null_value,
4655          bomc_wip_supply_type(bomc_index) := formula_detail_tab(loop_index).phantom_type ;
4656            -- bomc_planning_factor := null_value,
4657            -- bomc_atp_flag := 1,
4658            -- bomc_component_yield_factor := 1,
4659            -- deleted_flag := 2,
4660          bomc_last_update_date(bomc_index) := current_date_time ;
4661            -- bomc_last_updated_by(bomc_index)  := 0 ;
4662          bomc_creation_date(bomc_index)    := current_date_time ;
4663            -- bomc_created_by(bomc_index)       := 0;
4664          IF  formula_detail_tab(loop_index).scale_multiple IS NOT NULL THEN
4665            bomc_scale_multiple(bomc_index) := formula_detail_tab(loop_index).scale_multiple ;
4666          ELSE
4667            bomc_scale_multiple(bomc_index) := null_value;
4668          END IF;
4669          IF formula_detail_tab(loop_index).scale_rounding_variance IS NOT NULL THEN
4670            bomc_scale_rounding_variance(bomc_index) :=
4671                      formula_detail_tab(loop_index).scale_rounding_variance ;
4672          ELSE
4673            bomc_scale_rounding_variance(bomc_index) := null_value;
4674          END IF;
4675          IF formula_detail_tab(loop_index).rounding_direction IS NOT NULL THEN
4676            bomc_rounding_direction(bomc_index) :=
4677                          formula_detail_tab(loop_index).rounding_direction ;
4678          ELSE
4679            bomc_rounding_direction(bomc_index) := null_value ;
4680          END IF;
4681 
4682          EXCEPTION
4683               WHEN OTHERS THEN
4684               log_message('Error co-products to msc_st_bom_comp: '||sqlerrm);
4685               /* B3837959 MMK Issue, set return status to false */
4686               return_status := FALSE;
4687          END ;   /* co-product */
4688 
4689       END IF ;  /* Primary BOM written */
4690 
4691    ELSE
4692 
4693      /* Do write all formula detail lines except primary product */
4694        IF formula_detail_tab(loop_index).line_type = -1 THEN
4695            p_primary_qty := formula_detail_tab(loop_index).primary_qty;
4696            /* B2559881, scrap_factor introduced */
4697            p_primary_qty := p_primary_qty *
4698             (1 + nvl(formula_detail_tab(loop_index).scrap_factor,0));
4699        ELSE
4700            p_primary_qty := (-1) * formula_detail_tab(loop_index).primary_qty;
4701            /* B2559881, scrap_factor introduced */
4702            p_primary_qty := p_primary_qty *
4703             (1 + nvl(formula_detail_tab(loop_index).scrap_factor,0));
4704        END IF;
4705 
4706        /* B3452524, If co-prodcut or by product is not same as product then
4707           component type should be 10 */
4708 
4709 	IF formula_detail_tab(loop_index).line_type = 1 THEN
4710 	  l_line_type := 10 ;
4711 	ELSE
4712 	  l_line_type := formula_detail_tab(loop_index).line_type ;
4713 	END IF ;
4714 
4715 
4716     /* B2657068 Scailing type decision Rajesh Patangya */
4717     /*  Scale type in material detail 0-Fixed, 1-proportional 2-Integer */
4718 
4719     IF formula_detail_tab(loop_index).contribute_yield_ind = 'Y' THEN
4720        IF formula_detail_tab(loop_index).scale_type = 0 THEN
4721           l_scale_type := 0 ;
4722        ELSIF formula_detail_tab(loop_index).scale_type = 1 THEN
4723           l_scale_type := 1 ;
4724        ELSIF  formula_detail_tab(loop_index).scale_type = 2 THEN
4725           l_scale_type := 4 ;
4726        ELSE
4727          /* scale type of other than 0,1,2 is not supported */
4728          l_scale_type := formula_detail_tab(loop_index).scale_type ;
4729        END IF ;
4730     ELSE
4731        IF formula_detail_tab(loop_index).scale_type = 0 THEN
4732           l_scale_type := 2 ;
4733        ELSIF formula_detail_tab(loop_index).scale_type = 1 THEN
4734           l_scale_type := 3 ;
4735        ELSIF  formula_detail_tab(loop_index).scale_type = 2 THEN
4736           l_scale_type := 5 ;
4737        ELSE
4738          /* scale type of other than 0,1,2 is not supported */
4739          l_scale_type := formula_detail_tab(loop_index).scale_type ;
4740        END IF ;
4741     END IF ;           /* IF contribute_yield_ind */
4742 	-- Now get the offsets
4743 	-- -------------------------------
4744 	IF g_curr_rstep_loc > 0  AND
4745 	(formula_detail_tab(loop_index).release_type between 1 AND 3)
4746 	THEN
4747 	 l_offset_loc := get_offsets( effectivity.formula_id,
4748 				effectivity.plant_code,
4749 		formula_detail_tab(loop_index).x_formulaline_id ) ;
4750 	 IF l_offset_loc < 0 THEN
4751           IF formula_detail_tab(loop_index).line_type < 0 THEN
4752                 l_offset := 0 ;
4753           ELSE
4754                 l_offset := 100 ;
4755           END IF ;
4756 	 ELSE
4757           IF formula_detail_tab(loop_index).line_type < 0 THEN
4758                 l_offset := rstep_offsets(l_offset_loc).start_offset ;
4759           ELSE
4760                 l_offset := rstep_offsets(l_offset_loc).end_offset ;
4761           END IF ;
4762 
4763 	 END IF ;
4764 	ELSE
4765 	  IF formula_detail_tab(loop_index).line_type < 0 THEN
4766 		l_offset := 0 ;
4767 	  ELSE
4768 		l_offset := 100 ;
4769 	  END IF ;
4770 	END IF ;
4771 	-- -----------------------------------
4772 
4773    /* B3267522, Rajesh Patangya Do not insert ingredients, if ingredient is same
4774       as product (single level circular reference) */
4775 
4776     IF (effectivity.aps_item_id = formula_detail_tab(loop_index).aps_item_id) AND
4777       (formula_detail_tab(loop_index).line_type = -1)  THEN
4778       NULL ;
4779     ELSE
4780          /* BOM Component Bulk Insert assignments */
4781          bomc_index := bomc_index + 1 ;
4782 
4783   -- Bug:6030499 Vpedarla
4784         IF formula_detail_tab(loop_index).x_formulaline_id IS NOT NULL THEN
4785                 bomc_component_sequence_id(bomc_index) := formula_detail_tab(loop_index).x_formulaline_id ;
4786          ELSE
4787                 gmd_formline_cnt := gmd_formline_cnt + 1;
4788                 bomc_component_sequence_id(bomc_index) := (( v_gmd_formula_lineid + gmd_formline_cnt ) * 2) + 1;
4789                 /*For sustitutes the formula line id will be null. component sequence id in
4790                 msc_st_bom_components is a primary key. So the max value from gmd formula line sequence
4791                 is fetched and global counter value is added to it.Then odd value is passed on to APS. */
4792          END IF;
4793   -- Bug:6030499 Vpedarla end of item sybstitution
4794   --    bomc_component_sequence_id(bomc_index) := formula_detail_tab(loop_index).x_formulaline_id;
4795 
4796 
4797          bomc_sr_instance_id(bomc_index)   := b_instance_id ;
4798          bomc_organization_id(bomc_index)  := effectivity.organization_id ;
4799          bomc_Inventory_item_id(bomc_index) := formula_detail_tab(loop_index).aps_item_id ;
4800          -- RDP B2445746, replace component aps_item_id to product aps_item_id
4801          bomc_using_assembly_id(bomc_index) := effectivity.aps_item_id ;
4802          bomc_bill_sequence_id(bomc_index) := p_x_aps_fmeff_id ;
4803          bomc_component_type(bomc_index) := l_line_type ;
4804          bomc_scaling_type(bomc_index) := l_scale_type; /* Scailing type for APS */
4805          bomc_uom_code(bomc_index) := formula_detail_tab(loop_index).aps_um ;
4806          bomc_usage_quantity(bomc_index) :=  p_primary_qty ;
4807          bomc_contribute_to_step_qty(bomc_index) := formula_detail_tab(loop_index).contribute_step_qty_ind;
4808 	-- Rounding off the start date
4809 	 IF formula_detail_tab(loop_index).start_date IS NULL  THEN
4810            bomc_effectivity_date(bomc_index) := trunc(current_date_time) ;
4811 	 ELSE
4812           -- Bug: 6030499 Vpedarla Item substitution change - removed if condition in else clause
4813 --	  IF
4814 --	  formula_detail_tab(loop_index).start_date > trunc(formula_detail_tab(loop_index).start_date) THEN
4815 --	  bomc_effectivity_date(bomc_index) := trunc(formula_detail_tab(loop_index).start_date) + 1 ;
4816 --	  ELSE
4817 --	  bomc_effectivity_date(bomc_index) := trunc(formula_detail_tab(loop_index).start_date) ;
4818 --	  END IF ;
4819           -- bug: 6030499 added the direct statedment
4820           bomc_effectivity_date(bomc_index) := trunc(formula_detail_tab(loop_index).start_date) ;
4821 	 END IF ;
4822 	 -- Rounding off the end date
4823 	 IF formula_detail_tab(loop_index).end_date IS NULL  THEN
4824            bomc_disable_date(bomc_index) := null_value ;
4825 	 ELSE
4826 --	  IF
4827 --	  formula_detail_tab(loop_index).end_date > trunc(formula_detail_tab(loop_index).end_date) THEN
4828 --	  bomc_disable_date(bomc_index) := trunc(formula_detail_tab(loop_index).end_date) + 1 ;
4829 --	  ELSE
4830 --	  bomc_disable_date(bomc_index) := trunc(formula_detail_tab(loop_index).end_date) ;
4831 --	  END IF ;
4832           -- bug: 6030499 added the direct statedment
4833           bomc_disable_date(bomc_index) := trunc(formula_detail_tab(loop_index).end_date) ;
4834 	 END IF ;
4835         -- end of bug:6030499
4836 
4837            -- bomc_from_unit_number := null_value,
4838            -- bomc_to_unit_number := null_value,
4839            -- bomc_use_up_code := null_value,
4840            -- bomc_suggested_effectivity_date := null_value,
4841            -- bomc_driving_item_id := null_value,
4842          IF l_offset IS NOT NULL THEN
4843            bomc_opr_offset_percent(bomc_index) := l_offset; /* offset percentage */
4844          ELSE
4845            bomc_opr_offset_percent(bomc_index) := null_value ;
4846          END IF;
4847 
4848          bomc_optional_component(bomc_index) := 2 ;
4849            -- bomc_old_effectivity_date := null_value,
4850          bomc_wip_supply_type(bomc_index) := formula_detail_tab(loop_index).phantom_type ;
4851          bomc_last_update_date(bomc_index) := current_date_time ;
4852          bomc_creation_date(bomc_index)    := current_date_time ;
4853          /* B2657068 Rajesh Patangya */
4854          IF  formula_detail_tab(loop_index).scale_multiple IS NOT NULL THEN
4855            bomc_scale_multiple(bomc_index) := formula_detail_tab(loop_index).scale_multiple ;
4856          ELSE
4857            bomc_scale_multiple(bomc_index) := null_value;
4858          END IF;
4859          IF formula_detail_tab(loop_index).scale_rounding_variance IS NOT NULL THEN
4860            bomc_scale_rounding_variance(bomc_index) :=
4861                      formula_detail_tab(loop_index).scale_rounding_variance ;
4862          ELSE
4863            bomc_scale_rounding_variance(bomc_index) := null_value;
4864          END IF;
4865          IF formula_detail_tab(loop_index).rounding_direction IS NOT NULL THEN
4866            bomc_rounding_direction(bomc_index) := formula_detail_tab(loop_index).rounding_direction ;
4867          ELSE
4868            bomc_rounding_direction(bomc_index) := null_value ;
4869          END IF;
4870 
4871     END IF;   /* Circular reference */
4872 
4873    END IF;
4874 
4875   END LOOP;
4876   return_status := TRUE;
4877 
4878   EXCEPTION
4879     WHEN OTHERS THEN
4880 	log_message('Error writing to msc_st_bom_components: '||sqlerrm);
4881 	return_status := FALSE;
4882 END write_bom_components;
4883 
4884 /*
4885 REM+=========================================================================+
4886 REM| PROCEDURE NAME                                                          |
4887 REM|    write_routing                                                        |
4888 REM|                                                                         |
4889 REM| TYPE                                                                    |
4890 REM|    Private                                                              |
4891 REM|                                                                         |
4892 REM| USAGE                                                                   |
4893 REM|    This procedure creates a routing in msc_routings                     |
4894 REM|                                                                         |
4895 REM| DESCRIPTION                                                             |
4896 REM|                                                                         |
4897 REM|                                                                         |
4898 REM| INPUT PARAMETERS                                                        |
4899 REM|    table_index      index into aps_effectivities structure for current  |
4900 REM|                     effectivity.                                        |
4901 REM|                                                                         |
4902 REM| OUTPUT PARAMETERS                                                       |
4903 REM|    return_status    TRUE => OK                                          |
4904 REM|                                                                         |
4905 REM| INPUT/OUTPUT PARAMETERS                                                 |
4906 REM|    None                                                                 |
4907 REM|                                                                         |
4908 REM| HISTORY                                                                 |
4909 REM|  07/14/2002   Rajesh Patangya - Reorgnized the complete code B2314052   |
4910 REM|  08/27/2002   B2098058 Alternate_routing_designator is being passed     |
4911 REM|               as the eff_id because 1. Alt_rtg_desgn is now required    |
4912 REM|               per explanation in the bug 2.alt_rtg_desgn should be same |
4913 REM|               alt_bom_desgn for the bom in the same eff 3.OPM has       |
4914 REM|               has no way to determine primary bom/rtg from alternate    |
4915 REM|                                                                         |
4916 REM+=========================================================================+
4917 */
4918 PROCEDURE write_routing
4919 (
4920   p_x_aps_fmeff_id   IN NUMBER,
4921   return_status      OUT NOCOPY BOOLEAN
4922 )
4923 IS
4924   p_routing_details  VARCHAR2(128) ;
4925   v_routing_qty      NUMBER ;
4926 BEGIN
4927   p_routing_details  := NULL;
4928   v_routing_qty      := 0;
4929   IF effectivity.rtg_hdr_location > 0 AND effectivity.product_index > 0 THEN
4930 
4931     p_routing_details := effectivity.routing_no ||delimiter||
4932                          to_char(effectivity.routing_vers) ||delimiter||
4933                          effectivity.routing_desc ;
4934 
4935     /*B2870041 The routing qty needs to be represented as the product of the
4936        effectivity so APS can scale the route correctly. If the product has
4937        fixed scaling then the route will need to use the full product qty
4938        as the route will not get scaled according to total output in APS.
4939        Otherwise the quantity will be the product qty scaled to match
4940        the total output if represented as the routing qty*/
4941     IF formula_detail_tab(effectivity.product_index).scale_type = 0 THEN
4942       v_routing_qty :=
4943         formula_detail_tab(effectivity.product_index).primary_qty;
4944     ELSE
4945       v_routing_qty := (effectivity.routing_qty /
4946         formula_header_tab(g_fm_hdr_loc).total_output) *
4947         formula_detail_tab(effectivity.product_index).primary_qty;
4948     END IF;
4949 
4950     /* B2870041 report the uom as the primary uom of the product in the discrete
4951       form. The quantity is the scaled version of the product to match the
4952       routing qty as explained previously */
4953 
4954           /* Routing Bulk insert assignments */
4955             rtg_index := rtg_index + 1 ;
4956             rtg_routing_sequence_id(rtg_index) := p_x_aps_fmeff_id ;
4957             rtg_sr_instance_id(rtg_index) := b_instance_id ;
4958               -- rtg_routing_type(rtg_index) := 1 ;
4959             rtg_routing_comment(rtg_index) := p_routing_details ;
4960             IF l_1237_count <> 0 OR l_1238_count <> 0 THEN -- Biogen start
4961             rtg_alt_routing_designator(rtg_index) := effectivity.recipe_no || delimiter || to_char(effectivity.recipe_version) || delimiter ||
4962                                                      effectivity.routing_no || delimiter || to_char(effectivity.routing_vers);
4963             ELSE
4964             rtg_alt_routing_designator(rtg_index) := p_x_aps_fmeff_id ; /* B2098058 */
4965             END IF;  -- Biogen end
4966               -- project_id :=  null_value ;
4967               -- task_id :=  null_value ;
4968               -- line_id :=  null_value ;
4969             /*B2870041*/
4970             rtg_uom_code(rtg_index) := formula_detail_tab(effectivity.product_index).aps_um ;
4971               -- cfm_routing_flag := null_value ;
4972               -- ctp_flag := null_value ;
4973             /*B2870041*/
4974             rtg_routing_quantity(rtg_index) := v_routing_qty ;
4975             rtg_assembly_item_id(rtg_index) := effectivity.aps_item_id ;
4976             rtg_organization_id(rtg_index) := effectivity.organization_id ;
4977 /* NAMIT_CR Calculate Step Quantities */
4978             rtg_auto_step_qty_flag(rtg_index) := effectivity.calculate_step_quantity ;
4979 
4980               -- deleted_flag  = 2 ;
4981             rtg_last_update_date(rtg_index) := current_date_time ;
4982             rtg_creation_date(rtg_index) := current_date_time ;
4983 
4984     return_status := TRUE;
4985   ELSE
4986     return_status := FALSE;
4987   END IF ;
4988 
4989 /* NAMIT_CR Write Step Dependency Data. */
4990   write_step_dependency(p_x_aps_fmeff_id);
4991 
4992   EXCEPTION
4993     WHEN OTHERS THEN
4994 	log_message('Error writing to msc_st_routings: '||sqlerrm);
4995 	return_status := FALSE;
4996 END write_routing;
4997 
4998 /*
4999 REM+=========================================================================+
5000 REM| PROCEDURE NAME                                                          |
5001 REM|    write_routing_operations                                             |
5002 REM|                                                                         |
5003 REM| TYPE                                                                    |
5004 REM|    Private                                                              |
5005 REM|                                                                         |
5006 REM| DESCRIPTION                                                             |
5007 REM|    This procedure writes operation/resource/activity details to the MSC |
5008 REM|    tables and also caters for alternate resources.                      |
5009 REM|                                                                         |
5010 REM| INPUT PARAMETERS                                                        |
5011 REM|    table_index: index of APS effectivity in aps_effectivities           |
5012 REM|                                                                         |
5013 REM| OUTPUT PARAMETERS                                                       |
5014 REM|    return_status  TRUE=> OK                                             |
5015 REM|                                                                         |
5016 REM| INPUT/OUTPUT PARAMETERS                                                 |
5017 REM|    None                                                                 |
5018 REM|                                                                         |
5019 REM| HISTORY                                                                 |
5020 REM|  07/14/2002   Rajesh Patangya - Reorgnized the complete code B2314052   |
5021 REM|  12/12/2002   Abhay Satpute   - Resource Load Changes Bug# 2710139      |
5022 REM|  01/22/2003   Rajesh Patangya - Resource Unit = resource_count B2761278 |
5023 REM|  05/23/2003   Sridhar Gidugu  - Populating Activity Group Id using      |
5024 REM|                                 Resource Id bug#2975261                 |
5025 REM+=========================================================================+
5026 */
5027 PROCEDURE write_routing_operations
5028 (
5029   p_x_aps_fmeff_id   IN PLS_INTEGER,
5030   return_status      OUT NOCOPY BOOLEAN
5031 )
5032 IS
5033 
5034   start_index          INTEGER;
5035   end_index            INTEGER;
5036   loop_index           INTEGER;
5037   k                    INTEGER ;
5038   alt_cnt              INTEGER ;
5039   previous_id          PLS_INTEGER     ;
5040   previous_activity    PLS_INTEGER ;
5041   seq_no               INTEGER ;
5042   statement_no         INTEGER ;
5043   v_counter            INTEGER ;
5044   alternates_inserted  VARCHAR2(1);
5045   v_alternate          PLS_INTEGER ;
5046   t_scale_type         PLS_INTEGER ;
5047 
5048   f_step_qty             NUMBER ;
5049   f_resource_usage       NUMBER ;
5050   f_activity_factor      NUMBER ;
5051   f_process_qty          NUMBER ;
5052   f_min_capacity         NUMBER ;
5053   f_max_capacity         NUMBER ;
5054 
5055   calculated_resource_usage NUMBER ;
5056 
5057   prod_scale_factor      NUMBER ; /*B2870041 contains factor to scale usage */
5058   l_prod_scale_factor    NUMBER ;
5059   temp_min_xfer_qty      NUMBER ; /*B2870041*/
5060 
5061    l_seq_dep_class     VARCHAR2(8);
5062    orig_rs_seq_num     NUMBER ;
5063    u_setup_id          NUMBER ;
5064 
5065    oprn_found 		BOOLEAN ;
5066 BEGIN
5067   k                    := 0;
5068   alt_cnt              := 0;
5069   previous_id          := 0;
5070   previous_activity    := -1;
5071   seq_no               := 1;
5072   statement_no         := 0;
5073   v_counter            := 0;
5074   alternates_inserted   := 'N';
5075   v_alternate          := 0;
5076   t_scale_type         := -1;
5077   f_step_qty             := 0;
5078   f_resource_usage       := 0;
5079   f_activity_factor      := 0;
5080   f_process_qty          := 0;
5081   f_min_capacity         := 0;
5082   f_max_capacity         := 999999;
5083   calculated_resource_usage := 0;
5084   prod_scale_factor      := 1;
5085   l_prod_scale_factor    := 1;
5086   temp_min_xfer_qty      := 0;
5087    orig_rs_seq_num      := 0;
5088    oprn_found 		:= FALSE ;
5089 
5090 
5091   statement_no := 0 ;
5092 
5093   start_index := rtg_org_hdr_tab(effectivity.rtg_hdr_location).orgn_start_loc ;
5094   end_index :=  rtg_org_hdr_tab(effectivity.rtg_hdr_location).orgn_end_loc ;
5095 
5096 --
5097   /*B2870041 If the product has fixed scaling the route will need to be scaled
5098      to match the total output not the product. If the product is linear
5099      then the route can be scaled in APS. The routing qty in the route header
5100      was modified to match the original routing qty. The product qty
5101       was scaled to match that value, thus the factor will always be 1 */
5102 
5103   statement_no := 10 ;
5104   /* B3145206, No matter what scale type it is, factor needs to be calculated */
5105     l_prod_scale_factor := formula_header_tab(g_fm_hdr_loc).total_output/
5106         effectivity.routing_qty;
5107   IF formula_detail_tab(effectivity.product_index).scale_type = 0 THEN
5108  	prod_scale_factor := l_prod_scale_factor ;
5109   ELSE
5110     	prod_scale_factor := 1;
5111   END IF;
5112 
5113   IF (start_index > 0) AND (end_index > 0) THEN
5114 
5115   FOR loop_index IN start_index..end_index
5116   LOOP
5117   /* Write only non Do Not Plan rows and rows in which usage UOM
5118   and GMP UOM for Hours profile have Time as base UOM class. */
5119   IF (rtg_org_dtl_tab(loop_index).include_rtg_row = 1) THEN
5120     t_scale_type  := rtg_org_dtl_tab(loop_index).rtg_scale_type ;
5121 
5122     -- Routing Step insertion
5123     IF rtg_org_dtl_tab(loop_index).routingstep_id <> previous_id THEN
5124 
5125 -- Note that this code differs from R12 code -
5126      IF  rtg_org_dtl_tab(loop_index).step_qty = 0 THEN
5127        temp_min_xfer_qty := 0 ;
5128      ELSE
5129     -- in R12 the code
5130     -- temp_min_xfer_qty :=  rtg_org_dtl_tab(loop_index).minimum_transfer_qty ;
5131      temp_min_xfer_qty := (effectivity.routing_qty *
5132        formula_detail_tab(effectivity.product_index).primary_qty *
5133        rtg_org_dtl_tab(loop_index).minimum_transfer_qty) /
5134        (formula_header_tab(g_fm_hdr_loc).total_output *
5135         rtg_org_dtl_tab(loop_index).step_qty);
5136      END IF;
5137 
5138      /*B2870041 the mtq quantity needs to be represented as a value based on the
5139         product not the step qty. Since a formula can have multiple products
5140         in different effectivities the calculation will use the relationhip
5141         of the mtq based on the step qty as applied to the product */
5142 
5143 
5144   statement_no := 20 ;
5145     -- Routing Step Bulk insert assignments
5146        opr_index := opr_index + 1 ;
5147        opr_operation_sequence_id(opr_index) :=
5148                                       rtg_org_dtl_tab(loop_index).x_routingstep_id ;
5149        opr_routing_sequence_id(opr_index) := p_x_aps_fmeff_id ;
5150        opr_operation_seq_num(opr_index) := rtg_org_dtl_tab(loop_index).routingstep_no ;
5151        opr_sr_instance_id(opr_index) := b_instance_id ;
5152        opr_operation_description(opr_index) := rtg_org_dtl_tab(loop_index).oprn_desc ;
5153        opr_effectivity_date(opr_index) := current_date_time ;
5154          -- disable_date,from_unit_number, to_unit_number, := null ;
5155          -- option_dependent_flag := 1,
5156          -- operation_type := null_value ;
5157        opr_mtransfer_quantity(opr_index) := temp_min_xfer_qty;   /*B2870041*/
5158 
5159        /* NAMIT_ASQC
5160        l_prod_scale_factor is Scale factor based on fm total output qty and rtg qty.
5161        (l_prod_scale_factor = formula_header_tab.total_output/effectivity.routing_qty)
5162        Also added the Step Qty UOM. Discrete UOM is obtained from Sy_UOM_Mst */
5163 --       opr_step_qty(opr_index) := l_prod_scale_factor * rtg_org_dtl_tab(loop_index).step_qty;
5164 
5165       /* Step Qty calculated In correctly */
5166        opr_step_qty(opr_index) := prod_scale_factor * rtg_org_dtl_tab(loop_index).step_qty;
5167 
5168        opr_step_qty_uom(opr_index) := rtg_org_dtl_tab(loop_index).process_qty_um;
5169          -- yield := null_value ; /*  B2365684 rtg_org_dtl_tab(loop_index).step_qty, */
5170 
5171        opr_department_id(opr_index) := (effectivity.organization_id * 2) + 1 ;
5172        opr_organization_id(opr_index) := effectivity.organization_id  ;
5173        opr_department_code(opr_index) := effectivity.whse_code ;
5174          --  operation_lead_time_percent,cumulative_yield, := null ;
5175          -- reverse_cumulative_yield,net_planning_percent, := null;
5176          -- setup_duration,tear_down_duration, := null ;
5177        /*B2870041*/
5178        opr_uom_code(opr_index) := formula_detail_tab(effectivity.product_index).aps_um ;
5179          -- standard_operation_code := null_value,
5180        opr_last_update_date(opr_index) := current_date_time ;
5181        opr_creation_date(opr_index) := current_date_time ;
5182 
5183      previous_id := rtg_org_dtl_tab(loop_index).routingstep_id;
5184      previous_activity := -1;
5185      seq_no := 0;
5186     END IF;   /* routing Step Insertion */
5187 
5188     --  Activity Insertion
5189   statement_no := 30 ;
5190     IF rtg_org_dtl_tab(loop_index).oprn_line_id <> previous_activity THEN
5191 
5192        seq_no := seq_no + 1;
5193 
5194      /*B2870041 modified the population of schedule_flag. The value of this will
5195         come from the plsql table and not hardcoded to 1. The value was set
5196         in the proceesing for the routing details */
5197 
5198      /* B2975261 - Populating activity group id using resource id */
5199 
5200      /* Operation resource seqs Bulk Insert assignments */
5201        rs_index := rs_index + 1 ;
5202        rs_operation_sequence_id(rs_index) := rtg_org_dtl_tab(loop_index).x_routingstep_id ;
5203 --       rs_resource_seq_num(rs_index) := seq_no ;
5204        /* B3596028 */
5205        rs_resource_seq_num(rs_index) := rtg_org_dtl_tab(loop_index).seq_dep_ind ;
5206        rs_sr_instance_id(rs_index)   := b_instance_id ;
5207        rs_department_id(rs_index)    := (effectivity.organization_id * 2) + 1 ;
5208          -- rs_resource_offset_percent := null_value ;
5209        /*B2870041 */
5210        rs_schedule_flag(rs_index)    := rtg_org_dtl_tab(loop_index).schedule_flag ;
5211        rs_routing_sequence_id(rs_index) := p_x_aps_fmeff_id ;
5212        rs_organization_id(rs_index)    := effectivity.organization_id ;
5213          -- deleted_flag := 2 ;
5214        rs_last_update_date(rs_index) := current_date_time ;
5215        rs_creation_date(rs_index) := current_date_time ;
5216        rs_activity_group_id(rs_index) := rtg_org_dtl_tab(loop_index).x_resource_id ;
5217 
5218       previous_activity := rtg_org_dtl_tab(loop_index).oprn_line_id;
5219 
5220     END IF;  /* End if for Activity Change */
5221 
5222     /*
5223     New Changes for Alternate Resources Begin : Bug# 1319610
5224     The following code depends on the ordering of prim_rsrc_ind, right
5225     now the Secondary Resources are Not considered, and the
5226     Primary_rsrc_indicator will have
5227               1 for Primary Resource
5228               2 for a Auxilary Resource.
5229               0 for a Secondary Resource.
5230               The Logic in brief goes like this :
5231               The Resources are inserted as usual and then a check is made
5232               to find if the resource is a Primary resource and if it has
5233               any alternates,
5234               the Alternate Resources are inserted. Then the groups secondaries
5235               are inserted.
5236      Insert the Resources : Bug# 1319610
5237      mfc 12-01-99 changed scale type to 0>2 1>1
5238      */
5239 
5240       f_step_qty  := 0;
5241       f_activity_factor    := 0 ;
5242       f_process_qty        := 0 ;
5243       f_resource_usage     := 0 ;
5244 /* NAMIT_OC */
5245       f_min_capacity       := 0 ;
5246       f_max_capacity       := 999999;
5247 
5248       -- Get process_qty,activity_factor override
5249       statement_no := 80 ;
5250       IF (rtg_org_dtl_tab(loop_index).o_step_qty  > 0) THEN
5251      /* B3145206, Note that the overriden qty is with respect to the total o/p
5252         and not with respect to just the product, let's have an example
5253         rtg_qty = 40 , step_qty = 40 , but when used
5254         in a formula having prod = 40 and by-prod = 40 , the recipe step_qty
5255         field will show 80 , if the user overrides it to be 40, then this new
5256         overriden qty 40 is wrt to total o/p of 80  */
5257 
5258          f_step_qty := rtg_org_dtl_tab(loop_index).o_step_qty / l_prod_scale_factor  ;
5259       ELSE
5260          f_step_qty := rtg_org_dtl_tab(loop_index).step_qty ;
5261       END IF;
5262 
5263       IF rtg_org_dtl_tab(loop_index).o_resource_usage > 0 THEN
5264          f_resource_usage := rtg_org_dtl_tab(loop_index).o_resource_usage ;
5265       ELSE
5266          f_resource_usage := rtg_org_dtl_tab(loop_index).resource_usage ;
5267       END IF ;
5268 
5269       IF (rtg_org_dtl_tab(loop_index).o_activity_factor > 0) THEN
5270          f_activity_factor := rtg_org_dtl_tab(loop_index).o_activity_factor;
5271       ELSE
5272          f_activity_factor := rtg_org_dtl_tab(loop_index).activity_factor;
5273       END IF ;
5274 
5275       IF (rtg_org_dtl_tab(loop_index).o_process_qty > 0) THEN
5276          f_process_qty := rtg_org_dtl_tab(loop_index).o_process_qty;
5277       ELSE
5278          f_process_qty := rtg_org_dtl_tab(loop_index).process_qty;
5279       END IF ;
5280 
5281 /* NAMIT_OC */
5282 
5283       IF (rtg_org_dtl_tab(loop_index).o_min_capacity > 0) THEN
5284          f_min_capacity := rtg_org_dtl_tab(loop_index).o_min_capacity ;
5285       ELSE
5286          f_min_capacity := rtg_org_dtl_tab(loop_index).min_capacity ;
5287       END IF ;
5288 
5289       IF (rtg_org_dtl_tab(loop_index).o_max_capacity > 0) THEN
5290          f_max_capacity := rtg_org_dtl_tab(loop_index).o_max_capacity ;
5291       ELSE
5292          f_max_capacity := rtg_org_dtl_tab(loop_index).max_capacity ;
5293       END IF ;
5294 
5295          --  SPECIAL !!! process_qty ZERO than take final step_qty */
5296          IF f_process_qty = 0 THEN
5297             f_process_qty := f_step_qty;
5298          END IF ;
5299 
5300   statement_no := 90 ;
5301 
5302   /* NAMIT_OC If the resource is scaled as fixed or By Charge, the resource
5303   usage will be treated as if it were fixed. If the scale type of the resource
5304   is "By Charge" then  the usage defined is that of the charge and will not need
5305   to be scaled in any way, except of course by the number of charges. */
5306 
5307       IF ((rtg_org_dtl_tab(loop_index).scale_type = 0) OR
5308           (rtg_org_dtl_tab(loop_index).scale_type = 2)) THEN
5309          -- fixed scaling
5310          calculated_resource_usage := ((f_resource_usage * f_activity_factor));
5311       ELSE
5312          /*B2870041 the scale factor was added to ensure the usages match
5313             what is represented by the product in the routing qty */
5314 
5315          calculated_resource_usage := ((f_step_qty / f_process_qty) *
5316            (f_resource_usage * f_activity_factor) * prod_scale_factor ) ;
5317       END IF; /* fixed scaling */
5318 
5319   statement_no := 100 ;
5320      /* Bulk insert assignments for operation_resources */
5321 	/* OR insert # 1 */
5322       orig_rs_seq_num := orig_rs_seq_num + 1;
5323       or_index := or_index + 1 ;
5324 
5325       or_operation_sequence_id(or_index) :=
5326                        rtg_org_dtl_tab(loop_index).x_routingstep_id ;
5327 --      or_resource_seq_num(or_index) := seq_no ; /* B3596028 */
5328       or_resource_seq_num(or_index) := rtg_org_dtl_tab(loop_index).seq_dep_ind ;
5329       or_resource_id(or_index) := rtg_org_dtl_tab(loop_index).x_resource_id ;
5330       or_alternate_number(or_index) := 0 ;
5331       /* For Primary Rsrc Principal flag = 1, for Aux and Sec Rsrcs Principal Flag = 2*/
5332       IF (rtg_org_dtl_tab(loop_index).prim_rsrc_ind = 1) THEN
5333          or_principal_flag(or_index) := rtg_org_dtl_tab(loop_index).prim_rsrc_ind ;
5334       ELSE
5335          or_principal_flag(or_index) := 2 ;
5336       END IF;
5337       or_basis_type(or_index) := t_scale_type ;
5338       or_resource_usage(or_index) := ( calculated_resource_usage
5339                    * rtg_org_dtl_tab(loop_index).resource_count ) ;
5340       or_max_resource_units(or_index) := rtg_org_dtl_tab(loop_index).resource_count ;
5341       or_resource_units(or_index) := rtg_org_dtl_tab(loop_index).resource_count ;
5342       or_uom_code(or_index) := rtg_org_dtl_tab(loop_index).aps_usage_um ;
5343       or_sr_instance_id(or_index) := b_instance_id ;
5344       or_routing_sequence_id(or_index) := p_x_aps_fmeff_id ;
5345       or_organization_id(or_index) := effectivity.organization_id ;
5346       or_minimum_capacity(or_index) := nvl(f_min_capacity,0) ;
5347       or_maximum_capacity(or_index) := nvl(f_max_capacity,9999999) ;
5348       or_last_update_date(or_index) := current_date_time ;
5349       or_creation_date(or_index) := current_date_time ;
5350       or_orig_rs_seq_num(or_index) := orig_rs_seq_num;
5351       or_break_ind(or_index) := rtg_org_dtl_tab(loop_index).break_ind;
5352 --
5353    statement_no := 110 ;
5354 -- ---------------------------------------------
5355      u_setup_id   := NULL ;
5356      or_setup_id(or_index) := null_value ;
5357      IF (rtg_org_dtl_tab(loop_index).is_sds_rout >= 1) THEN
5358        IF (rtg_org_dtl_tab(loop_index).is_unique = 1) THEN
5359            or_setup_id(or_index) := rtg_org_dtl_tab(loop_index).setup_id ;
5360        ELSE
5361           IF (rtg_org_dtl_tab(loop_index).is_nonunique = 1) THEN
5362            -- If the resource is not unique then it should get the setup_id of
5363            -- unique resource present anywhere in a route
5364              bsearch_unique(rtg_org_dtl_tab(loop_index).resource_id,
5365                             effectivity.category_id,
5366                             u_setup_id);
5367             or_setup_id(or_index) := u_setup_id ;
5368             rtg_org_dtl_tab(loop_index).setup_id := u_setup_id;
5369           ELSE
5370             -- It is niether unique nor nonunique
5371             or_setup_id(or_index)  := null_value;
5372             rtg_org_dtl_tab(loop_index).setup_id := null_value;
5373           END IF;
5374 
5375        END IF; /* is_unique */
5376 
5377      END IF; /* Is sds route */
5378 
5379      IF rtg_org_dtl_tab(loop_index).prim_rsrc_ind = 1 THEN
5380        -- This assignment will ensure that , alternate will use this setup
5381        rtg_org_dtl_tab(loop_index).setup_id := or_setup_id(or_index) ;
5382      END IF;
5383 
5384 -- ---------------------------------------------
5385        /*
5386         Now the check if the above resource inserted is a Primary. If it is
5387         Primary then find its Alternates if existing, and then insert its rows
5388         into msc_st_operation_resources table. Also keep track of number of
5389         times alternates are inserted. 1319610
5390        */
5391 
5392   statement_no := 120 ;
5393         IF rtg_org_dtl_tab(loop_index).prim_rsrc_ind = 1 THEN
5394 
5395           --  Reset the Counters and the Flags
5396            v_counter := 0;
5397            alternates_inserted := 'N';
5398            v_alternate  := 0;
5399            k  := 0;
5400 
5401         --  Open the Alternate resource Cursor, for the above Primary Resource
5402  	/* we shall have to put a new BSEARCH function if this looping become
5403 		a performance problem */
5404         alt_cnt := 1 ;
5405         FOR alt_cnt IN 1..alt_rsrc_size
5406         LOOP
5407 -- 	    Prod Spec alternates
5408 --	    IF ( rtg_alt_rsrc_tab(alt_cnt).prim_resource_id =
5409 --                      rtg_org_dtl_tab(loop_index).resource_id ) THEN
5410 	    IF ( rtg_alt_rsrc_tab(alt_cnt).prim_resource_id =
5411                       rtg_org_dtl_tab(loop_index).resource_id
5412 		AND (rtg_alt_rsrc_tab(alt_cnt).item_id = -1 OR
5413 		     rtg_alt_rsrc_tab(alt_cnt).item_id = effectivity.item_id)) THEN
5414              orig_rs_seq_num := orig_rs_seq_num + 1;
5415             /* B2353759, alternate runtime_factor considered */
5416                v_alternate := v_alternate + 1;
5417 
5418             /* Bulk insert assignments for operation_resources, Alternate resources */
5419 		/* OR insert # 2 */
5420              or_index := or_index + 1 ;
5421              or_operation_sequence_id(or_index) :=
5422                         rtg_org_dtl_tab(loop_index).x_routingstep_id ;
5423 --             or_resource_seq_num(or_index) := seq_no ;
5424              /* B3596028 */
5425              or_resource_seq_num(or_index) := rtg_org_dtl_tab(loop_index).seq_dep_ind ;
5426              or_resource_id(or_index) :=
5427                   ((rtg_alt_rsrc_tab(alt_cnt).alt_resource_id * 2) + 1) ;
5428 
5429 --	Prod spec alternates
5430       /* B5688153 Rajesh Patangya
5431       We are removing the preference logic for primary resource and will continue
5432       to use the old logic of numbering the primary resources in sequence as per the
5433       order by clause used by alternate resource cursor.
5434       */
5435              or_alternate_number(or_index) := v_alternate ;
5436 
5437              or_principal_flag(or_index) := 1;  /* Taking Principal flag as 1 for Alternates */
5438              or_basis_type(or_index) := t_scale_type ;
5439              or_resource_usage(or_index) := ( calculated_resource_usage
5440                           * rtg_org_dtl_tab(loop_index).resource_count
5441                           * rtg_alt_rsrc_tab(alt_cnt).runtime_factor ) ;
5442              or_max_resource_units(or_index) := rtg_org_dtl_tab(loop_index).resource_count ;
5443              /* B2761278 */
5444              or_resource_units(or_index) := rtg_org_dtl_tab(loop_index).resource_count ;
5445              or_uom_code(or_index) := rtg_org_dtl_tab(loop_index).aps_usage_um ;
5446                -- or_deleted_flag(or_index) := 2 ;
5447              or_sr_instance_id(or_index) := b_instance_id ;
5448              or_routing_sequence_id(or_index) := p_x_aps_fmeff_id ;
5449              or_organization_id(or_index) := effectivity.organization_id ;
5450              /* SGIDUGU added min capacity and max capacity inserts */
5451              or_minimum_capacity(or_index) :=
5452                        nvl(rtg_alt_rsrc_tab(alt_cnt).min_capacity,0) ;
5453              or_maximum_capacity(or_index) :=
5454                        nvl(rtg_alt_rsrc_tab(alt_cnt).max_capacity,999999) ;
5455 
5456              or_orig_rs_seq_num(or_index) := orig_rs_seq_num;
5457              or_break_ind(or_index) := rtg_org_dtl_tab(loop_index).break_ind;
5458 -- ----------------------------------------------------
5459                statement_no := 125 ;
5460                IF  rtg_org_dtl_tab(loop_index).setup_id IS NOT NULL THEN
5461                  or_setup_id(or_index) := rtg_org_dtl_tab(loop_index).setup_id ;
5462                ELSE
5463                  or_setup_id(or_index) := null_value ;
5464                END IF;
5465 
5466 -- ----------------------------------------------------
5467              or_last_update_date(or_index) := current_date_time ;
5468                -- or_last_updated_by(or_index) := 0 ;
5469              or_creation_date(or_index) := current_date_time ;
5470                -- or_created_by(or_index) := 0 ;
5471 
5472                /* Increment counter to check the number of times the
5473                   alternates are inserted */
5474 
5475                alternates_inserted := 'Y'; /* Inserted alternates */
5476 
5477 	    ELSIF ( rtg_alt_rsrc_tab(alt_cnt).prim_resource_id >
5478                       rtg_org_dtl_tab(loop_index).resource_id ) THEN
5479                EXIT ;
5480             ELSE
5481                NULL ;
5482             END IF;  /* End if for alternate resource and orgn code match */
5483 	END LOOP;  /* Alternate loop */
5484 
5485         END IF;  /* End if for Check in Primary Resource Indicator */
5486 
5487       /*
5488       Now check if the resource is a Auxilary resource and if the
5489       alternates are inserted, if both the conditions are satisfied,
5490       then loop thru the number of times the alternate resources are inserted
5491       and insert the Auxilary resources.
5492       This will take care of the combinations that has to come with the
5493       alternate resources. 1319610
5494       08/10/00 - Bug# 1388757 Changed != to <> as per the Standards
5495       */
5496 
5497   statement_no := 130 ;
5498      IF ( rtg_org_dtl_tab(loop_index).prim_rsrc_ind <> 1) AND
5499         (alternates_inserted = 'Y')
5500      THEN
5501          for k in 1 ..v_alternate
5502          LOOP
5503 
5504             /* Bulk insert assignments operation_resources, Alternate resources */
5505 		/* OR insert # 3 */
5506              or_index := or_index + 1 ;
5507 
5508              or_operation_sequence_id(or_index) := rtg_org_dtl_tab(loop_index).x_routingstep_id ;
5509 --             or_resource_seq_num(or_index) := seq_no ;
5510             /* B3596028 */
5511              or_resource_seq_num(or_index) := rtg_org_dtl_tab(loop_index).seq_dep_ind ;
5512              or_resource_id(or_index) := rtg_org_dtl_tab(loop_index).x_resource_id ;
5513              or_alternate_number(or_index) := k ;
5514             /* K will determine the no. of times altenates are used */
5515              or_principal_flag(or_index) := 2 ;
5516             /* Principal flag as 2 for Secondary Resources */
5517              or_basis_type(or_index) := t_scale_type ;
5518              or_resource_usage(or_index) := ( calculated_resource_usage
5519                     * rtg_org_dtl_tab(loop_index).resource_count ) ;
5520 
5521              or_max_resource_units(or_index) := rtg_org_dtl_tab(loop_index).resource_count ;
5522              /* B2761278 */
5523              or_resource_units(or_index) := rtg_org_dtl_tab(loop_index).resource_count ;
5524              or_uom_code(or_index) := rtg_org_dtl_tab(loop_index).aps_usage_um ;
5525                -- or_deleted_flag(or_index) := 2 ;
5526              or_sr_instance_id(or_index) := b_instance_id ;
5527              or_routing_sequence_id(or_index) := p_x_aps_fmeff_id ;
5528              or_organization_id(or_index) := effectivity.organization_id ;
5529              /* SGIDUGU - Added min capacity and max capacity inserts */
5530              or_minimum_capacity(or_index) := nvl(f_min_capacity,0) ;
5531              or_maximum_capacity(or_index) := nvl(f_max_capacity,9999999) ;
5532              or_break_ind(or_index) := rtg_org_dtl_tab(loop_index).break_ind;
5533              or_setup_id(or_index) := null_value ;
5534              or_last_update_date(or_index) := current_date_time ;
5535                -- or_last_updated_by(or_index) := 0 ;
5536              or_creation_date(or_index) := current_date_time ;
5537                -- or_created_by(or_index) := 0 ;
5538              or_orig_rs_seq_num(or_index) := orig_rs_seq_num;
5539 
5540          END LOOP; /* End loop of the v_counter */
5541      END IF;  /* End if condition for the secondary resource flag */
5542 
5543   END IF; /* End if condition for include rtg row check */
5544          -- To nullify the override effect for next recipe to use
5545          rtg_org_dtl_tab(loop_index).o_step_qty := -1 ;
5546          rtg_org_dtl_tab(loop_index).o_process_qty := -1 ;
5547          rtg_org_dtl_tab(loop_index).o_activity_factor := -1 ;
5548          rtg_org_dtl_tab(loop_index).o_resource_usage := -1 ;
5549          rtg_org_dtl_tab(loop_index).o_max_capacity   := -1 ;
5550          rtg_org_dtl_tab(loop_index).o_min_capacity   := -1 ;
5551 /*
5552      log_message (
5553      rtg_org_hdr_tab(effectivity.rtg_hdr_location).valid_flag || ' ***' ||
5554      rtg_org_dtl_tab(loop_index).routing_id ||'*'||
5555      effectivity.recipe_id ||'*'||
5556      rtg_org_dtl_tab(loop_index).routingstep_id         ||' Us '||
5557      rtg_org_dtl_tab(loop_index).resource_usage      ||' *'||
5558      rtg_org_dtl_tab(loop_index).o_resource_usage      ||' AF '||
5559      rtg_org_dtl_tab(loop_index).activity_factor      ||' *'||
5560      rtg_org_dtl_tab(loop_index).o_activity_factor      ||' SQ '||
5561      rtg_org_dtl_tab(loop_index).step_qty      ||' *'||
5562      rtg_org_dtl_tab(loop_index).o_step_qty     ||' PQ '||
5563      rtg_org_dtl_tab(loop_index).process_qty      ||' *'||
5564      rtg_org_dtl_tab(loop_index).o_process_qty      ||' M '||
5565      rtg_org_dtl_tab(loop_index).min_capacity   ||' *'||
5566      rtg_org_dtl_tab(loop_index).o_min_capacity   ||' X '||
5567      rtg_org_dtl_tab(loop_index).max_capacity   ||' *'||
5568      rtg_org_dtl_tab(loop_index).o_max_capacity);
5569 */
5570   END LOOP;  /* End loop of the Main */
5571   END IF ;  /* Positive counter value check */
5572 
5573   statement_no := 140 ;
5574   return_status := TRUE;
5575 
5576   EXCEPTION
5577   WHEN OTHERS THEN
5578 	log_message('Write routing operations failed at statement '
5579                      ||to_char(statement_no)||': '||sqlerrm);
5580 	return_status := FALSE;
5581 
5582 END write_routing_operations;
5583 
5584 /*
5585 REM+=========================================================================+
5586 REM| PROCEDURE NAME                                                          |
5587 REM|    write_operation_componenets                                          |
5588 REM|                                                                         |
5589 REM| TYPE                                                                    |
5590 REM|    Private                                                              |
5591 REM|                                                                         |
5592 REM| DESCRIPTION                                                             |
5593 REM|     Writes routing/material associations to the MSC tables              |
5594 REM|                                                                         |
5595 REM| INPUT PARAMETERS                                                        |
5596 REM|    table_index: index of APS effectivity in aps_effectivities           |
5597 REM|                                                                         |
5598 REM| OUTPUT PARAMETERS                                                       |
5599 REM|    return_status  TRUE=> OK                                             |
5600 REM|                                                                         |
5601 REM| INPUT/OUTPUT PARAMETERS                                                 |
5602 REM|    None                                                                 |
5603 REM|                                                                         |
5604 REM| HISTORY                                                                 |
5605 REM|  07/14/2002   Rajesh Patangya - Reorgnized the complete code B2314052   |
5606 REM+=========================================================================+
5607 */
5608 PROCEDURE write_operation_components
5609 (
5610   p_x_aps_fmeff_id   IN  PLS_INTEGER,
5611   precipe_id         IN  PLS_INTEGER,
5612   return_status      OUT NOCOPY BOOLEAN
5613 )
5614 IS
5615 
5616   st_mst_operation_components VARCHAR2(4000) ;
5617   i    INTEGER ;
5618   record_written BOOLEAN ;    /* B3562488 */
5619   already_done INTEGER ;          /* 3562488  */
5620   stmt_no NUMBER ;
5621   found_product                 BOOLEAN ;
5622   write_row                     BOOLEAN ;
5623 
5624 BEGIN
5625   st_mst_operation_components := NULL ;
5626   i    				:= 1;
5627   record_written 		:= FALSE ;
5628   already_done 		:= 0 ;
5629   stmt_no 		:= 0;
5630 
5631    found_product        := FALSE;
5632    write_row            := TRUE;
5633 
5634   -- write routing/material associations to msc_operation_components
5635 --         log_message('Enter --- > ' || g_mat_assoc
5636 --          || ' Effec ' || effectivity.formula_id
5637 --          || ' Material ' || mat_assoc_tab(g_mat_assoc).formula_id || ' Recipe ' || precipe_id ) ;
5638 
5639 stmt_no := 0;
5640    FOR i in g_mat_assoc..material_assocs_size
5641    LOOP
5642 
5643      IF  effectivity.formula_id > mat_assoc_tab(i).formula_id THEN
5644 --         log_message(i || ' --- ' ||
5645 --          effectivity.formula_id || ' > ' || mat_assoc_tab(i).formula_id ) ;
5646           NULL ;   /* Keep on looping */
5647 
5648      ELSIF effectivity.formula_id < mat_assoc_tab(i).formula_id THEN
5649             /* B3562488 */
5650             IF record_written = TRUE THEN
5651                g_mat_assoc := already_done ;
5652             END IF ;
5653 
5654 --           log_message('Exit ' || g_mat_assoc || ' ***'
5655 --             || effectivity.formula_id || ' < ' || mat_assoc_tab(i).formula_id ) ;
5656 
5657            EXIT;
5658      ELSIF effectivity.formula_id = mat_assoc_tab(i).formula_id THEN
5659             /* B3562488 */
5660         IF record_written = FALSE THEN
5661            already_done := i ;
5662            record_written := TRUE ;
5663 --         log_message('Written ' || already_done);
5664         END IF ;
5665 
5666 stmt_no := 10;
5667         IF mat_assoc_tab(i).recipe_id = precipe_id  THEN
5668 --       AND primary_bom_formulaline_id <> mat_assoc_tab(i).x_formulaline_id  THEN
5669 -- /* Bug # 4879588*/
5670 -- Backed this out as the new code already has a check for product_id
5671 
5672            /*  Do Not write material association
5673                       for the product line */
5674 
5675            IF mat_assoc_tab(i).item_id = effectivity.item_id THEN
5676 	      IF NOT (found_product )THEN
5677 	         found_product := TRUE ;
5678 		 write_row := FALSE ;
5679 	      ELSE
5680                  write_row := TRUE ;
5681               END IF ;
5682            ELSE
5683               write_row := TRUE ;
5684            END IF ;
5685 
5686            /*  operation components bulk insert */
5687            IF (write_row ) THEN
5688               oc_index := oc_index + 1 ;
5689 
5690               --Bug: 6030499 Vpedarla item substitution
5691                 IF mat_assoc_tab(i).x_formulaline_id IS NOT NULL THEN
5692                     oc_component_sequence_id(oc_index) := mat_assoc_tab(i).x_formulaline_id ;
5693                 ELSE
5694                     op_formline_cnt := op_formline_cnt + 1;
5695                     oc_component_sequence_id(oc_index) :=(( v_gmd_formula_lineid + op_formline_cnt ) * 2) + 1;
5696                 END IF;
5697                 --Bug: 6030499 Vpedarla end of item substitution
5698 
5699 
5700                 --Bug: 5979692 Vpedarla uncommented the below statement.
5701               oc_operation_sequence_id(oc_index) := mat_assoc_tab(i).x_routingstep_id ;
5702 
5703               oc_component_sequence_id(oc_index) := mat_assoc_tab(i).x_formulaline_id  ;
5704               oc_sr_instance_id(oc_index) := b_instance_id ;
5705               oc_bill_sequence_id(oc_index) := p_x_aps_fmeff_id  ;
5706               oc_routing_sequence_id(oc_index) := p_x_aps_fmeff_id ;
5707               oc_organization_id(oc_index) := effectivity.organization_id ;
5708               -- deleted_flag := 2,
5709               oc_last_update_date(oc_index) := current_date_time ;
5710               oc_creation_date(oc_index) := current_date_time ;
5711            END IF;
5712 
5713 stmt_no := 20;
5714 /* NAMIT_MTQ */
5715            IF ((mat_assoc_tab(i).min_trans_qty IS NOT NULL) OR
5716                    (mat_assoc_tab(i).min_delay IS NOT NULL)) THEN
5717 
5718               IF (mat_assoc_tab(i).min_trans_qty IS NULL) THEN
5719                  mat_assoc_tab(i).min_trans_qty := 0;
5720               END IF;
5721 
5722               mtq_index := mtq_index + 1;
5723 
5724    /* nsinghi B3970993 Start */
5725    /* If either the org, recipe, formula, rtg, step or item changes; re-initialize
5726    the globals. Write this MTQ row, and let the g_min_mtq be the mtq qty from this
5727    row. Also store the index of mtq row in global variable.
5728    The first MTQ row for a item belonging to a step is always written. If the same
5729    item is defined in the same step, then the row having minimum MTQ will be written. */
5730 
5731    /*
5732    1) If the MTQ is defined as null in one row, but min and/or max delay
5733    is defined for that row. Another row for the same item in same step, if MTQ is
5734    not null, but min and/or max delay are null, then which row to transfer. The code
5735    will transfer the row that has null MTQ.
5736    2) If MTQ is defined for same item multiple times in same step, and if all the
5737    MTQ values are equal, then the first row where MTQ is found will be sent. */
5738 
5739               IF g_old_recipe_id <> mat_assoc_tab(i).recipe_id OR
5740                  g_old_formula_id <> mat_assoc_tab(i).formula_id OR
5741                  g_old_rtg_id <> p_x_aps_fmeff_id OR
5742                  g_old_rtgstep_id <> mat_assoc_tab(i).x_routingstep_id OR
5743                  g_old_aps_item_id <> mat_assoc_tab(i).aps_item_id
5744               THEN
5745                  g_old_recipe_id := mat_assoc_tab(i).recipe_id;
5746                  g_old_formula_id := mat_assoc_tab(i).formula_id;
5747                  g_old_rtg_id := p_x_aps_fmeff_id;
5748                  g_old_rtgstep_id := mat_assoc_tab(i).x_routingstep_id;
5749                  g_old_aps_item_id := mat_assoc_tab(i).aps_item_id;
5750                  g_mtq_loc := mtq_index;
5751                  g_min_mtq := mat_assoc_tab(i).min_trans_qty;
5752 
5753                  itm_mtq_from_op_seq_id(mtq_index) :=  mat_assoc_tab(i).x_routingstep_id;
5754                  itm_mtq_routing_sequence_id(mtq_index) := p_x_aps_fmeff_id ;
5755                  itm_mtq_sr_instance_id(mtq_index) := b_instance_id ;
5756                  itm_mtq_from_item_id(mtq_index) := mat_assoc_tab(i).aps_item_id ;
5757                  itm_mtq_organization_id(mtq_index) := effectivity.organization_id ;
5758                  itm_mtq_min_tran_qty(mtq_index) := mat_assoc_tab(i).min_trans_qty * mat_assoc_tab(i).uom_conv_factor;
5759                  itm_mtq_min_time_offset(mtq_index) := mat_assoc_tab(i).min_delay;
5760                  itm_mtq_max_time_offset(mtq_index) := mat_assoc_tab(i).max_delay;
5761                  itm_mtq_frm_op_seq_num(mtq_index) := mat_assoc_tab(i).routingstep_no;
5762               END IF;
5763 
5764      /* If an item is yielded in the same step multiple times and if MTQ value is associated
5765       to that item multiple times, then write row that has min MTQ. */
5766 
5767               IF g_old_recipe_id = mat_assoc_tab(i).recipe_id AND
5768                  g_old_formula_id = mat_assoc_tab(i).formula_id AND
5769                  g_old_rtg_id = p_x_aps_fmeff_id AND
5770                  g_old_rtgstep_id = mat_assoc_tab(i).x_routingstep_id AND
5771                  g_old_aps_item_id = mat_assoc_tab(i).aps_item_id AND
5772                  g_mtq_loc <> mtq_index
5773               THEN
5774                  log_message('Item : '||mat_assoc_tab(i).item_id||' in recipe : '||mat_assoc_tab(i).recipe_id
5775                  ||' is associated multiple times in step '||mat_assoc_tab(i).routingstep_no
5776                  ||' with MTQ/Min/Max Delay defined. Row with Minimum/Null MTQ will be considered. ');
5777                  IF mat_assoc_tab(i).min_trans_qty < g_min_mtq THEN
5778                     itm_mtq_from_op_seq_id(g_mtq_loc) :=  mat_assoc_tab(i).x_routingstep_id;
5779                     itm_mtq_routing_sequence_id(g_mtq_loc) := p_x_aps_fmeff_id ;
5780                     itm_mtq_sr_instance_id(g_mtq_loc) := b_instance_id ;
5781                     itm_mtq_from_item_id(g_mtq_loc) := mat_assoc_tab(i).aps_item_id ;
5782                     itm_mtq_organization_id(g_mtq_loc) := effectivity.organization_id ;
5783                     itm_mtq_min_tran_qty(g_mtq_loc) := mat_assoc_tab(i).min_trans_qty * mat_assoc_tab(i).uom_conv_factor;
5784                     itm_mtq_min_time_offset(g_mtq_loc) := mat_assoc_tab(i).min_delay;
5785                     itm_mtq_max_time_offset(g_mtq_loc) := mat_assoc_tab(i).max_delay;
5786                     itm_mtq_frm_op_seq_num(g_mtq_loc) := mat_assoc_tab(i).routingstep_no;
5787                  END IF;
5788                  mtq_index := mtq_index - 1;
5789               END IF;
5790         /* nsinghi B3970993 End */
5791 
5792            END IF;
5793 stmt_no := 30;
5794 
5795 --       log_message(i || ' - RCP - ' || p_x_aps_fmeff_id || ' ** ' || mat_assoc_tab(i).recipe_id ) ;
5796 
5797         END IF ;   /* Recipe check */
5798 
5799      END IF ;   /* formula check */
5800    END LOOP ;
5801 
5802   return_status := TRUE;
5803 
5804   EXCEPTION
5805   WHEN OTHERS THEN
5806 	log_message('Error writing operation components: '||stmt_no||' :'||sqlerrm);
5807 	return_status := FALSE;
5808 END write_operation_components;
5809 /*
5810 REM+=========================================================================+
5811 REM| PROCEDURE NAME                                                          |
5812 REM|    export_effectivities                                                 |
5813 REM|                                                                         |
5814 REM| TYPE                                                                    |
5815 REM|    Private                                                              |
5816 REM|                                                                         |
5817 REM| DESCRIPTION                                                             |
5818 REM|    This procedure is called after all of the effectivities have been    |
5819 REM|    validated and extracted. It exports the data gathered to APS using   |
5820 REM|    the defined table mappings.                                          |
5821 REM|                                                                         |
5822 REM| INPUT PARAMETERS                                                        |
5823 REM|    None                                                                 |
5824 REM|                                                                         |
5825 REM| OUTPUT PARAMETERS                                                       |
5826 REM|    return_status    TRUE => OK                                          |
5827 REM|                                                                         |
5828 REM| INPUT/OUTPUT PARAMETERS                                                 |
5829 REM|    None                                                                 |
5830 REM|                                                                         |
5831 REM| HISTORY                                                                 |
5832 REM|  07/14/2002   Rajesh Patangya - Reorgnized the complete code B2314052   |
5833 REM|  06/02/2003   Sridhar Gidugu  - Added code to check aps fm eff          |
5834 REM|                                 B2989806                                |
5835 REM+=========================================================================+
5836 */
5837 PROCEDURE export_effectivities
5838 (
5839   return_status            OUT NOCOPY BOOLEAN
5840 )
5841 IS
5842   p_status       BOOLEAN;
5843   b_status       BOOLEAN;
5844   r_status       BOOLEAN;
5845   ro_status      BOOLEAN;
5846   oc_status      BOOLEAN;
5847   lv_msc_schema varchar2(10); -- Biogen
5848 
5849   cursor c_vcp_release(p_owner varchar2, p_column_name varchar2) is
5850   select count(*)
5851   from all_tab_columns
5852   where owner = p_owner
5853   and table_name = 'MSC_PLANS'
5854   and column_name = p_column_name;
5855 
5856 BEGIN
5857 
5858         /* Finally generate the effectivity_id */
5859 
5860         /* B2989806
5861            If aps_fmeff_id from gmp_form_eff was null,
5862            then create a new one.  Otherwise, use original.
5863         */
5864 
5865         /*
5866           g_aps_eff_id := g_aps_eff_id + 1 ;
5867           aps_fmeff_id := g_aps_eff_id ;
5868           x_aps_fmeff_id := (aps_fmeff_id * 2 ) + 1 ;
5869           B2989806
5870         */
5871 
5872         IF effectivity.aps_fmeff_id = -1 THEN
5873          g_aps_eff_id := g_aps_eff_id + 1 ;
5874          aps_fmeff_id := g_aps_eff_id ;
5875         ELSE
5876          aps_fmeff_id := effectivity.aps_fmeff_id ;
5877         END IF ;
5878 
5879         x_aps_fmeff_id := (aps_fmeff_id * 2 ) + 1 ;
5880      begin  -- Biogen start
5881       begin
5882         select application_short_name
5883         into   lv_msc_schema
5884         from   fnd_application
5885         where  application_id = 724;
5886       exception
5887         When No_Data_Found Then
5888             log_message('MSC Application short name not found: '||sqlerrm);
5889       end;
5890   --use this code to find out if vcp release is 12.1.3.7 or greater
5891   open c_vcp_release(lv_msc_schema, 'ENFORCE_WRH_CPTY');
5892   fetch c_vcp_release into l_1237_count;
5893   close c_vcp_release;
5894   --use this code to find out if vcp release is 12.1.3.8 or greater
5895   open c_vcp_release(lv_msc_schema, 'DAILY_MWO_AGGR_LVL');
5896   fetch c_vcp_release into l_1238_count;
5897   close c_vcp_release;
5898 
5899   end ;  -- Biogen end
5900 
5901 
5902     /* B3837959 MMK Issue, Handling of return status */
5903     write_process_effectivity(x_aps_fmeff_id, aps_fmeff_id, p_status);
5904     return_status := p_status ;
5905 
5906     IF return_status = TRUE THEN
5907       write_bom_components(x_aps_fmeff_id, b_status);
5908       return_status := b_status ;
5909 
5910       IF (effectivity.routing_id IS NOT NULL) AND (b_status = TRUE) THEN
5911         write_routing(x_aps_fmeff_id, r_status);
5912         return_status := r_status ;
5913 
5914         IF return_status = TRUE THEN
5915           write_routing_operations(x_aps_fmeff_id,ro_status);
5916           return_status := ro_status ;
5917 
5918           IF return_status = TRUE THEN
5919              write_operation_components(x_aps_fmeff_id,
5920                                         effectivity.recipe_id,
5921                                         oc_status);
5922              return_status := oc_status ;
5923              IF return_status = FALSE THEN
5924                log_message('write_operation_components Returned FALSE');
5925              END IF;
5926           ELSE
5927             log_message('write_routing_operations Returned FALSE');
5928             return_status := FALSE;
5929           END IF;
5930         ELSE
5931           log_message('write_routing Returned FALSE');
5932           return_status := FALSE;
5933         END IF;
5934       ELSE
5935           IF return_status = FALSE THEN
5936             log_message('write_bom_components Returned FALSE');
5937           END IF;
5938       END IF;
5939     ELSE
5940       log_message('write_process_effectivity Returned FALSE');
5941       return_status := FALSE;
5942     END IF;
5943 
5944   EXCEPTION
5945     WHEN OTHERS THEN
5946        log_message('Export Effectivities Raised Exception: '||sqlerrm);
5947        log_message(to_char(effectivity.fmeff_id));
5948        return_status := FALSE;
5949 END export_effectivities;
5950 
5951 /*
5952 REM+=========================================================================+
5953 REM+                                                                         +
5954 REM+                         PUBLIC PROCEDURES                               +
5955 REM+                                                                         +
5956 REM+=========================================================================+
5957 
5958 REM+=========================================================================+
5959 REM| PROCEDURE NAME                                                          |
5960 REM|    extract_effectivities                                                |
5961 REM|                                                                         |
5962 REM| TYPE                                                                    |
5963 REM|    Public                                                               |
5964 REM|                                                                         |
5965 REM| USAGE                                                                   |
5966 REM|    This is the 'main' procedure for extracting effectivities and then   |
5967 REM|    exploding the ones which are valid for export to APS                 |
5968 REM|                                                                         |
5969 REM| DESCRIPTION                                                             |
5970 REM|                                                                         |
5971 REM|                                                                         |
5972 REM| INPUT PARAMETERS                                                        |
5973 REM|    None                                                                 |
5974 REM|                                                                         |
5975 REM| OUTPUT PARAMETERS                                                       |
5976 REM|    return_status                                                        |
5977 REM|                                                                         |
5978 REM| INPUT/OUTPUT PARAMETERS                                                 |
5979 REM|    None                                                                 |
5980 REM|                                                                         |
5981 REM| HISTORY                                                                 |
5982 REM|  07/14/2002   Rajesh Patangya - Reorgnized the complete code B2314052   |
5983 REM| 04/21/2004   - Navin Sinha - B3577871 -ST:OSFME2: collections failing   |
5984 REM|                               in planning data pull.                    |
5985 REM|                               Added handling of NO_DATA_FOUND Exception.|
5986 REM|                               And return the return_status as TRUE.     |
5987 REM+=========================================================================+
5988 */
5989 PROCEDURE extract_effectivities
5990 (
5991   at_apps_link     IN VARCHAR2,
5992   delimiter_char   IN VARCHAR2,
5993   instance         IN INTEGER,
5994   run_date         IN DATE,
5995   return_status    IN OUT NOCOPY BOOLEAN
5996 )
5997 IS
5998   valid            BOOLEAN;
5999   setup_failure    EXCEPTION;
6000   extract_failure  EXCEPTION;
6001   export_failure   EXCEPTION;
6002 
6003   retrieval_cursor        VARCHAR2(32700) ;
6004 BEGIN
6005 g_aps_eff_id              := 0; /* Global Aps Effectivity ID */
6006 aps_fmeff_id              := 0 ;/* Generated effectivity Id */
6007 x_aps_fmeff_id            := 0 ;/* encoded effectivity Id */
6008 retrieval_cursor          := NULL ;
6009 
6010   IF return_status THEN
6011     v_cp_enabled := TRUE;
6012   ELSE
6013     v_cp_enabled := FALSE;
6014   END IF;
6015 
6016   collect_ps_data := TRUE;
6017 
6018   /* B2104059 GMP-APS ENHANCEMENT FOR GMD FORMULA SECURITY FUNCTIONALITY  */
6019   /* Disable the security  */
6020 
6021     retrieval_cursor := ' begin gmd_p_fs_context.set_additional_attr'
6022                         || at_apps_link || ';end;'   ;
6023     EXECUTE IMMEDIATE retrieval_cursor ;
6024 
6025   /* Before we do anything we need to create/setup/size a few things */
6026 
6027   g_instance_id := instance ;
6028 
6029   setup(at_apps_link, delimiter_char, instance, run_date, valid);
6030 
6031   IF NOT valid THEN
6032     RAISE setup_failure;
6033   END IF;
6034 
6035   /* If all is OK, extract the effectivities to PL/SQL tables */
6036   retrieve_effectivities(valid);
6037 
6038   IF NOT valid THEN
6039     RAISE extract_failure;
6040   END IF;
6041 
6042   return_status := TRUE;
6043 
6044   EXCEPTION
6045 	WHEN setup_failure THEN
6046 	    /* Initial setup failed */
6047 		log_message('Effectivity extract setup failure');
6048 		return_status := FALSE;
6049 
6050 	WHEN extract_failure THEN
6051 	    /* Effectivity extraction failed */
6052 		log_message('Effectivity extraction failed');
6053 		return_status := FALSE;
6054 
6055 	WHEN export_failure THEN
6056 	    /* Effectivity export failed */
6057 		log_message('Effectivity export failed');
6058 		return_status := FALSE;
6059 
6060         WHEN NO_DATA_FOUND THEN  /* B3577871 */
6061                 log_message(' NO_DATA_FOUND exception raised in Procedure: MSC_CL_GMP_UTILITY.Extract_effectivities ' );
6062                 return_status := TRUE;
6063 	WHEN OTHERS THEN
6064 		log_message('Untrapped effectivity extraction error');
6065 		log_message(sqlerrm);
6066         return_status := FALSE;
6067 
6068 END extract_effectivities;
6069 
6070 /*
6071 REM+=========================================================================+
6072 REM| PROCEDURE NAME                                                          |
6073 REM|    Extract_Items                                                        |
6074 REM|                                                                         |
6075 REM| TYPE                                                                    |
6076 REM|    Public                                                               |
6077 REM|                                                                         |
6078 REM| USAGE                                                                   |
6079 REM|                                                                         |
6080 REM|                                                                         |
6081 REM| DESCRIPTION                                                             |
6082 REM|    This procedure refreshes the gmp_items_aps table with all items for  |
6083 REM|    which planning is required. An item is deemed to fall within the     |
6084 REM|    scope of planning if it occurs in the plant/warehouse effectivity    |
6085 REM|    (ps_whse_eff). If a row in ps_whse_eff has a blank item_id this      |
6086 REM|    indicates all items, and this means that we must generate rows in    |
6087 REM|    gmp_item_aps for all items using the plant/warehouse combination     |
6088 REM|    just read.                                                           |
6089 REM|                                                                         |
6090 REM|                                                                         |
6091 REM| INPUT PARAMETERS                                                        |
6092 REM|    opm_link   VARCHAR2 database link to opm_instance                    |
6093 REM|    aps_link   VARCHAR2 database link to aps_instance                    |
6094 REM|                                                                         |
6095 REM|    Either or both of these parameters may be NULL or they may both be   |
6096 REM|    be set up, depending on requirements and which server(s) are         |
6097 REM|    present.                                                             |
6098 REM|                                                                         |
6099 REM| OUTPUT PARAMETERS                                                       |
6100 REM|    return_status    BOOLEAN: TRUE=> OK                                  |
6101 REM|                                                                         |
6102 REM| INPUT/OUTPUT PARAMETERS                                                 |
6103 REM|    None                                                                 |
6104 REM|                                                                         |
6105 REM| HISTORY                                                                 |
6106 REM|    Created 8th July 1999 by P.J.Schofield (OPM Development Oracle UK)   |
6107 REM|                                                                         |
6108 REM|    15th July 1999 P.J.Schofield                                         |
6109 REM|    Include inventory_item_id from mtl_system_items and uom_code from    |
6110 REM|    mtl_units_of_measure                                                 |
6111 REM|    04/03/2000 - Using mtl_organization_id from ic_item_mst instead of   |
6112 REM|               - organization_id from sy_orgn_mst table. Bug# 1252322    |
6113 REM|    12/14/00   - B1540127 By Rajesh Patangya                             |
6114 REM|                 join change for unit_of_measure field in sy_uoms_mst    |
6115 REM| 04/21/2004   - Navin Sinha - B3577871 -ST:OSFME2: collections failing   |
6116 REM|                               in planning data pull.                    |
6117 REM|                               Added handling of NO_DATA_FOUND Exception.|
6118 REM|                               And return the return_status as TRUE.     |
6119 REM|                                                                         |
6120 REM+=========================================================================+
6121 */
6122 PROCEDURE extract_items
6123 (
6124   at_apps_link  IN VARCHAR2,
6125   instance      IN INTEGER,
6126   run_date      IN DATE,
6127   return_status IN OUT NOCOPY BOOLEAN
6128 )
6129 IS
6130   c_item_cursor           ref_cursor_typ;
6131 
6132   retrieval_cursor        VARCHAR2(32700);
6133   insert_statement        VARCHAR2(32700);
6134 
6135   TYPE gmp_item_aps_typ  IS RECORD (
6136     item_no               VARCHAR2(32),
6137     item_id               NUMBER,        /* Bug 11779842 */
6138     category_id           NUMBER,        /* SGIDUGU  Bug 5882984 */
6139     seq_dpnd_class        VARCHAR2(8),   /* SGIDUGU  Bug 5882984 */
6140     item_um               VARCHAR2(4),
6141     uom_code              VARCHAR2(3),
6142     lot_control           PLS_INTEGER,
6143     item_desc1            VARCHAR2(70),
6144     aps_item_id           PLS_INTEGER,
6145     organization_id       PLS_INTEGER,
6146     whse_code             VARCHAR2(4),
6147     replen_ind            PLS_INTEGER,
6148     consum_ind            PLS_INTEGER,
6149     plant_code            VARCHAR2(4),
6150     creation_date         DATE,
6151     created_by            PLS_INTEGER,
6152     last_update_date      DATE,
6153     last_updated_by       PLS_INTEGER,
6154     last_update_login     PLS_INTEGER,
6155     experimental_ind      PLS_INTEGER);   /* Bug # 5238790 */
6156 
6157   gmp_item_aps_rec        gmp_item_aps_typ;
6158   v_dummy                 NUMBER ; /* B8401372 */
6159   org_str VARCHAR2(32700) ;
6160   in_position number;
6161 
6162 
6163   continue_flag boolean  ;
6164   temp_str varchar2(32700);
6165   final_str varchar2(32700);
6166   i number;
6167   j number;
6168   pos number;
6169 
6170 BEGIN
6171   i                       := 0;
6172   v_dummy                 := 0;
6173   pos                     := 1;
6174   j                       := 10; -- break into 10 orgs
6175 
6176  /* Bug: 6030499 Vpedarla added profile verification */
6177   collect_ps_data := TRUE;
6178 
6179   IF return_status THEN
6180     v_cp_enabled := TRUE;
6181   ELSE
6182     v_cp_enabled := FALSE;
6183   END IF;
6184 
6185    /* populate the org_string */
6186      IF MSC_CL_GMP_UTILITY.org_string(instance) THEN
6187         NULL ;
6188      ELSE
6189         RAISE invalid_string_value  ;
6190      END IF;
6191 
6192      l_in_str_org := MSC_CL_GMP_UTILITY.g_in_str_org ;    /* 3491625 */
6193      log_message('Extract_items : l_in_str_org   =  '||l_in_str_org );
6194 
6195      org_str := l_in_str_org ;
6196 
6197          in_position := instr(org_str,'(' );
6198          org_str := replace( substr(org_str,(in_position+1)), ')','') ;
6199 
6200          IF in_position > 0 THEN
6201                 gmp_calendar_pkg.g_in_str_org  := org_str ;
6202                 continue_flag := TRUE;
6203          ELSE
6204                 gmp_calendar_pkg.g_in_str_org := NULL ;
6205                 continue_flag := FALSE;
6206          END IF;
6207 
6208   retrieval_cursor := 'DELETE FROM gmp_item_aps'||at_apps_link;
6209   EXECUTE IMMEDIATE retrieval_cursor;
6210   COMMIT;
6211 
6212 /*   New Changes - Using mtl_organization_id from ic_whse_mst , instead of organization_id
6213                    from sy_orgn_mst , Bug# 1252322
6214 */
6215 
6216   WHILE continue_flag LOOP
6217     temp_str := instr(org_str, ',', pos, j);
6218     IF instr(org_str, ',', pos, j) = 0 then
6219       final_str := replace(substr(org_str, pos),' ','');
6220     ELSE
6221       final_str := replace(substr(org_str, pos,(temp_str - pos)),' ','');
6222 
6223     END IF;
6224    final_str := 'IN (' || final_str || ')';
6225    l_in_str_org := final_str ;
6226    LOG_MESSAGE('Extract_items : final_str : ' || final_str );
6227 
6228   /* SGIDUGU - code added for Seq Dep Bug 5882984 */
6229   retrieval_cursor :=
6230       'INSERT INTO gmp_item_aps'||at_apps_link||' '
6231                 ||' ( '
6232                 ||'  item_no, '
6233                 ||'  item_id,category_id, '
6234                 ||'  seq_dpnd_class, '
6235                 ||'  item_um, uom_code, '
6236                 ||'  lot_control, item_desc1, '
6237                 ||'  aps_item_id, organization_id, '
6238                 ||'  whse_code, replen_ind,'
6239                 ||'  consum_ind, '
6240                 ||'  plant_code, creation_date, created_by, '
6241                 ||'  last_update_date, last_updated_by, last_update_login, '
6242                 ||'  experimental_ind '  /* Bug # 5238790 */
6243                 ||' ) '
6244                 ||' SELECT '
6245                 ||' /*+ DRIVING_SITE(iim) DRIVING_SITE(sou) DRIVING_SITE(pwe) '
6246                 ||' DRIVING_SITE(iwm) DRIVING_SITE(msi)'
6247                 ||' DRIVING_SITE(mum) DRIVING_SITE(som) */   '
6248                 ||'  iim.item_no, '
6249                 ||'  iim.item_id,nvl(iim.seq_category_id,-1), '
6250                 ||'  iim.seq_dpnd_class , '
6251                 ||'  iim.item_um, mum.uom_code, '
6252                 ||'  iim.lot_ctl, substr(iim.item_desc1,1,69) item_desc1, '
6253                 ||'  msi.inventory_item_id, iwm.mtl_organization_id, '
6254                 ||'  pwe.whse_code, decode(sum(pwe.replen_ind), 0, 0, 1), '
6255                 ||'  decode(sum(pwe.consum_ind), 0, 0, 1), '
6256                 ||'  pwe.plant_code, :r_dt1, iim.created_by, '
6257                 ||'  :r_dt2,iim.last_updated_by, 0, '
6258                 ||'  NVL(iim.experimental_ind,0) ' /* Bug # 5238790 */
6259                 ||'  FROM  ic_item_mst'||at_apps_link||' iim,'
6260              	||'  sy_uoms_mst'||at_apps_link||' sou,'   /* B1540127 */
6261              	||'  ps_whse_eff'||at_apps_link||' pwe,'
6262              	||'  ic_whse_mst'||at_apps_link||' iwm,'
6263              	||'  mtl_system_items'||at_apps_link||' msi,'
6264              	||'  mtl_units_of_measure'||at_apps_link||' mum, '
6265                 ||'  sy_orgn_mst'||at_apps_link||' som '
6266              	||'  WHERE iim.delete_mark = 0 '
6267              	||'    AND som.delete_mark = 0 '
6268              	||'    AND iim.inactive_ind = 0 '
6269              	||'    AND iim.item_no = msi.segment1 '
6270              	||'    AND iwm.mtl_organization_id = msi.organization_id '
6271                 ||'    AND pwe.plant_code = som.orgn_code '
6272              	||'    AND pwe.whse_code = iwm.whse_code '
6273              	||'    AND sou.unit_of_measure = mum.unit_of_measure '
6274                 ||'    AND sou.delete_mark = 0 ' ;
6275              IF l_in_str_org  IS NOT NULL THEN     /* B3491625 */
6276                 retrieval_cursor := retrieval_cursor
6277                 ||'    AND iwm.mtl_organization_id ' || l_in_str_org ;
6278              END IF;
6279                 retrieval_cursor := retrieval_cursor
6280              	||'    AND iim.item_um = sou.um_code '
6281              	/*||'    AND iim.experimental_ind = 0 '*//* Bug # 5238790 */
6282              	||'    AND ( '
6283              	||'          pwe.whse_item_id IS NULL OR '
6284              	||'          pwe.whse_item_id = iim.whse_item_id OR '
6285              	||'          ( '
6286              	||'            pwe.whse_item_id = iim.item_id AND '
6287              	||'            iim.item_id <> iim.whse_item_id '
6288              	||'          ) '
6289                 ||'        ) '
6290              	||' GROUP BY '
6291              	||'   iim.item_id, iim.item_no,iim.seq_category_id, '
6292                 ||'   iim.seq_dpnd_class, '
6293                 ||'   iim.item_desc1, iim.item_um, '
6294                 ||'   iim.lot_ctl, pwe.whse_code, '
6295 		||'   pwe.plant_code, mum.uom_code, msi.inventory_item_id, '
6296                 ||'   iwm.mtl_organization_id, '
6297 		||'   :r_dt3, iim.created_by, :r_dt4, '
6298                 ||'   iim.last_updated_by, 0, '
6299                 ||'   iim.experimental_ind ' ;
6300 
6301 
6302    log_message('Extract_items : Retrieval Cursor  =  '||retrieval_cursor);
6303    EXECUTE IMMEDIATE retrieval_cursor USING
6304    run_date, run_date, run_date, run_date;
6305    COMMIT;
6306 
6307   EXIT WHEN instr(org_str, ',', pos, j) = 0;
6308    pos := temp_str+1;
6309   END LOOP;
6310 
6311  /*   IF gmp_item_aps_rec.item_id IN (755, 7826) THEN
6312     LOG_MESSAGE('Extract_items : itm_no : ' || gmp_item_aps_rec.item_no );
6313     LOG_MESSAGE('Extract_items : item_um : ' || gmp_item_aps_rec.item_um);
6314     LOG_MESSAGE('Extract_items : uom_code : ' || gmp_item_aps_rec.uom_code);
6315     LOG_MESSAGE('Extract_items : item_desc1: ' || gmp_item_aps_rec.item_desc1);
6316     LOG_MESSAGE('Extract_items : organization_id: ' || gmp_item_aps_rec.organization_id);
6317     end if;
6318  */
6319 
6320           SELECT st.VALUE INTO v_dummy from V$MYSTAT st, V$STATNAME sn
6321           where st.STATISTIC# = sn.STATISTIC#
6322           and sn.NAME in ('session pga memory');
6323           log_message('After Item Cursor Session pga memory = ' || TO_CHAR(v_dummy) );
6324 
6325   return_status := TRUE;
6326 
6327   EXCEPTION
6328     WHEN invalid_string_value  THEN
6329       log_message('Organization string is Invalid ' );
6330       return_status := FALSE;
6331     WHEN NO_DATA_FOUND THEN /* B3577871 */
6332       log_message(' NO_DATA_FOUND exception raised in Procedure: Extract_Items ' );
6333       return_status := TRUE;
6334     WHEN OTHERS THEN
6335       log_message('Item extraction failed with error '||sqlerrm);
6336       return_status := FALSE;
6337 
6338 END Extract_Items;
6339 
6340 /*
6341 REM+=========================================================================+
6342 REM| PROCEDURE NAME                                                          |
6343 REM|    extract_sub_inventory                                                |
6344 REM|                                                                         |
6345 REM| TYPE                                                                    |
6346 REM|    Public                                                               |
6347 REM|                                                                         |
6348 REM| USAGE                                                                   |
6349 REM|                                                                         |
6350 REM|                                                                         |
6351 REM| DESCRIPTION                                                             |
6352 REM|    This procedure creates sub-inventories for each eligible OPM         |
6353 REM|    warehouse and writes them to the msc_sub_inventories table.          |
6354 REM|                                                                         |
6355 REM| INPUT PARAMETERS                                                        |
6356 REM|    opm_link   VARCHAR2 database link to opm_instance                    |
6357 REM|    aps_link   VARCHAR2 database link to aps_instance                    |
6358 REM|                                                                         |
6359 REM|    Either or both of these parameters may be NULL or they may both be   |
6360 REM|    be set up, depending on requirements and which server(s) are         |
6361 REM|    present.                                                             |
6362 REM|                                                                         |
6363 REM| OUTPUT PARAMETERS                                                       |
6364 REM|    return_status    BOOLEAN: TRUE=> OK                                  |
6365 REM|                                                                         |
6366 REM| INPUT/OUTPUT PARAMETERS                                                 |
6367 REM|    None                                                                 |
6368 REM|                                                                         |
6369 REM| HISTORY                                                                 |
6370 REM|    Created 12th August 1999 by P.J.Schofield (OPM Development UK)       |
6371 REM|    10/13/99 - Added deleted_flag in the insert statement                |
6372 REM| 04/21/2004  - Navin Sinha - B3577871 -ST:OSFME2: collections failing    |
6373 REM|                               in planning data pull.                    |
6374 REM|                               Return return_status as TRUE in case      |
6375 REM|                               no_warehouses Exception is raised.        |
6376 REM|                                                                         |
6377 REM+=========================================================================+
6378 */
6379 PROCEDURE extract_sub_inventory
6380 (
6381   at_apps_link  IN VARCHAR2,
6382   instance      IN INTEGER,
6383   run_date      IN DATE,
6384   return_status IN OUT NOCOPY BOOLEAN
6385 )
6386 IS
6387   c_whse_cursor           ref_cursor_typ;
6388 
6389   retrieval_cursor        VARCHAR2(32700);
6390 
6391   whse_code           VARCHAR2(4);
6392   organization_id     NUMBER;
6393   valid               BOOLEAN;
6394 
6395   no_warehouses       EXCEPTION;
6396   setup_failure       EXCEPTION;
6397 BEGIN
6398 
6399 /* Bug: 6030499 Vpedarla added profile verification */
6400    collect_ps_data := TRUE;
6401 
6402 
6403   IF return_status THEN
6404     v_cp_enabled := TRUE;
6405   ELSE
6406     v_cp_enabled := FALSE;
6407   END IF;
6408 
6409    /* populate the org_string */
6410      IF MSC_CL_GMP_UTILITY.org_string(instance) THEN
6411         NULL ;
6412      ELSE
6413         RAISE invalid_string_value  ;
6414      END IF;
6415 
6416      l_in_str_org := MSC_CL_GMP_UTILITY.g_in_str_org ;    /* B3491625 */
6417 
6418   /* New Changes - Using mtl_organization_id from ic_whse_mst , instead of
6419      organization_id from sy_orgn_mst , Bug# 1252322 */
6420 
6421   retrieval_cursor :=
6422                      ' SELECT iwm.whse_code, iwm.mtl_organization_id '
6423 		   ||' FROM  ic_whse_mst'||at_apps_link||' iwm '
6424 	           ||' WHERE iwm.delete_mark = 0 AND '
6425 		   ||'       iwm.mtl_organization_id IS NOT NULL ';
6426 
6427         IF l_in_str_org  IS NOT NULL THEN     /* B3491625 */
6428            retrieval_cursor := retrieval_cursor
6429                 ||'    AND iwm.mtl_organization_id ' || l_in_str_org ;
6430         END IF;
6431 
6432   OPEN c_whse_cursor FOR retrieval_cursor;
6433 
6434   FETCH c_whse_cursor
6435   INTO  whse_code, organization_id;
6436 
6437   IF c_whse_cursor%NOTFOUND
6438   THEN
6439     raise no_warehouses;
6440   END IF;
6441 
6442   WHILE c_whse_cursor%FOUND
6443   LOOP
6444      INSERT INTO msc_st_sub_inventories
6445 	 (
6446 	   sub_inventory_code,
6447 	   organization_id,
6448 	   netting_type,
6449 	   sr_instance_id,
6450            deleted_flag,
6451 	   creation_date,
6452 	   created_by,
6453 	   last_update_date,
6454 	   last_updated_by
6455 	 )
6456 	 VALUES
6457 	 (
6458 	   whse_code,
6459 	   organization_id,
6460 	   1,
6461 	   instance,
6462            2,
6463 	   run_date,
6464 	   0,
6465 	   run_date,
6466 	   0
6467 	 );
6468 
6469      COMMIT;
6470 
6471      FETCH c_whse_cursor
6472 	 INTO  whse_code, organization_id;
6473 
6474   END LOOP;
6475   CLOSE c_whse_cursor;
6476 
6477   return_status := TRUE;
6478 
6479   EXCEPTION
6480     WHEN invalid_string_value  THEN
6481         log_message('Organization string is Invalid ' );
6482         return_status := FALSE;
6483 
6484     WHEN no_warehouses
6485 	THEN
6486 	  log_message('No warehouses found to export');
6487 	  return_status := TRUE;   /* B3577871 */
6488 
6489     WHEN setup_failure
6490 	THEN
6491 	  log_message('Sub-inventory export setup failure');
6492 	  return_status := FALSE;
6493 
6494     WHEN OTHERS
6495 	THEN
6496 	  log_message('Sub-Inventory Export failed:');
6497 	  log_message(sqlerrm);
6498 	  return_status := FALSE;
6499 END extract_sub_inventory;
6500 
6501 /*
6502 REM+=========================================================================+
6503 REM| PROCEDURE NAME                                                          |
6504 REM|    setup                                                                |
6505 REM|                                                                         |
6506 REM| TYPE                                                                    |
6507 REM|    Private                                                              |
6508 REM|                                                                         |
6509 REM| USAGE                                                                   |
6510 REM|    This procedure sets up and initilialises various program structures  |
6511 REM|    for the extraction of effectivities                                  |
6512 REM|                                                                         |
6513 REM| DESCRIPTION                                                             |
6514 REM|                                                                         |
6515 REM|                                                                         |
6516 REM| INPUT PARAMETERS                                                        |
6517 REM|    apps_link_name VARCHAR2 - database link to APPS database instance    |
6518 REM|    delimtiter_char VARCHAR2 - used to links strings together            |
6519 REM|    instance       INTEGER - the GMP instance ID                         |
6520 REM|    run_date       DATE    - the run date                                |
6521 REM|                                                                         |
6522 REM| OUTPUT PARAMETERS                                                       |
6523 REM|    return_status: TRUE => OK                                            |
6524 REM|                                                                         |
6525 REM| INPUT/OUTPUT PARAMETERS                                                 |
6526 REM|    None                                                                 |
6527 REM|                                                                         |
6528 REM| HISTORY                                                                 |
6529 REM|  07/14/2002   Rajesh Patangya - Reorgnized the complete code B2314052   |
6530 REM+=========================================================================+
6531 */
6532 PROCEDURE setup
6533 (
6534   apps_link_name IN VARCHAR2,
6535   delimiter_char IN VARCHAR2,
6536   instance       IN INTEGER,
6537   run_date       IN DATE,
6538   return_status  OUT NOCOPY BOOLEAN
6539 )
6540 IS
6541   stat           VARCHAR2(1024);
6542   statement_no   INTEGER;
6543 
6544 BEGIN
6545   /* Construct link names */
6546 
6547   IF apps_link_name IS NOT NULL
6548   THEN
6549     at_apps_link := apps_link_name;
6550   ELSE
6551     at_apps_link := ' ';
6552   END IF;
6553 
6554   /* select maximum aps_effectivity ID */
6555 
6556   stat := ' SELECT max(APS_FMEFF_ID) from gmp_form_eff'||at_apps_link ;
6557   EXECUTE IMMEDIATE stat INTO g_aps_eff_id ;
6558 
6559   IF NVL(g_aps_eff_id,0) = 0 THEN
6560      g_aps_eff_id := 1 ;
6561   END IF ;
6562 
6563   /* Everything starts with index # of 1 */
6564 
6565   alt_rsrc_size             := 1;
6566   formula_headers_size      := 1;
6567   fd_size           	    := 1;
6568   formula_orgn_size         := 1;
6569   routing_headers_size      := 1;
6570   rtg_org_dtl_size          := 1;
6571   rtg_gen_dtl_size          := 1;
6572   material_assocs_size      := 1;
6573   recipe_orgn_over_size     := 1;
6574   recipe_override_size      := 1;
6575   g_mat_assoc      	    := 1;
6576   opr_stpdep_size           := 1;
6577   g_dep_index               := 1;
6578 
6579 /* These variables store the MTQ related values that is last inserted. */
6580   g_old_formula_id          := -1; /* B3970993 */
6581   g_old_recipe_id           := -1; /* B3970993 */
6582   g_old_rtg_id              := -1; /* B3970993 */
6583   g_old_rtgstep_id          := -1; /* B3970993 */
6584   g_old_aps_item_id         := -1; /* B3970993 */
6585   g_mtq_loc                 := -1; /* B3970993 */
6586   g_min_mtq                 := -1; /* B3970993 */
6587 
6588   current_date_time := run_date;
6589 
6590   b_instance_id := instance;
6591 
6592   delimiter := delimiter_char;
6593 
6594   /* Initialize the counter values for bulk inserts */
6595    bom_index   := 0 ;
6596    bomc_index  := 0 ;
6597    or_index    := 0 ;
6598    rtg_index   := 0 ;
6599    opr_index   := 0 ;
6600    rs_index    := 0 ;
6601    oc_index    := 0 ;
6602    mtq_index   := 0 ;
6603 
6604   return_status := TRUE;
6605 
6606    /* Get the directory specified in the 'utl_file_dir' in init.ora file */
6607    BEGIN
6608        SELECT substrb(translate(ltrim(value),',',' '), 1,
6609                      instr(translate(ltrim(value),',',' '),' ') - 1)
6610         INTO p_location
6611         FROM v$parameter
6612        WHERE name = 'utl_file_dir';
6613   EXCEPTION
6614     WHEN OTHERS THEN
6615 	return_status := FALSE;
6616 	log_message('directory select failed ');
6617 	log_message(sqlerrm);
6618     END ;
6619 
6620     IF p_location IS NOT NULL THEN
6621       -- gmp_putline ( 'file opened ' || p_location  || ' at '
6622       --    || TO_CHAR ( SYSDATE, 'DD-MON-YYYY HH24:MI:SS' ), 'w' );
6623       -- gmp_putline ('  ' , 'a' );
6624       null ;
6625     END IF ;
6626 
6627   EXCEPTION
6628     WHEN OTHERS THEN
6629 	return_status := FALSE;
6630 	log_message('Setup failed at statement ');
6631 	log_message(sqlerrm);
6632 
6633 END setup;
6634 /*
6635 REM+=========================================================================+
6636 REM| FUNCTION NAME                                                           |
6637 REM|    find_routing_offsets                                                  |
6638 REM| DESCRIPTION                                                             |
6639 REM|                                                                         |
6640 REM| HISTORY                                                                 |
6641 REM+=========================================================================+
6642 */
6643 FUNCTION find_routing_offsets (p_formula_id    	IN NUMBER,
6644                                p_plant_code 	IN VARCHAR2)
6645                                RETURN NUMBER IS
6646 
6647 i 	    NUMBER ;
6648 retvar 	    NUMBER ;
6649 
6650 BEGIN
6651 i 	    := 1 ;
6652 retvar 	    := -1 ;
6653 
6654 IF p_formula_id = g_prev_formula_id THEN
6655  retvar := g_prev_locn ;
6656  IF g_prev_locn > 0 THEN
6657    g_rstep_loc := g_prev_locn ;
6658  END IF ;
6659 ELSE
6660 g_prev_formula_id := p_formula_id ;
6661 FOR i in g_rstep_loc..rtg_offsets_size
6662 LOOP
6663   IF rstep_offsets(i).formula_id = p_formula_id THEN
6664     IF rstep_offsets(i).plant_code = p_plant_code THEN
6665       retvar := i ;
6666       g_rstep_loc := i ;
6667       EXIT ;
6668     ELSIF rstep_offsets(i).plant_code > p_plant_code THEN
6669       g_rstep_loc := i ;
6670       retvar := -1 ;
6671       EXIT ;
6672     ELSE  /* continue looping */
6673       NULL ;
6674     END IF ;
6675   ELSIF rstep_offsets(i).formula_id < p_formula_id THEN
6676     NULL ;  /* Continue looping */
6677   ELSE -- rstep_offsets(i).formula_id > p_formula_id THEN
6678    retvar := -1 ;
6679    g_rstep_loc := i ;
6680    EXIT ;
6681   END IF;
6682 END LOOP ;
6683 
6684 END IF ; /* different formula_id */
6685  g_prev_locn := retvar ;
6686  return retvar ;
6687 END find_routing_offsets;
6688 
6689 /*
6690 REM+=========================================================================+
6691 REM| FUNCTION NAME                                                           |
6692 REM|    get_offsets                                                          |
6693 REM| DESCRIPTION                                                             |
6694 REM|                                                                         |
6695 REM| HISTORY                                                                 |
6696 REM+=========================================================================+
6697 */
6698 FUNCTION get_offsets( p_formula_id		IN NUMBER,
6699 			p_plant_code 		IN VARCHAR2,
6700 			p_formulaline_id	IN NUMBER )
6701 			RETURN NUMBER IS
6702 
6703 i 	    NUMBER ;
6704 retvar 	    NUMBER ;
6705 
6706 BEGIN
6707 i 	    := 1 ;
6708 retvar 	    := -1 ;
6709 
6710 FOR i in g_rstep_loc..rtg_offsets_size
6711 LOOP
6712   IF rstep_offsets(i).formula_id = p_formula_id THEN
6713     IF rstep_offsets(i).plant_code = p_plant_code THEN
6714       IF rstep_offsets(i).formulaline_id = p_formulaline_id THEN
6715 	retvar := i ;
6716 	g_rstep_loc := i+1 ;
6717 	EXIT ;
6718       ELSIF
6719 	rstep_offsets(i).formulaline_id > p_formulaline_id THEN
6720 	retvar := -1 ;
6721 	g_rstep_loc := i ;
6722 	EXIT ;
6723       ELSE
6724 	NULL ; /* continue looping */
6725       END IF ;
6726     ELSIF rstep_offsets(i).plant_code > p_plant_code THEN
6727       g_rstep_loc := i ;
6728       retvar := -1 ;
6729       EXIT ;
6730     ELSE  /* continue looping */
6731       NULL ;
6732     END IF ;
6733   ELSIF rstep_offsets(i).formula_id < p_formula_id THEN
6734     NULL ;  /* Continue looping */
6735   ELSE -- rstep_offsets(i).formula_id > p_formula_id THEN
6736    retvar := -1 ;
6737    g_rstep_loc := i ;
6738    EXIT ;
6739   END IF;
6740 END LOOP ;
6741  return retvar ;
6742 END get_offsets;
6743 
6744 /*
6745 REM+=========================================================================+
6746 REM| PROCEDURE NAME                                                          |
6747 REM|    gmp_putline                                                          |
6748 REM| HISTORY                                                                 |
6749 REM|    Created by Rajesh Patangya (OPM Development Oracle US)               |
6750 REM+=========================================================================+
6751 */
6752    /* Define a function that open the log file, makes entry into the log file
6753       and close the log file */
6754    PROCEDURE gmp_putline (
6755        v_text                    IN       VARCHAR2,
6756        v_mode                    IN       VARCHAR2 )
6757    IS
6758       LOG   UTL_FILE.file_type;
6759   BEGIN
6760 
6761     IF p_location IS NOT NULL THEN
6762       LOG    :=
6763              UTL_FILE.fopen ( p_location, 'GMPBM11B.log', v_mode );
6764       UTL_FILE.put_line ( LOG, v_text );
6765       UTL_FILE.fflush ( LOG );
6766       UTL_FILE.fclose ( LOG );
6767     ELSE
6768       NULL ;
6769     END IF;
6770 END gmp_putline;
6771 
6772 /*
6773 REM+=========================================================================+
6774 REM| PROCEDURE NAME                                                          |
6775 REM|    time_stamp                                                           |
6776 REM| DESCRIPTION                                                             |
6777 REM|                                                                         |
6778 REM| HISTORY                                                                 |
6779 REM| 07/14/2002   Rajesh Patangya - Reorgnized the complete code B2314052    |
6780 REM+=========================================================================+
6781 */
6782 PROCEDURE time_stamp IS
6783 
6784   cur_time VARCHAR2(25) ;
6785 BEGIN
6786   cur_time := NULL ;
6787 
6788    SELECT to_char(sysdate,'DD-MON-RRRR HH24:MI:SS')
6789    INTO cur_time FROM sys.dual ;
6790 
6791    log_message(cur_time);
6792   EXCEPTION
6793     WHEN OTHERS THEN
6794         log_message('Failure occured in time_stamp');
6795         log_message(sqlerrm);
6796       RAISE;
6797 END time_stamp ;
6798 
6799 /*
6800 REM+=========================================================================+
6801 REM| PROCEDURE NAME                                                          |
6802 REM|    msc_inserts                                                          |
6803 REM| DESCRIPTION                                                             |
6804 REM|    All the Bulk insert to MSC tables for OPM data                       |
6805 REM|                                                                         |
6806 REM| HISTORY                                                                 |
6807 REM| 03/12/2004   Created Rajesh Patangya                                    |
6808 REM|                                                                         |
6809 REM+=========================================================================+
6810 */
6811 PROCEDURE msc_inserts
6812 (
6813   return_status  OUT NOCOPY BOOLEAN
6814 )
6815 IS
6816 
6817 stmt_no   NUMBER ;
6818 i         integer ;
6819 
6820 BEGIN
6821 stmt_no   := 0 ;
6822 i         := 1;
6823 
6824 /* --------------------------- Process Effectivity Insert ------------------------- */
6825 
6826      stmt_no := 901 ;
6827      i := 1 ;
6828      IF pef_organization_id.FIRST > 0 THEN
6829      FORALL i IN pef_organization_id.FIRST..pef_organization_id.LAST
6830       INSERT INTO msc_st_process_effectivity (
6831              process_sequence_id,
6832              item_id,
6833              organization_id,
6834              effectivity_date,
6835              disable_date,
6836              minimum_quantity,
6837              maximum_quantity,
6838              preference,
6839              routing_sequence_id,
6840              bill_sequence_id,
6841              sr_instance_id,
6842              item_process_cost, line_id,
6843              total_product_cycle_time, primary_line_flag, production_line_rate,
6844              deleted_flag,
6845              last_update_date,
6846              last_updated_by,
6847              creation_date,
6848              created_by )
6849              VALUES
6850              (
6851              pef_process_sequence_id(i) ,
6852              pef_item_id(i) ,
6853              pef_organization_id(i) ,
6854              pef_effectivity_date(i) ,
6855              pef_disable_date(i) ,
6856              pef_minimum_quantity(i) ,
6857              pef_maximum_quantity(i) ,
6858              pef_preference(i) ,
6859              pef_routing_sequence_id(i) ,
6860              pef_bill_sequence_id(i) ,
6861              pef_sr_instance_id(i) ,
6862              null_value, null_value,
6863              null_value, null_value, null_value,
6864              2     ,                           /* Deleted Flag */
6865              pef_last_update_date(i) ,
6866              0  ,                              /* Last Updated By */
6867              pef_creation_date(i)    ,
6868              0                                /* Created By */
6869              ) ;
6870      END IF;
6871 /* -------------------------------  BOM Insert --------------------------- */
6872      stmt_no := 902 ;
6873      i := 1 ;              /* B3837959 MMK Issue */
6874      IF bom_organization_id.FIRST > 0 THEN
6875      FORALL i IN bom_organization_id.FIRST..bom_organization_id.LAST
6876        INSERT INTO msc_st_boms (
6877 	 bill_sequence_id,
6878          sr_instance_id,
6879          organization_id,
6880 	 assembly_item_id,
6881          assembly_type,
6882          alternate_bom_designator,
6883 	 specific_assembly_comment,
6884          scaling_type,
6885          assembly_quantity,
6886 	 uom,
6887 /* NAMIT_CR */
6888          operation_seq_num,
6889          deleted_flag,
6890          last_update_date,
6891          last_updated_by,
6892          creation_date,
6893          created_by )
6894 	 VALUES
6895          (
6896          bom_bill_sequence_id(i),
6897          bom_sr_instance_id(i)  ,
6898          bom_organization_id(i) ,
6899          bom_assembly_item_id(i),
6900          1   ,                             /* Assembly Type  */
6901          bom_alternate_bom_designator(i),
6902          bom_specific_assembly_comment(i),
6903          bom_scaling_type(i)     ,
6904          bom_assembly_quantity(i),
6905          bom_uom(i)              ,
6906 /* NAMIT_CR */
6907          bom_op_seq_number(i)    ,
6908 	 2     ,                           /* Deleted Flag */
6909          bom_last_update_date(i) ,
6910          0  ,                              /* Last Updated By */
6911          bom_creation_date(i)    ,
6912          0                                 /* Created By */
6913          ) ;
6914       END IF;
6915 
6916 
6917 /* --------------------------- BOM Components Insert Stars ------------------------- */
6918 
6919      stmt_no := 903 ;
6920      i := 1 ;
6921      IF bomc_organization_id.FIRST > 0 THEN
6922      FORALL i IN bomc_organization_id.FIRST..bomc_organization_id.LAST
6923         INSERT INTO msc_st_bom_components
6924        (
6925        component_sequence_id,
6926        sr_instance_id,
6927        organization_id,
6928        Inventory_item_id,
6929        using_assembly_id,
6930        bill_sequence_id,
6931        component_type,
6932        scaling_type,
6933        change_notice,
6934        revision,
6935        uom_code,
6936        usage_quantity,
6937        effectivity_date,
6938        contribute_to_step_qty,
6939        disable_date,
6940        from_unit_number,
6941        to_unit_number,
6942        use_up_code,
6943        suggested_effectivity_date,
6944        driving_item_id,
6945        operation_offset_percent,
6946        optional_component,
6947        old_effectivity_date,
6948        wip_supply_type,
6949        planning_factor,
6950        atp_flag,
6951        component_yield_factor,
6952        deleted_flag,
6953        last_update_date,
6954        last_updated_by,
6955        creation_date,
6956        created_by,
6957        scale_multiple,
6958        scale_rounding_variance,
6959        rounding_direction
6960        )
6961        VALUES
6962        (
6963        bomc_component_sequence_id(i),
6964        bomc_sr_instance_id(i),
6965        bomc_organization_id(i),
6966        bomc_Inventory_item_id(i),
6967        bomc_using_assembly_id(i),
6968        bomc_bill_sequence_id(i),
6969        bomc_component_type(i),
6970        bomc_scaling_type(i),
6971        null_value,
6972        null_value,
6973        bomc_uom_code(i),
6974        bomc_usage_quantity(i),
6975        bomc_effectivity_date(i),
6976         /* NAMIT_ASQC */
6977        bomc_contribute_to_step_qty(i),
6978        bomc_disable_date(i),
6979        null_value,
6980        null_value,
6981        null_value,
6982        null_value,
6983        null_value,
6984        bomc_opr_offset_percent(i),
6985        bomc_optional_component(i),
6986        null_value,
6987        bomc_wip_supply_type(i),
6988        null_value,
6989        1,                                /* atp flag */
6990        1,                                /* component_yield_factor */
6991        2     ,                           /* Deleted Flag */
6992        bomc_last_update_date(i) ,
6993        0  ,                              /* Last Updated By */
6994        bomc_creation_date(i)    ,
6995        0 ,                               /* Created By */
6996        bomc_scale_multiple(i),
6997        bomc_scale_rounding_variance(i),
6998        bomc_rounding_direction(i)
6999        );
7000       END IF;
7001 
7002 /* --------------------------- Routing Insert Stars ------------------------- */
7003      stmt_no := 904 ;
7004      i := 1 ;
7005      IF rtg_organization_id.FIRST > 0 THEN
7006      FORALL i IN rtg_organization_id.FIRST..rtg_organization_id.LAST
7007           INSERT INTO msc_st_routings (
7008            routing_sequence_id,
7009            sr_instance_id,
7010            routing_type,
7011            routing_comment,
7012            alternate_routing_designator,
7013            project_id,
7014            task_id,
7015            line_id,
7016            uom_code,
7017            cfm_routing_flag,
7018            ctp_flag,
7019            routing_quantity,
7020            assembly_item_id,
7021            organization_id,
7022            auto_step_qty_flag,
7023            deleted_flag,
7024            last_update_date,
7025            last_updated_by,
7026            creation_date,
7027            created_by )
7028            VALUES (
7029            rtg_routing_sequence_id(i),
7030            rtg_sr_instance_id(i),
7031            1 ,                                    /* routing_type */
7032            rtg_routing_comment(i),
7033            rtg_alt_routing_designator(i),
7034            null_value,
7035            null_value,
7036            null_value,
7037            rtg_uom_code(i),
7038            null_value,
7039            null_value,
7040            rtg_routing_quantity(i),
7041            rtg_assembly_item_id(i),
7042            rtg_organization_id(i),
7043            rtg_auto_step_qty_flag(i),
7044            2,                                   /* Deleted Flag */
7045            rtg_last_update_date(i),             /* Last Update Date */
7046            0,
7047            rtg_creation_date(i),                /* Creation Date */
7048            0 ) ;
7049       END IF;
7050 
7051 /* ----------------------- Operation Resource  Insert --------------------- */
7052      stmt_no := 905 ;
7053      i := 1 ;
7054 
7055   /*
7056      for i in or_operation_sequence_id.FIRST..or_operation_sequence_id.LAST
7057      loop
7058         dbms_output.put_line('========');
7059         dbms_output.put_line('Op seq id '||or_operation_sequence_id(i)) ;
7060         dbms_output.put_line('Res Seq Num '||or_resource_seq_num(i)) ;
7061         dbms_output.put_line('Resource id '||or_resource_id(i)) ;
7062         dbms_output.put_line(' Alternate Num ' ||or_alternate_number(i));
7063         dbms_output.put_line( 'principal flag '||or_principal_flag(i));
7064         dbms_output.put_line( 'Basis type '||or_basis_type(i));
7065         dbms_output.put_line( 'resource usage '||or_resource_usage(i));
7066         dbms_output.put_line( 'Max rsrc units '||or_max_resource_units(i)) ;
7067         dbms_output.put_line(' rsrc units '||or_resource_units(i)) ;
7068         dbms_output.put_line(' uom code '||or_uom_code(i)) ;
7069         dbms_output.put_line('Min capacity '||or_minimum_capacity(i)) ;
7070         dbms_output.put_line('Max capacity '||or_maximum_capacity(i)) ;
7071         dbms_output.put_line('Setup Id '||or_setup_id(i)) ;
7072         dbms_output.put_line('========');
7073      end loop;
7074     */
7075 
7076 --
7077      IF or_operation_sequence_id.FIRST > 0 THEN
7078      FORALL i IN or_operation_sequence_id.FIRST..or_operation_sequence_id.LAST
7079         INSERT INTO msc_st_operation_resources (
7080         operation_sequence_id,
7081         resource_seq_num,
7082         resource_id,
7083         alternate_number,
7084         principal_flag,
7085         basis_type,
7086         resource_usage,
7087         max_resource_units,
7088         resource_units,
7089         uom_code,
7090         deleted_flag,
7091         sr_instance_id,
7092         routing_sequence_id,
7093         organization_id,
7094         minimum_capacity,
7095         maximum_capacity,
7096         setup_id,
7097         orig_resource_seq_num,
7098         breakable_activity_flag,
7099         last_update_date,
7100         last_updated_by,
7101         creation_date,
7102         created_by )
7103         VALUES (
7104         or_operation_sequence_id(i) ,
7105         or_resource_seq_num(i) ,
7106         or_resource_id(i) ,
7107         or_alternate_number(i) ,
7108         or_principal_flag(i) ,
7109         or_basis_type(i) ,
7110         or_resource_usage(i) ,
7111         or_max_resource_units(i) ,
7112         or_resource_units(i) ,
7113         or_uom_code(i) ,
7114         2,
7115         or_sr_instance_id(i) ,
7116         or_routing_sequence_id(i) ,
7117         or_organization_id(i),
7118         or_minimum_capacity(i),
7119         or_maximum_capacity(i),
7120         or_setup_id(i),
7121         or_orig_rs_seq_num(i),
7122         or_break_ind(i),
7123         or_last_update_date(i) ,
7124         0,
7125         or_creation_date(i) ,
7126         0 );
7127       END IF;
7128 /* ----------------------- Operations Insert --------------------- */
7129      stmt_no := 906 ;
7130      i := 1 ;
7131      IF opr_operation_sequence_id.FIRST > 0 THEN
7132      FORALL i IN opr_operation_sequence_id.FIRST..opr_operation_sequence_id.LAST
7133        INSERT INTO msc_st_routing_operations (
7134        operation_sequence_id,
7135        routing_sequence_id,
7136        operation_seq_num,
7137        sr_instance_id,
7138        operation_description,
7139        effectivity_date,
7140        disable_date,
7141        from_unit_number,
7142        to_unit_number,
7143        option_dependent_flag,
7144        operation_type,
7145        minimum_transfer_quantity,
7146        yield,
7147 /* NAMIT_ASQC */
7148        step_quantity,
7149        step_quantity_uom,
7150        department_id,
7151        department_code,
7152        operation_lead_time_percent,
7153        cumulative_yield,
7154        reverse_cumulative_yield,
7155        net_planning_percent,
7156        setup_duration,
7157        tear_down_duration,
7158        uom_code,
7159        organization_id,
7160        standard_operation_code,
7161        deleted_flag,
7162        last_update_date,
7163        last_updated_by,
7164        creation_date,
7165        created_by )
7166        VALUES
7167        (
7168        opr_operation_sequence_id(i),
7169        opr_routing_sequence_id(i),
7170        opr_operation_seq_num(i),
7171        opr_sr_instance_id(i),
7172        opr_operation_description(i),
7173        opr_effectivity_date(i),
7174        null_value,
7175        null_value,
7176        null_value,
7177        1,
7178        null_value,
7179        opr_mtransfer_quantity(i),    /*B2870041*/
7180        null_value, /*  B2365684 rtg_org_dtl_tab(loop_index).step_qty, */
7181 /* NAMIT_ASQC */
7182        opr_step_qty(i),
7183        opr_step_qty_uom(i),
7184        opr_department_id(i),
7185        opr_department_code(i),
7186        null_value,
7187        null_value,
7188        null_value,
7189        null_value,
7190        null_value,
7191        null_value,
7192        opr_uom_code(i),
7193        opr_organization_id(i),
7194        null_value ,
7195        2,                    /* Deleted Flag */
7196        opr_last_update_date(i),
7197        0,
7198        opr_creation_date(i),
7199        0 ) ;
7200       END IF;
7201 
7202 /* ----------------------- Operation Sequence Insert --------------------- */
7203      stmt_no := 907 ;
7204      i := 1 ;
7205      IF rs_operation_sequence_id.FIRST > 0 THEN
7206      FORALL i IN rs_operation_sequence_id.FIRST..rs_operation_sequence_id.LAST
7207        INSERT INTO msc_st_operation_resource_seqs (
7208        operation_sequence_id,
7209        resource_seq_num,
7210        sr_instance_id,
7211        department_id,
7212        resource_offset_percent,
7213        schedule_flag,
7214        routing_sequence_id,
7215        organization_id,
7216        deleted_flag,
7217        last_update_date,
7218        last_updated_by,
7219        creation_date,
7220        created_by,
7221        activity_group_id )
7222        VALUES (
7223        rs_operation_sequence_id(i),
7224        rs_resource_seq_num(i),
7225        rs_sr_instance_id(i),
7226        rs_department_id(i),
7227        null_value,
7228        rs_schedule_flag(i),
7229        rs_routing_sequence_id(i),
7230        rs_organization_id(i),
7231        2,                         /* deleted flag */
7232        rs_last_update_date(i),
7233        0,
7234        rs_creation_date(i),
7235        0 ,
7236        rs_activity_group_id(i)
7237        ) ;
7238       END IF;
7239 
7240 /* ----------------------- Operation Component Insert --------------------- */
7241      stmt_no := 908 ;
7242      i := 1 ;
7243   /*
7244      for i in oc_operation_sequence_id.FIRST..oc_operation_sequence_id.LAST
7245      loop
7246         dbms_output.put_line('========');
7247         dbms_output.put_line('Op seq id '||oc_operation_sequence_id(i)) ;
7248         dbms_output.put_line('Comp seq id '||oc_component_sequence_id(i)) ;
7249         dbms_output.put_line('Instance '||oc_sr_instance_id(i)) ;
7250         dbms_output.put_line('Bill Seq '||oc_bill_sequence_id(i)) ;
7251         dbms_output.put_line('Routing Seq '||oc_routing_sequence_id(i)) ;
7252         dbms_output.put_line('Org Id '||oc_organization_id(i)) ;
7253      end loop;
7254   */
7255      IF oc_operation_sequence_id.FIRST > 0 THEN
7256      FORALL i IN oc_operation_sequence_id.FIRST..oc_operation_sequence_id.LAST
7257       INSERT INTO msc_st_operation_components (
7258       operation_sequence_id, component_sequence_id, sr_instance_id,
7259       bill_sequence_id, routing_sequence_id, organization_id,
7260       deleted_flag, last_update_date, last_updated_by,
7261       creation_date, created_by )
7262       VALUES (
7263       oc_operation_sequence_id(i),
7264       oc_component_sequence_id(i),
7265       oc_sr_instance_id(i),
7266       oc_bill_sequence_id(i),
7267       oc_routing_sequence_id(i),
7268       oc_organization_id(i),
7269       2,
7270       oc_last_update_date(i),
7271       0,
7272       oc_creation_date(i),
7273       0   ) ;
7274 
7275       END IF;
7276 
7277 -- Bug: 6030499 Vpedarla conditional code
7278 
7279 IF collect_ps_data THEN
7280 
7281 
7282 /* ----------------------- MTQ Insert --------------------- */
7283 /*  NAMIT_MTQ */
7284 
7285      stmt_no := 909 ;
7286      i := 1 ;
7287      IF itm_mtq_from_op_seq_id.FIRST > 0 THEN
7288      FORALL i IN itm_mtq_from_op_seq_id.FIRST..itm_mtq_from_op_seq_id.LAST
7289        INSERT INTO msc_st_operation_networks(
7290        from_op_seq_id,
7291        routing_sequence_id,
7292        dependency_type,
7293        transition_type,
7294        plan_id,
7295        sr_instance_id,
7296        deleted_flag,
7297        from_item_id,
7298        organization_id,
7299        minimum_transfer_qty,
7300        minimum_time_offset,
7301        maximum_time_offset,
7302        last_update_date,
7303        last_updated_by,
7304        creation_date,
7305        created_by,
7306        from_op_seq_num,
7307        planning_pct    -- Bug: 6064590 Vpedarla added the column to send default value of 100
7308        ) VALUES
7309        (
7310         itm_mtq_from_op_seq_id(i),
7311         itm_mtq_routing_sequence_id(i),
7312         5, /* MTQ with Hardlink */
7313         1, /* Primary */
7314         -1,
7315         itm_mtq_sr_instance_id(i),
7316         2,
7317         itm_mtq_from_item_id(i),
7318         itm_mtq_organization_id(i),
7319         itm_mtq_min_tran_qty(i),
7320         itm_mtq_min_time_offset(i),
7321         itm_mtq_max_time_offset(i),
7322         opr_last_update_date(i),
7323         0,
7324         opr_creation_date(i),
7325         0,
7326         itm_mtq_frm_op_seq_num(i),
7327         100   -- Bug: 6064590 Vpedarla added the column to send default value of 100
7328        );
7329 
7330       END IF;
7331 
7332 /* ----------------------- Step Dependency Insert --------------------- */
7333 /* NAMIT_CR */
7334 
7335      stmt_no := 910 ;
7336      i := 1 ;
7337      IF opr_stpdep_frm_seq_id.FIRST > 0 THEN
7338      FORALL i IN opr_stpdep_frm_seq_id.FIRST..opr_stpdep_frm_seq_id.LAST
7339        INSERT INTO msc_st_operation_networks(
7340        from_op_seq_id,
7341        to_op_seq_id,
7342        routing_sequence_id,
7343        dependency_type,
7344        transition_type,
7345        plan_id,
7346        sr_instance_id,
7347        deleted_flag,
7348        minimum_time_offset,
7349        maximum_time_offset,
7350        transfer_pct,
7351 --     Bug: 6064590 Vpedarla inserting into column planning_pct along with transfer_pct
7352        planning_pct,
7353        last_update_date,
7354        last_updated_by,
7355        creation_date,
7356        created_by,
7357        from_op_seq_num,
7358        to_op_seq_num,
7359        apply_to_charges,
7360        organization_id
7361        ) VALUES
7362        (
7363         opr_stpdep_frm_seq_id(i),
7364         opr_stpdep_to_seq_id(i),
7365         opr_stpdep_routing_sequence_id(i),
7366         opr_stpdep_dependency_type(i),
7367         1, /* Transition Type, 1 = Primary*/
7368         -1, /* Plan Id */
7369         opr_stpdep_sr_instance_id(i),
7370         2, /* Deleted Flag */
7371         opr_stpdep_min_time_offset(i),
7372         opr_stpdep_max_time_offset(i),
7373         opr_stpdep_trans_pct(i),
7374         opr_stpdep_trans_pct(i),   -- Bug: 6064590 Vpedarla
7375         opr_last_update_date(i),
7376         0,
7377         opr_creation_date(i),
7378         0,
7379         opr_stpdep_frm_op_seq_num(i),
7380         opr_stpdep_to_op_seq_num(i),
7381         opr_stpdep_app_to_chrg(i),
7382         opr_stpdep_organization_id(i)
7383        );
7384 
7385       END IF;
7386 
7387  END IF;  --Bug: 6030499 Vpedarla end of conditional code
7388 
7389 
7390               bom_organization_id.delete  ;
7391               bomc_organization_id.delete ;
7392               pef_organization_id.delete ;
7393               rtg_organization_id.delete ;
7394               oc_organization_id.delete ;
7395               opr_organization_id.delete   ;
7396               or_organization_id.delete ;
7397               rs_organization_id.delete ;
7398 
7399               bom_bill_sequence_id.delete ;
7400               bomc_bill_sequence_id.delete ;
7401               pef_bill_sequence_id.delete ;
7402               oc_bill_sequence_id.delete ;
7403 
7404               bom_last_update_date.delete ;
7405               bomc_last_update_date.delete ;
7406               pef_last_update_date.delete ;
7407               rtg_last_update_date.delete ;
7408               or_last_update_date.delete ;
7409               opr_last_update_date.delete ;
7410               rs_last_update_date.delete ;
7411               oc_last_update_date.delete ;
7412 
7413               bom_creation_date.delete ;
7414               bomc_creation_date.delete ;
7415               pef_creation_date.delete ;
7416               rtg_creation_date.delete ;
7417               or_creation_date.delete ;
7418               opr_creation_date.delete ;
7419               rs_creation_date.delete ;
7420               oc_creation_date.delete ;
7421 
7422               pef_effectivity_date.delete ;
7423               bomc_effectivity_date.delete ;
7424               opr_effectivity_date.delete ;
7425 
7426               rtg_routing_sequence_id.delete ;
7427               pef_routing_sequence_id.delete ;
7428               or_routing_sequence_id.delete ;
7429               opr_routing_sequence_id.delete ;
7430               rs_routing_sequence_id.delete ;
7431               oc_routing_sequence_id.delete ;
7432 
7433               bomc_uom_code.delete;
7434               rtg_uom_code.delete;
7435               or_uom_code.delete ;
7436               opr_uom_code.delete;
7437 
7438               bom_assembly_item_id.delete ;
7439               rtg_assembly_item_id.delete ;
7440 
7441               bomc_component_sequence_id.delete ;
7442               oc_component_sequence_id.delete ;
7443 
7444               or_operation_sequence_id.delete  ;
7445               opr_operation_sequence_id.delete ;
7446               rs_operation_sequence_id.delete ;
7447               oc_operation_sequence_id.delete ;
7448 
7449               or_resource_seq_num.delete ;
7450               rs_resource_seq_num.delete ;
7451 
7452             /* -- BOM Variable Initialization -- */
7453               bom_alternate_bom_designator.delete ;
7454               bom_specific_assembly_comment.delete ;
7455               bom_scaling_type.delete ;
7456               bom_assembly_quantity.delete ;
7457               bom_uom.delete ;
7458               bom_index := 0 ;
7459 
7460             /* -- BOMC Variable Initialization -- */
7461               bomc_Inventory_item_id.delete ;
7462               bomc_using_assembly_id.delete ;
7463               bomc_component_type.delete ;
7464               bomc_scaling_type.delete ;
7465               bomc_usage_quantity.delete ;
7466               bomc_opr_offset_percent.delete  ;
7467               bomc_optional_component.delete  ;
7468               bomc_wip_supply_type.delete ;
7469               bomc_scale_multiple.delete  ;
7470               bomc_scale_rounding_variance.delete ;
7471               bomc_rounding_direction.delete  ;
7472               bomc_index := 0 ;
7473 
7474             /* -- Pef Variable Initialization -- */
7475               pef_process_sequence_id.delete ;
7476               pef_item_id.delete ;
7477               pef_disable_date.delete ;
7478               pef_minimum_quantity.delete ;
7479               pef_maximum_quantity.delete ;
7480               pef_preference.delete ;
7481               pef_index := 0 ;
7482 
7483             /* -- Rtg Variable Initialization -- */
7484               rtg_routing_comment.delete ;
7485               rtg_alt_routing_designator.delete ;
7486               rtg_routing_quantity.delete ;
7487               rtg_index := 0 ;
7488 
7489             /* -- Or Variable Initialization -- */
7490               or_resource_id.delete ;
7491               or_alternate_number.delete ;
7492               or_principal_flag.delete ;
7493               or_basis_type.delete ;
7494               or_resource_usage.delete ;
7495               or_max_resource_units.delete ;
7496               or_resource_units.delete ;
7497               or_index := 0 ;
7498 
7499             /* -- Opr Variable Initialization -- */
7500               opr_operation_seq_num.delete ;
7501               opr_operation_description.delete ;
7502               opr_mtransfer_quantity.delete ;
7503               opr_department_id.delete ;
7504               rs_department_id.delete ;
7505               opr_department_code.delete ;
7506               rs_activity_group_id.delete ;
7507               rs_schedule_flag.delete ;
7508               opr_index := 0 ;
7509               rs_index := 0 ;
7510               oc_index := 0 ;
7511 
7512               -- bug: 6851919 Vpedarla
7513               mtq_index := 0;
7514               g_dep_index := 1 ;
7515               opr_stpdep_frm_seq_id.delete;
7516               opr_stpdep_to_seq_id.delete;
7517               opr_stpdep_routing_sequence_id.delete;
7518               opr_stpdep_dependency_type.delete;
7519               opr_stpdep_app_to_chrg.delete;
7520               opr_stpdep_sr_instance_id.delete;
7521               opr_stpdep_organization_id.delete;
7522               opr_stpdep_frm_op_seq_num.delete;
7523               opr_stpdep_to_op_seq_num.delete;
7524               opr_stpdep_trans_pct.delete;
7525               opr_stpdep_min_time_offset.delete;
7526               opr_stpdep_max_time_offset.delete;
7527 
7528               itm_mtq_frm_op_seq_num.delete;
7529               itm_mtq_max_time_offset.delete;
7530               itm_mtq_min_tran_qty.delete;
7531               itm_mtq_organization_id.delete;
7532               itm_mtq_from_item_id.delete;
7533               itm_mtq_sr_instance_id.delete;
7534               itm_mtq_routing_sequence_id.delete;
7535               itm_mtq_from_op_seq_id.delete;
7536 
7537               bom_sr_instance_id.delete;
7538               bom_op_seq_number.delete;
7539               bomc_sr_instance_id.delete;
7540               bomc_contribute_to_step_qty.delete;
7541               bomc_disable_date.delete;
7542               rtg_sr_instance_id.delete;
7543               rtg_auto_step_qty_flag.delete;
7544               or_sr_instance_id.delete;
7545               or_minimum_capacity.delete;
7546               or_maximum_capacity.delete;
7547               or_setup_id.delete;
7548               or_orig_rs_seq_num.delete;
7549               or_break_ind.delete;
7550               opr_sr_instance_id.delete;
7551               opr_step_qty.delete;
7552               opr_step_qty_uom.delete;
7553               oc_sr_instance_id.delete;
7554 
7555               --bug: 6851919 end of changes
7556 
7557 
7558               dbms_session.free_unused_user_memory;/* akaruppa B5007729 */
7559 
7560 
7561         return_status := TRUE ;
7562   EXCEPTION
7563     WHEN OTHERS THEN
7564         log_message('Error in MSC Inserts : '||stmt_no || ':' || sqlerrm);
7565         return_status := FALSE;
7566 
7567 END msc_inserts ;
7568 --
7569 /*
7570 REM+=========================================================================+
7571 REM| PROCEDURE NAME                                                          |
7572 REM|    write_setups_and_transitions                                         |
7573 REM|                                                                         |
7574 REM| TYPE                                                                    |
7575 REM|    Private                                                              |
7576 REM|                                                                         |
7577 REM| USAGE                                                                   |
7578 REM|    This procedure inserts rows into msc_st_resource_setups and          |
7579 REM|    msc_st_setup_transitions                                             |
7580 REM|                                                                         |
7581 REM| DESCRIPTION                                                             |
7582 REM|                                                                         |
7583 REM|                                                                         |
7584 REM| INPUT PARAMETERS                                                        |
7585 REM|    None                                                                 |
7586 REM|                                                                         |
7587 REM| OUTPUT PARAMETERS                                                       |
7588 REM|    None                                                                 |
7589 REM|                                                                         |
7590 REM| INPUT/OUTPUT PARAMETERS                                                 |
7591 REM|    None                                                                 |
7592 REM|                                                                         |
7593 REM| HISTORY                                                                 |
7594 REM|  06/02/2004   Sridhar Gidugu  created                                   |
7595 REM|  0519/06 Rewrite for SDS                                                |
7596 REM|   MSC_RESOURCE_SETUPS unique key is ON                                  |
7597 REM|   Instance_id,resource_id,organization_id and setup_id                  |
7598 REM+=========================================================================+
7599 */
7600 PROCEDURE write_setups_and_transitions
7601 (
7602   at_apps_link   IN VARCHAR2,
7603   return_status  OUT NOCOPY BOOLEAN
7604 )  IS
7605    l_profile            VARCHAR2(4);
7606    stmt_no              NUMBER;
7607    Zero_tran            VARCHAR2(32767);
7608    fact_tran            VARCHAR2(32767);
7609    rsrc_setup           VARCHAR2(32767);
7610 BEGIN
7611    Zero_tran   := NULL ;
7612    fact_tran   := NULL ;
7613    rsrc_setup  := NULL ;
7614 /* bug: 6710684 Vpedarla making changes to take the profile value from source server
7615            and also made changes to use procedure get_profile_value */
7616 --       commented the below code line
7617 --      l_profile       := FND_PROFILE.VALUE('BOM:HOUR_UOM_CODE');
7618         l_profile       := get_profile_value('BOM:HOUR_UOM_CODE' , at_apps_link);
7619 
7620      -- ZERO Transitions  (Alternate Resources are considered)
7621      stmt_no := 910 ;
7622      Zero_tran := ' INSERT INTO msc_st_setup_transitions ( '
7623      ||'    resource_id,          '
7624      ||'    organization_id,     '
7625      ||'    from_setup_id,        '
7626      ||'    to_setup_id,         '
7627      ||'    transition_time,      '
7628      ||'    transition_penalty,   '
7629      ||'    transition_uom,       '
7630      ||'    sr_instance_id,     '
7631      ||'    deleted_flag )   '
7632      ||' SELECT  '
7633      ||'    ((a.resource_id * 2 ) +1 ), '
7634      ||'    a.mtl_organization_id, '
7635      ||'    a.seq_dep_id, '
7636      ||'    b.seq_dep_id, '
7637      ||'    0 setup_time, '
7638      ||'    0 penalty_factor, '
7639      ||'    :profile, '
7640      ||'    :instance1 , '
7641      ||'    2 '
7642      ||' FROM ( '
7643      ||' SELECT '
7644      ||' iwm.mtl_organization_id, '
7645      ||' s.category_id, '
7646      ||' s.seq_dep_id, '
7647      ||' o.oprn_id, '
7648      ||' rd.resource_id, '
7649      ||' count(o.oprn_id) OVER (PARTITION BY rd.orgn_code,s.category_id,rd.resource_id) CNT '
7650      ||' FROM '
7651      ||'     ic_whse_mst'||at_apps_link||' iwm, '
7652      ||'     sy_orgn_mst'||at_apps_link||' sy, '
7653      ||'     cr_rsrc_dtl'||at_apps_link||' rd, '
7654      ||'     gmp_sequence_types'||at_apps_link||' s, '
7655      ||'     gmd_operation_resources'||at_apps_link||' r, '
7656      ||'     gmd_operation_activities'||at_apps_link||' a, '
7657      ||'     gmd_operations'||at_apps_link||' o '
7658      ||' WHERE o.oprn_id = a.oprn_id '
7659      ||' AND a.oprn_line_id = r.oprn_line_id '
7660      ||' AND rd.orgn_code = sy.orgn_code '
7661      ||' AND sy.resource_whse_code = iwm.whse_code '
7662      ||' AND a.sequence_dependent_ind = 1 '
7663      ||' AND r.prim_rsrc_ind = 1 '
7664      ||' AND r.resources = rd.resources '
7665      ||' AND o.oprn_id = s.oprn_id ' ;
7666 --     ||' AND iwm.mtl_organization_id in (1381,1382,1383,11159) '
7667      IF l_in_str_org  IS NOT NULL THEN
7668       Zero_tran := Zero_tran
7669       ||'   AND iwm.mtl_organization_id ' || l_in_str_org  ;
7670      END IF;
7671      Zero_tran := Zero_tran
7672      ||' UNION ALL '
7673      ||' SELECT '
7674      ||' rd.mtl_organization_id, '
7675      ||' s.category_id, '
7676      ||' s.seq_dep_id, '
7677      ||' o.oprn_id, '
7678      ||' rd.alt_resource_id, '
7679      ||' count(o.oprn_id) OVER (PARTITION BY rd.mtl_organization_id,s.category_id,rd.alt_resource_id) CNT '
7680      ||' FROM '
7681      ||'     gmp_sequence_types'||at_apps_link||' s, '
7682      ||'     gmd_operation_resources'||at_apps_link||' r, '
7683      ||'     gmd_operation_activities'||at_apps_link||' a, '
7684      ||'     gmd_operations'||at_apps_link||' o, '
7685      ||' (SELECT pcrd.resource_id prim_resource_id, '
7686      ||'         pcrd.resources prim_resources,  '
7687      ||'         acrd.resource_id alt_resource_id,  '
7688      ||'         acrd.resources alt_resources, '
7689      ||'         iwm.mtl_organization_id  '
7690      ||'                     FROM  ic_whse_mst'||at_apps_link||' iwm,  '
7691      ||'                           sy_orgn_mst'||at_apps_link||' sy,  '
7692      ||'                           cr_rsrc_dtl'||at_apps_link||' acrd,  '
7693      ||'                           cr_rsrc_dtl'||at_apps_link||' pcrd,  '
7694      ||'                           cr_ares_mst'||at_apps_link||' cam  '
7695      ||'                     WHERE cam.alternate_resource = acrd.resources  '
7696      ||'                       AND cam.primary_resource = pcrd.resources  '
7697      ||'                       AND acrd.orgn_code = pcrd.orgn_code  '
7698      ||'                       AND acrd.orgn_code = sy.orgn_code'
7699      ||'                       AND sy.resource_whse_code = iwm.whse_code  ' ;
7700 --     ||'                       AND iwm.mtl_organization_id in (1381,1382,1383,11159) '
7701      IF l_in_str_org  IS NOT NULL THEN
7702         Zero_tran := Zero_tran
7703         ||'   AND iwm.mtl_organization_id ' || l_in_str_org  ;
7704      END IF;
7705      Zero_tran := Zero_tran
7706      ||'                       AND acrd.delete_mark = 0   '
7707      ||'                     ORDER BY pcrd.resource_id ) rd '
7708      ||' WHERE o.oprn_id = a.oprn_id '
7709      ||' AND a.oprn_line_id = r.oprn_line_id '
7710      ||' AND a.sequence_dependent_ind = 1 '
7711      ||' AND r.prim_rsrc_ind = 1 '
7712      ||' AND o.oprn_id = s.oprn_id '
7713      ||' AND r.resources = rd.prim_resources '
7714      ||' ) a, '
7715      ||' ( '
7716      ||' SELECT '
7717      ||' iwm.mtl_organization_id, '
7718      ||' s.category_id, '
7719      ||' s.seq_dep_id, '
7720      ||' o.oprn_id, '
7721      ||' rd.resource_id, '
7722      ||' count(o.oprn_id) OVER (PARTITION BY rd.orgn_code,s.category_id,rd.resource_id) CNT '
7723      ||' FROM '
7724      ||'     ic_whse_mst'||at_apps_link||' iwm, '
7725      ||'     sy_orgn_mst'||at_apps_link||' sy, '
7726      ||'     cr_rsrc_dtl'||at_apps_link||' rd, '
7727      ||'     gmp_sequence_types'||at_apps_link||' s, '
7728      ||'     gmd_operation_resources'||at_apps_link||' r, '
7729      ||'     gmd_operation_activities'||at_apps_link||' a, '
7730      ||'     gmd_operations'||at_apps_link||' o '
7731      ||' WHERE o.oprn_id = a.oprn_id '
7732      ||' AND a.oprn_line_id = r.oprn_line_id '
7733      ||' AND rd.orgn_code = sy.orgn_code '
7734      ||' AND sy.resource_whse_code = iwm.whse_code '
7735      ||' AND a.sequence_dependent_ind = 1 '
7736      ||' AND r.prim_rsrc_ind = 1 '
7737      ||' AND r.resources = rd.resources '
7738      ||' AND o.oprn_id = s.oprn_id ' ;
7739 --     ||' AND iwm.mtl_organization_id in (1381,1382,1383,11159) '
7740      IF l_in_str_org  IS NOT NULL THEN
7741         Zero_tran := Zero_tran
7742         ||'   AND iwm.mtl_organization_id ' || l_in_str_org  ;
7743      END IF;
7744      Zero_tran := Zero_tran
7745      ||' UNION ALL '
7746      ||' SELECT '
7747      ||' rd.mtl_organization_id, '
7748      ||' s.category_id, '
7749      ||' s.seq_dep_id, '
7750      ||' o.oprn_id, '
7751      ||' rd.alt_resource_id, '
7752      ||' count(o.oprn_id) OVER (PARTITION BY rd.mtl_organization_id,s.category_id,rd.alt_resource_id) CNT '
7753      ||' FROM '
7754      ||'     gmp_sequence_types'||at_apps_link||' s, '
7755      ||'     gmd_operation_resources'||at_apps_link||' r, '
7756      ||'     gmd_operation_activities'||at_apps_link||' a, '
7757      ||'     gmd_operations'||at_apps_link||' o, '
7758      ||' (SELECT pcrd.resource_id prim_resource_id, '
7759      ||'         pcrd.resources prim_resources,  '
7760      ||'         acrd.resource_id alt_resource_id,  '
7761      ||'         acrd.resources alt_resources, '
7762      ||'         iwm.mtl_organization_id  '
7763      ||'                     FROM  ic_whse_mst'||at_apps_link||' iwm,  '
7764      ||'                           sy_orgn_mst'||at_apps_link||' sy,  '
7765      ||'                           cr_rsrc_dtl'||at_apps_link||' acrd,  '
7766      ||'                           cr_rsrc_dtl'||at_apps_link||' pcrd,  '
7767      ||'                           cr_ares_mst'||at_apps_link||' cam  '
7768      ||'                     WHERE cam.alternate_resource = acrd.resources  '
7769      ||'                       AND cam.primary_resource = pcrd.resources  '
7770      ||'                       AND acrd.orgn_code = sy.orgn_code  '
7771      ||'                       AND sy.resource_whse_code = iwm.whse_code  '
7772      ||'                       AND acrd.orgn_code = pcrd.orgn_code  ' ;
7773 --     ||'                       AND iwm.mtl_organization_id in (1381,1382,1383,11159) '
7774      IF l_in_str_org  IS NOT NULL THEN
7775         Zero_tran := Zero_tran
7776         ||'   AND iwm.mtl_organization_id ' || l_in_str_org  ;
7777      END IF;
7778 
7779      Zero_tran := Zero_tran
7780      ||'                       AND acrd.delete_mark = 0   '
7781      ||'                     ORDER BY pcrd.resource_id ) rd '
7782      ||' WHERE o.oprn_id = a.oprn_id '
7783      ||' AND a.oprn_line_id = r.oprn_line_id '
7784      ||' AND a.sequence_dependent_ind = 1 '
7785      ||' AND r.prim_rsrc_ind = 1 '
7786      ||' AND o.oprn_id = s.oprn_id '
7787      ||' AND r.resources = rd.prim_resources '
7788      ||' ORDER BY 1,2,4,3 '
7789      ||' ) b '
7790      ||' WHERE a.mtl_organization_id = b.mtl_organization_id '
7791      ||'   AND a.category_id = b.category_id '
7792      ||'   AND a.resource_id = b.resource_id '
7793      ||'   AND a.cnt = b.cnt '
7794      ||'   AND a.seq_dep_id <> b.seq_dep_id '
7795      ||'   AND a.cnt > 1 ' ;
7796 
7797      IF l_in_str_org  IS NOT NULL THEN
7798         Zero_tran := Zero_tran
7799         ||' AND  a.mtl_organization_id ' || l_in_str_org  ;
7800      END IF;
7801 
7802      EXECUTE IMMEDIATE Zero_tran USING l_profile, b_instance_id ;
7803     -- Fact Transitions (Alternate Resources are considered)
7804      stmt_no := 920 ;
7805      Fact_tran := ' INSERT INTO msc_st_setup_transitions ( '
7806      ||'   resource_id, '
7807      ||'   organization_id, '
7808      ||'   from_setup_id, '
7809      ||'   to_setup_id, '
7810      ||'   transition_time, '
7811      ||'   transition_penalty, '
7812      ||'   transition_uom, '
7813      ||'   sr_instance_id, '
7814      ||'   deleted_flag ) '
7815      ||' SELECT unique  '
7816      ||'   b.resource_id, '
7817      ||'   b.organization_id, '
7818      ||'   a.from_seq_dep_id, '
7819      ||'   a.to_seq_dep_id, '
7820      ||'   a.setup_time, '
7821      ||'   a.penalty_factor, '
7822      ||'   b.uom_code, '
7823      ||'   b.sr_instance_id, '
7824      ||'   b.deleted_flag '
7825      ||' FROM gmp_sequence_dependencies'||at_apps_link||' a, '
7826      ||'     (select unique RESOURCE_ID, ORGANIZATION_ID,'
7827      ||'       setup_id , deleted_flag, sr_instance_id, uom_code '
7828      ||'   from msc_st_operation_resources '
7829      ||'      WHERE sr_instance_id = :instance1 '
7830      ||'   and setup_id is not null  ) b '
7831      ||' WHERE ( b.setup_id = a.from_seq_dep_id OR '
7832      ||'         b.setup_id = a.to_seq_dep_id ) '  ;
7833      IF l_in_str_org  IS NOT NULL THEN
7834         Fact_tran := Fact_tran
7835         ||'   AND b.organization_id ' || l_in_str_org  ;
7836      END IF;
7837 
7838      EXECUTE IMMEDIATE Fact_tran USING b_instance_id ;
7839 
7840    -- Resource Setups (Alternate Resources are considered)
7841    stmt_no := 930 ;
7842    rsrc_setup := ' INSERT INTO msc_st_resource_setups ( '
7843     ||'   resource_id,      '
7844     ||'   organization_id,  '
7845     ||'   sr_instance_id,   '
7846     ||'   setup_id,         '
7847     ||'   setup_code,       '
7848     ||'   setup_description,'
7849     ||'   deleted_flag   ) '
7850     ||'SELECT unique  '
7851     ||'   mst.resource_id, '
7852     ||'   mst.organization_id, '
7853     ||'   mst.sr_instance_id, '
7854     ||'   gst.SEQ_DEP_ID , '
7855     ||'   mc.CONCATENATED_SEGMENTS, '
7856     ||'   mc.CONCATENATED_SEGMENTS, '
7857     ||'   2 '
7858     ||' FROM gmp_sequence_types'||at_apps_link||' gst, '
7859     ||'     MTL_CATEGORIES_B_KFV'||at_apps_link||' mc, '
7860     ||'    ( SELECT unique mt.organization_id, mt.resource_id, '
7861     ||'      mt.transition_uom,mt.sr_instance_id, '
7862     ||'      mt.deleted_flag , mt.from_setup_id, mt.to_setup_id '
7863     ||'      FROM mtl_parameters'||at_apps_link|| ' mp, '
7864     ||'       msc_st_setup_transitions mt  '
7865     ||'      WHERE mp.organization_id = mt.organization_id AND '
7866     ||'       mp.process_enabled_flag = '|| ''''||'Y'||'''' ||' )  mst '
7867     ||' WHERE gst.oprn_id <> -1 '
7868     ||'  AND mc.category_id = gst.category_id  '
7869     ||'  AND mst.sr_instance_id = :instance1 '
7870     ||'  AND (gst.seq_dep_id = mst.from_setup_id OR '
7871     ||'       gst.seq_dep_id = mst.to_setup_id )  ' ;
7872 
7873     IF l_in_str_org  IS NOT NULL THEN
7874       rsrc_setup := rsrc_setup
7875       ||'     AND mst.organization_id ' || l_in_str_org  ;
7876     END IF;
7877 
7878        EXECUTE IMMEDIATE rsrc_setup USING b_instance_id ;
7879 
7880         return_status := TRUE ;
7881   EXCEPTION
7882     WHEN NO_DATA_FOUND THEN
7883       NULL ;
7884       return_status := TRUE ;
7885     WHEN OTHERS THEN
7886        log_message('Write setups and Transitions Exception: '||sqlerrm||'-'||stmt_no);
7887         return_status := FALSE ;
7888 
7889 END write_setups_and_transitions ;
7890 
7891 /*
7892 REM+=========================================================================+
7893 REM| PROCEDURE NAME                                                          |
7894 REM|    write_step_dependency                                                |
7895 REM|                                                                         |
7896 REM| TYPE                                                                    |
7897 REM|    Private                                                              |
7898 REM|                                                                         |
7899 REM| USAGE                                                                   |
7900 REM|    This procedure inserts rows for step dependency                      |
7901 REM|                                                                         |
7902 REM| DESCRIPTION                                                             |
7903 REM|                                                                         |
7904 REM|                                                                         |
7905 REM| INPUT PARAMETERS                                                        |
7906 REM|    None                                                                 |
7907 REM|                                                                         |
7908 REM| OUTPUT PARAMETERS                                                       |
7909 REM|    None                                                                 |
7910 REM|                                                                         |
7911 REM| INPUT/OUTPUT PARAMETERS                                                 |
7912 REM|    None                                                                 |
7913 REM|                                                                         |
7914 REM| HISTORY                                                                 |
7915 REM|  06/16/2004   Namit Singhi created                                      |
7916 REM+=========================================================================+
7917 */
7918 
7919 PROCEDURE write_step_dependency (
7920   p_x_aps_fmeff_id   IN NUMBER
7921 )
7922 IS
7923 
7924   stpdep_start_index   INTEGER;
7925   stpdep_end_index     INTEGER;
7926   dep_index            NUMBER ;
7927 
7928 BEGIN
7929 
7930    dep_index := g_dep_index ;
7931 
7932 /* Get index for Routing Step Dependency */
7933   stpdep_start_index :=
7934       rtg_org_hdr_tab(effectivity.rtg_hdr_location).stpdep_start_loc ;
7935   stpdep_end_index :=
7936       rtg_org_hdr_tab(effectivity.rtg_hdr_location).stpdep_end_loc ;
7937 
7938   IF ((stpdep_start_index > 0) AND (stpdep_end_index > 0) AND (stpdep_end_index >= stpdep_start_index)) THEN
7939       FOR stpdp_cnt IN stpdep_start_index..stpdep_end_index
7940       LOOP
7941           opr_stpdep_frm_seq_id(dep_index) :=  gmp_opr_stpdep_tbl(stpdp_cnt).x_dep_routingstep_id;
7942           opr_stpdep_to_seq_id(dep_index) :=  gmp_opr_stpdep_tbl(stpdp_cnt).x_routingstep_id;
7943           opr_stpdep_routing_sequence_id(dep_index) := p_x_aps_fmeff_id ;
7944           opr_stpdep_dependency_type(dep_index) := gmp_opr_stpdep_tbl(stpdp_cnt).dep_type;
7945           opr_stpdep_sr_instance_id(dep_index) := b_instance_id ;
7946           opr_stpdep_min_time_offset(dep_index) := gmp_opr_stpdep_tbl(stpdp_cnt).standard_delay;
7947           opr_stpdep_max_time_offset(dep_index) := gmp_opr_stpdep_tbl(stpdp_cnt).max_delay;
7948           opr_stpdep_trans_pct(dep_index) := gmp_opr_stpdep_tbl(stpdp_cnt).transfer_pct;
7949           opr_stpdep_frm_op_seq_num(dep_index) := gmp_opr_stpdep_tbl(stpdp_cnt).dep_routingstep_no;
7950           opr_stpdep_to_op_seq_num(dep_index) := gmp_opr_stpdep_tbl(stpdp_cnt).routingstep_no;
7951           opr_stpdep_app_to_chrg(dep_index) := gmp_opr_stpdep_tbl(stpdp_cnt).chargeable_ind;
7952           opr_stpdep_organization_id(dep_index) := effectivity.organization_id;
7953           dep_index := dep_index + 1;
7954       END LOOP;  /* Step Dependency loop */
7955   END IF;
7956     g_dep_index := dep_index ;
7957 
7958 END write_step_dependency ;
7959 
7960 /*
7961 REM+=========================================================================+
7962 REM| FUNCTION NAME                                                           |
7963 REM|    enh_bsearch_stpno                                                    |
7964 REM|                                                                         |
7965 REM| TYPE                                                                    |
7966 REM|    Private                                                              |
7967 REM|                                                                         |
7968 REM| USAGE                                                                   |
7969 REM|    This function returns the location in mat_assoc_tab                  |
7970 REM|    for given recipe, formula and formulaline_id                         |
7971 REM|                                                                         |
7972 REM| DESCRIPTION                                                             |
7973 REM|                                                                         |
7974 REM|                                                                         |
7975 REM| INPUT PARAMETERS                                                        |
7976 REM|    l_formula_id   IN NUMBER                                             |
7977 REM|    l_recipe_id IN NUMBER                                                |
7978 REM|    l_item_id IN NUMBER                                                  |
7979 REM|                                                                         |
7980 REM| OUTPUT PARAMETERS                                                       |
7981 REM|    INTEGER - Location in mat_assoc_tab                                  |
7982 REM|                                                                         |
7983 REM| INPUT/OUTPUT PARAMETERS                                                 |
7984 REM|    None                                                                 |
7985 REM|                                                                         |
7986 REM| HISTORY                                                                 |
7987 REM|  06/16/2004   Namit Singhi created                                      |
7988 REM+=========================================================================+
7989 */
7990 
7991 FUNCTION enh_bsearch_stpno ( l_formula_id   IN NUMBER,
7992                              l_recipe_id    IN NUMBER,
7993                              l_item_id      IN NUMBER)
7994 		RETURN INTEGER IS
7995 
7996 top     INTEGER ;
7997 bottom  INTEGER ;
7998 mid     INTEGER ;
7999 loop_direction NUMBER;
8000 ret_loc     INTEGER ;
8001 formula_start INTEGER ;
8002 
8003 BEGIN
8004      top    := 1;
8005      bottom := material_assocs_size ;
8006      mid    := -1 ;
8007      ret_loc   := -1 ;
8008      loop_direction := 0;
8009      formula_start := -1;
8010 
8011    WHILE  (top <= bottom )
8012     LOOP
8013      mid := top + ( ( bottom - top ) / 2 );
8014 --
8015      IF l_formula_id < mat_assoc_tab(mid).formula_id THEN
8016 	bottom := mid - 1 ;
8017      ELSIF l_formula_id > mat_assoc_tab(mid).formula_id THEN
8018 	top := mid + 1 ;
8019      ELSE
8020 	ret_loc := mid ;
8021         EXIT;
8022      END IF ;
8023     END LOOP;
8024 
8025     IF ret_loc > 0 THEN
8026         IF ret_loc = 1 THEN
8027             formula_start := 1 ;
8028         ELSE  /* ret_loc > 1*/
8029         LOOP
8030             ret_loc := ret_loc - 1;
8031             IF ret_loc = 1 THEN
8032                 formula_start := 1 ;
8033                 EXIT;
8034             ELSIF mat_assoc_tab(ret_loc).formula_id <> l_formula_id THEN
8035                 formula_start := ret_loc + 1;
8036                 EXIT;
8037             END IF;
8038         END LOOP;
8039         END IF;
8040     ELSE
8041         RETURN -1 ;
8042     END IF;
8043 
8044     ret_loc := formula_start;
8045 
8046     WHILE(ret_loc <= material_assocs_size) LOOP
8047     IF(mat_assoc_tab(ret_loc).formula_id > l_formula_id) THEN
8048         RETURN -1;
8049     ELSIF mat_assoc_tab(ret_loc).recipe_id = l_recipe_id AND
8050     mat_assoc_tab(ret_loc).item_id = l_item_id THEN
8051         RETURN ret_loc;
8052     ELSE
8053         ret_loc := ret_loc + 1;
8054     END IF;
8055     END LOOP;
8056 
8057     RETURN -1;
8058 
8059 EXCEPTION WHEN OTHERS THEN
8060    log_message(' Error in MSC_CL_GMP_UTILITY.enh_bsearch_stpno: '||SQLERRM);
8061    RETURN -1;
8062 END enh_bsearch_stpno ;
8063 
8064 /*
8065 REM+=========================================================================+
8066 REM| PROCEDURE NAME                                                          |
8067 REM|    bsearch_unique                                                       |
8068 REM|                                                                         |
8069 REM| DESCRIPTION                                                             |
8070 REM|    This procedure finds the unique setup id for the combination passed  |
8071 REM|                                                                         |
8072 REM| HISTORY                                                                 |
8073 REM|  02/10/2006 B4918786 Rajesh Patangya Rewrite for SDS Enhancement        |
8074 REM|                                                                         |
8075 REM+=========================================================================+
8076 */
8077 PROCEDURE bsearch_unique (p_resource_id   IN NUMBER ,
8078                           p_category_id   IN NUMBER ,
8079                           p_setup_id      OUT NOCOPY NUMBER
8080                          ) IS
8081 i  INTEGER;
8082 BEGIN
8083   i := 1 ;
8084    FOR i IN 1..SD_INDEX LOOP
8085      IF  (sds_tab(i).resource_id = p_resource_id) AND
8086          (sds_tab(i).category_id = p_category_id) THEN
8087              p_setup_id := sds_tab(i).setup_id ;
8088              EXIT ;
8089      ELSE
8090              p_setup_id := NULL ;
8091      END IF ;
8092    END LOOP;
8093 EXCEPTION
8094    WHEN OTHERS THEN
8095    log_message('Error in bsearch_unique ' || sqlerrm);
8096    p_setup_id := NULL ;
8097 END bsearch_unique ;
8098 
8099 
8100 /*
8101 REM+=========================================================================+
8102 REM| FUNCTION NAME                                                           |
8103 REM|    get_profile_value                                                    |
8104 REM| DESCRIPTION                                                             |
8105 REM|    This procedure is created to get the profile value from the source or|
8106 REM|     destination server basing on the dblink                             |
8107 REM| HISTORY                                                                 |
8108 REM|    Vpedarla B6710684 created this procedure                             |
8109 REM+=========================================================================+
8110 */
8111 FUNCTION get_profile_value(
8112   profile_name            IN VARCHAR2,
8113   pdblink                 IN VARCHAR2) return VARCHAR2 IS
8114   uom_code_dblink         VARCHAR2(20000) ; /* bug: 6710684 Vpedarla */
8115   uom_code_ref            ref_cursor_typ ;
8116   l_gmp_um_code           VARCHAR2(32767);
8117 BEGIN
8118      LOG_MESSAGE(' get_profile_value called for profile '
8119                 ||profile_name||' with dblink '||pdblink);
8120 
8121      uom_code_dblink :=
8122        'SELECT fnd_profile.VALUE'||pdblink||'('''||profile_name||''')'||' FROM dual ';
8123 
8124      OPEN uom_code_ref for uom_code_dblink ;
8125        FETCH uom_code_ref INTO l_gmp_um_code;
8126      CLOSE uom_code_ref;
8127      RETURN l_gmp_um_code ;
8128 EXCEPTION
8129    WHEN OTHERS THEN
8130    log_message('Error in get_profile_value ' || sqlerrm);
8131    RETURN NULL ;
8132 END get_profile_value;
8133 
8134 
8135 -- for future use
8136 FUNCTION GMP_BOM_UTILITY1_R10
8137             (
8138                           p_dblink      IN VARCHAR2,
8139                           p_delimiter   IN VARCHAR2,
8140                           p_instance    IN INTEGER,
8141                           p_run_date    IN DATE,
8142                           p_num1        IN NUMBER,
8143                           p_num2        IN NUMBER,
8144                           p_num3        IN NUMBER,
8145                           p_num4        IN NUMBER,
8146                           p_varchar1    IN VARCHAR2,
8147                           p_varchar2    IN VARCHAR2,
8148                           p_varchar3    IN VARCHAR2,
8149                           p_varchar4    IN VARCHAR2
8150             ) RETURN INTEGER IS
8151 BEGIN
8152     return 0;
8153 END GMP_BOM_UTILITY1_R10;
8154 
8155 FUNCTION GMP_BOM_UTILITY2_R10
8156             (
8157                           p_dblink      IN VARCHAR2,
8158                           p_delimiter   IN VARCHAR2,
8159                           p_instance    IN INTEGER,
8160                           p_run_date    IN DATE,
8161                           p_num1        IN NUMBER,
8162                           p_num2        IN NUMBER,
8163                           p_num3        IN NUMBER,
8164                           p_num4        IN NUMBER,
8165                           p_varchar1    IN VARCHAR2,
8166                           p_varchar2    IN VARCHAR2,
8167                           p_varchar3    IN VARCHAR2,
8168                           p_varchar4    IN VARCHAR2
8169             ) RETURN INTEGER IS
8170 BEGIN
8171     return 0;
8172 END GMP_BOM_UTILITY2_R10;
8173 
8174 PROCEDURE GMP_BOM_PROC1_R10
8175             (
8176                           p_dblink      IN VARCHAR2,
8177                           p_delimiter   IN VARCHAR2,
8178                           p_instance    IN INTEGER,
8179                           p_run_date    IN DATE,
8180                           p_num1        IN NUMBER,
8181                           p_num2        IN NUMBER,
8182                           p_num3        IN NUMBER,
8183                           p_num4        IN NUMBER,
8184                           p_varchar1    IN VARCHAR2,
8185                           p_varchar2    IN VARCHAR2,
8186                           p_varchar3    IN VARCHAR2,
8187                           p_varchar4    IN VARCHAR2,
8188                           return_status  OUT NOCOPY BOOLEAN
8189             ) IS
8190 BEGIN
8191     return_status := TRUE;
8192 END GMP_BOM_PROC1_R10;
8193 
8194 PROCEDURE GMP_BOM_PROC2_R10
8195             (
8196                           p_dblink      IN VARCHAR2,
8197                           p_delimiter   IN VARCHAR2,
8198                           p_instance    IN INTEGER,
8199                           p_run_date    IN DATE,
8200                           p_num1        IN NUMBER,
8201                           p_num2        IN NUMBER,
8202                           p_num3        IN NUMBER,
8203                           p_num4        IN NUMBER,
8204                           p_varchar1    IN VARCHAR2,
8205                           p_varchar2    IN VARCHAR2,
8206                           p_varchar3    IN VARCHAR2,
8207                           p_varchar4    IN VARCHAR2,
8208                           return_status  OUT NOCOPY BOOLEAN
8209               ) IS
8210 BEGIN
8211     return_status := TRUE;
8212 END GMP_BOM_PROC2_R10;
8213 
8214 /*======================OPM BOM Package End ===================================*/
8215 
8216 /***********************************************************************
8217 *
8218 *   NAME
8219 *	bsearch_rsrc_chg
8220 *
8221 *   DESCRIPTION
8222 *	This function will search through the resource charges PL/SQL table
8223 *       using Binary Search.
8224 *
8225 *       IF  p_batch_id Found IN  stp_chg_tbl THEN
8226 *         Return the last record location for p_batch_id in stp_chg_tbl.
8227 *       ELSE if p_batch_id NOT Found IN the stp_chg_tbl THEN
8228 *          Return -1
8229 *       END IF;
8230 *
8231 *   HISTORY
8232 *	Navin Sinha
8233 ************************************************************************/
8234 FUNCTION bsearch_rsrc_chg ( p_batch_id IN NUMBER)
8235 	 RETURN INTEGER IS
8236 
8237 top         INTEGER ;
8238 bottom      INTEGER ;
8239 mid         INTEGER ;
8240 ret_loc     INTEGER ;
8241 BEGIN
8242      top    := 1;
8243      bottom := stp_chg_tbl.count;
8244      mid    := -1 ;
8245      ret_loc   := -1 ;
8246 
8247    WHILE  (top <= bottom )
8248     LOOP
8249      mid := top + ( ( bottom - top ) / 2 );
8250 
8251      IF p_batch_id < stp_chg_tbl(mid).wip_entity_id THEN
8252 	bottom := mid -1 ;
8253      ELSIF p_batch_id > stp_chg_tbl(mid).wip_entity_id THEN
8254 	top := mid + 1 ;
8255      ELSE
8256 	ret_loc := mid ;
8257               EXIT;
8258      END IF ;
8259     END LOOP; /* (top <= bottom ) */
8260 
8261     -- Identify the location of the last record for the currently processed p_batch_id in stp_chg_tbl.
8262     IF ret_loc > 0 AND ret_loc <= stp_chg_tbl.count THEN
8263       LOOP
8264        IF ret_loc = stp_chg_tbl.count THEN
8265           -- Pointer is at last record of the array.
8266           Return ret_loc;
8267        END IF ;
8268 
8269        ret_loc :=  ret_loc + 1;
8270        IF p_batch_id <> stp_chg_tbl(ret_loc).wip_entity_id THEN
8271           -- Missmatch occurred hence return the previous location.
8272           Return (ret_loc - 1);
8273        END IF ;
8274       END LOOP;
8275     ELSE
8276        -- Not found
8277        Return -1 ;
8278     END IF ;
8279 
8280 END bsearch_rsrc_chg ;
8281 
8282 /* **********************************************************************
8283 *   NAME
8284 *	inst_stp_chg_tbl
8285 *
8286 *   DESCRIPTION
8287 *       Inserts Data into step charge staging table.
8288 *   HISTORY
8289 *       B4761946, 20-DEC-2005 Rajesh Patangya Changed the while loop logic
8290 ************************************************************************/
8291 
8292 PROCEDURE inst_stp_chg_tbl(pinstance_id IN NUMBER, p_batch_loc IN NUMBER)
8293 IS
8294 
8295 rsrc_chg_loc NUMBER;
8296 
8297 BEGIN
8298   -- Locate the batch in Resource Charge PL/SQL table, i.e stp_chg_tbl
8299   -- rsrc_chg_loc will be -1 if NOT found OR it will point to last record
8300   -- location for x_batch_id in stp_chg_tbl.
8301   rsrc_chg_loc := bsearch_rsrc_chg(rsrc_tab(p_batch_loc).x_batch_id);
8302 
8303   -- IF resource charges found then process....
8304   IF rsrc_chg_loc > 0 THEN
8305      IF prod_tab(p).firmed_ind = 1 AND
8306          stp_chg_tbl(rsrc_chg_loc).charge_start_dt_time IS NULL AND
8307          stp_chg_tbl(rsrc_chg_loc).charge_end_dt_time IS NULL THEN
8308             -- APS decoded value as per
8309             -- DECODE(rsrc_tab(p_batch_loc).scale_type,0,2,1,1,2,3);
8310             rsrc_tab(p_batch_loc).scale_type := 1;
8311      ELSE
8312       -- Insert all the resource charge records untill the batch_id,
8313       -- batchstep_id and resource_id
8314       -- are same as currently processed resource record.
8315      /* B4761946, Rajesh Patangya Changed the while loop logic */
8316       LOOP
8317   /*
8318       log_message(rsrc_tab(p_batch_loc).x_batch_id || ' -- ' ||
8319                   rsrc_tab(p_batch_loc).batchstep_id || ' -- ' ||
8320                   rsrc_tab(p_batch_loc).x_resource_id || ' -- ' ||
8321              rsrc_chg_loc || ' -- ' ||
8322              stp_chg_tbl(rsrc_chg_loc).wip_entity_id   || ' -- ' ||
8323       ((stp_chg_tbl(rsrc_chg_loc).operation_seq_id -1)/2) || ' --'||
8324              stp_chg_tbl(rsrc_chg_loc).resource_id );
8325 */
8326        IF (rsrc_tab(p_batch_loc).x_batch_id =
8327              stp_chg_tbl(rsrc_chg_loc).wip_entity_id) AND
8328           (rsrc_tab(p_batch_loc).batchstep_id =
8329              ((stp_chg_tbl(rsrc_chg_loc).operation_seq_id -1)/2)) AND
8330           (rsrc_tab(p_batch_loc).x_resource_id =
8331              stp_chg_tbl(rsrc_chg_loc).resource_id) THEN
8332 
8333 
8334     /*  log_message(rsrc_tab(p_batch_loc).x_batch_id || ' -- ' ||
8335              stp_chg_tbl(rsrc_chg_loc).operation_seq_id || ' --'||
8336              stp_chg_tbl(rsrc_chg_loc).resource_id || ' --'|| rsrc_chg_loc || '--' ||
8337              stp_chg_tbl(rsrc_chg_loc).wip_entity_id );  */
8338 
8339 	chg_res_index := chg_res_index + 1 ;
8340         stp_chg_resource_id(chg_res_index) := stp_chg_tbl(rsrc_chg_loc).resource_id ;
8341         stp_chg_organization_id(chg_res_index) := stp_chg_tbl(rsrc_chg_loc).organization_id ;
8342         stp_chg_department_id(chg_res_index) := ((v_orgn_id * 2) + 1) ;
8343         stp_chg_wip_entity_id(chg_res_index) := stp_chg_tbl(rsrc_chg_loc).wip_entity_id ;
8344         stp_chg_operation_seq_id(chg_res_index) := stp_chg_tbl(rsrc_chg_loc).operation_seq_id ;
8345         stp_chg_operation_seq_no(chg_res_index) := stp_chg_tbl(rsrc_chg_loc).operation_seq_no ;
8346         stp_chg_resource_seq_num(chg_res_index) := stp_chg_tbl(rsrc_chg_loc).resource_seq_num ;
8347         stp_chg_charge_num(chg_res_index) := stp_chg_tbl(rsrc_chg_loc).charge_num ;
8348         stp_chg_charge_quanitity(chg_res_index) := stp_chg_tbl(rsrc_chg_loc).charge_quantity ;
8349         stp_chg_charge_start_dt_time(chg_res_index) := stp_chg_tbl(rsrc_chg_loc).charge_start_dt_time ;
8350         stp_chg_charge_end_dt_time(chg_res_index) := stp_chg_tbl(rsrc_chg_loc).charge_end_dt_time ;
8351         stp_instance_id (chg_res_index) := pinstance_id ;
8352        END IF;
8353 
8354        rsrc_chg_loc := rsrc_chg_loc - 1 ;
8355 
8356        IF ((rsrc_chg_loc = 0) OR (rsrc_tab(p_batch_loc).x_batch_id <>
8357                 stp_chg_tbl(rsrc_chg_loc).wip_entity_id)) THEN
8358                 -- No more records to process in Step Charge PL/SQL table.
8359            EXIT;
8360        END IF;
8361       END LOOP;
8362      END IF;
8363   END IF;  /*  rsrc_chg_loc > 0 */
8364 END inst_stp_chg_tbl;
8365 
8366 /***********************************************************************
8367 *
8368 *   NAME
8369 *	Enh_bsearch_alternate_rsrc
8370 *
8371 *
8372 *       IF  pprim_resource_id Found IN  prod_alt_rsrc_tab THEN
8373 *         Return the first record location for pprim_resource_id in prod_alt_rsrc_tab.
8374 *       ELSE IF pprim_resource_id NOT Found IN  prod_alt_rsrc_tab THEN
8375 *          Return -1
8376 *       END IF;
8377 *
8378 *   DESCRIPTION
8379 *	This function will search throught the alternate resource PL/SQL table
8380 *       using Binary Search. It is a modified Binary Search, as after finding a hit
8381 *       it loops back to find the first row that gave the hit.
8382 *   HISTORY
8383 *	Navin Sinha
8384 ************************************************************************/
8385 
8386 FUNCTION Enh_bsearch_alternate_rsrc ( pprim_resource_id   IN NUMBER)
8387 		RETURN INTEGER IS
8388 
8389 top     INTEGER ;
8390 bottom  INTEGER ;
8391 mid     INTEGER ;
8392 
8393 ret_loc     INTEGER ;
8394 BEGIN
8395      top    := 1;
8396      bottom := alt_prod_size ;
8397      mid    := -1 ;
8398      ret_loc   := -1 ;
8399 
8400    WHILE  (top <= bottom )
8401     LOOP
8402      mid := top + ( ( bottom - top ) / 2 );
8403 
8404      IF pprim_resource_id < prod_alt_rsrc_tab(mid).prim_resource_id THEN
8405 	bottom := mid -1 ;
8406      ELSIF pprim_resource_id > prod_alt_rsrc_tab(mid).prim_resource_id THEN
8407 	top := mid + 1 ;
8408      ELSE
8409 	ret_loc := mid ;
8410               EXIT;
8411      END IF ;
8412     END LOOP; /* (top <= bottom ) */
8413 
8414     -- Bring back the pointer to the first location from where the Primary resource data starts.
8415     IF ret_loc >= 1 THEN
8416       LOOP
8417        IF ret_loc = 1 THEN
8418           -- Pointer is at first location of the array.
8419           Return ret_loc;
8420        END IF ;
8421 
8422        ret_loc :=  ret_loc - 1;
8423        IF pprim_resource_id <> prod_alt_rsrc_tab(ret_loc).prim_resource_id THEN
8424           -- Missmatch occurred hence return the previous location.
8425           Return (ret_loc +1);
8426        END IF ;
8427       END LOOP;
8428     ELSE
8429       -- Not found
8430       Return -1 ;
8431     END IF ;  /* ret_loc >= 1 */
8432 
8433 END Enh_bsearch_alternate_rsrc ;
8434 
8435 /***********************************************************************
8436 *
8437 *   NAME
8438 *     production_orders
8439 *
8440 *   DESCRIPTION
8441 *     This procedure will take the production orders, batches and FPOs,
8442 *     that have valid item/warehouse definitions as defined in the
8443 *     the plant/whse eff and write them to the table msc_std_demands and \
8444 *     msc_st_supplies. The products and byproducts will be written as
8445 *     supplies and ingredients as demands
8446 *   HISTORY
8447 *     M Craig
8448 *   04/03/2000 - Using mtl_organization_id instead of organization_id from
8449 *              - sy_orgn_mst , Bug# 1252322
8450 *   Sridhar 31-DEC-01 B2159482 - Added Alcoa Cursor Changes to the
8451 *                                latest version of the package
8452 *   Sridhar 15-JAN-02 B1992371   Modified the Cursor with GME Changes
8453 *   Sridhar 27-FEB-2002 B2239948 Added correction for poc_ind comparisons
8454 *   Sridhar 15-MAY-2002 B2363117 Added nvl Statement for If statements with
8455 *                                Actual_cmplt_date and Start Date
8456 *   Sridhar 10-JUL-2002 B2383692 Added code to take care of the last record
8457 *   Sridhar 10-JUL-2002 B1522576 Added code to differentiate FPO Batches
8458 *   Sridhar 19-MAR-2003 B2858929 Added Code to take resolve the Bug
8459 *                                Resource Seq is incremented only if the
8460 *                                activity is Changed
8461 *   Sridhar 31-MAR-2003 B2882286 Ensuring the Order so that if the last batch
8462 *                                resource requirements are written
8463 *   Sridhar 30-APR-2003 B2919303 Added Operation Seq Number in msc_st_supplies
8464 *                                and in msc_st_demands table
8465 *   Sridhar 09-MAY-2003 B2919303 Added line_no and included in order by clause
8466 *   Sridhar 12-MAY-2003 B2953953 Populated BY_PRODUCT_USING_ASSY_ID with
8467 *                                product_line which is the assembly_item_id
8468 *   Navin   21-APR-2003 B3577871 ST:OSFME2: collections failing in planning data pull.
8469 *                                Added handling of NO_DATA_FOUND Exception.
8470 *                                And return the return_status as TRUE.
8471 *   Sulipta 25-JAN-2006 B4612203 Populating supply_type as 1 in
8472 *                                MSC_ST_RESOURCE_REQUIREMENTS table
8473 ************************************************************************/
8474 
8475 PROCEDURE production_orders(
8476   pdblink        IN  VARCHAR2,
8477   pinstance_id   IN  NUMBER,
8478   prun_date      IN  DATE,
8479   pdelimiter     IN  VARCHAR2,
8480   return_status  IN OUT NOCOPY BOOLEAN)
8481 
8482 IS
8483 
8484 /* Defining the dynamic cursors to be used to retrieve data later. Production
8485    details, resource details, resource warehouse, and warehouse organization */
8486 
8487   TYPE gmp_cursor_typ IS REF CURSOR;
8488   c_prod_dtl           gmp_cursor_typ;
8489   rsrc_dtl             gmp_cursor_typ;
8490   rsrc_whse            gmp_cursor_typ;
8491   cur_alt_resource     gmp_cursor_typ; /* NAVIN :- Alternate Resource */
8492   cur_rs_intance       gmp_cursor_typ; /* NAVIN :- Resource Intance */
8493   c_chg_cursor         gmp_cursor_typ; /* NAVIN :- Resource Charges */
8494   rsrc_uoms_cur        gmp_cursor_typ; /* Sowmya - As per latest FDD Changes */
8495   uom_code_ref         gmp_cursor_typ; /* NAMIT - UOM Class */
8496 
8497   v_prod_cursor        VARCHAR2(32000) ;
8498   v_rsrc_cursor        VARCHAR2(32000) ;
8499   sql_stmt	       VARCHAR2(32000) ;
8500   uom_code_cursor      VARCHAR2(32000);
8501 
8502   l_charges_remaining  NUMBER;
8503   res_whse             BOOLEAN ;
8504   res_whse_id          PLS_INTEGER ;
8505   supply_type          PLS_INTEGER ;
8506   old_batch_id         PLS_INTEGER;
8507   product_line         PLS_INTEGER ;
8508   opm_product_line     NUMBER ;
8509   prod_line_id         NUMBER ;
8510   prod_plant           VARCHAR2(4) ;
8511   order_no             VARCHAR2(37) ;
8512   v_inflate_wip        NUMBER ;
8513   found_mtl            NUMBER ;
8514   i                    PLS_INTEGER ;
8515   old_step_no          NUMBER ;
8516   prod_count           PLS_INTEGER ;
8517   resource_count       PLS_INTEGER ;
8518   stp_chg_count        PLS_INTEGER ;
8519   /* B1224660 added locals to develop resource sequence numbers */
8520   v_resource_usage     NUMBER ;
8521   v_res_seq            NUMBER ;
8522   v_schedule_flag      PLS_INTEGER ;
8523   v_parent_seq_num     NUMBER ;
8524   v_seq_dep_usage      NUMBER ; /* NAVIN :- Sequence Dependency */
8525   found_chrg_rsrc      NUMBER ; /* NAVIN :- Chargeable Resource */
8526   chrg_activity        NUMBER ; /* NAVIN :- Chargeable Activity */
8527   v_rsrc_cnt           PLS_INTEGER ;
8528   v_start_date         DATE ;
8529   v_end_date           DATE ;
8530   old_activity         NUMBER ;
8531   v_alternate          NUMBER ; /* NAVIN :- added for alternate resource */
8532   alternate_rsrc_loc   NUMBER ; /* NAVIN :- added for alternate resource */
8533   alt_cnt              NUMBER ; /* NAVIN :- added for alternate resource */
8534   row_count            NUMBER ;
8535   start_loc            NUMBER ;
8536   l_gmp_um_code        VARCHAR2(25);
8537   l_gmp_uom_class      VARCHAR2(10); /* UOM Class */
8538   v_max_rsrcs          NUMBER; --for collecting the max resources
8539   v_activity_group_id  PLS_INTEGER ;   /* B3995361 rpatangy */
8540   mk_alt_grp           NUMBER ;   /* B3995361 rpatangy */
8541 
8542   /* Bug:6030499 Vpedarla following declarations extra in nonps code */
8543 
8544   v_min_xfer_qty NUMBER ;
8545   l_process_seq_id      PLS_INTEGER ; -- B6795244
8546 
8547 BEGIN
8548 
8549 /* Bug: 6030499 Vpedarla added profile verification */
8550 /* Get the profile value for collecting PS reatled data from destination */
8551 
8552   LOG_MESSAGE(' production_orders started ');
8553 
8554     collect_ps_data := TRUE;
8555 
8556   /* Initialize the values */
8557   v_activity_group_id  := 0;     /* B3995361 rpatangy */
8558   mk_alt_grp           := 0 ;    /* B3995361 rpatangy */
8559   v_prod_cursor        := NULL;
8560   v_rsrc_cursor        := NULL;
8561 
8562   res_whse             := FALSE;
8563   res_whse_id          := 0;
8564   supply_type          := 0;
8565   product_line         := 0;
8566   opm_product_line     := 0;
8567   prod_line_id         := 0;
8568   prod_plant           := NULL;
8569   order_no             := NULL;
8570   v_inflate_wip        := 0;
8571   found_mtl            := 0;
8572   i                    := 0;
8573   p                    := 0;
8574   r                    := 0;
8575   old_step_no          := 0;
8576   prod_count           := 1;
8577   resource_count       := 1;
8578   stp_chg_count        := 1;
8579   v_min_xfer_qty       := 0; -- Bug:6030499 Vpedarla
8580 
8581   /* B1224660 added locals to develop resource sequence numbers */
8582   v_resource_usage     := 0;
8583   v_res_seq            := 0;
8584   v_schedule_flag      := 0;
8585   v_parent_seq_num     := 0;
8586   v_seq_dep_usage      := 0; /* NAVIN :- Sequence Dependency */
8587   found_chrg_rsrc      := 0; /* NAVIN :- Chargeable Resource */
8588   chrg_activity        := -1; /* NAVIN :- Chargeable Activity */
8589   chg_res_index        := 0; /* NAVIN :- Resource Charges */
8590   v_rsrc_cnt           := 0;
8591   v_start_date         := NULL;
8592   v_end_date           := NULL;
8593   old_activity         := 0;
8594   v_alternate          := 0; /* NAVIN :- added for alternate resource */
8595   alternate_rsrc_loc   := 0; /* NAVIN :- added for alternate resource */
8596   alt_cnt              := 0; /* NAVIN :- added for alternate resource */
8597 
8598   d_index              := 0 ;
8599   s_index              := 0 ;
8600   rr_index             := 0 ;
8601   arr_index            := 0 ;
8602   jo_index             := 0;
8603   gprod_size           := 0 ;
8604   grsrc_size           := 0;
8605   g_rsrc_cnt           := 1;
8606   si_index             := 1;
8607   inst_indx            := 0;
8608   row_count            := 1; /* NAVIN :- Maintains the row count. From set of repetitive rows, only one row is inserted. */
8609   start_loc            := 1;
8610   l_res_inst_process   := 0;
8611   v_max_rsrcs          := 0;
8612   l_process_seq_id     := 0 ; -- B6795244
8613 
8614   IF return_status THEN
8615     v_cp_enabled := TRUE;
8616   ELSE
8617     v_cp_enabled := FALSE;
8618   END IF;
8619 
8620     /* populate the org_string */
8621    IF MSC_CL_GMP_UTILITY.org_string(pinstance_id) THEN
8622         NULL ;
8623      ELSE
8624         RAISE invalid_string_value  ;
8625      END IF;
8626 
8627     /* Disable Formula Security Functionality */
8628 
8629   v_sql_stmt := 'BEGIN '
8630     || ' gmd_p_fs_context.set_additional_attr' || pdblink
8631     || ';END;'   ;
8632   EXECUTE IMMEDIATE v_sql_stmt ;
8633 
8634    BEGIN  -- B6795244
8635    select NVL(max(process_seq_id),0) into l_process_seq_id  from msc_st_supplies
8636         where sr_instance_id = pinstance_id ;
8637     log_message('production_orders pinstance_id = ' || pinstance_id || ' AND l_process_seq_id = ' || l_process_seq_id );
8638    EXCEPTION
8639      WHEN no_data_found then
8640         l_process_seq_id := 0 ;
8641      WHEN others then
8642         l_process_seq_id := 0 ;
8643     END; -- B6795244
8644 
8645   /* Get the profile value for inflating usage by the utilization and
8646      efficiency from destination */
8647   IF NVL(fnd_profile.value('MSC_INFLATE_WIP') ,'N')= 'N' THEN
8648     v_inflate_wip := 0 ;
8649   ELSE
8650     v_inflate_wip := 1 ;
8651   END IF;
8652 
8653   /* NAMIT UOM Changes */
8654  /* bug:6710684 Vpedarla made changes to fetch the profile value from source server*/
8655 --  l_gmp_um_code   := fnd_profile.VALUE('SY$UOM_HOURS'); /* OPM UOM */
8656    l_gmp_um_code   := get_profile_value('SY$UOM_HOURS', pdblink );
8657 
8658   IF l_gmp_um_code IS NOT NULL THEN
8659 /* Get the UOM code and UOM Class corresponding to "GMP: UOM for Hour" Profile */
8660      uom_code_cursor :=
8661                       ' select um_type '
8662                       ||' from sy_uoms_mst'||pdblink
8663                       ||' where um_code = :gmp_um_code ';
8664 
8665      OPEN uom_code_ref FOR uom_code_cursor USING l_gmp_um_code;
8666      FETCH uom_code_ref INTO l_gmp_uom_class;
8667      CLOSE uom_code_ref;
8668   ELSE
8669      RAISE invalid_gmp_uom_profile  ;
8670   END IF;
8671   IF (l_gmp_uom_class IS NULL) THEN
8672      RAISE invalid_gmp_uom_profile  ;
8673   END IF;
8674 
8675 
8676   /* B2919303 - The following cursor has been modified to include
8677      batchstep_no for material txns which has release type as 3 ( auto by step )
8678      , if the rows are not release type as 3 then batchstep is taken as 0
8679   */
8680   /* B2953953 Added two temporary columns so that we can get the correct
8681      Order , Note that the Line_type is decoded so that Line_type - prod
8682      becomes 3 and is ordered first and product row is made into line_no 0
8683   */
8684   /* B2964633 - Added t.trans_date also in the Order by Clause to make sure
8685      Product comes in the first row, because product is always in the last
8686      step and therefore ordering by trans_date in the descending order */
8687   /* B3054460 - OPM/APS TO CATER FOR CHANGE TO TIME PHASED PLANNING
8688      OF MANUAL CONSUMPTION TYPE, - Considered release_type 1 also
8689   */
8690 
8691   /* Bug 4774975 -- FRUTAROM INDUSTRIES LTD, org string check should be
8692      removed so that all the supplies and demand belongs to other warehouse
8693      should be sent to APS in resource warehouse */
8694 
8695   v_prod_cursor := 'SELECT /*+ DRIVING_SITE(h) DRIVING_SITE(d) DRIVING_SITE(gbsi) DRIVING_SITE(gbs) '
8696       ||'  DRIVING_SITE(v) DRIVING_SITE(iwm) DRIVING_SITE(t) DRIVING_SITE(i) */ '
8697       || '   h.batch_no,'
8698       || '   h.plant_code,'
8699       || '   h.batch_id,'
8700       || '   ((h.batch_id * 2) + 1), '
8701       || '   h.wip_whse_code,'
8702       || '   iwm.mtl_organization_id, '
8703       || '   h.routing_id,'
8704       || '   h.plan_start_date, '
8705       || '   h.plan_cmplt_date end_date,'
8706       || '   DECODE(d.line_type,-1,MIN(t.trans_date),MAX(t.trans_date)),'
8707       || '   h.batch_status,'
8708       || '   h.batch_type,'
8709       || '   i.organization_id,'
8710       || '   t.whse_code,'
8711       || '   i.aps_item_id,'
8712       || '   d.material_detail_id,'
8713       || '   d.line_no  ,'     /* B2919303 */
8714       || ' DECODE(d.item_id ,v.item_id,0,d.line_no) t_line_no,' /* B2953953 */
8715       || '   d.line_type,'
8716       || ' DECODE(d.line_type,1,3,d.line_type) t_line_type,' /* B2953953 */
8717       || '   SUM(t.trans_qty),'
8718       || '   d.item_id  matl_item_id,'
8719       || '   v.item_id  recipe_item_id, '
8720       || '   h.poc_ind,   '
8721       || '   DECODE(h.firmed_ind,1,1,2), '
8722       || '   decode(d.release_type,0, -1, nvl(gbs.batchstep_no,-1)) batchstep_no,'
8723       || '   d.plan_qty, '
8724       || '   DECODE(d.item_um, i.item_um, 1, '
8725       || '     GMICUOM.uom_conversion'||pdblink
8726       || '       (d.item_id, 0, 1, d.item_um, i.item_um, 0)), ' /* NAVIN: Get UOM
8727                                         conversion factor for unit qty */
8728       || '   h.due_date,'
8729       || '   h.order_priority,'
8730    --   || '   gbsi.batchstep_id,'
8731       ||'   ((gbsi.batchstep_id*2)+1) from_op_seq_id, '     /* Bug:6030499 Vpedarla Back Porting of Bug: 5461922 */
8732       || '   DECODE(d.line_type,1,nvl(gbsi.minimum_transfer_qty,gbs.minimum_transfer_qty), NULL) t_minimum_transfer_qty,'
8733       /* Bug: 6327356 vpedarla changed the column expression for mtq.
8734       || '   DECODE(d.line_type,1,gbsi.minimum_transfer_qty, NULL) t_minimum_transfer_qty,' */
8735       || '   DECODE(d.line_type,1,gbsi.minimum_delay, NULL) t_minimum_delay, '
8736       || '   DECODE(d.line_type,1,gbsi.maximum_delay, NULL) t_maximum_delay,'
8737       || '   gbs.batchstep_no'
8738       || ' FROM'
8739       || '   gme_batch_header'||pdblink||' h,'
8740       || '   gme_material_details'||pdblink||' d,'
8741       || '   gme_batch_step_items'||pdblink||' gbsi,'  /* 2919303 */
8742       || '   gme_batch_steps'||pdblink||' gbs,'       /* 2919303 */
8743       || '   gmd_recipe_validity_rules'||pdblink||' v,'
8744       || '   ic_whse_mst'||pdblink||' iwm,'
8745       || '   ic_tran_pnd'||pdblink||' t,'
8746       || '   gmp_item_aps'||pdblink||' i'
8747       || ' WHERE'
8748       || '     h.batch_id = d.batch_id'
8749       || '   AND h.recipe_validity_rule_id = v.recipe_validity_rule_id'
8750       || '   AND EXISTS (SELECT 1 '
8751       || '               FROM '
8752       || '                 gme_material_details'||pdblink||' gmd '
8753       || '               WHERE '
8754       || '                     gmd.batch_id = h.batch_id '
8755       || '                 AND gmd.item_id = v.item_id  '
8756       || '                 AND gmd.line_type = 1 )  '    /* B11794865  */
8757       || '   AND h.wip_whse_code = iwm.whse_code'
8758       || '   AND h.batch_id = t.doc_id'
8759       || '   AND ((h.batch_type = 0 and t.doc_type = :p1) OR'
8760       || '        (h.batch_type = 10 and t.doc_type = :p2))'
8761       || '   AND d.material_detail_id = gbsi.material_detail_id (+)' /* 2919303 */
8762       || '   AND d.batch_id = gbsi.batch_id (+)  '      /* 2919303 */
8763       || '   AND gbsi.batch_id = gbs.batch_id (+) '       /* 2919303 */
8764       || '   AND gbsi.batchstep_id  = gbs.batchstep_id (+)'    /* 2919303 */
8765       || '   AND d.material_detail_id = t.line_id'
8766       || '   AND t.item_id = i.item_id'
8767       || '   AND t.whse_code = i.whse_code'
8768       || '   AND t.orgn_code = i.plant_code'
8769       || '   AND h.batch_status in (1, 2)'
8770       || '   AND t.completed_ind = 0'
8771       || '   AND t.delete_mark = 0'
8772   -- B3721336 Rajesh Patangya If product is 100% Yeiled, But steps are pending
8773   --  || '   AND t.trans_qty <> 0'
8774       || ' GROUP BY'
8775       || '   h.batch_no,'
8776       || '   h.plant_code,'
8777       || '   h.batch_id,'
8778       || '   h.wip_whse_code,'
8779       || '   iwm.mtl_organization_id, '
8780       || '   h.routing_id,'
8781       || '   h.plan_start_date,'
8782       || '   h.plan_cmplt_date,'
8783       || '   v.item_id,'
8784       || '   h.poc_ind,'
8785       || '   h.firmed_ind,'
8786       || '   decode(d.release_type, 0, -1, nvl(gbs.batchstep_no,-1)),' /*2919303*/
8787       || '   d.item_id,'
8788       || '   h.batch_status,'
8789       || '   h.batch_type,'
8790       || '   i.organization_id,'
8791       || '   t.whse_code,'
8792       || '   i.aps_item_id,'
8793       || '   d.material_detail_id,'
8794       || '   d.line_no,'
8795       || '   d.line_type,'
8796       /* NAVIN:  Added following columns in group by as these are newly added in the select clouse.*/
8797       || '   d.plan_qty, '
8798       || '   DECODE(d.item_um, i.item_um, 1, GMICUOM.uom_conversion' || pdblink
8799       || '       (d.item_id, 0, 1, d.item_um, i.item_um, 0)), '
8800       || '   h.due_date,'
8801       || '   h.order_priority,'
8802       || '   gbsi.batchstep_id,'
8803       || '   DECODE(d.line_type,1,nvl(gbsi.minimum_transfer_qty,gbs.minimum_transfer_qty), NULL) ,'
8804       || '   DECODE(d.line_type,1,gbsi.minimum_delay, NULL), '
8805       || '   DECODE(d.line_type,1,gbsi.maximum_delay, NULL),'
8806       || '   gbs.batchstep_no'
8807       || ' ORDER BY h.batch_id ,t_line_type DESC ,t_line_no , '
8808       || '   DECODE(d.line_type,-1,MIN(t.trans_date),MAX(t.trans_date)) DESC ';
8809 
8810 log_message('v_prod_cursor - '||v_prod_cursor);
8811 
8812     OPEN c_prod_dtl FOR v_prod_cursor USING v_doc_prod, v_doc_fpo;
8813     LOOP
8814       FETCH  c_prod_dtl INTO prod_tab(prod_count);
8815       EXIT WHEN  c_prod_dtl%NOTFOUND ;
8816       prod_count := prod_count + 1;
8817     END LOOP;
8818     CLOSE c_prod_dtl ;
8819     gprod_size := prod_count - 1;
8820     log_message('Batches size is = '|| to_char(gprod_size) );
8821     time_stamp ;
8822 
8823     -- Bug: 6030499
8824           SELECT st.VALUE INTO v_dummy from V$MYSTAT st, V$STATNAME sn
8825           where st.STATISTIC# = sn.STATISTIC#
8826           and sn.NAME in ('session pga memory');
8827           log_message('Session pga memory = ' || TO_CHAR(v_dummy) );
8828 
8829 
8830     v_rsrc_cursor := 'SELECT /*+ DRIVING_SITE(uom) DRIVING_SITE(uom2) DRIVING_SITE(h) DRIVING_SITE(r) '
8831       ||'  DRIVING_SITE(o) DRIVING_SITE(gs) DRIVING_SITE(t) DRIVING_SITE(gri) DRIVING_SITE(c) */ '
8832       || ' h.batch_id,'
8833       || ' ((r.batch_id * 2) + 1), '
8834       || ' r.batchstep_no,'
8835       || ' NVL(o.sequence_dependent_ind, -1),'	/* NAVIN: Moved this column up for order by clause and changed from NVL(o.sequence_dependent_ind,0) */
8836       || ' DECODE(gs.prim_rsrc_ind, 1,1,2,2,0,3),' /* This will ensure that ordering will always have primary first */
8837       || ' gs.resources,'
8838       || ' ((gri.instance_id * 2) + 1) , '  /* SOWMYA - Resources Instances */
8839       || ' NVL(t.sequence_dependent_ind,0), '
8840       || ' gs.plan_start_date,'
8841       || ' h.plant_code,'
8842       -- || ' o.activity,'			/* NAVIN: Remove this column. */
8843       || ' gs.prim_rsrc_ind,'
8844       || ' c.resource_id,'
8845       || ' ((c.resource_id * 2) + 1),'
8846       || ' gs.plan_rsrc_count,'
8847       || ' gs.actual_rsrc_count,'
8848       || ' gs.actual_start_date,'
8849       || ' gs.plan_cmplt_date,'
8850       || ' gs.actual_cmplt_date,'
8851 --      || ' DECODE(r.step_status,2,1,NULL), '
8852       || ' r.step_status, '  /* B3995361 */
8853       || ' SUM(t.resource_usage) OVER (PARTITION BY t.doc_id, t.resources, t.line_id) resource_usage, '  -- summarized usage for the step resource
8854       || ' SUM(t.resource_usage) OVER (PARTITION BY t.doc_id, t.resources, t.line_id, t.instance_id) resource_instance_usage, ' -- summarized usage for the step resource instances
8855       || ' nvl(gri.eqp_serial_number,to_char(gri.instance_number)), '  /* SOWMYA - As Per latest FDD changes - Resources Instances */
8856       || ' DECODE(gs.scale_type,0,2,1,1,2,3), '
8857       || ' c.capacity_constraint , '
8858       || ' r.plan_step_qty, '
8859       || ' NVL(r.minimum_transfer_qty,-1), '
8860       || ' NVL(o.material_ind,0), '
8861       || ' 1 schedule_flag, '
8862        --  || ' o.offset_interval, '	/* NAVIN: Remove this column. */
8863       || ' o.plan_start_date, '
8864       || ' (DECODE(c.utilization,0,100,NVL(c.utilization,100))/100) * '
8865       || '   (DECODE(c.efficiency,0,100,NVL(c.efficiency,100))/100), '
8866       || ' o.batchstep_activity_id, '
8867       || ' gs.group_sequence_id,'
8868       || ' gs.group_sequence_number,'
8869       || ' nvl(gs.firm_type,0),'	/*Sowmya - If null then pass 0*/
8870       || ' gs.sequence_dependent_id  setup_id,'
8871   -- In the situation that value of calculate_charges at Step Resource has been
8872   -- set to 0 or NULL the values will need to be adjusted for min and max capacity
8873   -- at the resource level. min capacity will be set to 0 and the max capacity
8874   -- will be set to 99999999999999999
8875       || ' DECODE(NVL(gs.calculate_charges,0), 0, 0, gs.min_capacity) t_min_capacity,'
8876       || ' DECODE(NVL(gs.calculate_charges,0), 0, 99999999999999999, gs.max_capacity) t_max_capacity,'
8877       || ' gs.sequence_dependent_usage, '
8878       || ' gs.batchstep_resource_id,'
8879       /* NAVIN: for calculating WIP Charges */
8880       || ' r.step_status, '
8881       || ' r.plan_charges,'
8882       || ' gs.plan_rsrc_usage,'
8883   -- Bug: 6925112 Vpedarla modified the actual_rsrc_usage column inserted a NVl funtion
8884       || ' nvl(gs.actual_rsrc_usage,0) actual_rsrc_usage,'
8885     --  || ' r.batchstep_id,'    /* Navin 6/23/2004 Added for resource charges*/
8886       || ' ((r.batchstep_id*2)+1),'   /* bug: 6030499 Vpedarla back porting of bug: 5461922 */
8887       || '  SUM(NVL(o.material_ind,0))  OVER (PARTITION BY '
8888       || '  o.batch_id, r.batchstep_id) mat_found, '
8889    -- OPM break_ind values 0 and NULL maps to value 2 of MSC breakable_activity_flag
8890    -- and 1 maps with 1.
8891       || ' DECODE(NVL(o.break_ind,0), 1, 1, 2) breakable_activity_flag , '
8892       || ' uom.uom_code ,'
8893       || ' uom2.uom_code ,'
8894       || ' gri.equipment_item_id ,' /* SOWMYA - As Per latest FDD changes */
8895       || ' gs.plan_rsrc_count gmd_rsrc_count,' /*passed on msc_st_resource_requirements*/
8896       || ' r.plan_start_date, ' /* populate msc_st_job_operations.reco_start_date */
8897       || ' r.plan_cmplt_date ' /* populate msc_st_job_operations.reco_completion_date */
8898       || ' FROM'
8899    --Bug 9760218. Use sy_uoms_mst instead of mtl_units_of_measure
8900    --   || ' mtl_units_of_measure'||pdblink||' uom, '
8901    --   || ' mtl_units_of_measure'||pdblink||' uom2, '
8902       || ' sy_uoms_mst'||pdblink||' uom, '
8903       || ' sy_uoms_mst'||pdblink||' uom2, '
8904       || ' gme_batch_header'||pdblink||' h,'
8905       || ' gme_batch_steps'||pdblink||' r,'
8906       || ' gme_batch_step_activities'||pdblink||' o,'
8907       || ' gme_batch_step_resources'||pdblink||' gs,'
8908       || ' gme_resource_txns'||pdblink||' t , '
8909       || ' gmp_resource_instances'||pdblink||' gri, '
8910       || ' cr_rsrc_dtl'||pdblink||' c'
8911       || ' WHERE'
8912       || '     h.batch_id = r.batch_id '
8913       || ' AND r.batch_id = o.batch_id'
8914       || ' AND r.batchstep_id = o.batchstep_id'
8915       || ' AND o.batchstep_activity_id = gs.batchstep_activity_id'
8916       || ' AND o.batch_id = t.doc_id'
8917       || ' AND gs.batchstep_resource_id = t.line_id'
8918       || ' AND t.completed_ind = 0 '
8919       || ' AND NVL(t.sequence_dependent_ind,0) = 0 ' /* B4900503, Rajesh Patangya */
8920       || ' AND t.delete_mark = 0 '
8921       || ' AND t.instance_id = gri.instance_id (+) '
8922       || ' AND nvl(gri.inactive_ind,0) = 0 '
8923       || ' AND c.orgn_code = h.plant_code '
8924       || ' AND c.resources = gs.resources'
8925 /*B4313202 COLLECTING DATA FOR COMPLETED OPERATIONS:Included a chk for step status = 3*/
8926       || ' AND r.step_status in (1, 2, 3)'
8927       || ' AND c.Schedule_Ind <> 3 ' /* NAVIN:  gs.prim_rsrc_ind in (1,2) */
8928    --Bug 9760218.
8929    --   || ' AND uom.uom_class = :gmp_uom_class '
8930    --   || ' AND uom.unit_of_measure = gs.usage_uom '
8931    --   || ' AND uom2.unit_of_measure = r.step_qty_uom '
8932       || ' AND uom.um_type = :gmp_uom_class '
8933       || ' AND uom.um_code = gs.usage_uom '
8934       || ' AND uom2.um_code = r.step_qty_uom '
8935       || ' AND c.delete_mark = 0 '
8936       || ' AND nvl(c.inactive_ind,0) = 0 ' ;
8937 
8938   -- Bug: 9760218 Commented the below code.
8939   -- as resource requirements are not collected for batches with resource warehouses not in collection group.
8940  --     IF MSC_CL_GMP_UTILITY.g_in_str_org  IS NOT NULL THEN
8941  --        v_rsrc_cursor := v_rsrc_cursor
8942  --          ||' AND EXISTS ( SELECT 1 FROM sy_orgn_mst'||pdblink||' som '
8943  --          ||' WHERE h.wip_whse_code = som.resource_whse_code )' ;
8944  --     END IF;
8945 
8946       v_rsrc_cursor := v_rsrc_cursor
8947         || ' ORDER BY '
8948         ||'         1,2,3,4,5,6,7,8 DESC,9';	/* NAVIN: converted to position notation in Order By*/
8949 
8950 --      || ' ORDER BY '
8951 --      || '   h.batch_id,'
8952 --      || '   ((r.batch_id * 2) + 1), '
8953 --      || '   r.batchstep_no, '
8954 --      || '   NVL(o.sequence_dependent_ind,0) DESC,'
8955 --      || '   o.offset_interval, '
8956 --      || '   o.activity,  '
8957 --      || '   o.batchstep_activity_id, '
8958 --      || '   gs.prim_rsrc_ind,'
8959 --      || '   gs.resources,'
8960 --      || '   NVL(t.sequence_dependent_ind,0) DESC, '
8961 --      || '   gs.plan_start_date';
8962 
8963 log_message(' v_rsrc_cursor - '||v_rsrc_cursor );
8964 
8965       /* RAJESH PATANGYA open and fetch all the batch details  */
8966       OPEN rsrc_dtl FOR v_rsrc_cursor USING l_gmp_uom_class;
8967       LOOP
8968             FETCH rsrc_dtl INTO rsrc_tab(resource_count);
8969             EXIT WHEN rsrc_dtl%NOTFOUND;
8970             resource_count := resource_count + 1;
8971       END LOOP;
8972       CLOSE rsrc_dtl ;
8973       grsrc_size := resource_count - 1;
8974       log_message('Batches Resource size is = '|| to_char(grsrc_size) );
8975       time_stamp ;
8976 
8977       -- Bug: 6030499 Vpedarla
8978           SELECT st.VALUE INTO v_dummy from V$MYSTAT st, V$STATNAME sn
8979           where st.STATISTIC# = sn.STATISTIC#
8980           and sn.NAME in ('session pga memory');
8981           log_message('Session pga memory = ' || TO_CHAR(v_dummy) );
8982 
8983 
8984 -- Bug:6030499 Vpedarla conditionalising the following code
8985 
8986 IF collect_ps_data THEN
8987 
8988       -- Get all the Operation Charges for the batch step
8989       -- NAVIN: START Operation Charges Data needs to be transferred to APS in to Msc_st_resource_charges
8990       stp_chg_cursor:=
8991         ' SELECT /*+ DRIVING_SITE(gbsc) DRIVING_SITE(crd) DRIVING_SITE(iwm) DRIVING_SITE(v) '
8992       ||'  DRIVING_SITE(gbs) DRIVING_SITE(h) */ '
8993       ||' ((gbsc.batch_id*2)+1) x_batch_id,'
8994     --  ||' gbsc.batchstep_id,'
8995       ||' ((gbsc.batchstep_id*2)+1),'       /* Bug: 6030499 Vpedarla back porting bug:5461922 */
8996       || ' ((crd.resource_id * 2) + 1),'
8997       ||' gbsc.charge_number,'
8998       ||' iwm.mtl_organization_id,'
8999       ||' gbs.batchstep_no,'
9000       ||' gbsc.activity_sequence_number,'
9001       ||' gbsc.charge_quantity, '
9002       ||' gbsc.plan_start_date, '
9003       ||' gbsc.plan_cmplt_date'
9004       ||' FROM'
9005       ||' gme_batch_step_charges'||pdblink||' gbsc,'
9006       ||' cr_rsrc_dtl'||pdblink||' crd,'
9007       ||' ic_whse_mst'||pdblink||' iwm,'
9008       ||' gmd_recipe_validity_rules'||pdblink||' v,'
9009       ||' gme_batch_steps'||pdblink||' gbs,'
9010       ||' gme_batch_header'||pdblink||' h'
9011       ||' WHERE       '
9012       ||' h.batch_id = gbs.batch_id '
9013       ||' AND gbsc.batch_id = gbs.batch_id '
9014       ||' AND gbsc.batchstep_id = gbs.batchstep_id '
9015       ||' AND h.recipe_validity_rule_id = v.recipe_validity_rule_id'
9016       || '   AND EXISTS (SELECT /*+ DRIVING_SITE(gmd) */ 1 '
9017       || '               FROM '
9018       || '                 gme_material_details'||pdblink||' gmd '
9019       || '               WHERE '
9020       || '                     gmd.batch_id = h.batch_id '
9021       || '                 AND gmd.item_id = v.item_id  '
9022       || '                 AND gmd.line_type = 1 )  '    /* B11794865  */
9023       ||' AND crd.resources = gbsc.resources '
9024       ||' AND h.wip_whse_code = iwm.whse_code'
9025       ||' AND gbs.step_status in (1, 2) ';
9026 
9027       IF MSC_CL_GMP_UTILITY.g_in_str_org  IS NOT NULL THEN
9028 	   stp_chg_cursor := stp_chg_cursor
9029           ||'   AND EXISTS ( SELECT 1 FROM sy_orgn_mst'||pdblink||' som '
9030           ||'   WHERE  h.wip_whse_code = som.resource_whse_code )' ;
9031       END IF;
9032 
9033       stp_chg_cursor := stp_chg_cursor
9034             ||' ORDER BY 1, 2, 3, 4 ' ;
9035 
9036       OPEN c_chg_cursor FOR stp_chg_cursor ;
9037       LOOP
9038             FETCH c_chg_cursor INTO stp_chg_tbl(stp_chg_count);
9039             EXIT WHEN c_chg_cursor%NOTFOUND;
9040             stp_chg_count := stp_chg_count + 1;
9041       END LOOP;
9042       CLOSE c_chg_cursor ;
9043       stp_chg_count := stp_chg_count - 1;
9044       log_message('Batch Step charge size is = '|| to_char(stp_chg_count) );
9045       time_stamp ;
9046 
9047 -- Bug:6030499 Vpedarla
9048           SELECT st.VALUE INTO v_dummy from V$MYSTAT st, V$STATNAME sn
9049           where st.STATISTIC# = sn.STATISTIC#
9050           and sn.NAME in ('session pga memory');
9051           log_message('Session pga memory = ' || TO_CHAR(v_dummy) );
9052 
9053 
9054       -- NAVIN: END Operation Charges Data needs to be transferred to APS in to Msc_st_resource_charges
9055 
9056      /* NAVIN :- alternate resource */
9057      /* NAVIN: In Procedure production_orders just before starting the looping for prod_dtl cursor
9058      try to get all the alternate Resources.*/
9059 
9060      /* Alternate Resource selection   */
9061      /* B5688153, Rajesh Patangya prod spec alt*/
9062      /* B5879844  Uday Phadtare replaced at_apps_link with pdblink for prod */
9063         statement_alt_resource :=
9064                  ' SELECT /*+ DRIVING_SITE(acrd) DRIVING_SITE(pcrd) DRIVING_SITE(cam) DRIVING_SITE(prod) */ '
9065                    ||' pcrd.resource_id, acrd.resource_id, '
9066                    ||' acrd.min_capacity, acrd.max_capacity, '
9067                    ||' cam.runtime_factor, '
9068 /*prod spec alt*/  ||' nvl(cam.preference,-1), nvl(prod.item_id,-1)   '
9069                    ||' FROM  cr_rsrc_dtl'||pdblink||' acrd, '
9070                    ||'       cr_rsrc_dtl'||pdblink||' pcrd, '
9071                    ||'       cr_ares_mst'||pdblink||' cam, '
9072                    ||'       gmp_altresource_products'||pdblink||' prod'
9073                    ||' WHERE cam.alternate_resource = acrd.resources '
9074                    ||'   AND cam.primary_resource = pcrd.resources '
9075                    ||'   AND acrd.orgn_code = pcrd.orgn_code '
9076                    ||'   AND cam.primary_resource = prod.primary_resource(+) '
9077                    ||'   AND cam.alternate_resource = prod.alternate_resource(+) '
9078                    ||'   AND acrd.delete_mark = 0  '
9079                    ||' ORDER BY pcrd.resource_id, '
9080                    ||' DECODE(cam.preference,NULL,cam.runtime_factor,cam.preference),'
9081                    ||'   prod.item_id ' ;
9082 
9083      -- Retrive the Details of all the Alternate Resources.
9084      alt_rsrc_size := 1;
9085      OPEN cur_alt_resource FOR statement_alt_resource ;
9086      LOOP
9087          FETCH cur_alt_resource INTO rtg_alt_rsrc_tab(alt_rsrc_size);
9088          EXIT WHEN cur_alt_resource%NOTFOUND;
9089          alt_rsrc_size := alt_rsrc_size + 1;
9090      END LOOP;
9091      CLOSE cur_alt_resource;
9092      alt_rsrc_size := alt_rsrc_size -1 ;
9093      log_message('alternate resource size is = '|| to_char(alt_rsrc_size) );
9094 
9095 END IF;  --Bug: 6030499 Vpedarla end of conditional code
9096 
9097     old_batch_id := -1;
9098     p := 1 ;
9099     FOR p IN 1..gprod_size LOOP  /* Batch loop starts */
9100 
9101     /* Multiply plan_qty with UOM conv factor. Factor will be 1 when the
9102     plan_qty and primary UOM is same. */
9103 
9104     prod_tab(p).matl_qty := prod_tab(p).matl_qty * prod_tab(p).uom_conv_factor;
9105     prod_tab(p).Minimum_Transfer_Qty := prod_tab(p).Minimum_Transfer_Qty * prod_tab(p).uom_conv_factor;
9106     /*Sowmya - As per the latest FDD changes - Modified as per Matt's review commet.
9107     The minimum tranfer qty should be passed in the primary uom*/
9108 
9109     IF old_batch_id <> prod_tab(p).batch_id THEN
9110 
9111       old_batch_id := prod_tab(p).batch_id;
9112       product_line := -1;
9113       opm_product_line := -1;
9114       prod_line_id := -1;
9115 
9116       /* create a logical number by combining the plant and batch number */
9117       order_no := prod_tab(p).plant_code || pdelimiter ||
9118                   prod_tab(p).batch_no;
9119 
9120       IF prod_tab(p).batch_type = 10 THEN
9121         order_no := 'F/'||order_no ;
9122       END IF;
9123 
9124       IF prod_tab(p).plant_code = prod_plant THEN
9125          IF (res_whse) THEN
9126            v_orgn_id := res_whse_id;
9127          ELSE
9128            v_orgn_id := prod_tab(p).mtl_org_id;
9129          END IF;
9130       ELSE
9131         prod_plant := prod_tab(p).plant_code;
9132 
9133      /* Bug 4774975 --  Rajesh Patangya starts */
9134         v_sql_stmt :=
9135              'SELECT '
9136           || ' iwm.mtl_organization_id '
9137           || 'FROM '
9138           || '  sy_orgn_mst' ||pdblink|| ' sy, '
9139           || '  ic_whse_mst' ||pdblink|| ' iwm '
9140           || 'WHERE '
9141           || '  sy.orgn_code = :p1'
9142           || '  AND sy.resource_whse_code = iwm.whse_code';
9143 
9144      /* Bug 4774975 --  Rajesh Patangya End */
9145 
9146         OPEN rsrc_whse FOR v_sql_stmt USING prod_tab(p).plant_code;
9147         FETCH rsrc_whse INTO res_whse_id;
9148           IF rsrc_whse%NOTFOUND THEN
9149             v_orgn_id := prod_tab(p).mtl_org_id;
9150             res_whse := FALSE;
9151           ELSE
9152             v_orgn_id := res_whse_id;
9153             res_whse := TRUE;
9154           END IF;
9155         CLOSE rsrc_whse;
9156 
9157       END IF;  /* for Plant code */
9158     END IF;   /* Batch Changes */
9159 
9160     IF ( prod_tab(p).matl_item_id = prod_tab(p).recipe_item_id) AND (product_line = -1) THEN
9161 
9162       product_line := prod_tab(p).item_id;  /* APS Item Identifier for Product */
9163       opm_product_line := prod_tab(p).recipe_item_id;  /* OPM Item Identifier for Product */
9164       prod_line_id := prod_tab(p).line_id;
9165       old_step_no := -1;
9166       i := 1;
9167 
9168       IF prod_tab(p).routing_id IS NOT NULL AND NVL(prod_tab(p).poc_ind, 'N') = 'Y'  AND
9169          (res_whse) THEN
9170 
9171         -- log_message( ' Entry --  ' || g_rsrc_cnt );
9172         r := 1 ;
9173         resource_usage_flag := 0 ;
9174         resource_instance_usage_flag := 0 ;
9175         old_rsrc_batch_id :=  -999;
9176         old_rsrc_resources :=  -999;
9177         old_rsrc_original_seq_num := -999;
9178         old_instance_number :=  -999;
9179         old_rsrc_inst_batch_id := -999;
9180         old_rsrc_inst_resources := -999;
9181         old_rsrc_inst_original_seq_num := -999;
9182 
9183         FOR r IN g_rsrc_cnt..grsrc_size LOOP   /* Resource Cursor */
9184 
9185            /* ------------- Navin: START Process Resource Requirements ------------- */
9186            IF old_rsrc_batch_id <> rsrc_tab(r).batch_id
9187               OR old_rsrc_resources <> rsrc_tab(r).resources
9188               OR old_rsrc_original_seq_num <> rsrc_tab(r).original_seq_num THEN
9189                 -- Reset the flags.
9190                 resource_usage_flag := 0 ;
9191            END IF;
9192 
9193            IF rsrc_tab(r).resource_usage > 0 AND resource_usage_flag = 0 THEN
9194              -- Process and insert the very first resource record
9195              resource_usage_flag := 1 ;
9196              -- Populate flags
9197              old_rsrc_batch_id := rsrc_tab(r).batch_id ;
9198              old_rsrc_resources := rsrc_tab(r).resources ;
9199              old_rsrc_original_seq_num := rsrc_tab(r).original_seq_num ;
9200 
9201             /*Sowmya - As per the latest FDD changes - process this resource only
9202             if the class type of this is same as the one defined in profile*/
9203             l_res_inst_process := 1;
9204 
9205              IF  prod_tab(p).batch_id > rsrc_tab(r).batch_id THEN --- MAIN IF
9206                NULL ;
9207              ELSIF  prod_tab(p).batch_id < rsrc_tab(r).batch_id THEN
9208                g_rsrc_cnt := r ;
9209                /* Initialize for the change of batch */
9210                v_resource_usage := 0;
9211                v_res_seq        := 0;
9212                v_schedule_flag  := 0;
9213                v_parent_seq_num := 0;
9214                v_rsrc_cnt       := 0;
9215                v_start_date     := NULL;
9216                v_end_date       := NULL;
9217                old_activity     := 0;
9218                /* NAVIN :- */
9219                V_ACTIVITY_GROUP_ID  := 0;  /* B3995361 rpatangy */
9220                v_seq_dep_usage  := 0;
9221                found_chrg_rsrc := 0;
9222                chrg_activity   := -1;
9223 
9224                EXIT;
9225              ELSIF  prod_tab(p).batch_id =  rsrc_tab(r).batch_id THEN
9226                IF old_step_no <> rsrc_tab(r).batchstep_no THEN /* Step change */
9227                  v_res_seq        := 0;
9228                  old_activity     := -1;
9229                  v_resource_usage := 0;
9230                  v_res_seq        := 0;
9231                  v_schedule_flag  := 0;
9232                  v_parent_seq_num := 0;
9233                  v_rsrc_cnt       := 0;
9234                  v_start_date     := NULL;
9235                  v_end_date       := NULL;
9236                  /* NAVIN :- */
9237                  V_ACTIVITY_GROUP_ID  := 0;  /* B3995361 rpatangy */
9238                  v_seq_dep_usage  := 0;
9239                  found_chrg_rsrc := 0;
9240                  chrg_activity   := -1;
9241                /* nsinghi APSK - Insert Step related information in msc_st_job_operations
9242                   every time step changes. */
9243 
9244                  jo_index := jo_index + 1;
9245                  jo_wip_entity_id(jo_index) := rsrc_tab(r).x_batch_id;
9246                  jo_instance_id(jo_index) := pinstance_id;
9247                  jo_operation_seq_num(jo_index) := rsrc_tab(r).batchstep_no;
9248                  jo_recommended(jo_index) := 'Y';
9249                  jo_network_start_end(jo_index) := null_value;
9250                  jo_reco_start_date(jo_index) := rsrc_tab(r).step_start_date;
9251                  jo_reco_completion_date(jo_index) := rsrc_tab(r).step_end_date;
9252                  jo_operation_sequence_id(jo_index) := rsrc_tab(r).batchstep_id;
9253                  jo_organization_id(jo_index) := v_orgn_id;
9254                  jo_department_id(jo_index) := ((v_orgn_id*2) + 1);
9255 
9256                  /* Bug:6360387 Vpedarla - changed the below assignment  */
9257                  -- jo_minimum_transfer_quantity(jo_index) := prod_tab(p).minimum_transfer_qty;
9258                  jo_minimum_transfer_quantity(jo_index) := rsrc_tab(r).min_xfer_qty ;
9259 
9260                END IF;   /* Step change */
9261 
9262                IF rsrc_tab(r).seq_dep_ind <> -1 THEN /* NAVIN :- Process Rows only if
9263                                            Sequence Dependent is not -1 */
9264 
9265                  IF (old_activity <> rsrc_tab(r).bs_activity_id) OR (old_activity = -1) THEN
9266                    v_res_seq := v_res_seq + 1;
9267                    old_activity := rsrc_tab(r).bs_activity_id;
9268 
9269                    /* B3421856, If materail indicator activity then previous = 3, Next = 4 */
9270                    IF rsrc_tab(r).mat_found > 0 THEN
9271 
9272                      IF rsrc_tab(r).material_ind = 1 THEN
9273                          v_schedule_flag := 4;
9274                      ELSE
9275                        IF v_schedule_flag < 4 THEN
9276                           v_schedule_flag := 3 ;
9277                        END IF ;
9278                      END IF;   /* Material Indicator */
9279                    END IF;  /* Mat_found */
9280                  END IF;   /* old_activity */
9281 
9282                  IF (rsrc_tab(r).material_ind = 0) AND  (rsrc_tab(r).mat_found > 0) THEN
9283                    rsrc_tab(r).schedule_flag := v_schedule_flag;
9284                  END IF;
9285 
9286                  IF NVL(rsrc_tab(r).actual_cmplt_date,v_null_date) = v_null_date THEN
9287                    /* when the actual start is null the resource has not started
9288                       and the plan start will be used.  */
9289 
9290                    /* bug: 6713691 vpedarla - made changes to add the partial resource transaction back to the resource usage
9291                                            which will be cut-off during the ODS LOAD(APS) */
9292                    IF  rsrc_tab(r).actual_start_date is not null and rsrc_tab(r).actual_cmplt_date is null THEN
9293                         rsrc_tab(r).resource_usage := rsrc_tab(r).resource_usage + rsrc_tab(r).actual_rsrc_usage ;
9294                    END IF;
9295 
9296                    IF rsrc_tab(r).tran_seq_dep = 1 THEN
9297                      v_parent_seq_num := v_res_seq;
9298                      v_resource_usage := rsrc_tab(r).resource_usage;
9299                      v_start_date := rsrc_tab(r).act_start_date;
9300                      v_end_date := rsrc_tab(r).plan_start_date;
9301                      /* NAVIN :- added Sequence Dependency */
9302                      v_seq_dep_usage := rsrc_tab(r).sequence_dependent_usage;
9303                    ELSE
9304                      v_seq_dep_usage  := 0;
9305                      v_parent_seq_num := TO_NUMBER(NULL);
9306                      v_start_date := rsrc_tab(r).plan_start_date;
9307                      v_end_date := rsrc_tab(r).plan_cmplt_date;
9308                      IF v_inflate_wip = 1 THEN
9309                        v_resource_usage := rsrc_tab(r).resource_usage / rsrc_tab(r).utl_eff;
9310                      ELSE
9311                        v_resource_usage := rsrc_tab(r).resource_usage;
9312                      END IF;
9313                    END IF;   /* tran_seq_ind */
9314 
9315                    /*Sowmya - As per the latest FDD changes - Start*/
9316                    /*For a Pending batch if the original resoucre count is less than the plan
9317                    resource count then pass pln resource count otherwise the original resource
9318                    count is passed*/
9319                    IF rsrc_tab(r).org_step_status = 1 THEN
9320         /* B4349002 Resource Count is same as Plan resource count */
9321                                 v_max_rsrcs := rsrc_tab(r).gmd_rsrc_count;
9322                    ELSIF rsrc_tab(r).org_step_status = 2 THEN
9323                         IF rsrc_tab(r).actual_rsrc_count IS NULL THEN
9324                                 v_max_rsrcs := rsrc_tab(r).plan_rsrc_count;
9325                         ELSE
9326                                 v_max_rsrcs := rsrc_tab(r).actual_rsrc_count;
9327                         END IF;
9328                    END IF;
9329                    /*Sowmya - As per the latest FDD changes - End*/
9330 
9331                    /* If no actual resource exists then the resource has not
9332                       started and the planned value will be used */
9333                    IF rsrc_tab(r).actual_rsrc_count IS NULL THEN
9334                      v_rsrc_cnt := rsrc_tab(r).plan_rsrc_count;
9335                    ELSE
9336                      v_rsrc_cnt := rsrc_tab(r).actual_rsrc_count;
9337                    END IF;
9338 
9339                   /* write the current resource detail row asscoiating it with the
9340                     batch through the product line */
9341 
9342                   /* NAVIN :- If there are more than 1 activities in a step having
9343                    chargeable resources and scale_type = 3 and scheduled, then
9344                    change scale_type for all activities after the 1st is changed
9345                    to linear  */
9346 
9347                    IF rsrc_tab(r).mat_found = 0 OR rsrc_tab(r).material_ind = 1 THEN
9348                      IF rsrc_tab(r).scale_type = 3 -- APS decoded value as per DECODE(rsrc_tab(r).scale_type,0,2,1,1,2,3);
9349                      AND rsrc_tab(r).capacity_constraint = 1
9350                      AND found_chrg_rsrc = 0 THEN
9351                            found_chrg_rsrc := 1;
9352                            chrg_activity := rsrc_tab(r).bs_activity_id;
9353                            /* if the rtg_scale_type is 3 but another activity was found
9354                            with 2 then this row will be assigned scale_type = 1. */
9355                      ELSIF rsrc_tab(r).scale_type = 3
9356                      AND rsrc_tab(r).capacity_constraint = 1
9357                      AND found_chrg_rsrc = 1
9358                      AND chrg_activity <> rsrc_tab(r).bs_activity_id THEN
9359                            rsrc_tab(r).scale_type := 1;
9360                      END IF;
9361                    END IF;
9362 
9363                    IF rsrc_tab(r).scale_type = 3 AND found_chrg_rsrc = 1 THEN
9364 -- APS decoded value as per DECODE(rsrc_tab(r).scale_type,0,2,1,1,2,3);
9365                    /* NAVIN: END Operation Charges Data needs to be transferred
9366                       to APS  in to Msc_st_resource_charges */
9367                       IF rsrc_tab(r).org_step_status = 2 THEN
9368                          l_charges_remaining := CEIL(((rsrc_tab(r).plan_rsrc_usage -
9369                              rsrc_tab(r).actual_rsrc_usage) * rsrc_tab(r).plan_charges) /
9370                              rsrc_tab(r).plan_rsrc_usage);
9371 -- HW B4761811- Calculate the remaining charged
9372                       ELSE
9373                         l_charges_remaining := rsrc_tab(r).plan_charges ;
9374 
9375                       END IF;
9376 
9377                       IF rsrc_tab(r).org_step_status = 1 OR (l_charges_remaining > 0 AND rsrc_tab(r).org_step_status = 2) THEN
9378                       /* Batch step status is pending OR there are some remaining charges for a WIP batch */
9379                          inst_stp_chg_tbl(pinstance_id, r);
9380                       END IF;
9381                    END IF ;
9382 
9383                    /* B3995361 rpatangy start */
9384                    IF rsrc_tab(r).prim_rsrc_ind = 1 THEN
9385                     v_activity_group_id := rsrc_tab(r).x_resource_id ;
9386                    END IF;
9387                    /* B3995361 rpatangy end */
9388 
9389                    IF v_resource_usage > 0 THEN
9390                      /* Bulk Insert for insert_resource_requirements */
9391                        rr_index := rr_index + 1 ;
9392                        rr_organization_id(rr_index) := v_orgn_id ;
9393                        rr_sr_instance_id(rr_index) := pinstance_id ;
9394                        rr_supply_id(rr_index) :=  rsrc_tab(r).x_batch_id ; /* B1177070 encoded key */
9395                        rr_resource_seq_num(rr_index) := rsrc_tab(r).seq_dep_ind ;
9396                        rr_resource_id(rr_index) := rsrc_tab(r).x_resource_id ; /* B1177070 encoded key */
9397                        rr_start_date(rr_index) := v_start_date ;
9398                        rr_end_date(rr_index)  :=  v_end_date ;
9399                        rr_opr_hours_required(rr_index) :=  v_resource_usage ;
9400        /* Bug 4431718 populate usage_rate column starts */
9401                     IF rsrc_tab(r).scale_type = 1 THEN /*linearly scaled */
9402                         IF rsrc_tab(r).plan_step_qty > 0 THEN
9403                         rr_usage_rate(rr_index) :=
9404                         v_resource_usage / rsrc_tab(r).plan_step_qty ;
9405                         ELSE
9406                         rr_usage_rate(rr_index) :=  v_resource_usage ;
9407                         END IF ;
9408                     ELSIF rsrc_tab(r).scale_type = 2 THEN /*fix scaled*/
9409                         rr_usage_rate(rr_index) := v_resource_usage ;
9410                     ELSIF rsrc_tab(r).scale_type = 3 THEN /* Charge Scaled */
9411                         IF l_charges_remaining > 0 THEN
9412                         rr_usage_rate(rr_index) :=
9413                                 v_resource_usage /l_charges_remaining ;
9414                         ELSE
9415                         rr_usage_rate(rr_index) := v_resource_usage ;
9416                         END IF ;
9417                     END IF ;
9418        /* Bug 4431718 populate usage_rate column Ends */
9419 
9420                        rr_assigned_units(rr_index) := v_rsrc_cnt ;
9421                        rr_department_id(rr_index) := ((v_orgn_id * 2) + 1) ;  /* B1177070 encoded key */
9422                        rr_wip_entity_id(rr_index) :=  rsrc_tab(r).x_batch_id ; /* B1177070 encoded key */
9423                        /* B1224660 write the step number for oper seq num */
9424                        rr_operation_seq_num(rr_index)  :=   rsrc_tab(r).batchstep_no ;
9425                       /* B3995361 */
9426                        IF rsrc_tab(r).step_status = 2 THEN
9427                         /* vpedarla Bug: 6739913 made firm_type flag to be 1 when the step status is WIP */
9428                           rr_firm_flag(rr_index) :=   1 ;
9429                       --  rr_firm_flag(rr_index) :=   7 ;
9430                        ELSE
9431                           rr_firm_flag(rr_index) :=    rsrc_tab(r).firm_type ;
9432                        END IF;
9433 --                       rr_firm_flag(rr_index) :=    rsrc_tab(r).firm_type ;
9434                        rr_minimum_transfer_quantity(rr_index) := 0 ;
9435                        rr_parent_seq_num(rr_index) := TO_NUMBER(NULL) ;
9436                        rr_schedule_flag(rr_index) := rsrc_tab(r).schedule_flag ;
9437                    -- HW B4902328 - Added inventory_item_id
9438                        rr_inventory_item_id(rr_index) := product_line;
9439                        /* NAVIN :- start */
9440                        rr_sequence_id(rr_index) := rsrc_tab(r).group_sequence_id ;
9441                        rr_sequence_number(rr_index) := rsrc_tab(r).group_sequence_number ;
9442                        rr_firm_type(rr_index) := rsrc_tab(r).firm_type ;
9443                        rr_setup_id(rr_index) := rsrc_tab(r).setup_id ;
9444                        rr_original_seq_num (rr_index) := rsrc_tab(r).original_seq_num;
9445                        rr_min_capacity(rr_index) := rsrc_tab(r).minimum_capacity;
9446                        rr_max_capacity(rr_index)  := rsrc_tab(r).maximum_capacity;
9447                        rr_alternate_number(rr_index) := 0 ;
9448                        rr_basis_type(rr_index) := rsrc_tab(r).scale_type;
9449                        rr_hours_expended(rr_index) := rsrc_tab(r).actual_rsrc_usage;
9450                        rr_breakable_activity_flag(rr_index) := rsrc_tab(r).breakable_activity_flag;
9451                        /* Sowmya - As per the latest FDD changes - Start */
9452                        rr_plan_step_qty(rr_index) := rsrc_tab(r).plan_step_qty ;
9453                        rr_step_qty_uom(rr_index) := rsrc_tab(r).step_qty_uom ;
9454                        rr_gmd_rsrc_cnt(rr_index) := v_max_rsrcs;
9455                        /* Sowmya - As per the latest FDD changes - End */
9456 
9457                        /* B3995361 rpatangy */
9458                        rr_activity_group_id(rr_index) := v_activity_group_id ;
9459 
9460                        rr_operation_sequence_id(rr_index) := rsrc_tab(r).batchstep_id ; /* Bug: 6030499 Vpedarla back porting of bug: 5461922 */
9461 
9462                        /* NAVIN :- START - Logic To Handle Alternate Resources */
9463                        /*
9464                            Now check if the above resource inserted is a Primary. If it is
9465                            Primary then find its Alternates if existing, and then insert its rows
9466                            into msc_st_operation_resources table. Also keep track of number of
9467                            times alternates are inserted.
9468                        */
9469 
9470                        IF rsrc_tab(r).prim_rsrc_ind = 1 THEN
9471                          ---------------------------------------------------------------------
9472                          -- Use Bsearch technique to identify if any Alternate exists for the primary.
9473                          -- Enh_bsearch_alternate_rsrc is a new procedure to locate the Alternate Resource
9474                          -- for a given Primary resource in the PL/SQl table.
9475                          ---------------------------------------------------------------------
9476                          alternate_rsrc_loc := Enh_bsearch_alternate_rsrc (rsrc_tab(r).resource_id);
9477                          v_alternate  := 0;
9478 
9479                          IF alternate_rsrc_loc > 0 THEN  /* Alternate resource location */
9480                          /*Sowmya - As per latest FDD changes - Included chks that determine
9481                          when the alternate resources will be passed */
9482                             IF prod_tab(p).firmed_ind <> 1 THEN /* Batch firm chk */
9483                             /*If batch not firmed then pass on the alternate resource data*/
9484                                 IF rsrc_tab(r).org_step_status <> 2 THEN /* Batch Step not in WIP */
9485                                 /*Pass on the alternate resource data when the batch step is not in WIP status*/
9486                                 IF ( rsrc_tab(r).firm_type <> 3 ) AND ( rsrc_tab(r).firm_type <> 5 ) AND ( rsrc_tab(r).firm_type <> 6 ) AND ( rsrc_tab(r).firm_type <> 7 ) THEN
9487                                  /* Batch resources not firmed */
9488                                  /*0 - UnFrim ,         1 - Firm Start Date ,
9489                                    2 - Firm End Date ,  3 - Firm Resource  ,
9490                                    4 - Firm Start Date and End Date ,
9491                                    5 - Firm Start Date and Resource ,
9492                                    6 - Firm End Date and Resource ,
9493                                    7 - Firm All*/
9494                                    alt_cnt := 1 ;
9495                                    --  Loop through the Alternate resources for the Primary Resource
9496                                    /*Sowmya - As per the latest FDD changes - Start */
9497                                    FOR alt_cnt IN alternate_rsrc_loc..alt_rsrc_size
9498                                    LOOP
9499      /* B5688153, Rajesh Patangya prod spec alt*/
9500                                        IF ( rtg_alt_rsrc_tab(alt_cnt).prim_resource_id =
9501                                             rsrc_tab(r).resource_id
9502                                        AND (rtg_alt_rsrc_tab(alt_cnt).item_id = -1 OR
9503                                             rtg_alt_rsrc_tab(alt_cnt).item_id = opm_product_line )) THEN
9504                            --          IF ( rtg_alt_rsrc_tab(alt_cnt).prim_resource_id = rsrc_tab(r).resource_id ) THEN
9505                                          v_alternate := v_alternate + 1;
9506                                          /* Bulk Insert for Alternate_resource_requirements */
9507                                          arr_index := arr_index + 1 ;
9508                                          arr_organization_id(arr_index) := v_orgn_id ;
9509                                          arr_sr_instance_id(arr_index) := pinstance_id;
9510                                          arr_res_seq_num(arr_index) := rsrc_tab(r).original_seq_num ;
9511                                          arr_assigned_units(arr_index) := v_rsrc_cnt ;
9512                                          arr_department_id(arr_index) :=
9513                                                              ((v_orgn_id * 2) + 1) ;
9514                                          arr_wip_entity_id(arr_index) :=
9515                                                              rsrc_tab(r).x_batch_id ;
9516                                          /* B1224660 write the step number for oper seq num */
9517                                          arr_operation_seq_num(arr_index) :=
9518                                                         rsrc_tab(r).batchstep_no ;
9519                                          arr_setup_id(arr_index) :=
9520                                                         rsrc_tab(r).setup_id ;
9521                                          arr_schedule_seq_num(arr_index) :=
9522                                                         rsrc_tab(r).seq_dep_ind;
9523                                          arr_maximum_assigned_units(arr_index) :=
9524                                                         v_max_rsrcs;
9525                                          arr_activity_group_id(arr_index) :=
9526                                 ((rtg_alt_rsrc_tab(alt_cnt).alt_resource_id * 2) + 1);
9527                                          arr_basis_type(arr_index):=
9528                                                         rsrc_tab(r).scale_type;
9529                                          arr_resource_id(arr_index) :=
9530                                 ((rtg_alt_rsrc_tab(alt_cnt).alt_resource_id * 2) + 1) ;
9531                                          arr_usage_rate(arr_index) := v_resource_usage
9532                                             * rtg_alt_rsrc_tab(alt_cnt).runtime_factor;
9533                                          arr_alternate_num(arr_index) := v_alternate ;
9534                                          arr_uom_code(arr_index) :=
9535                                                         rsrc_tab(r).usage_uom;
9536                 --                       arr_gmd_rsrc_cnt(rr_index) := v_max_rsrcs;
9537                                        ELSIF ( rtg_alt_rsrc_tab(alt_cnt).prim_resource_id > rsrc_tab(r).resource_id ) THEN
9538                                            EXIT ;
9539                                        END IF;  /* End if for alternate resource and orgn code match */
9540                                    END LOOP;  /* Alternate loop */
9541                                 END IF; /* Batch resources not firmed */
9542                                 END IF;/* Batch Step not in WIP */
9543                            END IF; /* Batch firm chk */
9544                          END IF ; /* Alternate resource location */
9545                        END IF;  /* rsrc_tab(r).prim_rsrc_ind = 1 */
9546 
9547                        /* NAVIN:
9548                        Below logic is to create the resource group pattern with different
9549                        values of Alternate_Number. Variable v_alternate holds the count of
9550                        alternate resources that has been inserted for the Primary resource
9551                        of the group. Now insert all the resource records other than primary
9552                        with a value of Alternate_Number from 1 to v_alternate, to complete
9553                        the pattern of resource group.
9554                        NAVIN: */
9555 
9556                        IF rsrc_tab(r).prim_rsrc_ind <> 1 AND v_alternate > 0 THEN
9557                        /* B3995361 rpatangy  start */
9558                          mk_alt_grp := 0 ;
9559                          FOR alt_cnt IN alternate_rsrc_loc..alt_rsrc_size
9560                           LOOP
9561                            -- BUg: 8704177 Vpedarla modifed the IF condition below
9562                        --   IF rtg_alt_rsrc_tab(alt_cnt).prim_resource_id =
9563                        --       ((v_activity_group_id - 1)/2) THEN
9564                           IF ( rtg_alt_rsrc_tab(alt_cnt).prim_resource_id =
9565                               ((v_activity_group_id - 1)/2) AND
9566                               (rtg_alt_rsrc_tab(alt_cnt).item_id = -1 OR
9567                                             rtg_alt_rsrc_tab(alt_cnt).item_id = opm_product_line )) THEN
9568                            arr_index := arr_index + 1 ;
9569                            mk_alt_grp := mk_alt_grp + 1 ;
9570                            arr_organization_id(arr_index) := v_orgn_id ;
9571                            arr_sr_instance_id(arr_index) := pinstance_id ;
9572                            arr_res_seq_num(arr_index) := rsrc_tab(r).original_seq_num ;
9573                            arr_resource_id(arr_index) := rsrc_tab(r).x_resource_id ;
9574                            arr_assigned_units(arr_index) := v_rsrc_cnt ;
9575                            arr_department_id(arr_index) := ((v_orgn_id * 2) + 1) ;
9576                            arr_wip_entity_id(arr_index) :=  rsrc_tab(r).x_batch_id ;
9577                            arr_operation_seq_num(arr_index)  := rsrc_tab(r).batchstep_no ;
9578                            arr_setup_id(arr_index) := rsrc_tab(r).setup_id ;
9579                            arr_schedule_seq_num(arr_index) := rsrc_tab(r).seq_dep_ind;
9580                            arr_maximum_assigned_units(arr_index) := v_max_rsrcs;
9581                            arr_activity_group_id(arr_index) :=
9582                                    ((rtg_alt_rsrc_tab(alt_cnt).alt_resource_id * 2) + 1);
9583                            arr_basis_type(arr_index):= rsrc_tab(r).scale_type;
9584                            arr_usage_rate(arr_index) := v_resource_usage ;
9585                            arr_alternate_num(arr_index) := mk_alt_grp ;
9586                            arr_uom_code(arr_index) := rsrc_tab(r).usage_uom;
9587                           ELSIF rtg_alt_rsrc_tab(alt_cnt).prim_resource_id >
9588                                 ((v_activity_group_id - 1)/2) THEN
9589                              EXIT ;
9590                           END IF;  /* End if for alternate resource and orgn code match */
9591                          /* B3995361 rpatangy  End */
9592                          END LOOP;  /* mk_alt_grp loop */
9593                        END IF;  /* End if for Check in Primary Resource Indicator and  v_alternate > 0*/
9594                        /* NAVIN :- END - Logic To Handle Alternate Resources */
9595 
9596                        /* NAVIN :- Logic to Handle Additional row For Sequence Dependency Start */
9597                        IF v_seq_dep_usage > 0 THEN
9598                          rr_index := rr_index + 1 ;
9599                          rr_organization_id(rr_index) := v_orgn_id ;
9600                          rr_sr_instance_id(rr_index) := pinstance_id ;
9601                          rr_supply_id(rr_index) :=  rsrc_tab(r).x_batch_id ; /* B1177070 encoded key */
9602                          /* B1224660 new value to write resource seq num */
9603                          rr_resource_seq_num(rr_index) := rsrc_tab(r).seq_dep_ind ;
9604                          rr_resource_id(rr_index) := rsrc_tab(r).x_resource_id ; /* B1177070 encoded key */
9605                          rr_start_date(rr_index) := v_start_date ;
9606                          rr_end_date(rr_index)  :=  v_end_date ;
9607                          rr_opr_hours_required(rr_index) :=  rsrc_tab(r).sequence_dependent_usage;-- * converted_usage;
9608     /* B4637398, We will treat This extra usage row as fixed and provide
9609           the same reosurce usage in usage_rate column */
9610                          rr_usage_rate(rr_index) := v_resource_usage ;
9611 
9612                          /* Sowmya - As per the latest FDD changes - multiply the usage with the conveted factor */
9613                          rr_assigned_units(rr_index) := v_rsrc_cnt ;
9614                          rr_department_id(rr_index) := ((v_orgn_id * 2) + 1) ;  /* B1177070 encoded key */
9615                          rr_wip_entity_id(rr_index) :=  rsrc_tab(r).x_batch_id ; /* B1177070 encoded key */
9616                          /* B1224660 write the step number for oper seq num */
9617                          rr_operation_seq_num(rr_index)  :=   rsrc_tab(r).batchstep_no ;
9618                          rr_operation_sequence_id(rr_index) := rsrc_tab(r).batchstep_id ; /* Bug: 6030499 vpedarla back port Bug:5461922 */
9619 
9620 		       /*B4320561 - sowsubra - start*/
9621                        rr_unadjusted_resource_hrs(rr_index) := rsrc_tab(r).resource_usage ;
9622                        rr_touch_time(rr_index) := rr_unadjusted_resource_hrs(rr_index)/ rsrc_tab(r).utl_eff ;
9623                        /*B4320561 - sowsubra - end*/
9624 
9625                          rr_firm_flag(rr_index) :=    rsrc_tab(r).firm_type ;
9626                          rr_minimum_transfer_quantity(rr_index) := 0 ;
9627                          rr_parent_seq_num(rr_index) := rsrc_tab(r).original_seq_num;
9628                          rr_schedule_flag(rr_index) := rsrc_tab(r).schedule_flag ;
9629                    -- HW B4902328 - Added inventory_item_id
9630                          rr_inventory_item_id(rr_index) := product_line;
9631                          rr_sequence_id(rr_index) := rsrc_tab(r).group_sequence_id ;
9632                          rr_sequence_number(rr_index) := rsrc_tab(r).group_sequence_number ;
9633                          rr_firm_type(rr_index) := rsrc_tab(r).firm_type ;
9634                          rr_setup_id(rr_index) := rsrc_tab(r).setup_id ;
9635                          rr_original_seq_num (rr_index) := TO_NUMBER(NULL) ;
9636                          rr_min_capacity(rr_index) := rsrc_tab(r).minimum_capacity;
9637                          rr_max_capacity(rr_index)  := rsrc_tab(r).maximum_capacity;
9638                          rr_alternate_number(rr_index) := 0 ;
9639                          rr_basis_type(rr_index) := rsrc_tab(r).scale_type;           -- Added 7/14/2004
9640                          rr_hours_expended(rr_index) := rsrc_tab(r).actual_rsrc_usage;
9641                          rr_breakable_activity_flag(rr_index) := rsrc_tab(r).breakable_activity_flag;
9642                          /* Sowmya - As per the latest FDD changes - Start */
9643                          rr_plan_step_qty(rr_index) := rsrc_tab(r).plan_step_qty ;
9644                          rr_step_qty_uom(rr_index) := rsrc_tab(r).step_qty_uom ;
9645                          rr_gmd_rsrc_cnt(rr_index) := v_max_rsrcs;
9646                          /* Sowmya - As per the latest FDD changes - End */
9647 
9648                          /* B3995361 rpatangy */
9649                        rr_activity_group_id(rr_index) := v_activity_group_id ;
9650 
9651                        /*B4320561 - sowsubra - start*/
9652                        rr_unadjusted_resource_hrs(rr_index) := rsrc_tab(r).resource_usage ;
9653                        rr_touch_time(rr_index) := rr_unadjusted_resource_hrs(rr_index)/ rsrc_tab(r).utl_eff ;
9654                        /*B4320561 - sowsubra - end*/
9655 
9656                        END IF;
9657                    END IF;   /* resource usage */  -- v_resource_usage > 0
9658                  END IF;   /* actual completion date */ -- NVL(rsrc_tab(r).actual_cmplt_date,v_null_date) = v_null_date
9659                END IF; /* NAVIN :- End If condition for seq_dep_ind <> -1 */ -- rsrc_tab(r).seq_dep_ind <> -1
9660 
9661                old_step_no := rsrc_tab(r).batchstep_no;
9662              END IF ;   /* entry/Exit Logic */  --- MAIN IF
9663 
9664            END IF; /* rsrc_tab(r).resource_usage > 0 AND resource_usage_flag = 0 */
9665 
9666            /* ------------- Navin: END Process Resource Requirements ------------- */
9667 
9668            /* ------------- Navin: START Process Resource Instances Requirements ------------- */
9669            IF rsrc_tab(r).instance_number <> -1 THEN
9670              IF old_rsrc_inst_batch_id <> rsrc_tab(r).batch_id
9671                 OR old_rsrc_inst_resources <> rsrc_tab(r).resources
9672                 OR old_rsrc_inst_original_seq_num <> rsrc_tab(r).original_seq_num
9673                 OR old_instance_number <> rsrc_tab(r).instance_number THEN
9674                   -- Reset the flags.
9675                   resource_instance_usage_flag := 0 ;
9676              END IF;
9677 
9678              IF rsrc_tab(r).resource_instance_usage > 0 AND resource_instance_usage_flag = 0  AND l_res_inst_process = 1 THEN
9679                   -- Process and insert the very first resource_instance_usage record
9680                   resource_instance_usage_flag := 1 ;
9681 
9682                   /* Sowmya - As per the latest FDD changes - Reinitialise the variable*/
9683                   l_res_inst_process := 0 ;
9684 
9685                   -- Populate flags
9686                   old_rsrc_inst_batch_id := rsrc_tab(r).batch_id ;
9687                   old_rsrc_inst_resources := rsrc_tab(r).resources ;
9688                   old_rsrc_inst_original_seq_num := rsrc_tab(r).original_seq_num ;
9689                   old_instance_number := rsrc_tab(r).instance_number;
9690 
9691                   -- Insert the very first resource_instance_usage record
9692                   inst_indx := inst_indx + 1 ;
9693 --                  dbms_output.put_line('converted_usage ' || converted_usage);
9694 
9695                   rec_inst_supply_id(inst_indx) := rsrc_tab(r).x_batch_id ;
9696                   rec_inst_organization_id(inst_indx) := v_orgn_id ;
9697                   rec_inst_sr_instance_id(inst_indx) := pinstance_id ;
9698                   rec_inst_rec_resource_seq_num(inst_indx) := rsrc_tab(r).seq_dep_ind ;
9699                   rec_inst_resource_id(inst_indx) := rsrc_tab(r).x_resource_id ;
9700                   rec_inst_instance_id(inst_indx) := rsrc_tab(r).instance_number ;
9701                   rec_inst_start_date(inst_indx) := v_start_date ;
9702                   rec_inst_end_date(inst_indx)  :=  v_end_date ;
9703                   rec_inst_rsrc_instance_hours(inst_indx) := rsrc_tab(r).resource_instance_usage;-- * converted_usage;
9704                   /* Sowmya - As per the latest FDD changes - multiply the usage with the conveted factor */
9705                   rec_inst_operation_seq_num(inst_indx) := rsrc_tab(r).batchstep_no ;
9706                   rec_inst_department_id(inst_indx) := ((v_orgn_id * 2) + 1) ;
9707                   rec_inst_wip_entity_id(inst_indx) :=  rsrc_tab(r).x_batch_id ;
9708                   rec_inst_serial_number(inst_indx)  :=   rsrc_tab(r).eqp_serial_number ;
9709                   rec_inst_original_seq_num(inst_indx)  :=   rsrc_tab(r).original_seq_num ;
9710                   rec_inst_parent_seq_num(inst_indx) := TO_NUMBER(NULL) ;
9711                   rec_inst_equp_item_id(inst_indx) := rsrc_tab(r).equp_item_id;
9712                   /*Sowmya - As per the latest FDD changes - Resource Instances */
9713 
9714                   IF v_seq_dep_usage > 0 THEN
9715                     /* Bulk Insert for insert_resource_requirements */
9716                     inst_indx := inst_indx + 1 ;
9717 
9718                     rec_inst_supply_id(inst_indx) := rsrc_tab(r).x_batch_id ;
9719                     rec_inst_organization_id(inst_indx) := v_orgn_id ;
9720                     rec_inst_sr_instance_id(inst_indx) := pinstance_id ;
9721                     rec_inst_rec_resource_seq_num(inst_indx) := rsrc_tab(r).seq_dep_ind ;
9722                     rec_inst_resource_id(inst_indx) := rsrc_tab(r).x_resource_id ;
9723                     rec_inst_instance_id(inst_indx) := rsrc_tab(r).instance_number ;
9724                     rec_inst_start_date(inst_indx) := v_start_date ;
9725                     rec_inst_end_date(inst_indx)  :=  v_end_date ;
9726                     /* NAVIN: Divide the seq dep usage equally amongst the instances. */
9727                     rec_inst_rsrc_instance_hours(inst_indx) := rsrc_tab(r).sequence_dependent_usage;-- * converted_usage;
9728                     /* Sowmya - As per the latest FDD changes - multiply the usage with the conveted factor */
9729                     rec_inst_operation_seq_num(inst_indx) := rsrc_tab(r).batchstep_no ;
9730                     rec_inst_department_id(inst_indx) := ((v_orgn_id * 2) + 1) ;
9731                     rec_inst_wip_entity_id(inst_indx) :=  rsrc_tab(r).x_batch_id ;
9732                     rec_inst_serial_number(inst_indx)  :=   rsrc_tab(r).eqp_serial_number ;
9733                     rec_inst_original_seq_num(inst_indx)  :=  TO_NUMBER(NULL) ;
9734                     rec_inst_parent_seq_num(inst_indx) := rsrc_tab(r).original_seq_num;
9735                     rec_inst_equp_item_id(inst_indx) := rsrc_tab(r).equp_item_id;
9736                     /*Sowmya - As per the latest FDD changes - Resource Instances */
9737 
9738                   END IF; /* Sequence Dependency Row */
9739              END IF; /* rsrc_tab(r).resource_instance_usage > 0 AND resource_instance_usage_flag = 0 */
9740            END IF; /* rsrc_tab(r).instance_number <> -1 */
9741            /* ------------- Navin: END Process Resource Instances Requirements ------------- */
9742 
9743        END LOOP;   /* Resource Cursor */
9744 
9745 
9746       END IF;   /* Routing_id is not null */
9747    END IF;  /* item should be product */
9748 
9749         IF prod_tab(p).line_id = prod_line_id THEN
9750           supply_type := 3;    /* Product */
9751         ELSE
9752           supply_type := 14;   /* Co Product or a by-Product */
9753         END IF;
9754 
9755         /* ingredient get written to the demands. the quantity needs to be
9756            positive so we reverse it */
9757         IF prod_tab(p).line_type = -1 THEN
9758           IF prod_tab(p).batchstep_no = -1   /* 2919303 */
9759           THEN
9760               prod_tab(p).batchstep_no := TO_NUMBER(NULL);
9761           END IF;
9762     -- ----------------
9763     /*  B3267522, Rajesh Patangya Do not insert demands, if ingradient is same as product
9764         (single level circular reference) */
9765 
9766         IF prod_tab(p).item_id <> product_line THEN
9767 
9768              /* Demands Bulk inserts */
9769                 d_index := d_index + 1 ;
9770                 d_organization_id(d_index) := v_orgn_id ;
9771                 d_inventory_item_id(d_index) :=  prod_tab(p).item_id ;
9772                 d_sr_instance_id(d_index) :=  pinstance_id ;
9773                 d_assembly_item_id(d_index) := product_line ;
9774                 d_demand_date(d_index) := prod_tab(p).trans_date ;
9775                 /* Reverse sign to make positive */
9776                 d_requirement_quantity(d_index) := (prod_tab(p).qty * -1);
9777                 d_demand_type(d_index) := 1 ;
9778                 d_origination_type(d_index) := 3 ;
9779                  /* B1177070 encoded key */
9780                 d_wip_entity_id(d_index) := prod_tab(p).x_batch_id ;
9781                 d_demand_schedule(d_index) := null_value ;
9782                 d_order_number(d_index)  := order_no ;
9783                 d_wip_entity_name(d_index) := null_value ;
9784                 d_operation_seq_num(d_index) := prod_tab(p).batchstep_no; /* B2919303 Batchstep */
9785                 d_selling_price(d_index) := null_value ;
9786 
9787                 /*B5100481 - sowsubra - WIP STATUS OF BATCHES NOT SHOWN*/
9788                 IF prod_tab(p).batch_status = 1 THEN
9789                    d_wip_status_code(d_index) := 16 ; /* batch status -> pending */
9790                 ELSE
9791                    d_wip_status_code(d_index) := 3 ; /* batch status -> WIP */
9792                 END IF;
9793 
9794          END IF;    /* Circular reference   */
9795     -- ----------------
9796 
9797     /* If the line is a product or byproduct write to the supplies */
9798         ELSE
9799           IF prod_tab(p).batchstep_no = -1   /* 2919303 */
9800           THEN
9801               prod_tab(p).batchstep_no := TO_NUMBER(NULL);
9802           END IF;
9803 
9804      -- Bug: 6080227 Vpedarla added if condition to elimate zero quantity supplies getting inseted into msc_st_supplies
9805            IF prod_tab(p).qty <> 0 THEN
9806 
9807            /* Supply Bulk Insert Assignments */
9808                 s_index := s_index + 1 ;
9809                 s_inventory_item_id(s_index) := prod_tab(p).item_id ;
9810                 s_organization_id(s_index)   := v_orgn_id ;
9811                 s_sr_instance_id(s_index)    := pinstance_id;
9812                 s_new_schedule_date(s_index) :=  prod_tab(p).trans_date ;
9813                 s_old_schedule_date(s_index)       := prod_tab(p).trans_date ;
9814                 s_new_wip_start_date(s_index) := prod_tab(p).start_date ;
9815                 s_old_wip_start_date(s_index) := prod_tab(p).start_date ;
9816                 s_lunit_completion_date(s_index) := prod_tab(p).end_date ;
9817                 /* B1177070 encoded key */
9818                 s_disposition_id(s_index)    :=  prod_tab(p).x_batch_id ;
9819 
9820                /* B6795244 Rajesh Patangya From ASCP planning perspective, we only need a
9821                    unique process_sequence_id in the msc_supplies (plan_id=-1, ODS data)
9822                    for WIP jobs. It is requirement from our new engine code, starting
9823                    from 11510 in other words for order_type 3,14.
9824                */
9825                 s_process_seq_id(s_index) := l_process_seq_id + s_index ;
9826 
9827                 /*B5100481 - sowsubra - WIP STATUS OF BATCHES NOT SHOWN*/
9828                 IF prod_tab(p).batch_status = 1 THEN
9829                    s_wip_status_code(s_index) := 16 ; /* batch status -> pending */
9830                 ELSE
9831                    s_wip_status_code(s_index) := 3 ; /* batch status -> WIP */
9832                 END IF;
9833 
9834              IF supply_type IS NOT NULL THEN
9835                 s_order_type(s_index)        := supply_type ;
9836              ELSE
9837                 s_order_type(s_index)        := null_value ;
9838              END IF ;
9839 
9840              IF order_no IS NOT NULL THEN
9841                 s_order_number(s_index)            := order_no ;
9842              ELSE
9843                 s_order_number(s_index)        := null_value ;
9844              END IF ;
9845                 s_new_order_quantity(s_index) := prod_tab(p).qty ;
9846                 s_old_order_quantity(s_index) := prod_tab(p).qty ;
9847                 s_firm_planned_type(s_index)  := prod_tab(p).firmed_ind; /* 2821248 Firmed Indicator */
9848                 s_firm_quantity(s_index)  := prod_tab(p).qty ; /* B2821248 Firmed Batches Qty  - */
9849                 s_firm_date(s_index) := prod_tab(p).trans_date; /* B2821248 Firmed Batches Date - */
9850 
9851                 s_requested_completion_date(s_index) := prod_tab(p).requested_completion_date; /* Navin : APS K Enh */
9852                 s_schedule_priority(s_index) := prod_tab(p).schedule_priority; /* Navin : APS K Enh */
9853 
9854              IF order_no IS NOT NULL THEN
9855                 s_wip_entity_name(s_index)        := order_no ;
9856              ELSE
9857                 s_wip_entity_name(s_index)        := null_value ;
9858              END IF ;
9859                 -- lot_number         := null_value ;
9860                 -- expiration_date    := null_value ;
9861             s_operation_seq_num(s_index) := prod_tab(p).batchstep_no;  /* B2919303 Batchstep  */
9862 
9863             IF supply_type = 3 THEN
9864               s_by_product_using_assy_id(s_index) := to_number(NULL) ;
9865             ELSE
9866               s_by_product_using_assy_id(s_index) := product_line ;
9867             END IF;
9868 
9869             /* Section 11.1.1.2 MTQ with Hardlinks */
9870             IF (prod_tab(p).Minimum_Time_Offset IS NOT NULL) THEN
9871                   stp_var_itm_instance_id(si_index) := pinstance_id;
9872                   stp_var_itm_from_op_seq_id(si_index) := prod_tab(p).from_op_seq_id ;
9873                   stp_var_itm_wip_entity_id (si_index) := prod_tab(p).x_batch_id;
9874 	          stp_var_itm_FROM_item_ID(si_index) := prod_tab(p).item_id;
9875 	          stp_var_min_tran_qty(si_index) := prod_tab(p).Minimum_Transfer_Qty;
9876         	  stp_var_itm_min_tm_off(si_index) := prod_tab(p).Minimum_Time_Offset;
9877 	          stp_var_itm_max_tm_off(si_index) := prod_tab(p).Maximum_Time_Offset;
9878                   stp_var_itm_from_op_seq_num(si_index) := prod_tab(p).from_op_seq_num;
9879                   stp_var_itm_organization_id(si_index)   := v_orgn_id ;
9880 	          si_index := si_index+1;
9881             END IF;
9882         END IF;  -- Bug: 6080227 Vpedarla
9883     END IF;
9884   END LOOP;   /* all the details are retrieved so close the cursor */
9885   --close prod_dtl;
9886 
9887      i := 1 ;
9888      log_message(rr_organization_id.FIRST || ' *rr*' || rr_organization_id.LAST );
9889      IF rr_organization_id.FIRST > 0 THEN
9890      FORALL i IN rr_organization_id.FIRST..rr_organization_id.LAST
9891         INSERT INTO msc_st_resource_requirements (
9892 		organization_id,
9893 		sr_instance_id,
9894 		supply_id,
9895     supply_type, /* sultripa B4612203 Need to populate supply_type field */
9896 		resource_seq_num,
9897 		resource_id,
9898 		start_date,
9899 		end_date,
9900 		operation_hours_required,
9901     usage_rate, /* B4637398 Rajesh Patangya */
9902 		assigned_units,
9903 		department_id,
9904 		wip_entity_id,
9905 		operation_seq_num,
9906 		deleted_flag,
9907 		firm_flag,
9908 		minimum_transfer_quantity,
9909 		parent_seq_num,
9910 		schedule_flag,
9911 -- HW B4902328 - Added inventory_item_id
9912     inventory_item_id,
9913 		basis_type,
9914 		setup_id,
9915 		group_sequence_id,
9916 		group_sequence_number,
9917 		minimum_capacity,
9918 		maximum_capacity,
9919 		orig_resource_seq_num,
9920 		alternate_number,
9921                 hours_expended,
9922                 breakable_activity_flag,
9923                 step_quantity,    /* Sowmya - As per latest FDD changes*/
9924                 step_quantity_uom , /* Sowmya - As per latest FDD changes*/
9925                 maximum_assigned_units, /* Sowmya - As per latest FDD changes*/
9926          --       unadjusted_resource_hours, /*B4320561 - Same as in wip (without eff and util) */
9927          --       touch_time, /* B4320561 - Unadjusted res. hrs / efficiency.*/
9928                 activity_group_id,  /* B3995361 rpatangy */
9929                 operation_sequence_id /* Bug: 6030499 vpedarla back port Bug:5461922 */
9930 	)
9931         VALUES (
9932 		rr_organization_id(i),
9933 		rr_sr_instance_id(i),
9934 		rr_supply_id(i),
9935                 1, /* sultripa B4612203 supply_type = 1 for OPM batches*/
9936 		rr_resource_seq_num(i),
9937 		rr_resource_id(i),
9938 		rr_start_date(i),
9939 		rr_end_date(i),
9940 		rr_opr_hours_required(i),
9941                 nvl(rr_usage_rate(i),0), /* B4637398 Rajesh Patangya */
9942 		rr_assigned_units(i),
9943 		rr_department_id(i),
9944 		rr_wip_entity_id(i),
9945 		rr_operation_seq_num(i),
9946 		2,
9947 		rr_firm_flag(i),
9948 		rr_minimum_transfer_quantity(i),
9949 		rr_parent_seq_num(i),
9950 		rr_schedule_flag(i),
9951             -- HW B4902328 - Added inventory_item_id
9952                 rr_inventory_item_id(i),
9953 		rr_basis_type(i),
9954 		rr_setup_id(i),
9955 		rr_sequence_id(i),     -- group_sequence_id
9956 		rr_sequence_number(i), -- group_sequence_number
9957 		rr_min_capacity(i),
9958 		rr_max_capacity(i),
9959 		rr_original_seq_num(i),
9960 		rr_alternate_number(i),
9961                 rr_hours_expended(i),
9962                 rr_breakable_activity_flag(i),
9963                 rr_plan_step_qty(i),  /* Sowmya - As per the latest FDD changes*/
9964                 rr_step_qty_uom(i) , /* Sowmya - As per the latest FDD changes*/
9965                 rr_gmd_rsrc_cnt(i),
9966           --      rr_unadjusted_resource_hrs(i), /*B4320561 - sowsubra*/
9967           --      rr_touch_time(i), /*B4320561 - sowsubra*/
9968                 rr_activity_group_id(i),  /* B3995361 rpatangy */
9969                 rr_operation_sequence_id(i) /* Bug: 6030499 vpedarla back port Bug:5461922 */
9970         )   ;
9971 
9972      END IF;
9973 
9974 /* akaruppa B5007729 */
9975         rr_organization_id   := empty_pls_table ;
9976         rr_inventory_item_id := empty_pls_table ;
9977         rr_sr_instance_id    := empty_pls_table ;
9978         rr_supply_id         := empty_pls_table ;
9979         rr_resource_seq_num  := empty_pls_table ;
9980         rr_resource_id       := empty_pls_table ;
9981         rr_start_date        := empty_dat_table ;
9982         rr_end_date          := empty_dat_table ;
9983         rr_opr_hours_required := empty_num_table ;
9984         rr_usage_rate        := empty_num_table ;
9985         rr_assigned_units    := empty_num_table ;
9986         rr_department_id     := empty_pls_table ;
9987         rr_wip_entity_id     := empty_pls_table ;
9988         rr_operation_seq_num := empty_pls_table ;
9989         rr_firm_flag         := empty_pls_table ;
9990         rr_minimum_transfer_quantity   := empty_num_table ;
9991         rr_parent_seq_num    := empty_num_table ;
9992         rr_schedule_flag     := empty_pls_table ;
9993         rr_basis_type        := empty_num_table ;
9994         rr_setup_id          := empty_pls_table ;
9995         rr_sequence_id       := empty_pls_table ;
9996         rr_sequence_number   := empty_pls_table ;
9997         rr_min_capacity      := empty_num_table ;
9998         rr_max_capacity      := empty_num_table ;
9999         rr_original_seq_num  := empty_num_table ;
10000         rr_alternate_number  := empty_num_table ;
10001         rr_hours_expended    := empty_num_table ;
10002         rr_breakable_activity_flag := empty_pls_table ;
10003         rr_plan_step_qty     := empty_num_table ;
10004         rr_step_qty_uom      := rr_step_qty_uom ;
10005         rr_gmd_rsrc_cnt      := empty_pls_table ;
10006         rr_unadjusted_resource_hrs  := empty_num_table;
10007         rr_touch_time           := empty_num_table  ;
10008         rr_activity_group_id := empty_pls_table ;
10009        rr_operation_sequence_id := empty_pls_table ; /* Bug: 6030499 vpedarla back port Bug:5461922 */
10010 /* ----------------------- Supply Insert --------------------- */
10011       i := 1 ;
10012       log_message(s_organization_id.FIRST || ' *s*' || s_organization_id.LAST );
10013       IF s_organization_id.FIRST > 0 THEN
10014       FORALL i IN s_organization_id.FIRST..s_organization_id.LAST
10015         INSERT INTO msc_st_supplies (
10016         plan_id,
10017         inventory_item_id,
10018         organization_id,
10019         sr_instance_id,
10020         new_schedule_date,
10021         old_schedule_date,
10022         new_wip_start_date,
10023         old_wip_start_date,
10024         last_unit_completion_date,
10025         disposition_id,
10026         order_type,
10027         order_number,
10028         new_order_quantity,
10029         old_order_quantity,
10030         firm_planned_type,
10031         firm_quantity,
10032         firm_date,
10033         wip_entity_name,
10034         lot_number,
10035         expiration_date,
10036         operation_seq_num,
10037         by_product_using_assy_id,
10038         deleted_flag,
10039         requested_completion_date,
10040         wip_status_code, /*B5100481*/
10041         schedule_priority,
10042         process_seq_id  /* B6795244 */
10043         )
10044         VALUES (
10045         -1,
10046         s_inventory_item_id(i),
10047         s_organization_id(i),
10048         s_sr_instance_id(i),
10049         s_new_schedule_date(i),
10050         s_old_schedule_date(i),
10051         s_new_wip_start_date(i),
10052         s_old_wip_start_date(i),
10053         s_lunit_completion_date(i),
10054         s_disposition_id(i),
10055         s_order_type(i),
10056         s_order_number(i),
10057         s_new_order_quantity(i),
10058         s_old_order_quantity(i),
10059         s_firm_planned_type(i),  /* 2 */
10060         s_firm_quantity(i),
10061         s_firm_date(i),
10062         s_wip_entity_name(i),   /* Order Number */
10063         null_value,
10064         null_value,
10065         s_operation_seq_num(i),
10066         s_by_product_using_assy_id(i),
10067         2,                      /* Deleted Flag */
10068         s_requested_completion_date(i),
10069         s_wip_status_code(i), /*B5100481 - 16 for pending, 3 for wip */
10070         s_schedule_priority(i),
10071         s_process_seq_id(i)  /* B6795244 */
10072         ) ;
10073       END IF;
10074 
10075         s_inventory_item_id  := empty_pls_table ;
10076         s_organization_id    := empty_pls_table ;
10077         s_sr_instance_id     := empty_pls_table ;
10078         s_new_schedule_date  := empty_dat_table ;
10079         s_old_schedule_date  := empty_dat_table ;
10080         s_new_wip_start_date := empty_dat_table ;
10081         s_old_wip_start_date := empty_dat_table ;
10082         s_lunit_completion_date  := empty_dat_table ;
10083         s_disposition_id      := empty_pls_table ;
10084         s_order_type          := empty_pls_table ;
10085         s_order_number        := se_order_number ;
10086         s_new_order_quantity  := empty_num_table ;
10087         s_old_order_quantity  := empty_num_table ;
10088         s_firm_planned_type   := empty_pls_table ;
10089         s_firm_quantity       := empty_num_table ;
10090         s_firm_date           := empty_dat_table ;
10091         s_wip_entity_name     := se_wip_entity_name ;
10092         s_operation_seq_num   := empty_pls_table ;
10093         s_by_product_using_assy_id  := empty_pls_table ;
10094         s_lot_number          := e_lot_number;
10095         s_wip_status_code     := empty_num_table;
10096         s_requested_completion_date := empty_dat_table ;
10097         s_process_seq_id      := empty_pls_table ; /* B6795244 */
10098 
10099 /* ----------------------- Demands Insert --------------------- */
10100       i := 1 ;
10101       log_message(d_organization_id.FIRST || '*' || d_index || '*' || d_organization_id.LAST );
10102       IF d_organization_id.FIRST > 0 THEN
10103       FORALL i IN d_organization_id.FIRST..d_organization_id.LAST
10104         INSERT INTO msc_st_demands (
10105         organization_id,
10106         inventory_item_id,
10107         sr_instance_id,
10108         using_assembly_item_id,
10109         using_assembly_demand_date,
10110         using_requirement_quantity,
10111         demand_type,
10112         origination_type,
10113         wip_entity_id,
10114         demand_schedule_name,
10115         order_number,
10116         wip_entity_name,
10117         selling_price,
10118         operation_seq_num,
10119         wip_status_code, /*B5100481*/
10120         deleted_flag )
10121         VALUES (
10122         d_organization_id(i),
10123         d_inventory_item_id(i),
10124         d_sr_instance_id(i),
10125         d_assembly_item_id(i),
10126         d_demand_date(i),
10127         d_requirement_quantity(i),
10128         d_demand_type(i),
10129         d_origination_type(i),
10130         d_wip_entity_id(i),
10131         d_demand_schedule(i),
10132         d_order_number(i),
10133         d_wip_entity_name(i),
10134         d_selling_price(i),
10135         d_operation_seq_num(i),
10136         d_wip_status_code(i), /*B5100481*/
10137         2 ) ;
10138       END IF;
10139 
10140 /* akaruppa B5007729 starts*/
10141         d_organization_id    := empty_pls_table ;
10142         d_inventory_item_id  := empty_pls_table ;
10143         d_sr_instance_id     := empty_pls_table ;
10144         d_assembly_item_id   := empty_pls_table ;
10145         d_demand_date        := empty_dat_table ;
10146         d_requirement_quantity  := empty_num_table ;
10147         d_demand_type      := empty_pls_table ;
10148         d_origination_type := empty_pls_table ;
10149         d_wip_entity_id    := empty_pls_table ;
10150         d_demand_schedule  := e_demand_schedule ;
10151         d_order_number     := e_order_number ;
10152         d_wip_entity_name  := e_wip_entity_name ;
10153         d_selling_price    := empty_num_table ;
10154         d_wip_status_code  := empty_num_table;
10155         d_operation_seq_num := empty_pls_table ;
10156 /* akaruppa B5007729 End*/
10157 
10158 
10159       s_index := 0 ;
10160       d_index := 0 ;
10161       rr_index := 0 ;
10162 
10163 
10164 -- Bug:6030499 Vpedarla
10165           SELECT st.VALUE INTO v_dummy from V$MYSTAT st, V$STATNAME sn
10166           where st.STATISTIC# = sn.STATISTIC#
10167           and sn.NAME in ('session pga memory');
10168           log_message('Session pga memory production END = ' || TO_CHAR(v_dummy) );
10169 
10170 
10171 /* Bug:6030499 Vpedarla conditionalsing the insert code  */
10172 
10173 IF ( NOT collect_ps_data ) THEN
10174         return_status := TRUE;
10175         dbms_session.free_unused_user_memory;
10176         RETURN;
10177 END IF;
10178 
10179 
10180 /* NAVIN: -- START: Complex Route -- Collect Batch Step Dependencies in one insert-select --*/
10181         sql_stmt :=
10182          ' INSERT INTO msc_st_job_operation_networks '
10183          || ' ( '
10184                 || '    from_op_seq_id, '
10185                 || '    to_op_seq_id, '
10186                 || '    wip_entity_id, '
10187                 || '    dependency_type, '
10188                 || '    transition_type, '
10189                 || '    sr_instance_id, '
10190                 || '    deleted_flag, '
10191                 || '    minimum_time_offset, '
10192                 || '    maximum_time_offset, '
10193                 || '    transfer_pct, '
10194                 || '    from_op_seq_num, '
10195                 || '    to_op_seq_num, '
10196                 || '    apply_to_charges, '
10197                 || '    organization_id, '
10198                 || '    recommended '
10199          || ' ) '
10200          || ' SELECT '
10201                 ||'          gbsd.dep_step_id, '
10202                 ||'          gbsd.batchstep_id, '
10203                 ||'          ((gbsd.batch_id * 2) + 1) x_batch_id, '
10204                 ||'          decode(gbsd.dep_type,0,1,2) dependency_type, '
10205                 ||'          1, '
10206                 ||'          :1, '
10207                 ||'          2, '
10208                 ||'          gbsd.standard_delay, '
10209                 ||'          gbsd.max_delay, '
10210                 ||'          gbsd.transfer_percent, '
10211                 ||'          gbs1.batchstep_no, '
10212                 ||'          gbs2.batchstep_no, '
10213                 ||'          DECODE(NVL(gbsd.chargeable_ind,0),1,1,2), '   /* convert a Null or 0 to a 2, a 1 remains a 1 */
10214                 ||'          iwm.mtl_organization_id, '
10215                 ||           '''Y'''
10216                 ||'      FROM '
10217                 ||'          gme_batch_step_dependencies'||pdblink||' gbsd, '
10218                 ||'          gme_batch_header'||pdblink||' h,'
10219                 ||'          gme_batch_steps'||pdblink||' gbs1, '
10220                 ||'          gme_batch_steps'||pdblink||' gbs2, '
10221                 ||'          ic_whse_mst'||pdblink||' iwm, '
10222                 ||'          sy_orgn_mst'||pdblink||' som '
10223                 ||'      WHERE '
10224                 ||'               h.batch_id = gbsd.batch_id '
10225                 ||'          AND gbs1.batch_id = gbsd.batch_id '
10226                 ||'          AND gbs1.batchstep_id = gbsd.dep_step_id '
10227                 ||'          AND gbs2.batch_id = gbsd.batch_id '
10228                 ||'          AND gbs2.batchstep_id = gbsd.batchstep_id '
10229                 ||'          AND h.batch_status in (1, 2) '
10230                 ||'          AND h.plant_code = som.orgn_code '
10231                 ||'          AND som.delete_mark = 0 '
10232                 ||'          AND som.resource_whse_code = iwm.whse_code ' ;
10233 
10234 
10235 	        IF MSC_CL_GMP_UTILITY.g_in_str_org  IS NOT NULL THEN
10236 	         sql_stmt := sql_stmt
10237 	                   ||'   AND iwm.mtl_organization_id ' || MSC_CL_GMP_UTILITY.g_in_str_org ;
10238 	        END IF;
10239 
10240 	         EXECUTE IMMEDIATE  sql_stmt USING pinstance_id;
10241         /* NAVIN: ------------ END: Complex Route -- Collect Batch Step Dependencies in one insert-select ------------*/
10242 
10243 /* NAVIN: ----------------------- MTQ with Hardlinks --------------------- */
10244 i := 1 ;
10245 log_message(stp_var_itm_from_op_seq_id.FIRST || ' *jonet*' || stp_var_itm_from_op_seq_id.LAST );
10246 IF stp_var_itm_from_op_seq_id.FIRST > 0 THEN
10247 FORALL i IN stp_var_itm_from_op_seq_id.FIRST..stp_var_itm_from_op_seq_id.LAST
10248  INSERT INTO msc_st_job_operation_networks(
10249 	from_op_seq_id,
10250 	wip_entity_id,
10251 	dependency_type,
10252 	transition_type,
10253 	sr_instance_id,
10254 	deleted_flag,
10255 	from_item_id,
10256 	organization_id,
10257 	minimum_time_offset,
10258 	maximum_time_offset,
10259 	from_op_seq_num,
10260         minimum_transfer_qty,
10261         recommended
10262   )
10263  VALUES
10264   (
10265 	stp_var_itm_from_op_seq_id(i),
10266 	stp_var_itm_wip_entity_id(i),
10267 	5,	-- dependency_type for mtq with hardlink
10268 	1,	-- transition_type: primary
10269 	stp_var_itm_instance_id(i),
10270 	2,
10271 	stp_var_itm_FROM_item_ID(i),
10272 	stp_var_itm_organization_id(i),
10273 	stp_var_itm_min_tm_off(i),
10274 	stp_var_itm_max_tm_off(i),
10275 	stp_var_itm_from_op_seq_num(i),
10276         stp_var_min_tran_qty(i),
10277         'Y'
10278   );
10279 
10280 END IF ;
10281 
10282         stp_var_itm_from_op_seq_id  := empty_pls_table ;
10283         stp_var_itm_wip_entity_id   := empty_pls_table ;
10284         stp_var_itm_instance_id     := empty_pls_table ;
10285         stp_var_itm_FROM_item_ID    := empty_pls_table ;
10286         stp_var_itm_organization_id := empty_pls_table ;
10287         stp_var_itm_min_tm_off      := empty_num_table ;
10288         stp_var_itm_max_tm_off      := empty_num_table ;
10289         stp_var_itm_from_op_seq_num := empty_pls_table ;
10290         stp_var_min_tran_qty        := empty_num_table ;
10291         si_index := 0 ;
10292 /* ----------------------- MTQ with Hardlinks --------------------- */
10293 
10294 
10295 /* ----------------------- Operation Charges --------------------- */
10296 /* NAVIN: Operation Charges */
10297 i := 1;
10298 IF stp_chg_resource_id.FIRST > 0 THEN
10299  FORALL i IN stp_chg_resource_id.FIRST..stp_chg_resource_id.LAST
10300   INSERT INTO msc_st_resource_charges
10301   (
10302       sr_instance_id          ,
10303       resource_id             ,
10304       organization_id         ,
10305       department_id         ,
10306       wip_entity_id           ,
10307       operation_sequence_id   ,
10308       operation_seq_num       ,
10309       resource_seq_num        ,
10310       charge_number              ,
10311       charge_quantity         ,
10312       deleted_flag            ,
10313       charge_start_datetime   ,
10314       charge_end_datetime
10315   )
10316 
10317    VALUES
10318 
10319   (
10320       stp_instance_id(i)      ,
10321       stp_chg_resource_id(i)  ,
10322       stp_chg_organization_id(i),
10323       stp_chg_department_id(i),
10324       stp_chg_wip_entity_id(i),
10325       stp_chg_operation_seq_id(i),
10326       stp_chg_operation_seq_no(i),
10327       stp_chg_resource_seq_num(i),
10328       stp_chg_charge_num(i),
10329       stp_chg_charge_quanitity(i),
10330       2,
10331       stp_chg_charge_start_dt_time(i) ,
10332       stp_chg_charge_end_dt_time(i)
10333   );
10334 END IF ;
10335 
10336         stp_instance_id           := empty_pls_table ;
10337         stp_chg_resource_id       := empty_pls_table ;
10338         stp_chg_organization_id   := empty_pls_table ;
10339         stp_chg_department_id     := empty_pls_table ;
10340         stp_chg_wip_entity_id     := empty_pls_table ;
10341         stp_chg_operation_seq_id  := empty_pls_table ;
10342         stp_chg_operation_seq_no  := empty_pls_table ;
10343         stp_chg_resource_seq_num  := empty_pls_table ;
10344         stp_chg_charge_num        := empty_num_table ;
10345         stp_chg_charge_quanitity  := empty_num_table ;
10346         stp_chg_charge_start_dt_time := stpe_chg_charge_start_dt_time ;
10347         stp_chg_charge_end_dt_time   := stpe_chg_charge_end_dt_time ;
10348         chg_res_index := 0 ;
10349 /* ----------------------- Operation Charges  --------------------- */
10350 
10351 /* ----------------------- Resource Instances  --------------------- */
10352 
10353      i := 1 ;
10354      log_message(rec_inst_organization_id.FIRST || ' *rir*' || rec_inst_organization_id.LAST );
10355      IF rec_inst_organization_id.FIRST > 0 THEN
10356      FORALL i IN rec_inst_organization_id.FIRST..rec_inst_organization_id.LAST
10357        INSERT INTO msc_st_resource_instance_reqs (
10358         supply_id,
10359         organization_id,
10360         sr_instance_id,
10361         resource_seq_num,
10362         resource_id,
10363         res_instance_id,
10364         start_date,
10365         end_date,
10366         resource_instance_hours,
10367 /* NAVIN :- CHECK Should This be Included. It is
10368 mentioned in FDD, but not included in APS script file. */
10369 --        schedule_flag,
10370         operation_seq_num,
10371         department_id,
10372         wip_entity_id,
10373         serial_number,
10374         deleted_flag,
10375         parent_seq_num, /* Sowmya -  as the column was changed from parent_seq_number to parent_seq_num */
10376         orig_resource_seq_num,
10377         equipment_item_id /*Sowmya - As per the latest FDD changes - End*/
10378         )
10379         VALUES (
10380         rec_inst_supply_id(i) ,
10381         rec_inst_organization_id(i) ,
10382         rec_inst_sr_instance_id(i) ,
10383         rec_inst_rec_resource_seq_num(i) ,
10384         rec_inst_resource_id(i) ,
10385         rec_inst_instance_id(i) ,
10386         rec_inst_start_date(i) ,
10387         rec_inst_end_date(i) ,
10388         rec_inst_rsrc_instance_hours(i) ,
10389 --        1 , /* Schedule Flag 1 = Scheduled */
10390         rec_inst_operation_seq_num(i) ,
10391         rec_inst_department_id(i) ,
10392         rec_inst_wip_entity_id(i) ,
10393         rec_inst_serial_number(i) ,
10394         2 , /* Delete Flag */
10395         rec_inst_parent_seq_num(i) ,
10396         rec_inst_original_seq_num(i),
10397         rec_inst_equp_item_id(i) /*Sowmya - As per the latest FDD changes - End*/
10398         )   ;
10399      END IF;
10400 
10401         rec_inst_supply_id             := empty_pls_table ;
10402         rec_inst_organization_id       := empty_pls_table ;
10403         rec_inst_sr_instance_id        := empty_pls_table ;
10404         rec_inst_rec_resource_seq_num  := empty_pls_table ;
10405         rec_inst_resource_id           := empty_pls_table ;
10406         rec_inst_instance_id           := empty_pls_table ;
10407         rec_inst_start_date            := empty_dat_table ;
10408         rec_inst_end_date              := empty_dat_table ;
10409         rec_inst_rsrc_instance_hours   := empty_num_table ;
10410         rec_inst_operation_seq_num     := empty_pls_table ;
10411         rec_inst_department_id         := empty_pls_table ;
10412         rec_inst_wip_entity_id         := empty_pls_table ;
10413         rec_inst_serial_number         := empty_inst_serial_number ;   -- Bug 5713355
10414         rec_inst_parent_seq_num        := empty_num_table ;
10415         rec_inst_original_seq_num      := empty_num_table ;
10416         rec_inst_equp_item_id          := empty_pls_table ;
10417         inst_indx := 0;
10418 /* ----------------------- Resource Instances  --------------------- */
10419 
10420 /* ----------------------- Alternate Resources --------------------- */
10421 /*Sowmya - As per the latest FDD changes - Start*/
10422      i := 1 ;
10423      log_message(arr_organization_id.FIRST || ' *rir*' || arr_organization_id.LAST );
10424      IF arr_organization_id.FIRST > 0 THEN
10425      FORALL i IN arr_organization_id.FIRST..arr_organization_id.LAST
10426 
10427         INSERT INTO msc_st_job_op_resources
10428         (
10429          wip_entity_id,
10430          organization_id,
10431          sr_instance_id ,
10432          operation_seq_num ,
10433          resource_seq_num ,
10434          resource_id ,
10435          alternate_num ,
10436          reco_start_date ,
10437          reco_completion_date ,
10438          usage_rate_or_amount  ,
10439          assigned_units ,
10440          schedule_flag ,
10441          parent_seq_num ,
10442          recommended ,
10443          department_id ,
10444          uom_code ,
10445          activity_group_id ,
10446          basis_type ,
10447          firm_flag ,
10448          setup_id ,
10449          schedule_seq_num  ,
10450          group_sequence_id ,
10451          group_sequence_number ,
10452 --         resource_batch_id ,
10453          maximum_assigned_units ,
10454          deleted_flag ,
10455          batch_number
10456         )
10457         VALUES
10458         (
10459         arr_wip_entity_id(i),
10460         arr_organization_id(i),
10461         arr_sr_instance_id(i),
10462         arr_operation_seq_num(i),
10463         arr_res_seq_num(i),
10464         arr_resource_id(i),
10465         arr_alternate_num(i),
10466         null_value,
10467         null_value,
10468         arr_usage_rate(i),
10469         arr_assigned_units(i),
10470         1,
10471         null_value,
10472         1,
10473         arr_department_id(i),
10474         arr_uom_code(i),
10475         arr_activity_group_id(i),
10476         arr_basis_type(i),
10477         null_value,
10478         arr_setup_id(i),
10479         arr_schedule_seq_num(i),
10480         null_value,
10481         null_value,
10482 --        null_value,
10483         arr_maximum_assigned_units(i),
10484         2,
10485         null_value
10486         );
10487 
10488      END IF;
10489 
10490         arr_wip_entity_id              := empty_pls_table ;
10491         arr_organization_id            := empty_pls_table ;
10492         arr_sr_instance_id             := empty_pls_table ;
10493         arr_operation_seq_num          := empty_pls_table ;
10494         arr_res_seq_num                := empty_num_table ;
10495         arr_resource_id                := empty_pls_table ;
10496         arr_alternate_num              := empty_num_table ;
10497         arr_usage_rate                 := empty_num_table ;
10498         arr_assigned_units             := empty_num_table ;
10499         arr_department_id              := empty_pls_table ;
10500         arr_uom_code                   := arre_uom_code   ;
10501         arr_activity_group_id          := empty_pls_table ;
10502         arr_basis_type                 := empty_pls_table ;
10503         arr_setup_id                   := empty_pls_table ;
10504         arr_schedule_seq_num           := empty_pls_table ;
10505         arr_maximum_assigned_units     := empty_pls_table ;
10506         arr_index := 0;
10507 
10508 
10509 /*Sowmya - As per the latest FDD changes - End*/
10510 /* ----------------------- Alternate Resources --------------------- */
10511 
10512 /* nsinghi : Populate Msc_Job_Operations Table. */
10513 /* ----------------------- Job Operations --------------------- */
10514      i := 1 ;
10515      log_message(jo_wip_entity_id.FIRST || ' *jo*' || jo_wip_entity_id.LAST );
10516      IF jo_wip_entity_id.FIRST > 0 THEN
10517      FORALL i IN jo_wip_entity_id.FIRST..jo_wip_entity_id.LAST
10518         INSERT INTO msc_st_job_operations
10519         (
10520            wip_entity_id,
10521            sr_instance_id,
10522            operation_seq_num,
10523            recommended,
10524            network_start_end,
10525            reco_start_date,
10526            reco_completion_date,
10527            operation_sequence_id,
10528            organization_id,
10529            department_id,
10530            minimum_transfer_quantity,
10531            effectivity_date,
10532            deleted_flag
10533         )
10534         VALUES
10535         (
10536            jo_wip_entity_id(i),
10537            jo_instance_id(i),
10538            jo_operation_seq_num(i),
10539            jo_recommended(i),
10540            jo_network_start_end(i),
10541            jo_reco_start_date(i),
10542            jo_reco_completion_date(i),
10543            jo_operation_sequence_id(i),
10544            jo_organization_id(i),
10545            jo_department_id(i),
10546            jo_minimum_transfer_quantity(i),
10547            (SYSDATE-100),
10548            2
10549         );
10550 
10551      END IF;
10552 
10553         jo_wip_entity_id         := empty_pls_table ;
10554         jo_instance_id           := empty_pls_table ;
10555         jo_operation_seq_num     := empty_pls_table ;
10556         jo_recommended           := joe_recommended ;
10557         jo_network_start_end     := joe_network_start_end;
10558         jo_reco_start_date       := empty_dat_table ;
10559         jo_reco_completion_date  := empty_dat_table ;
10560         jo_operation_sequence_id := empty_pls_table ;
10561         jo_organization_id       := empty_pls_table ;
10562         jo_department_id         := empty_pls_table ;
10563         jo_minimum_transfer_quantity := empty_num_table ;
10564         jo_index := 0;
10565 
10566 -- Bug: 6030499 Vpedarla end of conditionalised code
10567 
10568 
10569       dbms_session.free_unused_user_memory;/* akaruppa B5007729 */
10570 
10571 /* ----------------------- Job Operations --------------------- */
10572 
10573   return_status := TRUE;
10574 
10575   EXCEPTION
10576     WHEN invalid_string_value  THEN
10577         log_message('Organization string is Invalid ' );
10578         return_status := FALSE;
10579 
10580     WHEN invalid_gmp_uom_profile THEN
10581         log_message('Profile "GMP: UOM for Hour" is Invalid ' );
10582         return_status := FALSE;
10583 
10584     WHEN NO_DATA_FOUND THEN /* B3577871 */
10585       log_message(' NO_DATA_FOUND exception raised in Procedure: Gmp_aps_ds_pull.Production_orders ' );
10586       return_status := TRUE;
10587 
10588     WHEN OTHERS THEN
10589 	return_status := FALSE;
10590 	log_message('Failure occured during Production Orders extract' || sqlerrm);
10591 	log_message(sqlerrm);
10592 
10593 END production_orders;
10594 
10595 /***********************************************************************
10596 *
10597 *   NAME
10598 *	insert_supplies
10599 *
10600 *   DESCRIPTION
10601 *	This procedure will take the parameter values and insert a row into
10602 *	the table msc_st_supplies
10603 *   HISTORY
10604 *	M Craig
10605 *  2/10/2000 - Populating Order number column with Wip Entity Name  ( porder_no )
10606 *  2/24/2003 - populating Firmed batches Indicator, Qty and Date
10607 ************************************************************************/
10608 PROCEDURE insert_supplies(
10609   pitem_id          NUMBER,
10610   porganization_id  NUMBER,
10611   pinstance_id      NUMBER,
10612   pdate             DATE,
10613   pstart_date       DATE,
10614   pend_date         DATE,
10615   pbatch_id         NUMBER,
10616   pqty              NUMBER,
10617   pfirmed_ind       NUMBER,
10618   pbatchstep_no     NUMBER,   /* Added pbatchstep_no - B2919303 */
10619   porder_no         VARCHAR2,
10620   plot_number       VARCHAR2,
10621   pexpire_date      DATE,
10622   psupply_type      NUMBER,
10623   pproduct_item_id  NUMBER)     /* B2953953 - CoProduct */
10624 
10625 AS
10626   st_supplies  VARCHAR2(32000) ;
10627   vproduct_item_id NUMBER ;  /* B2953953 - CoProduct */
10628 BEGIN
10629 
10630   st_supplies :=
10631     ' INSERT INTO msc_st_supplies ( '
10632   ||' plan_id, inventory_item_id, organization_id, sr_instance_id, '
10633   ||' new_schedule_date, old_schedule_date, new_wip_start_date, '
10634   ||' old_wip_start_date, last_unit_completion_date, disposition_id, '
10635   ||' order_type, order_number, new_order_quantity, old_order_quantity, '
10636   ||' firm_planned_type,firm_quantity,firm_date, wip_entity_name, '
10637   ||' lot_number, expiration_date,operation_seq_num, by_product_using_assy_id, '
10638   ||' deleted_flag ) '
10639   ||' VALUES '
10640   ||' (:p1, :p2, :p3, :p4, '
10641   ||'  :p5, :p6, :p7,      '
10642   ||'  :p8, :p9, :p10,     '
10643   ||'  :p11,:p12,:p13,:p14,'
10644   ||'  :p15,:p16,:p17,:p18,'
10645   ||'  :p19,:p20,:p21,'
10646   ||'  :p22,:p23 ) ' ;
10647 
10648   /* B2953953 The by_product_assy_id should not be written for Products ,
10649      but should be written for co-products and by-products */
10650 
10651   IF psupply_type = 3 THEN
10652      vproduct_item_id := to_number(NULL) ;
10653   ELSE
10654     vproduct_item_id := pproduct_item_id ;
10655   END IF;
10656 
10657     EXECUTE IMMEDIATE st_supplies USING
10658     -1,
10659     pitem_id,
10660     porganization_id,
10661     pinstance_id,
10662     pdate,
10663     pdate,
10664     pstart_date,
10665     pstart_date,
10666     pend_date,
10667     pbatch_id,
10668     psupply_type,
10669     porder_no,     /* Populating Order no column - bug#1152778 */
10670     pqty,
10671     pqty,
10672     /* 2, */
10673     pfirmed_ind,  /* B2821248 Firmed Batches Indicator - */
10674     pqty,         /* B2821248 Firmed Batches Qty  - */
10675     pdate,        /* B2821248 Firmed Batches Date - */
10676     porder_no,
10677     plot_number,
10678     pexpire_date,
10679     pbatchstep_no,  /* B2919303 */
10680     vproduct_item_id,  /* B2953953 - Co-Product      - */
10681     2 ;
10682 
10683   EXCEPTION
10684     WHEN OTHERS THEN
10685 	log_message('Failure occured during the insert into msc_st_supplies');
10686 	log_message(sqlerrm);
10687         RAISE;
10688 
10689 END insert_supplies;
10690 
10691 /***********************************************************************
10692 *
10693 *   NAME
10694 *	 insert_resource_requirements
10695 *
10696 *   DESCRIPTION
10697 *	This procedure wil insert a row into the table
10698 *	msc_st_resource_requirements using the parameters passed in
10699 *   HISTORY
10700 * 	M Craig
10701 * 	10/13/99 - Added deleted_flag in the insert statement
10702 *       13-SEP-2002 - firm_flag = 1 for WIP steps B2266934
10703 ************************************************************************/
10704 PROCEDURE insert_resource_requirements(
10705   porganization_id  IN NUMBER,
10706   pinstance_id      IN NUMBER,
10707   pseq_num          IN NUMBER,
10708   presource_id      IN NUMBER,
10709   pstart_date       IN DATE,
10710   pend_date         IN DATE,
10711   presource_usage   IN NUMBER,
10712   prsrc_cnt         IN NUMBER,
10713   pbatchstep_no     IN NUMBER,  /* B1224660 new parm to write step number */
10714   pbatch_id         IN NUMBER,
10715   pstep_status      IN NUMBER,
10716   pschedule_flag    IN NUMBER,
10717   pparent_seq_num   IN NUMBER,
10718   pmin_xfer_qty     IN NUMBER)
10719 
10720 AS
10721   st_resource_requirements  VARCHAR2(32000) ;
10722 
10723 BEGIN
10724   st_resource_requirements :=
10725        ' INSERT INTO msc_st_resource_requirements ( '
10726        ||' organization_id, sr_instance_id, supply_id, resource_seq_num,'
10727        ||' resource_id, start_date, end_date, operation_hours_required,'
10728        ||' assigned_units, department_id, wip_entity_id, operation_seq_num, '
10729        ||' deleted_flag, firm_flag, minimum_transfer_quantity, '
10730        ||' parent_seq_num, schedule_flag ) '
10731        ||' VALUES '
10732        ||' ( :p1, :p2, :p3, :p4, '
10733        ||'   :p5, :p6, :p7, :p8, '
10734        ||'   :p9, :p10,:p11,:p12, '
10735        ||'   :p13,:p14, :p15, '
10736        ||'   :p16, :p17 ) ';
10737 
10738   EXECUTE IMMEDIATE st_resource_requirements USING
10739     porganization_id,
10740     pinstance_id,
10741     pbatch_id,
10742     pseq_num,
10743     presource_id,
10744     pstart_date,
10745     pend_date,
10746     presource_usage,
10747     prsrc_cnt,
10748     ((porganization_id * 2) + 1),  /* B1177070 encoded key */
10749     pbatch_id,
10750     pbatchstep_no,  /* B1224660 write the step number for oper seq num */
10751     2,
10752     pstep_status,
10753     pmin_xfer_qty,
10754     pparent_seq_num,
10755     pschedule_flag ;
10756 
10757   EXCEPTION
10758     WHEN OTHERS THEN
10759 	log_message('Failure occured during the insert into msc_st_resource_requirements');
10760 	log_message(sqlerrm);
10761         RAISE;
10762 
10763 END insert_resource_requirements;
10764 
10765 /***********************************************************************
10766 *
10767 *   NAME
10768 *	insert_demands
10769 *
10770 *   DESCRIPTION
10771 *	This procedure will take the parameter values and insert a row into
10772 *	the table msc_st_demands
10773 *   HISTORY
10774 *	M Craig
10775 *	10/13/99 - Added deleted_flag in the insert statement
10776 *     P Dong
10777 *     09/14/01 - added api_mode and pschedule_id parameters
10778 ************************************************************************/
10779 PROCEDURE insert_demands(
10780   pitem_id          NUMBER,
10781   porganization_id  NUMBER,
10782   pinstance_id      NUMBER,
10783   pbatch_id         NUMBER,
10784   pproduct_item_id  NUMBER,
10785   pdate             DATE,
10786   pqty              NUMBER,
10787   pbatchstep_no     NUMBER,   /* B2919303 - BatchStep */
10788   porder_no         VARCHAR2,
10789   pdesignator       VARCHAR2,
10790   pnet_price        NUMBER,  /* B1200400 added net price */
10791   porigination_type NUMBER,
10792   api_mode          BOOLEAN,
10793   pschedule_id      NUMBER )
10794 
10795 AS
10796 
10797   statement_demands_api  VARCHAR2(32000) ;
10798   statement_demands      VARCHAR2(32000) ;
10799   t_order_number         VARCHAR2(70)   ;
10800   t_wip_entity_name      VARCHAR2(70)   ;
10801 
10802 BEGIN
10803   t_order_number         := NULL ;
10804   t_wip_entity_name      := NULL ;
10805 
10806 /* mfc 11-30-99 changed to write batch_id to wip_entity_id */
10807 
10808 IF api_mode
10809 THEN
10810   BEGIN
10811     statement_demands_api  :=
10812       ' INSERT INTO gmp_demands_api ( '
10813     ||'  organization_id, schedule_id, inventory_item_id, demand_date, '
10814     ||'  demand_quantity, origination_type, doc_id, selling_price ) '
10815     ||' VALUES '
10816     ||' ( :p1, :p2, :p3, :p4, '
10817     ||'   :p5, :p6, :p7, :p8 ) ';
10818 
10819     EXECUTE IMMEDIATE statement_demands_api USING
10820       porganization_id,
10821       pschedule_id,
10822       pitem_id,
10823       pdate,
10824       pqty,
10825       porigination_type,
10826       pbatch_id,
10827       pnet_price;
10828 
10829   EXCEPTION
10830     WHEN OTHERS THEN
10831 	log_message('Failure occured during the insert into gmp_demands_api');
10832 	log_message(sqlerrm);
10833       RAISE;
10834   END;
10835 ELSE
10836   BEGIN
10837 
10838      SELECT DECODE(porigination_type,1,NULL,porder_no) ,
10839             DECODE(porigination_type,1,porder_no,NULL)
10840      INTO t_order_number, t_wip_entity_name
10841      FROM dual ;
10842 
10843     statement_demands  :=
10844       ' INSERT INTO msc_st_demands ( '
10845     ||' organization_id, inventory_item_id, sr_instance_id, '
10846     ||' using_assembly_item_id, using_assembly_demand_date, '
10847     ||' using_requirement_quantity, demand_type, origination_type, '
10848     ||' wip_entity_id, demand_schedule_name, order_number, '
10849     ||' wip_entity_name, selling_price,operation_seq_num,deleted_flag ) '
10850     ||' VALUES '
10851     ||' ( :p1, :p2, :p3,  '
10852     ||'   :p4, :p5,       '
10853     ||'   :p6, :p7, :p8 , '
10854     ||'   :p9, :p10,:p11, '
10855     ||'   :p12,:p13,:p14,:p15 )' ;
10856 
10857     EXECUTE IMMEDIATE statement_demands USING
10858       porganization_id,
10859       pitem_id,
10860       pinstance_id,
10861       pproduct_item_id,
10862       pdate,
10863       pqty,
10864       1,
10865       porigination_type,
10866       pbatch_id,
10867       pdesignator,
10868       t_order_number,
10869       t_wip_entity_name,
10870       pnet_price,    /* B1200400 added for net price */
10871       pbatchstep_no,  /* B2919303 */
10872       2 ;
10873   EXCEPTION
10874     WHEN OTHERS THEN
10875 	log_message('Failure occured during the insert into msc_st_demands');
10876 	log_message(sqlerrm);
10877       RAISE;
10878   END;
10879 
10880 END IF;
10881 
10882 END insert_demands;
10883 
10884 /***********************************************************************
10885 *
10886 *   NAME
10887 *	 onhand_inventory
10888 *
10889 *   DESCRIPTION
10890 *	This procedure will insert records into the table msc_st_supplies
10891 *	for the onhand balances in inventory. The insert is split into 3 parts
10892 *	one for non-lot controlled, lot controlled, and lot and status
10893 *	controlled item. Each inserted will need touse a distnct list from
10894 *	the table gmp_item_aps. The table may contain multiple values for
10895 *	the item/whse combination
10896 *   HISTORY
10897 * 	M Craig
10898 *  M Craig B1332662 changed to call two new procs to collect onhand and
10899 *          Inventory transfers
10900 *   Navin   21-APR-2003 B3577871 ST:OSFME2: collections failing in planning data pull.
10901 *                                Added handling of NO_DATA_FOUND Exception.
10902 *                                And return the return_status as TRUE.
10903 ************************************************************************/
10904 PROCEDURE onhand_inventory(
10905   pdblink        IN  VARCHAR2,
10906   pinstance_id   IN  NUMBER,
10907   prun_date      IN  DATE,
10908   pdelimiter     IN  VARCHAR2,
10909   return_status  IN OUT NOCOPY BOOLEAN)
10910 AS
10911 
10912   local_ret_status1       BOOLEAN ;
10913   local_ret_status2       BOOLEAN ;
10914   onhand_balances_failure EXCEPTION ;
10915   inv_transfer_failure    EXCEPTION ;
10916 
10917 BEGIN
10918 
10919 /* Bug:6030499 Vpedarla added profile verification */
10920 
10921     collect_ps_data := TRUE;
10922 
10923   local_ret_status1  := TRUE;
10924   local_ret_status2  := TRUE;
10925 
10926   IF return_status THEN
10927     v_cp_enabled := TRUE;
10928   ELSE
10929     v_cp_enabled := FALSE;
10930   END IF;
10931 
10932   extract_onhand_balances( pdblink, pinstance_id, prun_date, pdelimiter,
10933     local_ret_status1);
10934 
10935   IF local_ret_status1 = TRUE THEN
10936     return_status := TRUE;
10937   ELSE
10938     return_status := FALSE;
10939     RAISE  onhand_balances_failure ;
10940   END IF;
10941 
10942    /* B 2756431 Changed the call to new proceudre */
10943   extract_inv_transfer_supplies(pdblink, pinstance_id, prun_date,
10944      pdelimiter, local_ret_status2);
10945 
10946 -- Bug: 6030499 Vpedarla added this as part of non-ps code
10947   /* B5665290, Same as 11.5.9 MDS demand needs to be sent to APS */
10948 	extract_inv_transfer_demands( pdblink     ,
10949 		pinstance_id   ,
10950 		prun_date      ,
10951 		pdelimiter    ,
10952 		NULL,
10953 		NULL ,
10954 		return_status ) ;
10955 
10956 
10957   IF local_ret_status2 = TRUE  THEN
10958     return_status := TRUE ;
10959   ELSE
10960     return_status := FALSE;
10961     RAISE  inv_transfer_failure ;
10962   END IF;
10963 
10964   EXCEPTION
10965     WHEN onhand_balances_failure THEN
10966       log_message(' extract_onhand_balances_failure raised in Procedure: Gmp_aps_ds_pull.Onhand_inventory ' );
10967       return_status := FALSE;
10968     WHEN inv_transfer_failure THEN
10969       log_message(' extract_inv_transfer_supplies_failure raised in Procedure: Gmp_aps_ds_pull.Onhand_inventory ' );
10970       return_status := FALSE;
10971     WHEN NO_DATA_FOUND THEN /* B3577871 */
10972       log_message(' NO_DATA_FOUND exception raised in Procedure: Gmp_aps_ds_pull.Onhand_inventory ' );
10973       return_status := TRUE;
10974 
10975 END onhand_inventory;  /* end onhand_inventory */
10976 
10977 /***********************************************************************
10978 *
10979 *   NAME
10980 *	extract_onhand_balances
10981 *
10982 *   DESCRIPTION
10983 *	This procedure will insert records into the table msc_st_supplies
10984 *	for the onhand balances in inventory. The insert is split into 3 parts
10985 *	one for non-lot controlled, lot controlled, and lot and status
10986 *	controlled item. Each inserted will need touse a distnct list from
10987 *	the table gmp_item_aps. The table may contain multiple values for
10988 *	the item/whse combination
10989 *   HISTORY
10990 * 	M Craig
10991 * 	10/13/99 - Added deleted_flag in the insert statement
10992 *	2/10/2000 - Populating sub inventory code with whse code - bug# 1172875
10993 *  M Craig B1332662 created a new function to just collect onhand inventory
10994 *  Sgidugu  B2251375 - Changed Substr Function to substrb Function
10995 *  AKARUPPA B4287033 - Changed direct insert selects to BULK INSERT as direct insert
10996 *		       select over dblink causes performance issues.
10997 *  AKARUPPA B4278082 - Changed query to select status controlled items to
10998 *		       fetch items with status control as No Inventory (status_ctl = 2)
10999 ************************************************************************/
11000 PROCEDURE extract_onhand_balances(
11001   pdblink        IN  VARCHAR2,
11002   pinstance_id   IN  NUMBER,
11003   prun_date      IN  DATE,
11004   pdelimiter     IN  VARCHAR2,
11005   return_status  IN OUT NOCOPY BOOLEAN)
11006 AS
11007 
11008 /* akaruppa B4287033 07-APR-2005 Adding new variable definitions for doing BULK INSERT in place of direct INSERT SELECT */
11009   TYPE onhand_balance_nolot_typ IS RECORD(
11010 	  plan_id		PLS_INTEGER,
11011 	  inventory_item_id	PLS_INTEGER,
11012 	  organization_id	PLS_INTEGER,
11013 	  sr_instance_id	PLS_INTEGER,
11014 	  new_schedule_date	DATE,
11015 	  order_type		PLS_INTEGER,
11016 	  firm_planned_type	PLS_INTEGER,
11017 	  deleted_flag		PLS_INTEGER,
11018 	  subinventory_code	VARCHAR2(10),
11019 	  new_order_quantity	NUMBER );
11020 
11021   TYPE onhand_balance_nolot_tbl IS TABLE OF onhand_balance_nolot_typ INDEX by BINARY_INTEGER;
11022   onhand_balance_nolot_tab   onhand_balance_nolot_tbl;
11023 
11024   TYPE onhand_balance_lot_typ IS RECORD(
11025 	  plan_id		PLS_INTEGER,
11026 	  inventory_item_id	PLS_INTEGER,
11027 	  organization_id	PLS_INTEGER,
11028 	  sr_instance_id	PLS_INTEGER,
11029 	  new_schedule_date	DATE,
11030 	  order_type		PLS_INTEGER,
11031 	  lot_number		VARCHAR2(30),
11032 	  expiration_date	DATE,
11033 	  firm_planned_type	PLS_INTEGER,
11034 	  deleted_flag		PLS_INTEGER,
11035 	  subinventory_code	VARCHAR2(10),
11036 	  new_order_quantity	NUMBER );
11037 
11038   TYPE onhand_balance_lot_tbl IS TABLE OF onhand_balance_lot_typ INDEX by BINARY_INTEGER;
11039   onhand_balance_lot_tab   onhand_balance_lot_tbl;
11040 
11041   TYPE onhand_balance_status_typ IS RECORD(
11042 	  plan_id		PLS_INTEGER,
11043 	  inventory_item_id	PLS_INTEGER,
11044 	  organization_id	PLS_INTEGER,
11045 	  sr_instance_id	PLS_INTEGER,
11046 	  new_schedule_date	DATE,
11047 	  new_dock_date		DATE,
11048 	  order_type		PLS_INTEGER,
11049 	  lot_number		VARCHAR2(30),
11050 	  expiration_date	DATE,
11051 	  firm_planned_type	PLS_INTEGER,
11052 	  deleted_flag		PLS_INTEGER,
11053 	  subinventory_code	VARCHAR2(10),
11054 	  new_order_quantity	NUMBER,
11055 	  non_nettable_qty 	NUMBER );
11056 
11057   TYPE onhand_balance_status_tbl IS TABLE OF onhand_balance_status_typ INDEX by BINARY_INTEGER;
11058   onhand_balance_status_tab   onhand_balance_status_tbl;
11059 
11060   TYPE gmp_cursor_typ IS REF CURSOR;
11061   c_onhand_balance_nolot  gmp_cursor_typ;
11062   c_onhand_balance_lot	  gmp_cursor_typ;
11063   c_onhand_balance_status gmp_cursor_typ;
11064 
11065   v_onhand_cursor   VARCHAR2(32000) ;
11066   onhand_count      NUMBER;
11067   insert_count      NUMBER;
11068 
11069   /* End of definitions for B4287033 */
11070 
11071  l_profile NUMBER ; /* Bug # 5238790 */
11072  sy_max_date DATE ; -- Vpedarla bug: 6030499
11073 
11074 BEGIN
11075 
11076    log_message('Entering Extract_OnHand_Balances. ');
11077    time_stamp ;
11078 
11079    /* Bug # 5238790 */
11080    l_profile := 0 ;
11081 
11082 --   l_profile := NVL(FND_PROFILE.VALUE('GMP_COLLECT_EXPR_ONHAND'),0) ;
11083  /* bug:6710684 Vpedarla made changes to fetch the profile value from source server*/
11084    l_profile := NVL(get_profile_value('GMP_COLLECT_EXPR_ONHAND', pdblink ),0);
11085 
11086   onhand_count     := 1;
11087   v_onhand_cursor  := NULL;
11088   insert_count     := 1;
11089 
11090 --  sy_max_date := to_date(FND_PROFILE.VALUE('SY$MAX_DATE'),'YYYY/MM/DD');   -- Bug:6030499 Vpedarla
11091  /* bug:6710684 Vpedarla made changes to fetch the profile value from source server*/
11092   sy_max_date := to_date(get_profile_value('SY$MAX_DATE', pdblink ),'YYYY/MM/DD');
11093 
11094   /* Query to select the production order details where the batch/fpo is pending
11095   the balances from ic_summ for the item/whse that are not lot controlled
11096   are inserted */
11097   v_onhand_cursor :=   ' SELECT '
11098 	 || ' -1,'
11099 	 || ' i.aps_item_id,'
11100 	 || ' i.organization_id,'
11101 	 || ' :pinstance_id, '
11102 	 || ' :prun_date, '
11103 	 || ' 18,'                        /* onhand inventory value */
11104 	 || ' 2,'
11105 	 || ' 2,'
11106 	 || ' s.whse_code,' /* Populate subinventory with Whse code B1172875 */
11107 	 || ' s.onhand_qty'
11108 	 || ' FROM '
11109 	 || ' ic_summ_inv_onhand_v' ||pdblink|| ' s,'
11110 	 || ' (select distinct aps_item_id,item_id,whse_code,organization_id, '
11111 	 || '  lot_control,experimental_ind from gmp_item_aps'||pdblink||') i'
11112 	 || ' WHERE '
11113 	 || ' s.item_id = i.item_id '
11114 	 || ' and s.whse_code = i.whse_code '
11115 	 || ' and i.lot_control = 0'
11116 	 || ' and s.onhand_qty <> 0';
11117 
11118         /* Bug # 5238790 */
11119         IF l_profile = 0 THEN
11120            v_onhand_cursor := v_onhand_cursor
11121          || ' and i.experimental_ind = 0 ' ;
11122         END IF;
11123 
11124     OPEN c_onhand_balance_nolot FOR v_onhand_cursor USING pinstance_id, prun_date;
11125     LOOP
11126       FETCH  c_onhand_balance_nolot INTO onhand_balance_nolot_tab(onhand_count);
11127       EXIT WHEN  c_onhand_balance_nolot%NOTFOUND ;
11128       onhand_count := onhand_count + 1;
11129     END LOOP;
11130     CLOSE c_onhand_balance_nolot ;
11131     gonhand_balance_size := onhand_count - 1;
11132 
11133    log_message('No lot on hand fetches : '|| to_char(gonhand_balance_size) );
11134    time_stamp ;
11135 
11136 -- Bug:6030499 Vpedarla
11137           SELECT st.VALUE INTO v_dummy from V$MYSTAT st, V$STATNAME sn
11138           where st.STATISTIC# = sn.STATISTIC#
11139           and sn.NAME in ('session pga memory');
11140           log_message('Session pga memory = ' || TO_CHAR(v_dummy) );
11141 
11142 
11143    IF onhand_count > 1 THEN
11144    FOR i in onhand_balance_nolot_tab.FIRST..onhand_balance_nolot_tab.LAST
11145    LOOP
11146     o_plan_id(insert_count)            :=  onhand_balance_nolot_tab(i).plan_id;
11147     o_inventory_item_id(insert_count)  :=  onhand_balance_nolot_tab(i).inventory_item_id;
11148     o_organization_id(insert_count)    :=  onhand_balance_nolot_tab(i).organization_id;
11149     o_sr_instance_id(insert_count)     :=  onhand_balance_nolot_tab(i).sr_instance_id;
11150     o_new_schedule_date(insert_count)  :=  onhand_balance_nolot_tab(i).new_schedule_date;
11151     o_new_dock_date(insert_count)      :=  NULL;
11152     o_order_type(insert_count)         :=  onhand_balance_nolot_tab(i).order_type;
11153     o_lot_number(insert_count)	       :=  NULL;
11154     o_expiration_date(insert_count)    :=  NULL;
11155     o_firm_planned_type(insert_count)  :=  onhand_balance_nolot_tab(i).firm_planned_type;
11156     o_deleted_flag(insert_count)       :=  onhand_balance_nolot_tab(i).deleted_flag;
11157     o_subinventory_code(insert_count)  :=  onhand_balance_nolot_tab(i).subinventory_code;
11158     o_new_order_quantity(insert_count) :=  onhand_balance_nolot_tab(i).new_order_quantity;
11159     o_non_nettable_qty(insert_count)   :=  NULL;
11160     insert_count := insert_count + 1;
11161    END LOOP;
11162    END IF;
11163 
11164     onhand_count := 1;
11165 
11166     v_onhand_cursor := NULL;
11167 
11168   /* Get onhand balances from the location inventory table for lot controlled
11169      items. The lot can not be status controlled, that will be in the next
11170      insert the lot number is the combo of lot and sublot
11171   */
11172   v_onhand_cursor :=   ' SELECT /*+ DRIVING_SITE(s) DRIVING_SITE(l) DRIVING_SITE(m) */ '
11173 	    || ' -1,'
11174 	    || ' i.aps_item_id,'
11175 	    || ' i.organization_id,'
11176 	    || ' :pinstance_id,'
11177 	    || ' :prun_date,'
11178 	    || ' 18,'                        /* onhand inventory value */
11179 	    || ' substrb(l.lot_no||DECODE(l.sublot_no, NULL,NULL ,:pdelimiter || '
11180 	    || ' l.sublot_no),1,30),'
11181 	    || ' l.expire_date,'
11182 	    || ' 2,'
11183 	    || ' 2,'
11184 	    || ' s.whse_code,' /* Populate subinventory with whse code B1172875 */
11185 	    || ' s.loct_onhand'
11186 	    || ' FROM'
11187 	    || ' ic_loct_inv'||pdblink||' s,'
11188 	    || ' ic_lots_mst'||pdblink||' l,'
11189 	    || ' ic_item_mst_b'||pdblink||' m,'
11190 	    || ' (select distinct aps_item_id,item_id,whse_code,organization_id, '
11191 	    || ' lot_control,experimental_ind from gmp_item_aps'||pdblink||') i'
11192 	    || ' WHERE'
11193 	    || '     s.item_id = i.item_id'
11194 	    || ' and s.item_id = m.item_id'
11195 	    || ' and s.whse_code = i.whse_code'
11196 	    || ' and i.lot_control = 1'
11197 	    || ' and m.status_ctl = 0'
11198 	    || ' and s.lot_id = l.lot_id'
11199 	    || ' and s.item_id = l.item_id'
11200 	    || ' and s.lot_id > 0'
11201 	    || ' and l.delete_mark = 0'
11202 	    || ' and s.loct_onhand <> 0';
11203     /* Bug # 5238790 */
11204     IF l_profile = 0 THEN
11205        v_onhand_cursor := v_onhand_cursor
11206     || ' and i.experimental_ind = 0 ' ;
11207     END IF;
11208 
11209 
11210     OPEN c_onhand_balance_lot FOR v_onhand_cursor USING pinstance_id, prun_date, pdelimiter;
11211     LOOP
11212       FETCH  c_onhand_balance_lot INTO onhand_balance_lot_tab(onhand_count);
11213       EXIT WHEN  c_onhand_balance_lot%NOTFOUND ;
11214       onhand_count := onhand_count + 1;
11215     END LOOP;
11216     CLOSE c_onhand_balance_lot ;
11217     gonhand_balance_size := gonhand_balance_size + onhand_count - 1;
11218 
11219    log_message('Lot on hand fetches : '|| to_char(gonhand_balance_size) );
11220    time_stamp ;
11221 
11222 -- Bug:6030499 Vpedarla
11223           SELECT st.VALUE INTO v_dummy from V$MYSTAT st, V$STATNAME sn
11224           where st.STATISTIC# = sn.STATISTIC#
11225           and sn.NAME in ('session pga memory');
11226           log_message('Session pga memory = ' || TO_CHAR(v_dummy) );
11227 
11228 
11229    IF onhand_count > 1 THEN
11230    FOR i in onhand_balance_lot_tab.FIRST..onhand_balance_lot_tab.LAST
11231    LOOP
11232      o_plan_id(insert_count)            :=  onhand_balance_lot_tab(i).plan_id;
11233      o_inventory_item_id(insert_count)  :=  onhand_balance_lot_tab(i).inventory_item_id;
11234      o_organization_id(insert_count)	:=  onhand_balance_lot_tab(i).organization_id;
11235      o_sr_instance_id(insert_count)	:=  onhand_balance_lot_tab(i).sr_instance_id;
11236      o_new_schedule_date(insert_count)  :=  onhand_balance_lot_tab(i).new_schedule_date;
11237      o_new_dock_date(insert_count)	:=  NULL;
11238      o_order_type(insert_count)  	:=  onhand_balance_lot_tab(i).order_type;
11239      o_lot_number(insert_count)	        :=  onhand_balance_lot_tab(i).lot_number;
11240 
11241       -- Bug: 6030499 Vpedarla
11242      IF (onhand_balance_lot_tab(i).expiration_date >= sy_max_date) THEN
11243      o_expiration_date(insert_count)	:=  NULL;
11244      ELSE
11245      o_expiration_date(insert_count)	:=  onhand_balance_lot_tab(i).expiration_date;
11246      END IF;
11247 
11248 --     o_expiration_date(insert_count)	:=  onhand_balance_lot_tab(i).expiration_date;
11249 --     o_firm_planned_type(insert_count)  :=  onhand_balance_lot_tab(i).firm_planned_type;
11250 --     o_deleted_flag(insert_count)	:=  onhand_balance_lot_tab(i).deleted_flag;
11251 --     o_subinventory_code(insert_count)  :=  onhand_balance_lot_tab(i).subinventory_code;
11252 
11253      o_firm_planned_type(insert_count)  :=  onhand_balance_lot_tab(i).firm_planned_type;
11254      o_deleted_flag(insert_count)	:=  onhand_balance_lot_tab(i).deleted_flag;
11255      o_subinventory_code(insert_count)  :=  onhand_balance_lot_tab(i).subinventory_code;
11256 -- Bug: 6030499 Vpedarla
11257 
11258      o_new_order_quantity(insert_count) :=  onhand_balance_lot_tab(i).new_order_quantity;
11259      o_non_nettable_qty(insert_count)   :=  NULL;
11260      insert_count := insert_count + 1;
11261    END LOOP;
11262    END IF;
11263 
11264     onhand_count := 1;
11265 
11266     v_onhand_cursor := NULL;
11267 
11268   /* Get the onhand balances for items that are lot and status controlled. The
11269      balances come from the location inventory table but the status must be
11270      nettable on the lots.
11271      B3177516 Rajesh D. Patangya  05-Oct-2003
11272      PPLT Logical change:
11273 	     If Hold release date is null then
11274 	          new schedule date = prun_date;
11275 	          new_dock_date=prun_date;
11276 	          order type = 18;
11277 	     Else
11278 	          new schedule date = hold release date ;
11279 	          new_dock_date=prun_date;
11280 	          order type = 8
11281 	     End if;
11282   */
11283 
11284   /* B2623374 -- Rajesh Patangya  PORT BUG FOR 2446925 (OM ATP CHECK TO
11285      RECOGNIZE THE ORDER PROCESSING FLAG) */
11286 
11287   v_onhand_cursor :=  ' SELECT /*+ DRIVING_SITE(s) DRIVING_SITE(l) DRIVING_SITE(m) */ '
11288 	  || ' -1,'
11289 	  || ' i.aps_item_id,'
11290 	  || ' i.organization_id,'
11291 	  || ' :pinstance_id,'
11292 	  || ' DECODE(c.ic_hold_date,NULL,:prun_date,c.ic_hold_date),'
11293  /* B8560329 dock date should be equal to schedule date, ASCP will calcualte the
11294  * new schedule date as new dock date + pre processing lead time and if it is on
11295  * not working day, it will push the calulated date to working day, As per discussion with sanjay
11296 	  || ' :prun_date,'     */
11297 	  || ' DECODE(c.ic_hold_date,NULL,:prun_date,c.ic_hold_date),'
11298 	  || ' DECODE(c.ic_hold_date,NULL,18,8),'   /* onhand inventory value */
11299 	  || ' substrb(l.lot_no||DECODE(l.sublot_no, NULL,NULL ,:pdelimiter || '
11300 	  || ' l.sublot_no),1,30),'
11301 	  || ' l.expire_date,'
11302 	  || ' 2,'
11303 	  || ' 2,'
11304 	  || ' s.whse_code,'  /* Populating subinventory code with whse code B1172875 */
11305 	  || ' s.loct_onhand, '
11306 	  || ' decode(t.order_proc_ind,0,s.loct_onhand,0)'
11307 	  || ' FROM'
11308 	  || ' ic_loct_inv'||pdblink||' s,'
11309 	  || ' ic_lots_mst'||pdblink||' l,'
11310 	  || ' ic_item_mst_b'||pdblink||' m,'
11311 	  || ' (select distinct aps_item_id, item_id, whse_code, organization_id, '
11312 	  || ' lot_control,experimental_ind from gmp_item_aps'||pdblink||') i,'
11313 	  || ' ic_lots_sts'||pdblink||' t,'
11314 	  || ' ic_lots_cpg'||pdblink||' c'
11315 	  || ' WHERE'
11316 	  || '     s.item_id = i.item_id'
11317 	  || ' and s.item_id = m.item_id'
11318 	  || ' and s.whse_code = i.whse_code'
11319 	  || ' and i.lot_control = 1'
11320 	  || ' and s.lot_id = l.lot_id'
11321 	  || ' and s.item_id = l.item_id'
11322 	  || ' and s.lot_id > 0'
11323 	  || ' and l.delete_mark = 0'
11324 	  || ' and m.status_ctl IN (1,2)' -- akaruppa B4278082 19-APR-2005 Added status_ctl = 2 also as Items with Status Control with No Inventory were not getting collected
11325 	  || ' and s.lot_status = t.lot_status'
11326 	  || ' and t.rejected_ind = 0'
11327 	  || ' and t.nettable_ind = 1'
11328 	  || ' and s.loct_onhand <> 0'
11329 	  || ' and c.item_id (+) = l.item_id'
11330 	  || ' and c.lot_id (+) = l.lot_id'
11331 	  || ' and c.ic_hold_date (+) > :run_date' ;
11332     /* Bug # 5238790 */
11333     IF l_profile = 0 THEN
11334        v_onhand_cursor := v_onhand_cursor
11335     || ' and i.experimental_ind = 0 ' ;
11336     END IF;
11337 
11338     OPEN c_onhand_balance_status FOR v_onhand_cursor USING pinstance_id, prun_date, prun_date, pdelimiter, prun_date;
11339     LOOP
11340       FETCH  c_onhand_balance_status INTO onhand_balance_status_tab(onhand_count);
11341       EXIT WHEN  c_onhand_balance_status%NOTFOUND ;
11342       onhand_count := onhand_count + 1;
11343     END LOOP;
11344     CLOSE c_onhand_balance_status ;
11345     gonhand_balance_size := gonhand_balance_size + onhand_count - 1;
11346 
11347    log_message('Lot and status on hand fetches : '|| to_char(gonhand_balance_size) );
11348    time_stamp ;
11349 
11350 -- Bug: 6030499 Vpedarla
11351           SELECT st.VALUE INTO v_dummy from V$MYSTAT st, V$STATNAME sn
11352           where st.STATISTIC# = sn.STATISTIC#
11353           and sn.NAME in ('session pga memory');
11354           log_message('Session pga memory = ' || TO_CHAR(v_dummy) );
11355 
11356 
11357     IF onhand_count > 1 THEN
11358     FOR i in onhand_balance_status_tab.FIRST..onhand_balance_status_tab.LAST
11359     LOOP
11360      o_plan_id(insert_count)           := onhand_balance_status_tab(i).plan_id;
11361      o_inventory_item_id(insert_count) := onhand_balance_status_tab(i).inventory_item_id;
11362      o_organization_id(insert_count)   := onhand_balance_status_tab(i).organization_id;
11363      o_sr_instance_id(insert_count)    := onhand_balance_status_tab(i).sr_instance_id;
11364      o_new_schedule_date(insert_count) := onhand_balance_status_tab(i).new_schedule_date;
11365      o_new_dock_date(insert_count)     := onhand_balance_status_tab(i).new_dock_date;
11366      o_order_type(insert_count)        := onhand_balance_status_tab(i).order_type;
11367      o_lot_number(insert_count)        := onhand_balance_status_tab(i).lot_number;
11368 
11369 --Bug: 6030499 Vpedarla
11370      /* B5501754 */
11371      IF (onhand_balance_status_tab(i).expiration_date >= sy_max_date) THEN
11372      o_expiration_date(insert_count)	:=  NULL;
11373      ELSE
11374      o_expiration_date(insert_count)   := onhand_balance_status_tab(i).expiration_date;
11375      END IF;
11376 --     o_expiration_date(insert_count)   := onhand_balance_status_tab(i).expiration_date;
11377 
11378      o_firm_planned_type(insert_count) := onhand_balance_status_tab(i).firm_planned_type;
11379      o_deleted_flag(insert_count)      := onhand_balance_status_tab(i).deleted_flag;
11380      o_subinventory_code(insert_count) := onhand_balance_status_tab(i).subinventory_code;
11381   o_new_order_quantity(insert_count) := onhand_balance_status_tab(i).new_order_quantity;
11382      o_non_nettable_qty(insert_count)  := onhand_balance_status_tab(i).non_nettable_qty;
11383      insert_count := insert_count + 1;
11384     END LOOP;
11385     END IF;
11386 
11387     insert_count := insert_count - 1;
11388 
11389     FORALL i IN 1..insert_count
11390     INSERT INTO msc_st_supplies
11391                 (plan_id,
11392 		inventory_item_id,
11393 		organization_id,
11394 		sr_instance_id,
11395 		new_schedule_date,
11396 		new_dock_date,
11397 		order_type,
11398 		lot_number,
11399 		expiration_date,
11400 		firm_planned_type,
11401 		deleted_flag,
11402 		subinventory_code,
11403 		new_order_quantity,
11404 		non_nettable_qty
11405 		)
11406          VALUES(o_plan_id(i),
11407 		o_inventory_item_id(i),
11408 		o_organization_id(i),
11409 		o_sr_instance_id(i),
11410 		o_new_schedule_date(i),
11411 		o_new_dock_date(i),
11412 		o_order_type(i),
11413 		o_lot_number(i),
11414 		o_expiration_date(i),
11415 		o_firm_planned_type(i),
11416 		o_deleted_flag(i),
11417 		o_subinventory_code(i),
11418 		o_new_order_quantity(i),
11419 		o_non_nettable_qty(i)
11420 		);
11421 
11422    log_message('On Hand Balances size is = '|| to_char(gonhand_balance_size) );
11423    time_stamp ;
11424 
11425 /* akaruppa B5007729 */
11426 	o_organization_id  := empty_pls_table ;
11427 	o_sr_instance_id   := empty_pls_table ;
11428 	o_plan_id          := empty_pls_table ;
11429 	o_inventory_item_id := empty_pls_table ;
11430 	o_new_schedule_date := empty_dat_table ;
11431         o_order_type        := empty_pls_table ;
11432 	o_new_order_quantity := empty_num_table ;
11433 	o_firm_planned_type  := empty_pls_table ;
11434 	o_lot_number         := e_lot_number;
11435 	o_expiration_date    := empty_dat_table ;
11436 	o_new_dock_date      := empty_dat_table ;
11437 	o_deleted_flag       := empty_pls_table ;
11438 	o_subinventory_code  := e_subinventory_code;
11439         o_non_nettable_qty   := empty_num_table ;
11440 
11441         dbms_session.free_unused_user_memory;
11442 
11443 /* akaruppa B5007729 End*/
11444 
11445   return_status := TRUE;
11446 
11447   EXCEPTION
11448     WHEN OTHERS THEN
11449 	log_message('Failure occured during the Onhand Balances extract');
11450 	log_message(sqlerrm);
11451         return_status := FALSE;
11452 
11453 END extract_onhand_balances; /* end extract_onhand_balances */
11454 
11455 /***********************************************************************
11456 *
11457 *   NAME
11458 *	extract_inv_transfer_demands
11459 *
11460 *   DESCRIPTION
11461 *	This procedure will insert records into the table msc_st_demands
11462 *       According to APS team (Sam Tupe < prganesh Shah etc.
11463 *        The inventory transfer demand is similar to Internal Sales Order
11464 *        demand hence should be added to each of the demand schedule
11465 *        The specifics are
11466 *        demand_type = 6
11467 *        origination_type = 6
11468 *        disposition_id = same transfer_id This should match with the
11469 *                        corresponding transaction_id of the supply created
11470 *                        by the same transfer
11471 *       demand_schedule_name =  OPM specific demand_schedule name - The
11472 *              MDS names used in forecast/SO extraction
11473 *   HISTORY
11474 * 	25-Jan-2003 B2756431
11475 *         Note : Old procedure extract_inv_transfers is now removed
11476 *                and replaced with these two new procedures
11477 ************************************************************************/
11478 PROCEDURE extract_inv_transfer_demands(
11479   pdblink        IN  VARCHAR2,
11480   pinstance_id   IN  NUMBER,
11481   prun_date      IN  DATE,
11482   pdelimiter     IN  VARCHAR2,
11483   pwhse_code     IN  VARCHAR2,
11484   pdesignator    IN  VARCHAR2,
11485   return_status  IN OUT NOCOPY BOOLEAN)
11486 AS
11487 
11488   pdoc_type      VARCHAR2(4) ;
11489   l_profile      PLS_INTEGER      ; /* Bug # 5238790 */
11490 
11491 -- Bug: 6030499 Vpedarla
11492   stmt_design    VARCHAR2(32000) ;   -- 8611066 Alcoa Issue 7637518.992
11493   pdescription	 VARCHAR2(30) ;
11494 
11495 BEGIN
11496   pdoc_type      := 'XFER';
11497   /* Bug # 5238790 */
11498    l_profile := 0 ;
11499 
11500 --   l_profile := nvl(FND_PROFILE.VALUE('GMP_COLLECT_EXPR_ONHAND'),0) ;
11501  /* bug:6710684 Vpedarla made changes to fetch the profile value from source server*/
11502    l_profile := NVL(get_profile_value('GMP_COLLECT_EXPR_ONHAND', pdblink ),0);
11503 
11504 --Bug: 6030499 Vpedarla
11505   pdescription  := 'OPM Inventory Transfer Demands' ;
11506 
11507   return_status := TRUE ;
11508 
11509   v_sql_stmt := 'INSERT into msc_st_demands ('
11510     || '   organization_id,'
11511     || '   inventory_item_id,'
11512     || '   sr_instance_id,'
11513     || '   using_assembly_item_id,'
11514     || '   using_assembly_demand_date,'
11515     || '   using_requirement_quantity,'
11516     || '   demand_type,'
11517     || '   origination_type,'
11518     || '   order_number,'
11519     || '   demand_schedule_name,'
11520     || '   disposition_id,' /* B2756431 */
11521     || '   demand_source_type,' /* B2756431 */
11522     || '   original_system_reference,' /* B2756431  */
11523     || '   original_system_line_reference,' /* being added for B2756431 */
11524     || '   deleted_flag)'
11525     || ' SELECT '
11526     || '   i.organization_id,'
11527     || '   i.aps_item_id,'
11528     || '   :pinstance_id, '
11529     || '   i.aps_item_id,'
11530     || '   s.scheduled_release_date,'
11531     || '   s.release_quantity1,'
11532     || '   1,'  /* Discrete , other demands types are interpreted as continuous */
11533     || '   6,'   /* Orig_type should br 6 per Sam Tupe so change from 11 */
11534     || '   :pdoc_type || :pdelimiter || s.orgn_code ||'
11535     || '     :pdelimiter2 || s.transfer_no, '
11536 --Bug: 6030499 Vpedarla Based on Bug: 5665290
11537 --  || '   :pdesignator,'
11538     || ' :p_doc_type  || :p_delimiter3 || s.from_warehouse , ' --Bug: 6030499 added this column.
11539 
11540     || '   s.transfer_id,'
11541     || '   8,'             /* B2756431 Demand_source_type    */
11542     || '   s.transfer_id,' /* B2756431 original_system_reference */
11543     || '   s.transfer_id,' /* B2756431 original_system_line_reference */
11544     || '   2'
11545     || ' FROM '
11546     || '   ic_xfer_mst' ||pdblink|| ' s,'
11547     || '   (select distinct aps_item_id, item_id, whse_code, organization_id '
11548     || '    ,experimental_ind from gmp_item_aps'||pdblink||') i'
11549     || ' WHERE '
11550     || '   s.item_id = i.item_id '
11551     || '   and s.from_warehouse = i.whse_code '
11552     || '   and s.transfer_status IN (1) '
11553     --Bug: 6242499 Vpedarla - commented the below line
11554 --    || '   and s.from_warehouse = :pwhse_code '
11555     || '   and s.release_quantity1 <> 0';
11556     /* Bug # 5238790 */
11557     IF l_profile = 0 THEN
11558        v_sql_stmt := v_sql_stmt
11559     || ' and i.experimental_ind = 0 ' ;
11560     END IF;
11561 
11562 --Bug: 6030499 Vpedarla
11563 IF MSC_CL_GMP_UTILITY.g_in_str_org is NOT NULL  THEN
11564 	v_sql_stmt := v_sql_stmt || ' AND   i.organization_id ' || MSC_CL_GMP_UTILITY.g_in_str_org  ;
11565 END IF ;
11566 
11567 EXECUTE IMMEDIATE v_sql_stmt USING pinstance_id, pdoc_type, pdelimiter, pdelimiter ,pdoc_type, pdelimiter ;
11568 
11569 -- Bug: 6030499 Vpedarla added based on bug: 5665290
11570   /* B5665290, Same as 11.5.9 MDS demand needs to be sent to APS */
11571    BEGIN
11572 	/* Abhay Now we should put an insert into the Designator table too */
11573 	stmt_design := 'INSERT into msc_st_designators ( '
11574 	|| ' designator, '
11575 	|| ' forecast_set, '
11576 	|| ' organization_id, '
11577 	|| ' sr_instance_id, '
11578 	|| ' description, '
11579 	|| ' mps_relief, '
11580 	|| ' inventory_atp_flag, '
11581 	|| ' designator_type, '
11582 	|| ' disable_date,  '
11583 	|| ' consume_forecast, '
11584 	|| ' update_type, '
11585 	|| ' backward_update_time_fence, '
11586 	|| ' forward_update_time_fence, '
11587 	|| ' bucket_type, '
11588 	|| ' deleted_flag, '
11589 	|| ' refresh_id ) '
11590 	|| ' SELECT '
11591 	|| ' :p_doc_type ||:p_delimitor|| organization_code, ' /* Designator */
11592 	|| ' NULL, '  /* forecast set   */
11593 	|| ' organization_id, ' /* org id   */
11594 	|| ' :p_instance_id, ' /* inst_id    */
11595 	|| ' :p_desgnDesc , ' /* description    */
11596 	|| ' 2, ' /* mps_relief    */
11597 	|| ' 2, ' /* atp_flag    */
11598 	|| ' 1, ' /* desgn_type    */
11599 	|| ' To_date(NULL)  , ' /* disable_date    */
11600 	|| ' 2, ' /* do not consume ??*/
11601 	|| ' 6, ' /* update_type    */
11602 	|| ' 0, ' /* backward_fence */
11603 	|| ' 0, ' /* forward_fence    */
11604 	|| ' 1, ' /* bucket_type  */
11605 	|| ' 2, ' /* deleted_flag */
11606 	|| ' 0 ' /*  refresh_id   */
11607 	|| ' FROM mtl_parameters'||pdblink
11608 	|| ' WHERE  process_enabled_flag = ' || '''Y'''  ;
11609 IF MSC_CL_GMP_UTILITY.g_in_str_org is NOT NULL  THEN
11610 	stmt_design := stmt_design || ' AND   organization_id ' || MSC_CL_GMP_UTILITY.g_in_str_org  ;
11611 END IF ;
11612 log_message(stmt_design) ;
11613 
11614 EXECUTE IMMEDIATE stmt_design USING pdoc_type, pdelimiter, pinstance_id, pdescription ;
11615 
11616    EXCEPTION
11617 	WHEN OTHERS THEN
11618 	log_message('Failure occured during designator extract');
11619 	log_message(sqlerrm);
11620         return_status := FALSE;
11621    END ;
11622 
11623 -- Bug: 6030499 Vpedarla end of code
11624 
11625 
11626 --Bug: 6030499
11627 --  EXECUTE IMMEDIATE v_sql_stmt USING pinstance_id, pdoc_type, pdelimiter, pdelimiter , pdesignator, pwhse_code ;
11628 
11629   EXCEPTION
11630     WHEN OTHERS THEN
11631 	log_message('Failure occured during the Inventory Transfer extract');
11632 	log_message(sqlerrm);
11633         return_status := FALSE;
11634 
11635 END extract_inv_transfer_demands;/* end extract_inv_transfer_dem */
11636 
11637 /***********************************************************************
11638 *
11639 *   NAME
11640 *	Extract_inventory_transfer_supplies
11641 *
11642 *   DESCRIPTION
11643 *	This procedure will insert records into the table msc_st_supplies
11644 *	and msc_st_demands for pending inventory transfers.
11645 *   HISTORY
11646 * 	25-Jan-2003 B1332662  Created New procedure to insert supplies
11647 *         Per discussions with APS team the specifics are
11648 *          Order_type = 2
11649 *          Transaction_id = transafer_id of the transfer in OPM
11650 ************************************************************************/
11651 PROCEDURE extract_inv_transfer_supplies(
11652   pdblink        IN  VARCHAR2,
11653   pinstance_id   IN  NUMBER,
11654   prun_date      IN  DATE,
11655   pdelimiter     IN  VARCHAR2,
11656   return_status  IN OUT NOCOPY BOOLEAN)
11657 AS
11658 
11659   pdoc_type      VARCHAR2(4) ;
11660   l_profile      PLS_INTEGER      ;/* Bug # 5238790 */
11661 
11662 BEGIN
11663 
11664    log_message('Entering extract_inv_transfer_supplies. ');
11665   pdoc_type      := 'XFER';
11666 
11667    /* Bug # 5238790 */
11668    l_profile := 0 ;
11669 --   l_profile := nvl(FND_PROFILE.VALUE('GMP_COLLECT_EXPR_ONHAND'),0) ;
11670  /* bug:6710684 Vpedarla made changes to fetch the profile value from source server*/
11671    l_profile := NVL(get_profile_value('GMP_COLLECT_EXPR_ONHAND', pdblink ),0);
11672 
11673   return_status := TRUE ;
11674 
11675   v_sql_stmt := 'INSERT into msc_st_supplies ('
11676     || ' plan_id,'
11677     || ' inventory_item_id,'
11678     || ' organization_id,'
11679     || ' sr_instance_id,'
11680     || ' source_sr_instance_id,'
11681     || ' new_schedule_date,'
11682     || ' order_type,'
11683     || ' order_number,'
11684     || ' lot_number,'
11685     || ' firm_planned_type,'
11686     || ' deleted_flag,'
11687     || ' subinventory_code,'
11688     || ' transaction_id,'          /* being added for B2756431 */
11689     || ' disposition_id,'          /* being added for B2756431 */
11690     || ' po_line_id,'              /* being added for B2756431 */
11691     || ' source_organization_id,'   /* being added for B2756431 */
11692     || ' new_order_quantity)'
11693     || ' SELECT '
11694     || ' -1,'
11695     || ' i.aps_item_id,'
11696     || ' i.organization_id,'
11697     || ' :pinstance_id, '
11698     || ' :pinstance_id, '
11699     || ' s.scheduled_receive_date, '
11700     || ' DECODE(s.transfer_status,1,2,11), '  /*  modified as per bug 12721880 Old value was hard coded 2 */
11701     || ' :pdoc_type || :pdelimiter || s.orgn_code ||'
11702     || '   :pdelimiter2 || s.transfer_no, '
11703     || ' DECODE(s.lot_id, 0, NULL, '
11704     || '   substrb(l.lot_no||DECODE(l.sublot_no, NULL,NULL ,:pdelimiter3 || '
11705     || '   l.sublot_no),1,30)),'
11706     || ' 2,'
11707     || ' 2,'
11708     || ' s.to_warehouse,'
11709     || ' s.transfer_id,' /* B2756431 transaction_id */
11710     || ' s.transfer_id,' /* B2756431 disposition_id */
11711     || ' s.transfer_id,' /* B2756431 po_line_id     */
11712     || ' w.mtl_organization_id,' /* B2756431 source_organization_id */
11713     || ' s.release_quantity1'
11714     || ' FROM '
11715     || ' ic_xfer_mst' ||pdblink|| ' s,'
11716     || ' ic_whse_mst' ||pdblink|| ' w,'
11717     || ' ic_lots_mst'||pdblink||' l,'
11718     || ' (select distinct aps_item_id, item_id, whse_code, organization_id '
11719     || '  ,experimental_ind from gmp_item_aps'||pdblink||') i'
11720     || ' WHERE '
11721     || ' s.item_id = i.item_id '
11722     || ' and s.to_warehouse = i.whse_code '
11723     || ' and s.from_warehouse = w.whse_code '
11724     || ' and s.transfer_status IN (1,2) '
11725     || ' and s.lot_id = l.lot_id'
11726     || ' and s.item_id = l.item_id'
11727     || ' and s.release_quantity1 <> 0';
11728    /* Bug # 5238790 */
11729     IF l_profile = 0 THEN
11730        v_sql_stmt := v_sql_stmt
11731     || ' and i.experimental_ind = 0 ' ;
11732     END IF;
11733 
11734   EXECUTE IMMEDIATE v_sql_stmt USING pinstance_id,pinstance_id, pdoc_type, pdelimiter,
11735     pdelimiter, pdelimiter;
11736 
11737   EXCEPTION
11738     WHEN OTHERS THEN
11739 	log_message('Failure occured during the Inventory Transfer supplies ');
11740 	log_message(sqlerrm);
11741         return_status := FALSE;
11742 
11743 END extract_inv_transfer_supplies;/* end extract_inv_transfer_sup */
11744 
11745 
11746 /***********************************************************************
11747 *
11748 *   NAME
11749 *	 build_designator
11750 *
11751 *   DESCRIPTION
11752 *       This procedure will create a new row in the pl/sql table if one does
11753 *	for the current schedule/whse. The rows will be inserted into the
11754 *	database in the procedure sales_forecast which calls this procedure.
11755 *	A unique designator must be created for each schedule/whse otherwise a
11756 *	number is added to make it unique. If the row exists already the value
11757 *	is returned otherwise the table is added to and the new value is returned
11758 *       in the out parameter
11759 *   HISTORY
11760 * 	M Craig
11761 ************************************************************************/
11762 PROCEDURE build_designator(
11763   poccur       IN  NUMBER,
11764   pdelimiter   IN  VARCHAR2,
11765   pdesignator  OUT NOCOPY VARCHAR2)
11766 AS
11767 
11768   temp_designator VARCHAR2(10);
11769   i               NUMBER;
11770   j               NUMBER;
11771   k               NUMBER;
11772   found           NUMBER ;
11773   j_char          VARCHAR2(5);
11774 
11775 BEGIN
11776   found := 0 ;
11777   /*  The default name generation is the first 5 chars of the schedule and the
11778       four chars of the warehouse
11779   */
11780   temp_designator := substrb(sched_dtl_tab(poccur).schedule,1,5) || pdelimiter
11781                      || sched_dtl_tab(poccur).whse_code;
11782 
11783   pdesignator := NULL;
11784   found := 0;
11785 
11786   /* if there are existing rows search them for the key values */
11787   IF desig_count > 0 THEN
11788   /* {
11789         loop through the existing designator rows */
11790     FOR i IN 1..desig_count LOOP
11791     /* {
11792 
11793       if a row has alreday been inserted for the schedule and warehouse
11794       use the value from that row and stop the loop
11795      */
11796       IF desig_tab(i).schedule = sched_dtl_tab(poccur).schedule and
11797          desig_tab(i).whse_code = sched_dtl_tab(poccur).whse_code THEN
11798 
11799         pdesignator := desig_tab(i).designator;
11800         found := 1;
11801         EXIT;
11802 
11803       END IF;
11804 
11805     /* } */
11806     END LOOP;
11807 
11808     /* when the schedule and warehouse are not represented we need to find
11809        a unique name for the designator
11810     */
11811     IF found = 0 THEN
11812     /* { */
11813 
11814       k := 5;
11815       j := 0;
11816       j_char := NULL;
11817 
11818       /* the loop will try the default value then change it if necessary and
11819         until we have exhasted all of the values of 0-99999 (5 chars of numbers)
11820       */
11821       LOOP
11822       /* { */
11823         temp_designator := j_char || SUBSTR(sched_dtl_tab(poccur).schedule,1,k) ||
11824                            pdelimiter || sched_dtl_tab(poccur).whse_code;
11825         /* this loop goes through the current list to see if there is a duplicate
11826            if found we stop and generate a new value then try again
11827         */
11828         FOR i IN 1..desig_count LOOP
11829         /* { */
11830           IF desig_tab(i).designator = temp_designator THEN
11831             EXIT;
11832           END IF;
11833           IF i =  desig_count THEN
11834             found := 1;
11835             pdesignator := temp_designator;
11836           END IF;
11837         /* } */
11838         END LOOP;
11839 
11840         /* if we found a value or reached the max we stop */
11841         IF found = 1 or j = 99999 THEN
11842           EXIT;
11843         END IF;
11844 
11845         /* to get a unique value we keep taking one char at a time from the
11846            the schedule leaving the warehouse intact.
11847         */
11848         j := j + 1;
11849         IF j < 10 THEN
11850           k := 4;
11851         ELSIF j < 100 THEN
11852           k := 3;
11853         ELSIF j < 1000 THEN
11854           k := 2;
11855         ELSIF j < 10000 THEN
11856           k := 1;
11857         ELSE
11858           k := 0;
11859         END IF;
11860 
11861         j_char := TO_CHAR(j);
11862 
11863       /* } */
11864       END LOOP;
11865 
11866 
11867       /* put a new row in for the value that was found */
11868       IF found = 1 and pdesignator = temp_designator THEN
11869 
11870         desig_count := desig_count + 1;
11871         desig_tab(desig_count).designator := temp_designator;
11872         desig_tab(desig_count).schedule := sched_dtl_tab(poccur).schedule;
11873         desig_tab(desig_count).orgn_code := sched_dtl_tab(poccur).orgn_code;
11874         desig_tab(desig_count).whse_code := sched_dtl_tab(poccur).whse_code;
11875         desig_tab(desig_count).organization_id :=
11876           sched_dtl_tab(poccur).organization_id;
11877 
11878       END IF;
11879 
11880     /* } */
11881     END IF;
11882 
11883   /* if no rows are in the table yet just put a new one in */
11884   ELSE
11885 
11886     desig_tab(1).designator := temp_designator;
11887     desig_tab(1).schedule := sched_dtl_tab(poccur).schedule;
11888     desig_tab(1).orgn_code := sched_dtl_tab(poccur).orgn_code;
11889     desig_tab(1).whse_code := sched_dtl_tab(poccur).whse_code;
11890     desig_tab(1).organization_id := sched_dtl_tab(poccur).organization_id;
11891     pdesignator := temp_designator;
11892     desig_count := 1;
11893 
11894   /* } */
11895   END IF;
11896 
11897 END build_designator;
11898 
11899 /***********************************************************************
11900 *
11901 *   NAME
11902 *	 sales_forecast_api
11903 *
11904 *   DESCRIPTION
11905 *     This procedure is a wrapper for the preexisting sales_forecast procedure.
11906 *     This version is set up with the proper parameters to be called as from the
11907 *     concurrent manager.  In addition, the main difference is the table into
11908 *     which demands are inserted.  The standard procedure inserts into
11909 *     msc_st_demands.
11910 *     This new procedure inserts into gmp_demands_api. The difference between
11911 *     the two tables is the addition of a schedule_id column in
11912 *     gmp_demands_api.  Also, this version of sales_forecast begins by
11913 *     truncating gmp_demands_api and leaves it populated after
11914 *     it completes. By contrast, msc_st_demands (which is an APS staging table)
11915 *     is immediately truncated after APS reads its data. This difference allows
11916 *     gmp_demands_api to be a general purpose version of msc_st_demands.
11917 *
11918 *   HISTORY
11919 * 	P. Dong
11920 * 	09/14/01 - Created
11921 *       12/21/01 - Replaced TRUNCATE with DELETE
11922 ************************************************************************/
11923 PROCEDURE sales_forecast_api(
11924   errbuf         OUT NOCOPY VARCHAR2,
11925   retcode        OUT NOCOPY VARCHAR2,
11926   p_cp_enabled   IN BOOLEAN ,
11927   p_run_date     IN DATE )
11928 AS
11929   lv_cp_enabled  BOOLEAN;
11930 BEGIN
11931 
11932   lv_cp_enabled := p_cp_enabled;
11933 
11934   MSC_CL_GMP_UTILITY.extract_items(
11935     at_apps_link => NULL,
11936     instance => NULL,
11937     run_date => p_run_date,
11938     return_status => lv_cp_enabled  );
11939 
11940   DELETE FROM gmp_demands_api;
11941 
11942   lv_cp_enabled := p_cp_enabled;
11943 
11944   sales_forecast(
11945     pdblink => NULL,
11946     pinstance_id => NULL,
11947     prun_date => p_run_date,
11948     pdelimiter => '/',
11949     return_status => lv_cp_enabled,
11950     api_mode => TRUE);
11951 
11952  errbuf := NULL;
11953  retcode := NULL;
11954 
11955  EXCEPTION
11956      WHEN OTHERS THEN
11957              errbuf := SUBSTRB(SQLERRM,1,100);
11958              retcode := SQLCODE;
11959 
11960 END sales_forecast_api;
11961 
11962 /***********************************************************************
11963 *
11964 *   NAME
11965 *	 sales_forecast
11966 *
11967 *   DESCRIPTION
11968 *       This procedure will retrieve all of the sales order lines and forecast
11969 *	details for their respective schedules. The forecast will be consumed
11970 *       and the all of the rows will be written to msc_st_demands. Each demand
11971 *	is applied to an MDS aka designator.
11972 *   HISTORY
11973 * 	M Craig
11974 * 	10/13/99 - Sridhar Added Designator Type column in the insert statement
11975 * 	12/17/99 - Changes made to the insert statement for designators,
11976 *                  changed desig_tab(1).schedule and desig_tab(1).whse_code to
11977 *                  desig_tab(i).schedule and desig_tab(i).whse_code
11978 * 	04/01/00 - Code Fix for Bug# 1137597.
11979 * 	07/01/00 - Code Fix for Error in Designators Insert
11980 *
11981 *       02-MAY-2002 Re-engineered By : Abhay Satpute, Rajesh Patangya
11982 *              Brief Logic of the new code
11983 *                  Fetch the following data into PL/SQL tables
11984 *                       a. Distinct schd/item/whse combinations
11985 *                       b. Sales order details
11986 *                       c. Forecast details
11987 *                       d. Schedule forecast associations
11988 *               For each item combination loop through and
11989 *                  For each change of schedule change mark reuqired
11990 *                  forecast rows as well note down the stock and ord ind.
11991 *                  For each item insert sales orders, unconsumed forecast
11992 *                  or the forecast , based on the indicators
11993 *     P Dong
11994 *     09/14/01 - Added api_mode to pass to insert_demands
11995 *
11996 *   Navin   21-APR-2003 B3577871 ST:OSFME2: collections failing in planning data pull.
11997 *                                Added handling of NO_DATA_FOUND Exception.
11998 *                                And return the return_status as TRUE.
11999 ****************************************************************************/
12000 
12001 PROCEDURE sales_forecast( pdblink        IN  VARCHAR2,
12002 			  pinstance_id   IN  NUMBER,
12003 			  prun_date      IN  DATE,
12004 			  pdelimiter     IN  VARCHAR2,
12005 			  return_status  IN  OUT NOCOPY BOOLEAN,
12006 			  api_mode       IN  BOOLEAN)
12007 
12008 AS
12009 
12010     TYPE gmp_cursor_typ IS REF CURSOR;
12011     cur_gmp_schd_items  gmp_cursor_typ;
12012     cur_fcst_dtl        gmp_cursor_typ;
12013     cur_sales_dtl       gmp_cursor_typ;
12014     cur_schd_fcst       gmp_cursor_typ;
12015 
12016     so_ind		BOOLEAN ;
12017     fcst_ind		BOOLEAN ;
12018     log_mesg            VARCHAR2(1000) ;
12019     i			INTEGER ;
12020     j			INTEGER ;
12021     old_schedule_id	INTEGER ;
12022     item_count		INTEGER ;
12023     fcst_count		INTEGER ;
12024     so_count		INTEGER ;
12025     schd_fcst_cnt	INTEGER ;
12026     local_ret_status    BOOLEAN;
12027     l_profile           PLS_INTEGER ; /* Bug # 5238790 */
12028 
12029 BEGIN
12030 
12031 /* Bug: 6030499 Vpedarla added profile verification */
12032 
12033     collect_ps_data := TRUE;
12034 
12035     g_delimiter         := '/';
12036     so_ind		:= FALSE ;
12037     fcst_ind		:= FALSE ;
12038     log_mesg            := NULL;
12039     i			:= 0;
12040     j			:= 0;
12041     old_schedule_id	:= 0 ;
12042     item_count		:= 1;
12043     fcst_count		:= 1;
12044     so_count		:= 1;
12045     schd_fcst_cnt	:= 1;
12046 
12047   gitem_size		:= 0;
12048   gfcst_size		:= 0;
12049   gso_size		:= 0;
12050   gschd_fcst_size	:= 0;
12051 
12052   gfcst_cnt		:= 0;
12053   gso_cnt		:= 0;
12054   gschd_fcst_cnt	:= 0;
12055   g_item_tbl_position	:= 0;
12056   local_ret_status      := return_status ;
12057 
12058   log_message('Start gmp_aps_ds_pull.sales forecast');
12059   time_stamp;
12060 
12061   IF return_status THEN
12062     v_cp_enabled := TRUE;
12063   ELSE
12064     v_cp_enabled := FALSE;
12065   END IF;
12066    g_delimiter		:= pdelimiter ;
12067    g_instance_id	:= pinstance_id ;
12068 
12069    /* Bug # 5238790 */
12070    l_profile := 0 ;
12071 --   l_profile := nvl(FND_PROFILE.VALUE('GMP_COLLECT_EXPR_ONHAND'),0) ;
12072  /* bug:6710684 Vpedarla made changes to fetch the profile value from source server*/
12073    l_profile := NVL(GMP_BOM_ROUTING_PKG.get_profile_value('GMP_COLLECT_EXPR_ONHAND', pdblink ),0);
12074 
12075 IF api_mode THEN
12076   /* If forecast and sales order select queries have joins with gmp_item_aps
12077      we need to select only schedules and warehouses here
12078      ORDERED By Schedule , Aps_Item, Organization_id(Warehouse) */
12079 
12080         /* Extract Schedule Details */
12081         v_item_sql_stmt := 'SELECT DISTINCT'
12082          || ' h.schedule,'
12083          || ' h.schedule_id,'
12084          || ' h.order_ind,'
12085          || ' h.stock_ind,'
12086          || ' a.whse_code,'
12087          || ' d.orgn_code,'
12088          || ' a.organization_id, '
12089          || ' a.aps_item_id inventory_item_id'
12090          || ' FROM'
12091          || '    ps_schd_hdr'||pdblink||' h,'
12092          || '    ps_schd_dtl'||pdblink||' d,'
12093          || '    gmp_item_aps'||pdblink||' a'
12094          || ' WHERE'
12095          || ' h.schedule_id = d.schedule_id'
12096          || ' and d.orgn_code = a.plant_code'
12097          || ' and h.active_ind = 1'
12098          || ' and a.replen_ind = 1'
12099          || ' and (h.order_ind = 1 or h.stock_ind = 1)'
12100          || ' and h.delete_mark = 0'
12101          || ' and a.item_id > 0 ' ;
12102          /* Bug # 5238790 */
12103          IF l_profile = 0 THEN
12104         v_item_sql_stmt := v_item_sql_stmt
12105          || ' and a.experimental_ind = 0 ' ;
12106          END IF;
12107 
12108         v_item_sql_stmt := v_item_sql_stmt
12109          || ' ORDER BY'
12110          || ' h.schedule_id ASC,'
12111          || ' a.aps_item_id, '
12112          || ' a.organization_id ' ;
12113 
12114    -- B2596464, Order changed for inv_item and organization_id
12115    -- B2973249, undershipped or overshipped sales orders have shipped_qty
12116    -- populated by OM and as per APS this lines can not be selected, as OM
12117    -- split original line and keep the open line without any shipped qty.
12118         /* Extract Sales Order */
12119         v_sales_sql_stmt := 'SELECT '
12120           || ' msi.inventory_item_id, '
12121           || ' msi.organization_id, '
12122           || ' h.orgn_code, '
12123           || ' h.order_no, '
12124           || ' d.line_id,  '
12125           || ' d.net_price, '
12126           || ' d.sched_shipdate, '
12127           || ' d.requested_shipdate, '      /* B2971996 */
12128           || ' (sum(t.trans_qty) * -1) trans_qty '
12129           || ' FROM '
12130           || ' mtl_system_items'||pdblink||' msi, '
12131           || ' ic_item_mst'||pdblink||' iim,'
12132           || ' ic_whse_mst'||pdblink||' wm, '
12133           || ' op_ordr_hdr'||pdblink||' h, '
12134           || ' op_ordr_dtl'||pdblink||' d, '
12135           || ' ic_tran_pnd'||pdblink||' t '
12136           || ' WHERE '
12137           || '     msi.organization_id = wm.mtl_organization_id '
12138           || ' AND msi.segment1 = iim.item_no '
12139           || ' and wm.delete_mark = 0 '
12140           || ' and h.order_id = d.order_id '
12141           || ' and h.order_status = 0 '
12142           || ' and h.delete_mark = 0 '
12143           || ' and h.order_id = t.doc_id '
12144           || ' and d.line_status >= 0 '
12145           || ' and d.line_status < 20 '
12146           || ' and h.from_whse = wm.whse_code '
12147           || ' and t.line_id = d.line_id '
12148           || ' and t.item_id = d.item_id  '
12149           || ' and iim.item_id = t.item_id  '
12150           || ' and iim.delete_mark = 0 '
12151           || ' AND iim.inactive_ind = 0 '
12152           || ' and t.trans_qty <> 0 '
12153           || ' and t.completed_ind = 0 '
12154           || ' and t.delete_mark = 0 '
12155           || ' and t.doc_type = :popso '
12156           || ' GROUP BY  '
12157           || ' msi.inventory_item_id, '
12158           || ' msi.organization_id, '
12159           || ' h.orgn_code, '
12160           || ' h.order_no, '
12161           || ' d.line_id,  '
12162           || ' d.net_price, '
12163           || ' d.sched_shipdate, '
12164           || ' d.requested_shipdate '    /* B2971996 */
12165           || ' UNION ALL '
12166           || ' SELECT '
12167           || ' items.inventory_item_id, '
12168           || ' items.organization_id, '
12169           || ' org.organization_code, '
12170           || ' TO_CHAR(hdr.order_number), '
12171           || ' TO_NUMBER(NULL), '
12172           || ' TO_NUMBER(NULL), '
12173           || ' mtl.requirement_date, '
12174           || ' dtl.request_date, '      /* B2971996 */
12175           || ' mtl.primary_uom_quantity '
12176           || ' FROM '
12177           || '     mtl_demand_omoe'||pdblink||' mtl, '
12178           || '     mtl_system_items'||pdblink||' items, '
12179           || '     oe_order_headers_all'||pdblink||' hdr, '
12180           || '     oe_order_lines_all'||pdblink||' dtl, '
12181           || '     mtl_parameters'||pdblink||' org '
12182           || ' WHERE '
12183           || '     items.organization_id   = mtl.organization_id  '
12184           || ' and items.inventory_item_id = mtl.inventory_item_id '
12185           || ' and NVL(mtl.completed_quantity,0) = 0 '
12186           || ' and mtl.open_flag = ' || '''Y'''
12187           || ' and mtl.available_to_mrp = 1 '
12188           || ' and mtl.parent_demand_id is NULL '
12189           || ' and mtl.demand_source_type IN (2,8) '
12190           || ' and mtl.demand_id = dtl.line_id '
12191           || ' and dtl.header_id = hdr.header_id '
12192         -- B2743626, Changed the join to take process sales order (OMSO)
12193           || ' and dtl.ship_from_org_id = org.organization_id  '
12194           || ' and org.process_enabled_flag = ' || '''Y'''
12195           || ' and NOT EXISTS  '
12196           || '     (SELECT 1 '
12197           || '        FROM so_lines_all'||pdblink||' sl,'
12198           || '          so_lines_all'||pdblink||' slp,'
12199           || '          mtl_demand_omoe'||pdblink||' dem'
12200           || '      WHERE '
12201           || '           slp.line_id(+) = nvl(sl.parent_line_id,sl.line_id) '
12202           || '        and to_number(dem.demand_source_line) = sl.line_id(+) '
12203           || '        and dem.demand_source_type in (2,8) '
12204           || '        and sl.end_item_unit_number IS NULL '
12205           || '        and slp.end_item_unit_number IS NULL '
12206           || '        and dem.demand_id = mtl.demand_id '
12207           || '        and items.effectivity_control = 2) '
12208           || ' ORDER BY 1,2,7 DESC ' ;
12209 
12210        /* Extract Forecast details */
12211         v_forecast_sql_stmt := 'SELECT '
12212           || ' msi.inventory_item_id, '
12213           || ' msi.organization_id, '
12214           || ' h.forecast_id, '
12215           || ' h.forecast, '
12216           || ' d.orgn_code, '
12217           || ' d.trans_date, '
12218           || ' (sum(d.trans_qty * -1) ) trans_qty, '
12219           || ' (sum(d.trans_qty * -1) ) consumed_qty ,'
12220           || ' 0 use_fcst_flag '
12221           || ' FROM '
12222           || ' mtl_system_items'||pdblink||' msi, '
12223           || ' ic_item_mst'||pdblink||' iim, '
12224           || ' ic_whse_mst'||pdblink||' wm, '
12225           || ' fc_fcst_hdr'||pdblink||' h, '
12226           || ' fc_fcst_dtl'||pdblink||' d '
12227           || ' WHERE '
12228           || '     msi.organization_id = wm.mtl_organization_id ' ;
12229           /* Bug # 5238790 */
12230          IF l_profile = 0 THEN
12231                   v_forecast_sql_stmt := v_forecast_sql_stmt
12232          || ' and iim.experimental_ind = 0 ' ;
12233          END IF;
12234 
12235           v_forecast_sql_stmt := v_forecast_sql_stmt
12236           || ' and msi.segment1 = iim.item_no '
12237           || ' and wm.delete_mark = 0 '
12238           || ' and h.forecast_id = d.forecast_id '
12239           || ' and d.forecast_id > 0  '
12240           || ' and d.item_id = iim.item_id '
12241           || ' and d.whse_code = wm.whse_code '
12242           || ' and d.orgn_code = wm.orgn_code '
12243           || ' and h.delete_mark = 0 '
12244           || ' and d.delete_mark = 0 '
12245           || ' and d.trans_qty <> 0 '
12246           || ' and d.trans_date >=  sysdate '
12247           || ' and EXISTS (SELECT 1 FROM '
12248           || '                      ps_schd_for'||pdblink||' sf, '
12249           || '                      ps_schd_hdr'||pdblink||' sh  '
12250           || '             WHERE sh.schedule_id = sf.schedule_id '
12251           || '               and sh.delete_mark = 0 '
12252           || '               and sh.active_ind = 1 '
12253           || '               and sf.forecast_id = h.forecast_id) '
12254           || ' GROUP BY '
12255           || ' msi.inventory_item_id, '
12256           || ' msi.organization_id, '
12257           || ' h.forecast, '
12258           || ' h.forecast_id, '
12259           || ' d.orgn_code, '
12260           || ' d.trans_date '
12261           || ' ORDER BY msi.inventory_item_id,msi.organization_id, '
12262           || ' d.trans_date DESC ' ;
12263 
12264        /* Extract Schedule Forecast Association SQL selection */
12265         v_association_sql_stmt := 'SELECT '
12266           || ' schedule_id, forecast_id '
12267           || ' from ps_schd_for'||pdblink
12268           || ' ORDER BY 1,2 ' ;
12269 
12270     /* Start Fetching the schedule, forecast, sales order and association
12271        data for above queries */
12272 
12273     OPEN cur_gmp_schd_items FOR v_item_sql_stmt;
12274     LOOP
12275       FETCH cur_gmp_schd_items INTO sched_dtl_tab(item_count);
12276       EXIT WHEN cur_gmp_schd_items%NOTFOUND;
12277       item_count := item_count + 1;
12278     END LOOP;
12279     CLOSE cur_gmp_schd_items;
12280     gitem_size := item_count -1 ;
12281     time_stamp ;
12282     log_message('Schedule Items size is = ' || to_char(gitem_size)) ;
12283 
12284 -- Bug: 6030499 Vpedarla
12285           SELECT st.VALUE INTO v_dummy from V$MYSTAT st, V$STATNAME sn
12286           where st.STATISTIC# = sn.STATISTIC#
12287           and sn.NAME in ('session pga memory');
12288           log_message('Session pga memory = ' || TO_CHAR(v_dummy) );
12289 
12290 
12291     OPEN cur_fcst_dtl FOR v_forecast_sql_stmt;
12292     LOOP
12293       FETCH cur_fcst_dtl INTO fcst_dtl_tab(fcst_count);
12294       EXIT WHEN cur_fcst_dtl%NOTFOUND;
12295       fcst_count := fcst_count + 1;
12296     END LOOP;
12297     CLOSE cur_fcst_dtl ;
12298     gfcst_size := fcst_count  -1 ;
12299     time_stamp ;
12300     log_message('Fcst size is = '|| to_char(gfcst_size) );
12301 
12302 
12303 -- Bug: 6030499 Vpedarla
12304           SELECT st.VALUE INTO v_dummy from V$MYSTAT st, V$STATNAME sn
12305           where st.STATISTIC# = sn.STATISTIC#
12306           and sn.NAME in ('session pga memory');
12307           log_message('Session pga memory = ' || TO_CHAR(v_dummy) );
12308 
12309     OPEN cur_sales_dtl FOR v_sales_sql_stmt USING v_doc_opso;
12310     LOOP
12311       FETCH cur_sales_dtl INTO sales_dtl_tab(so_count);
12312       EXIT WHEN cur_sales_dtl%NOTFOUND;
12313       so_count := so_count + 1;
12314     END LOOP;
12315     CLOSE cur_sales_dtl ;
12316     gso_size := so_count  -1 ;
12317     time_stamp ;
12318     log_message ('SO size is = '||to_char(gso_size));
12319 
12320 -- Bug: 6030499 Vpedarla
12321           SELECT st.VALUE INTO v_dummy from V$MYSTAT st, V$STATNAME sn
12322           where st.STATISTIC# = sn.STATISTIC#
12323           and sn.NAME in ('session pga memory');
12324           log_message('Session pga memory = ' || TO_CHAR(v_dummy) );
12325 
12326     OPEN cur_schd_fcst FOR v_association_sql_stmt;
12327     LOOP
12328       FETCH cur_schd_fcst INTO SCHD_FCST_DTL_TAB(schd_fcst_cnt);
12329       EXIT WHEN cur_schd_fcst%NOTFOUND;
12330       schd_fcst_cnt := schd_fcst_cnt + 1;
12331     END LOOP;
12332     CLOSE cur_schd_fcst ;
12333     gschd_fcst_size := schd_fcst_cnt -1 ;
12334     time_stamp ;
12335     log_message('Schedule Forecast Assoc size is ='||to_char(gschd_fcst_size));
12336 
12337 -- Bug: 6030499 Vpedarla
12338           SELECT st.VALUE INTO v_dummy from V$MYSTAT st, V$STATNAME sn
12339           where st.STATISTIC# = sn.STATISTIC#
12340           and sn.NAME in ('session pga memory');
12341           log_message('Session pga memory = ' || TO_CHAR(v_dummy) );
12342 
12343      gschd_fcst_cnt := 1;
12344      so_ind 	:= FALSE ;
12345      fcst_ind	:= FALSE ;
12346 
12347     FOR i IN 1..gitem_size LOOP
12348     g_item_tbl_position := i ;
12349     IF old_schedule_id <> sched_dtl_tab(i).schedule_id THEN
12350 	-- Keep commiting the data to avoid Rollback segment growing problem
12351         COMMIT ;
12352 	time_stamp ;
12353 	  gfcst_cnt      := 1 ;
12354 	  gso_cnt        := 1 ;
12355      	  so_ind 	:= FALSE ;
12356      	  fcst_ind	:= FALSE ;
12357 
12358 	  IF sched_dtl_tab(i).order_ind = 1 THEN
12359 		so_ind := TRUE ;
12360 	  END IF;
12361 	  IF sched_dtl_tab(i).stock_ind = 1 THEN
12362 		fcst_ind := TRUE ;
12363 	  END IF;
12364 
12365         /* If there is no forecast associated to current schedule
12366            then set FCST_IND = FALSE */
12367 	IF sched_dtl_tab(i).stock_ind = 1 AND
12368           NOT (associate_forecasts(gschd_fcst_cnt,sched_dtl_tab(i).schedule_id))
12369         THEN
12370 		fcst_ind := FALSE;
12371 	/* Note that we are not Dis-associating the forecasts detail
12372 	  rows when stock_ind is turned OFF. Make sure that the
12373 	  forecast table is not used at all in such cases */
12374 	END IF ;   /* Stock Indicator  */
12375 
12376        old_schedule_id := sched_dtl_tab(i).schedule_id ;
12377     END IF;  /* Schedule ID match */
12378 
12379       -- If both stock_ind and order_ind are 0 , we should simply continue to
12380       -- the next record , the easiest method may be <<goto>>
12381 
12382        IF (fcst_ind) THEN
12383           IF (so_ind) THEN
12384               consume_forecast(sched_dtl_tab(i).inventory_item_id,
12385                                sched_dtl_tab(i).organization_id,api_mode) ;
12386            ELSE
12387     	       write_forecast(gfcst_cnt,sched_dtl_tab(i).inventory_item_id,
12388                               sched_dtl_tab(i).organization_id,api_mode ) ;
12389 	   END IF;
12390        ELSE
12391           IF (so_ind)  THEN
12392     		write_so(gso_cnt,sched_dtl_tab(i).inventory_item_id,
12393                           sched_dtl_tab(i).organization_id,api_mode ) ;
12394  	   END IF;
12395        END IF;
12396 
12397     END LOOP ;   /* Main Loop for Schedule, item, Warehouse */
12398 
12399     /* Bug 2756431 Moved the call to this function here per thisbug */
12400     /* the transfer demands and supplies need to be put under EACH of the
12401       demand schedules - Note that the supplies should NOT be replicated */
12402     FOR i IN 1..desig_tab.COUNT LOOP
12403       extract_inv_transfer_demands(pdblink, pinstance_id, prun_date,
12404       pdelimiter, desig_tab(i).whse_code,desig_tab(i).designator,
12405       local_ret_status);
12406     END LOOP ;
12407 
12408     return_status := local_ret_status ;
12409 
12410     Insert_Designator;
12411 
12412     log_message('End of gmp_aps_ds_pull.sales forecast') ;
12413     time_stamp ;
12414     return_status := TRUE;
12415 ELSE
12416   extract_forecasts( pdblink       ,
12417                           pinstance_id   ,
12418                           prun_date      ,
12419                           pdelimiter    ,
12420                           return_status  );
12421 
12422 END IF ; -- if NOT api_mode
12423   EXCEPTION
12424     WHEN NO_DATA_FOUND THEN /* B3577871 */
12425       log_message(' NO_DATA_FOUND exception raised in Procedure: Gmp_aps_ds_pull.Sales_forecast ' );
12426       return_status := TRUE;
12427 
12428     WHEN OTHERS THEN
12429 	log_message('Failure occured during the Sales_Forecast extract');
12430 	log_message(sqlerrm);
12431         return_status := FALSE;
12432 END sales_forecast;
12433 
12434 /************************************************************************
12435 *   NAME
12436 *	sales_order_allocation
12437 *
12438 *   DESCRIPTION
12439 *  This procedure will have a new procedure to collect the additional data
12440 *  element for ASCP. OPM does not have sales order reservation
12441 *  functionality. Hence OM Reservation does not impact ic_tran_pnd. Only
12442 *  Allocation, which can be be done just after Order creation or after
12443 *  order is booked but before Shipping will create a  record in ic_tran_pnd
12444 *  table. Sales order Reservation Quantity is summation of allocated -
12445 *  quantity + remaining Quantity. We can Reserve/Allocate more than On hand
12446 *   committed quantity. These sales order item allocation record will be
12447 *  send to ASCP.
12448 *   For non-controlled items, no allocation/reservations are allowed
12449 *   and hence this enhancement will not send any information.
12450 *   The following enhancement will also support org specific
12451 *   collection for reservation entity. The net change
12452 *   functionality will not be supported by process code collection.
12453 *
12454 *   HISTORY
12455 *       Created By : B5501754 Rajesh Patangya
12456 ************************************************************************/
12457 PROCEDURE sales_order_allocation (
12458                           pdblink        IN  VARCHAR2,
12459                           pinstance_id   IN  NUMBER,
12460                           pentity        IN  NUMBER,
12461                           return_status  IN  OUT NOCOPY BOOLEAN)
12462 IS
12463 
12464    l_profile      VARCHAR2(40) ;
12465    b_profile      VARCHAR2(70) ;
12466    pdoc_type      VARCHAR2(4) ;
12467    v_instance_id  NUMBER;
12468    v_entity       NUMBER;
12469    v_sql_stmt     VARCHAR2(30000);
12470 BEGIN
12471 
12472    log_message( 'DB LINK = ' || pdblink);
12473    log_message( 'DB LINK = ' || pinstance_id   );
12474    log_message( 'DB LINK = ' || pentity        );
12475 
12476    v_instance_id := pinstance_id ;
12477    v_entity := pentity ;
12478    return_status := TRUE ;
12479    pdoc_type     := 'OMSO' ;
12480    l_profile := NULL ;
12481 
12482    log_message('Entering into the Program, Begin ');
12483 
12484    /* This profile value holds the Defualt Location */
12485 --   l_profile := FND_PROFILE.value('IC$DEFAULT_LOCT') ;
12486  /* bug:6710684 Vpedarla made changes to fetch the profile value from source server*/
12487    l_profile := GMP_BOM_ROUTING_PKG.get_profile_value('IC$DEFAULT_LOCT', pdblink );
12488 
12489    log_message('Default Location = ' || l_profile );
12490 
12491 --   b_profile := fnd_profile.value('BIS_PRIMARY_RATE_TYPE') ;
12492  /* bug:6710684 Vpedarla made changes to fetch the profile value from source server*/
12493    b_profile := GMP_BOM_ROUTING_PKG.get_profile_value('BIS_PRIMARY_RATE_TYPE', pdblink );
12494 
12495    log_message('Primary Rate = ' || b_profile);
12496 
12497     /* populate the org_string */
12498      IF MSC_CL_GMP_UTILITY.org_string(pinstance_id) THEN
12499         NULL ;
12500      ELSE
12501         RAISE invalid_string_value  ;
12502      END IF;
12503 
12504     IF v_entity = 1 THEN
12505 /* to consider ATP,
12506 1. Sales order Record should be inserted in msc_sales_order table, this record is directly coming from APS data collection, we have to modify ceratin columns (or insert an record in mtl_demand table).
12507 2. Reservation record should be inserted in msc_sales_order table
12508 */
12509 
12510     --Bug 6047794. Added missing database links.
12511     v_sql_stmt := 'INSERT INTO MSC_ST_SALES_ORDERS ( '
12512    ||'    INVENTORY_ITEM_ID,'
12513    ||'    SOURCE_INVENTORY_ITEM_ID,'
12514    ||'    ORGANIZATION_ID,'
12515    ||'    PRIMARY_UOM_QUANTITY,'
12516    ||'    RESERVATION_TYPE, '
12517    ||'    RESERVATION_QUANTITY,'
12518    ||'    DEMAND_SOURCE_TYPE, '
12519    ||'    DEMAND_SOURCE_HEADER_ID,   '
12520    ||'    COMPLETED_QUANTITY,'
12521    ||'    SUBINVENTORY,'
12522    ||'    DEMAND_CLASS, '
12523    ||'    REQUIREMENT_DATE,'
12524    ||'    DEMAND_SOURCE_LINE, '
12525    ||'    SOURCE_DEMAND_SOURCE_LINE, '
12526    ||'    DEMAND_SOURCE_DELIVERY,'
12527    ||'    DEMAND_SOURCE_NAME,'
12528    ||'    PARENT_DEMAND_ID,'
12529    ||'    DEMAND_ID,'
12530    ||'    SOURCE_DEMAND_ID,'
12531    ||'    SALES_ORDER_NUMBER,'
12532    ||'    FORECAST_VISIBLE, '
12533    ||'    DEMAND_VISIBLE,'
12534    ||'    SALESREP_CONTACT,'
12535    ||'    SALESREP_ID,'
12536    ||'    CUSTOMER_ID,'
12537    ||'    SHIP_TO_SITE_USE_ID,'
12538    ||'    BILL_TO_SITE_USE_ID, '
12539    ||'    REQUEST_DATE, '
12540    ||'    PROJECT_ID, '
12541    ||'    TASK_ID, '
12542    ||'    PLANNING_GROUP,'
12543    ||'    SELLING_PRICE, '
12544    ||'    END_ITEM_UNIT_NUMBER, '
12545    ||'    ORDERED_ITEM_ID, '
12546    ||'    ORIGINAL_ITEM_ID,'
12547    ||'    LINK_TO_LINE_ID ,'
12548    ||'    CUST_PO_NUMBER, '
12549    ||'    CUSTOMER_LINE_NUMBER,'
12550    ||'    MFG_LEAD_TIME, '
12551    ||'    ORG_FIRM_FLAG,'
12552    ||'    SHIP_SET_ID, '
12553    ||'    ARRIVAL_SET_ID,'
12554    ||'    SHIP_SET_NAME, '
12555    ||'    ARRIVAL_SET_NAME,'
12556    ||'    ATP_REFRESH_NUMBER, '
12557    ||'    DELETED_FLAG, '
12558    ||'    ORIGINAL_SYSTEM_LINE_REFERENCE, '
12559    ||'    ORIGINAL_SYSTEM_REFERENCE, '
12560    ||'    CTO_FLAG, '
12561    ||'    AVAILABLE_TO_MRP,'
12562    ||'    DEMAND_PRIORITY,'
12563    ||'    PROMISE_DATE, '
12564    ||'    REFRESH_ID,'
12565    ||'    SR_INSTANCE_ID, '
12566    ||'    SCHEDULE_ARRIVAL_DATE, '
12567    ||'    LATEST_ACCEPTABLE_DATE,'
12568    ||'    SHIPPING_METHOD_CODE, '
12569    ||'    ATO_LINE_ID,'
12570    ||'    ORDER_DATE_TYPE_CODE,'
12571    ||'    INTRANSIT_LEAD_TIME '
12572    ||'   )  '
12573    ||'    SELECT '
12574    ||'    OOL.INVENTORY_ITEM_ID, '
12575    ||'    OOL.INVENTORY_ITEM_ID SOURCE_INVENTORY_ITEM_ID, '
12576    ||'    OOL.ORGANIZATION_ID, '
12577    ||'    (t.trans_qty * -1) PRIMARY_UOM_QUANTITY, '
12578    ||'    2 RESERVATION_TYPE, '
12579    ||'    TO_NUMBER(NULL) RESERVATION_QUANTITY, '
12580    ||'    decode(ool.SOURCE_DOCUMENT_TYPE_ID,10,8,2) DEMAND_SOURCE_TYPE, '
12581    ||'    so.SALES_ORDER_ID    DEMAND_SOURCE_HEADER_ID, '
12582    ||'    0 COMPLETED_QUANTITY, '
12583    ||'    TO_CHAR(NULL) SUBINVENTORY, '
12584    ||'    OOL.DEMAND_CLASS, '
12585    ||'    OOL.SCHEDULE_SHIP_DATE REQUIREMENT_DATE, '
12586    ||'    TO_CHAR(OOL.LINE_ID) DEMAND_SOURCE_LINE, '
12587    ||'    TO_CHAR(OOL.LINE_ID) SOURCE_DEMAND_SOURCE_LINE, '
12588    ||'    TO_CHAR(NULL) DEMAND_SOURCE_DELIVERY, '
12589    ||'    TO_CHAR(NULL) DEMAND_SOURCE_NAME, '
12590    ||'    TO_NUMBER(NULL) PARENT_DEMAND_ID, '
12591    ||'    MTL_DEMAND_S.nextval DEMAND_ID, '
12592    ||'    MTL_DEMAND_S.currval SOURCE_DEMAND_ID, '
12593    ||'    so.Concatenated_Segments, '
12594    ||'    ''Y'' , '
12595    ||'    ''Y'' , '
12596    ||'    TO_CHAR(NULL) Salesrep_Contact, '
12597    ||'    ool.salesrep_id, '
12598    ||'    ool.CUSTOMER_ID, '
12599    ||'    ool.SHIP_TO_SITE_ID, '
12600    ||'    ool.BILL_TO_SITE_ID, '
12601    ||'    ool.REQUEST_DATE, '
12602    ||'    ool.project_id, '
12603    ||'    ool.task_id, '
12604    ||'    TO_CHAR(NULL) PLANNING_GROUP, '
12605    ||'    ool.LIST_PRICE * decode(   GL_CURRENCY_API.get_rate_sql'||pdblink||' ( '
12606    ||'				 h.transactional_curr_code, '
12607    ||'				 gsb.currency_code, '
12608    ||'				 h.booked_date, '
12609    ||'				 nvl(h.conversion_type_code, :b_prof1 )), '
12610    ||'				 -2,1,-1,1, '
12611    ||'				 GL_CURRENCY_API.get_rate_sql'||pdblink||' ( '
12612    ||'				 h.transactional_curr_code, '
12613    ||'				 gsb.currency_code, '
12614    ||'				 h.booked_date, '
12615    ||'				 nvl(h.conversion_type_code, :b_prof2 )) '
12616    ||'				 ) LIST_PRICE, '
12617    ||'    ool.end_item_unit_number, '
12618    ||'    DECODE(DECODE(ool.ITEM_TYPE_CODE, '
12619    ||'          ''CLASS'',2, '
12620    ||'          ''CONFIG'',4, '
12621    ||'          ''MODEL'',1, '
12622    ||'          ''OPTION'' ,3, '
12623    ||'          ''STANDARD'',6, -1), 1, ool.inventory_item_id, NULL) ORDERED_ITEM_ID, '
12624    ||'    decode(ool.ORIGINAL_INVENTORY_ITEM_ID,-1,to_number(null), '
12625    ||'		  decode(ool.ITEM_RELATIONSHIP_TYPE,-1,to_number(null), '
12626    ||'						    2, ool.ORIGINAL_INVENTORY_ITEM_ID,  '
12627    ||'						    null,ool.ORIGINAL_INVENTORY_ITEM_ID,  '
12628    ||'						    to_number(null)) '
12629    ||'						    ) ORIGINAL_ITEM_ID, '
12630    ||'    TO_NUMBER(NULL) LINK_TO_LINE_ID, '
12631    ||'    nvl(ool.CUST_PO_NUMBER,''-1'') CUST_PO_NUMBER, '
12632    ||'    nvl(ool.CUSTOMER_LINE_NUMBER,''-1'') CUSTOMER_LINE_NUMBER, '
12633    ||'    ool.mfg_lead_time, '
12634    ||'    decode(ool.firm_demand_flag,NULL,to_number(null),''Y'',1,2) FIRM_DEMAND_FLAG, '
12635    ||'    ool.SHIP_SET_ID, '
12636    ||'    ool.ARRIVAL_SET_ID, '
12637    ||'    mrp_cl_function.get_ship_set_name(ool.SHIP_SET_ID) SHIP_SET_NAME, '
12638    ||'    mrp_cl_function.get_arrival_set_name(ool.ARRIVAL_SET_ID) ARRIVAL_SET_NAME, '
12639    ||'    TO_NUMBER(NULL) ATP_REFRESH_NUMBER, '
12640    ||'    2 DELETED_FLAG, '
12641    ||'    ool.original_system_reference, '
12642    ||'    ool.original_system_line_reference, '
12643    ||'    2 CTO_FLAG, '
12644    ||'    TO_NUMBER(NULL) available_to_mrp, '
12645    ||'    ool.DEMAND_PRIORITY, '
12646    ||'    ool.PROMISE_DATE, '
12647    ||'    TO_NUMBER(NULL) refresh_id, '
12648    ||'    :instance_id, '
12649    ||'    ool.SCHEDULE_ARRIVAL_DATE, '
12650    ||'    ool.LATEST_ACCEPTABLE_DATE, '
12651    ||'    ool.SHIPPING_METHOD_CODE, '
12652    ||'    ool.ATO_LINE_ID, '
12653    ||'    decode(h.ORDER_DATE_TYPE_CODE,''ARRIVAL'',2,1) ORDER_DATE_TYPE_CODE, '
12654    ||'    OOL.DELIVERY_LEAD_TIME  '
12655    ||'    FROM  '
12656    ||'        MRP_SN_SYS_ITEMS'||pdblink||' msik, '
12657    ||'        MTL_SALES_ORDERS_KFV'||pdblink||' so, '
12658    ||'        OE_ORDER_HEADERS_ALL'||pdblink||' h,       '
12659    ||'        GL_SETS_OF_BOOKS'||pdblink||' gsb, '
12660    ||'        AR_SYSTEM_PARAMETERS_ALL'||pdblink||' aspa   , '
12661    ||'        IC_TRAN_PND'||pdblink||' t , '
12662    ||'        GMP_ITEM_APS'||pdblink||' i , '
12663    ||'        MRP_SN_ODR_LINES'||pdblink||' ool '
12664    ||'    WHERE  '
12665    ||'      t.item_id = i.item_id  '
12666    ||'      AND t.doc_type = :p_doc_type '
12667    ||'      AND ool.line_id = t.line_id '
12668    ||'      AND ( t.lot_id <> 0 OR t.location <> :p_prof ) '
12669    ||'      AND t.whse_code = i.whse_code  '
12670    ||'      AND t.orgn_code = i.plant_code  '
12671    ||'      AND t.completed_ind = 0  '
12672    ||'      AND t.trans_qty <> 0  '
12673    ||'      AND t.delete_mark = 0 '
12674    ||'      AND msik.inventory_item_id = i.aps_item_id '
12675    ||'      AND msik.organization_id = i.organization_id '
12676    ||'      AND so.Sales_Order_ID = t.doc_id  '
12677    ||'      AND ool.header_id = h.header_id(+) '
12678    ||'      AND h.org_id = aspa.org_id(+) '
12679    ||'      AND aspa.set_of_books_id = gsb.set_of_books_id(+) '
12680    ||'      AND h.org_id is not null ' ;
12681 
12682      IF MSC_CL_GMP_UTILITY.g_in_str_org  IS NOT NULL THEN
12683      v_sql_stmt := v_sql_stmt
12684      || '  AND i.organization_id ' || MSC_CL_GMP_UTILITY.g_in_str_org ;
12685      END IF;
12686 
12687     log_message('OMSO for Entity 1  =  '||v_sql_stmt);
12688 
12689     EXECUTE IMMEDIATE v_sql_stmt USING
12690       b_profile, b_profile, v_instance_id, pdoc_type, l_profile  ;
12691 
12692     --Bug 6047794. Added missing database links.
12693     v_sql_stmt := 'INSERT INTO MSC_ST_SALES_ORDERS ( '
12694    ||'    INVENTORY_ITEM_ID,'
12695    ||'    SOURCE_INVENTORY_ITEM_ID,'
12696    ||'    ORGANIZATION_ID,'
12697    ||'    PRIMARY_UOM_QUANTITY,'
12698    ||'    RESERVATION_TYPE, '
12699    ||'    RESERVATION_QUANTITY,'
12700    ||'    DEMAND_SOURCE_TYPE, '
12701    ||'    DEMAND_SOURCE_HEADER_ID,   '
12702    ||'    COMPLETED_QUANTITY,'
12703    ||'    SUBINVENTORY,'
12704    ||'    DEMAND_CLASS, '
12705    ||'    REQUIREMENT_DATE,'
12706    ||'    DEMAND_SOURCE_LINE, '
12707    ||'    SOURCE_DEMAND_SOURCE_LINE, '
12708    ||'    DEMAND_SOURCE_DELIVERY,'
12709    ||'    DEMAND_SOURCE_NAME,'
12710    ||'    PARENT_DEMAND_ID,'
12711    ||'    DEMAND_ID,'
12712    ||'    SOURCE_DEMAND_ID,'
12713    ||'    SALES_ORDER_NUMBER,'
12714    ||'    FORECAST_VISIBLE, '
12715    ||'    DEMAND_VISIBLE,'
12716    ||'    SALESREP_CONTACT,'
12717    ||'    SALESREP_ID,'
12718    ||'    CUSTOMER_ID,'
12719    ||'    SHIP_TO_SITE_USE_ID,'
12720    ||'    BILL_TO_SITE_USE_ID, '
12721    ||'    REQUEST_DATE, '
12722    ||'    PROJECT_ID, '
12723    ||'    TASK_ID, '
12724    ||'    PLANNING_GROUP,'
12725    ||'    SELLING_PRICE, '
12726    ||'    END_ITEM_UNIT_NUMBER, '
12727    ||'    ORDERED_ITEM_ID, '
12728    ||'    ORIGINAL_ITEM_ID,'
12729    ||'    LINK_TO_LINE_ID ,'
12730    ||'    CUST_PO_NUMBER, '
12731    ||'    CUSTOMER_LINE_NUMBER,'
12732    ||'    MFG_LEAD_TIME, '
12733    ||'    ORG_FIRM_FLAG,'
12734    ||'    SHIP_SET_ID, '
12735    ||'    ARRIVAL_SET_ID,'
12736    ||'    SHIP_SET_NAME, '
12737    ||'    ARRIVAL_SET_NAME,'
12738    ||'    ATP_REFRESH_NUMBER, '
12739    ||'    DELETED_FLAG, '
12740    ||'    ORIGINAL_SYSTEM_LINE_REFERENCE, '
12741    ||'    ORIGINAL_SYSTEM_REFERENCE, '
12742    ||'    CTO_FLAG, '
12743    ||'    AVAILABLE_TO_MRP,'
12744    ||'    DEMAND_PRIORITY,'
12745    ||'    PROMISE_DATE, '
12746    ||'    REFRESH_ID,'
12747    ||'    SR_INSTANCE_ID, '
12748    ||'    SCHEDULE_ARRIVAL_DATE, '
12749    ||'    LATEST_ACCEPTABLE_DATE,'
12750    ||'    SHIPPING_METHOD_CODE, '
12751    ||'    ATO_LINE_ID,'
12752    ||'    ORDER_DATE_TYPE_CODE,'
12753    ||'    INTRANSIT_LEAD_TIME '
12754    ||'   )  '
12755    ||'    SELECT '
12756    ||'    OOL.INVENTORY_ITEM_ID, '
12757    ||'    OOL.INVENTORY_ITEM_ID SOURCE_INVENTORY_ITEM_ID, '
12758    ||'    OOL.ORGANIZATION_ID, '
12759    ||'    (t.trans_qty * -1 ) PRIMARY_UOM_QUANTITY, '
12760    ||'    2 RESERVATION_TYPE, '
12761    ||'    TO_NUMBER(NULL) RESERVATION_QUANTITY, '
12762    ||'    decode(ool.SOURCE_DOCUMENT_TYPE_ID,10,8,2) DEMAND_SOURCE_TYPE, '
12763    ||'    so.SALES_ORDER_ID    DEMAND_SOURCE_HEADER_ID, '
12764    ||'    0 COMPLETED_QUANTITY, '
12765    ||'    TO_CHAR(NULL) SUBINVENTORY, '
12766    ||'    OOL.DEMAND_CLASS, '
12767    ||'    OOL.SCHEDULE_SHIP_DATE REQUIREMENT_DATE, '
12768    ||'    TO_CHAR(OOL.LINE_ID) DEMAND_SOURCE_LINE, '
12769    ||'    TO_CHAR(OOL.LINE_ID) SOURCE_DEMAND_SOURCE_LINE, '
12770    ||'    TO_CHAR(NULL) DEMAND_SOURCE_DELIVERY, '
12771    ||'    TO_CHAR(NULL) DEMAND_SOURCE_NAME, '
12772    ||'    TO_NUMBER(NULL) PARENT_DEMAND_ID, '
12773    ||'    MTL_DEMAND_S.nextval DEMAND_ID, '
12774    ||'    MTL_DEMAND_S.currval SOURCE_DEMAND_ID, '
12775    ||'    so.Concatenated_Segments, '
12776    ||'    ''Y'' , '
12777    ||'    ''Y'' , '
12778    ||'    TO_CHAR(NULL) Salesrep_Contact, '
12779    ||'    ool.salesrep_id, '
12780    ||'    ool.CUSTOMER_ID, '
12781    ||'    ool.SHIP_TO_SITE_ID, '
12782    ||'    ool.BILL_TO_SITE_ID, '
12783    ||'    ool.REQUEST_DATE, '
12784    ||'    ool.project_id, '
12785    ||'    ool.task_id, '
12786    ||'    TO_CHAR(NULL) PLANNING_GROUP, '
12787    ||'    ool.LIST_PRICE * decode(   GL_CURRENCY_API.get_rate_sql'||pdblink||' ( '
12788    ||'				 h.transactional_curr_code, '
12789    ||'				 gsb.currency_code, '
12790    ||'				 h.booked_date, '
12791    ||'				 nvl(h.conversion_type_code, :b_prof1 )), '
12792    ||'				 -2,1,-1,1, '
12793    ||'				 GL_CURRENCY_API.get_rate_sql'||pdblink||' ( '
12794    ||'				 h.transactional_curr_code, '
12795    ||'				 gsb.currency_code, '
12796    ||'				 h.booked_date, '
12797    ||'				 nvl(h.conversion_type_code, :b_prof2 )) '
12798    ||'				 ) LIST_PRICE, '
12799    ||'    ool.end_item_unit_number, '
12800    ||'    DECODE(DECODE(ool.ITEM_TYPE_CODE, '
12801    ||'          ''CLASS'',2, '
12802    ||'          ''CONFIG'',4, '
12803    ||'          ''MODEL'',1, '
12804    ||'          ''OPTION'' ,3, '
12805    ||'          ''STANDARD'',6, -1), 1, ool.inventory_item_id, NULL) ORDERED_ITEM_ID, '
12806    ||'    decode(ool.ORIGINAL_INVENTORY_ITEM_ID,-1,to_number(null), '
12807    ||'		  decode(ool.ITEM_RELATIONSHIP_TYPE,-1,to_number(null), '
12808    ||'						    2, ool.ORIGINAL_INVENTORY_ITEM_ID,  '
12809    ||'						    null,ool.ORIGINAL_INVENTORY_ITEM_ID,  '
12810    ||'						    to_number(null)) '
12811    ||'						    ) ORIGINAL_ITEM_ID, '
12812    ||'    TO_NUMBER(NULL) LINK_TO_LINE_ID, '
12813    ||'    nvl(ool.CUST_PO_NUMBER,''-1'') CUST_PO_NUMBER, '
12814    ||'    nvl(ool.CUSTOMER_LINE_NUMBER,''-1'') CUSTOMER_LINE_NUMBER, '
12815    ||'    ool.mfg_lead_time, '
12816    ||'    decode(ool.firm_demand_flag,NULL,to_number(null),''Y'',1,2) FIRM_DEMAND_FLAG, '
12817    ||'    ool.SHIP_SET_ID, '
12818    ||'    ool.ARRIVAL_SET_ID, '
12819    ||'    mrp_cl_function.get_ship_set_name(ool.SHIP_SET_ID) SHIP_SET_NAME, '
12820    ||'    mrp_cl_function.get_arrival_set_name(ool.ARRIVAL_SET_ID) ARRIVAL_SET_NAME, '
12821    ||'    TO_NUMBER(NULL) ATP_REFRESH_NUMBER, '
12822    ||'    2 DELETED_FLAG, '
12823    ||'    ool.original_system_reference, '
12824    ||'    ool.original_system_line_reference, '
12825    ||'    2 CTO_FLAG, '
12826    ||'    TO_NUMBER(NULL) available_to_mrp, '
12827    ||'    ool.DEMAND_PRIORITY, '
12828    ||'    ool.PROMISE_DATE, '
12829    ||'    TO_NUMBER(NULL) refresh_id, '
12830    ||'    :instance_id, '
12831    ||'    ool.SCHEDULE_ARRIVAL_DATE, '
12832    ||'    ool.LATEST_ACCEPTABLE_DATE, '
12833    ||'    ool.SHIPPING_METHOD_CODE, '
12834    ||'    ool.ATO_LINE_ID, '
12835    ||'    decode(h.ORDER_DATE_TYPE_CODE,''ARRIVAL'',2,1) ORDER_DATE_TYPE_CODE, '
12836    ||'    OOL.DELIVERY_LEAD_TIME  '
12837    ||'    FROM  '
12838    ||'        MRP_SN_SYS_ITEMS'||pdblink||' msik, '
12839    ||'        MTL_SALES_ORDERS_KFV'||pdblink||' so, '
12840    ||'        OE_ORDER_HEADERS_ALL'||pdblink||' h,       '
12841    ||'        GL_SETS_OF_BOOKS'||pdblink||' gsb, '
12842    ||'        AR_SYSTEM_PARAMETERS_ALL'||pdblink||' aspa   , '
12843    ||'        IC_TRAN_PND'||pdblink||' t , '
12844    ||'        GMP_ITEM_APS'||pdblink||' i , '
12845    ||'        MRP_SN_ODR_LINES'||pdblink||' ool '
12846    ||'    WHERE  '
12847    ||'      t.item_id = i.item_id  '
12848    ||'      AND t.doc_type = :p_doc_type '
12849    ||'      AND ool.line_id = t.line_id '
12850    ||'      AND ( t.lot_id <> 0 OR t.location <> :p_prof ) '
12851    ||'      AND t.whse_code = i.whse_code  '
12852    ||'      AND t.orgn_code = i.plant_code  '
12853    ||'      AND t.completed_ind = 0  '
12854    ||'      AND t.trans_qty <> 0  '
12855    ||'      AND t.delete_mark = 0 '
12856    ||'      AND msik.inventory_item_id = i.aps_item_id '
12857    ||'      AND msik.organization_id = i.organization_id '
12858    ||'      AND so.Sales_Order_ID = t.doc_id  '
12859    ||'      AND ool.header_id = h.header_id(+) '
12860    ||'      AND h.org_id = nvl(aspa.org_id,-99) '
12861    ||'      AND aspa.set_of_books_id = gsb.set_of_books_id(+) '
12862    ||'      AND h.org_id is null  ' ;
12863 
12864      IF MSC_CL_GMP_UTILITY.g_in_str_org  IS NOT NULL THEN
12865      v_sql_stmt := v_sql_stmt
12866      || '  AND i.organization_id ' || MSC_CL_GMP_UTILITY.g_in_str_org ;
12867      END IF;
12868 
12869     log_message('OMSO for Entity 1 (Part 2) =  '||v_sql_stmt);
12870 
12871     EXECUTE IMMEDIATE v_sql_stmt USING
12872       b_profile, b_profile, v_instance_id, pdoc_type, l_profile  ;
12873 
12874     END IF ;
12875 
12876     IF v_entity = 2 THEN
12877 --   log_message(MSC_CL_GMP_UTILITY.g_in_str_org);
12878 
12879    /* For Engine Reseration record inserted */
12880    --Bug 6056320. Insert MTL_DEMAND_S.nextval as transaction_id to avoid unique constraint violation.
12881    v_sql_stmt := 'INSERT into msc_st_reservations ('
12882     || ' inventory_item_id,'
12883     || ' organization_id,'
12884     || ' sr_instance_id,'
12885     || ' transaction_id,'
12886     || ' parent_demand_id,'
12887     || ' disposition_id ,'
12888     || ' requirement_date,'
12889     || ' reserved_quantity,'
12890     || ' disposition_type,'
12891     || ' subinventory,'
12892     || ' reservation_type,'
12893     || ' demand_class,'
12894     || ' available_to_mrp,'
12895     || ' reservation_flag,'
12896     || ' planning_group,'
12897     || ' deleted_flag'
12898     || ' )'
12899     || ' SELECT '
12900     || '    i.aps_item_id, '
12901     || '    ool.organization_id, '
12902     || '    :p_instance_id , '
12903     || '    ((MTL_DEMAND_S.nextval * 2 ) + 1), '  /* Bug 6056320. Replaced t.doc_id with MTL_DEMAND_S.nextval */
12904     || '    ool.line_id, '
12905     || '    INV_SALESORDER.GET_SALESORDER_FOR_OEHEADER'||pdblink||' ( '
12906     || '    ool.HEADER_ID), '
12907     || '    t.trans_date , '
12908     || '    (t.trans_qty * -1 ), '
12909     || '    2, '    /* DISPOSITION_TYPE */
12910     || '    NULL, ' /* SUBINVENTORY */
12911     || '    1,  '   /* RESERVATION_TYPE 1 is for Discrete ?? */
12912     || '    ool.demand_class, ' /* DEMAND_CLASS CODE */
12913     || '    NULL, ' /* AVAILABLE_TO_MRP */
12914     || '    2,  '   /* RESERVATION_FLAG */
12915     || '    NULL, ' /* PLANNING_GROUP */
12916     || '    2  '
12917     || ' FROM '
12918     || '   ic_tran_pnd'||pdblink|| ' t,'
12919     || '   gmp_item_aps'||pdblink|| ' i,'
12920     || '   MRP_SN_ODR_LINES'||pdblink|| ' ool'
12921     || ' WHERE '
12922     || '     t.doc_type = :p_doctype '
12923     || ' AND t.item_id = i.item_id '
12924     || ' AND ool.line_id = t.line_id'
12925     || ' AND ( t.lot_id <> 0 OR '
12926     || '   t.location <> :loc_profile ) '
12927     || ' AND t.whse_code = i.whse_code '
12928     || ' AND t.orgn_code = i.plant_code '
12929     || ' AND t.completed_ind = 0 '
12930     || ' and ool.open_flag = ' || '''Y'''
12931     || ' AND t.trans_qty <> 0 '
12932     || ' AND t.delete_mark = 0 ' ;
12933 
12934      IF MSC_CL_GMP_UTILITY.g_in_str_org  IS NOT NULL THEN
12935      v_sql_stmt := v_sql_stmt
12936      || ' and i.organization_id ' || MSC_CL_GMP_UTILITY.g_in_str_org ;
12937      END IF;
12938 
12939     log_message('OMSO for Entity 2 =  '||v_sql_stmt);
12940 
12941     EXECUTE IMMEDIATE v_sql_stmt USING v_instance_id, pdoc_type, l_profile ;
12942 
12943     END IF; /* pentity */
12944 
12945 EXCEPTION
12946    WHEN NO_DATA_FOUND THEN
12947       log_message(' NO DATA FOUND exception in: Gmp_aps_ds_pull.sales_order_allocation');
12948       return_status := TRUE;
12949     WHEN invalid_string_value  THEN
12950         log_message('Organization string is Invalid ' );
12951         return_status := FALSE;
12952     WHEN OTHERS THEN
12953       log_message('Failure occured during the sales_order_allocation extract');
12954       log_message(sqlerrm);
12955       return_status := FALSE;
12956 
12957 END sales_order_allocation;
12958 
12959 /************************************************************************
12960 *   NAME
12961 *	extract_forecasts
12962 *
12963 *   DESCRIPTION
12964 *
12965 *
12966 *
12967 *   HISTORY
12968 *       Created By : Abhay Satpute
12969 *		24-Oct-2003 Chnaged origincation_type to 29
12970 ************************************************************************/
12971 PROCEDURE extract_forecasts ( pdblink        IN  VARCHAR2,
12972                           pinstance_id   IN  NUMBER,
12973                           prun_date      IN  DATE,
12974                           pdelimiter     IN  VARCHAR2,
12975                           return_status  IN  OUT NOCOPY BOOLEAN)
12976 IS
12977 
12978 TYPE gmp_cursor_typ IS REF CURSOR;
12979 fcst_hdr   	gmp_cursor_typ;
12980 cur_fcst_dtl   	gmp_cursor_typ;
12981 
12982 l_design_stmt   	VARCHAR2(32000) ;
12983 l_fcst_stmt             VARCHAR2(32700) ; /* Bug # 5086464 */
12984 l_demands_stmt 		VARCHAR2(32000) ;
12985 l_insert_set_stmt 	VARCHAR2(32000);
12986 
12987 TYPE fcst_hdr_rec IS RECORD (
12988 fcst_id 		PLS_INTEGER,
12989 orig_forecast 		VARCHAR2(16),
12990 fcst_name 		VARCHAR2(10),
12991 fcst_set  		VARCHAR2(10),
12992 desgn_ind 		PLS_INTEGER,
12993 consumption_ind		PLS_INTEGER,
12994 backward_time_fence	NUMBER,
12995 forward_time_fence	NUMBER
12996 );
12997 TYPE fcst_dtl_rec_typ IS RECORD
12998    (
12999     inventory_item_id   PLS_INTEGER,
13000     organization_id     PLS_INTEGER,
13001     forecast_id         PLS_INTEGER,
13002     line_id             PLS_INTEGER,
13003     forecast            VARCHAR2(16),
13004     forecast_set        VARCHAR2(10),
13005     trans_date          DATE,
13006     orgn_code           VARCHAR2(4),
13007     trans_qty           NUMBER,
13008     use_fcst_flag       NUMBER(1)
13009   );
13010 fcst_dtl_rec fcst_dtl_rec_typ ;
13011 
13012 TYPE fcst_hdr_tab_typ IS TABLE OF fcst_hdr_rec
13013 INDEX BY BINARY_INTEGER ;
13014 fcst_hdr_tbl fcst_hdr_tab_typ ;
13015 
13016 cnt             	PLS_INTEGER ;
13017 l_cnt           	PLS_INTEGER ;
13018 curr_cnt        	PLS_INTEGER ;
13019 temp_name       	VARCHAR2(10) ;
13020 i               	PLS_INTEGER ;
13021 j               	PLS_INTEGER ;
13022 k               	PLS_INTEGER ;
13023 x 			PLS_INTEGER ;
13024 duplicate_found 	BOOLEAN ;
13025 prev_org_id  		PLS_INTEGER ;
13026 prev_fcst_id	  	PLS_INTEGER ;
13027 prev_fcst_set		VARCHAR2(10);
13028 prev_fcst    		VARCHAR2(10);
13029 write_fcst		BOOLEAN ;
13030 write_fcst_set		BOOLEAN ;
13031 fcst_locn		PLS_INTEGER ;
13032 
13033 BEGIN
13034 cnt             	:= 0 ;
13035 l_cnt           	:= 1 ;
13036 curr_cnt        	:= 0 ;
13037 temp_name       	:= NULL ;
13038 i               	:= 1 ;
13039 j               	:= 10 ;
13040 k               	:= 0;
13041 x 			:= 1;
13042 duplicate_found 	:= FALSE ;
13043 prev_org_id  		:= 0 ;
13044 prev_fcst_id	  	:= 0 ;
13045 d_index                 := 0 ;
13046 i_index                 := 0 ;
13047 prev_fcst_set           := '-1' ;
13048 prev_fcst               := '-1';
13049 
13050     /* populate the org_string */
13051      IF MSC_CL_GMP_UTILITY.org_string(pinstance_id) THEN
13052         NULL ;
13053      ELSE
13054         RAISE invalid_string_value  ;
13055      END IF;
13056 
13057 l_fcst_stmt := 'SELECT '
13058           || ' msi.inventory_item_id, '
13059           || ' msi.organization_id, '
13060           || ' h.forecast_id, '
13061           || ' d.line_id, '
13062           || ' h.forecast, '
13063           || ' h.forecast_set  FSET , '
13064           || ' d.trans_date, '
13065           || ' d.orgn_code, '
13066           || ' (d.trans_qty * -1)  trans_qty, '
13067           || ' 0 use_fcst_flag '
13068           || ' FROM '
13069           || ' mtl_system_items'||pdblink||' msi, '
13070           || ' ic_item_mst'||pdblink||' iim, '
13071           || ' ic_whse_mst'||pdblink||' wm, '
13072           || ' fc_fcst_hdr'||pdblink||' h, '
13073           || ' fc_fcst_dtl'||pdblink||' d '
13074           || ' WHERE '
13075           || '     msi.organization_id = wm.mtl_organization_id ' ;
13076 
13077         IF MSC_CL_GMP_UTILITY.g_in_str_org  IS NOT NULL THEN
13078         l_fcst_stmt := l_fcst_stmt
13079           || ' and msi.organization_id ' || MSC_CL_GMP_UTILITY.g_in_str_org ;
13080         END IF;
13081 
13082         l_fcst_stmt := l_fcst_stmt
13083           || ' and msi.segment1 = iim.item_no '
13084           || ' and wm.delete_mark = 0 '
13085           || ' and h.forecast_id = d.forecast_id '
13086           || ' and d.forecast_id > 0  '
13087           || ' and d.item_id = iim.item_id '
13088           || ' and d.whse_code = wm.whse_code '
13089           || ' and d.orgn_code = wm.orgn_code '
13090           || ' and h.forecast_set is NOT NULL '
13091           || ' and h.delete_mark = 0 '
13092           || ' and d.delete_mark = 0 '
13093           || ' and d.trans_qty <> 0 '
13094           || ' ORDER BY wm.mtl_organization_id ,FSET DESC,h.forecast_id ' ;
13095 
13096 l_insert_set_stmt  :=
13097         ' INSERT INTO msc_st_designators ( '
13098       ||' designator,forecast_set, organization_id, sr_instance_id, '
13099       ||' description, mps_relief, inventory_atp_flag, '
13100       ||' designator_type,disable_date,consume_forecast, '
13101       ||' update_type,backward_update_time_fence,forward_update_time_fence, '
13102       ||' bucket_type,deleted_flag,refresh_id ) '
13103       ||' VALUES '
13104       ||' ( :p1, :p2, :p3,:p4, '
13105       ||'   :p5, :p6, :p7, '
13106       ||'   :p8, :p9, :p10, '
13107       ||'   :p11, :p12, :p13, '
13108       ||'   :p14,:p15,:p16 ) ';
13109 
13110 l_demands_stmt  :=
13111       ' INSERT INTO msc_st_demands ( '
13112     ||' organization_id, inventory_item_id, sr_instance_id, '
13113     ||' using_assembly_item_id, using_assembly_demand_date, '
13114     ||' using_requirement_quantity,demand_class,bucket_type, '
13115     ||' demand_type, origination_type, wip_entity_id, '
13116     ||' demand_schedule_name,forecast_designator, order_number,'
13117     ||' wip_entity_name,sales_order_line_id, selling_price, deleted_flag ) '
13118     ||' VALUES '
13119     ||' ( :p1, :p2, :p3,  '
13120     ||'   :p4, :p5, :p6, '
13121     ||'   :p7, :p8, :p9, '
13122     ||'   :p10,:p11,:p12, '
13123     ||'   :p13,:p14,:p15, '
13124     ||'   :p16,:p17,:p18 )' ;
13125 
13126 -- ===+++++++====++++ build designator++++=======++++=======
13127 l_design_stmt := 'SELECT '||
13128 ' forecast_id, '||
13129 ' forecast, '||
13130 ' substr(forecast,1,10) DESGN, '||
13131 ' nvl(forecast_set ,substr(forecast,1,10)) FSET,  '||
13132 ' 1 DESGN_IND ,' ||
13133 ' consumption_ind, '||
13134 ' backward_time_fence, '||
13135 ' forward_time_fence '||
13136 ' FROM fc_fcst_hdr'||pdbLink ||
13137 ' WHERE delete_mark = 0 '||
13138 ' UNION ALL '||
13139 -- Add forecast_sets to the list
13140 ' SELECT '||
13141 ' -1 , '||
13142 ' min(forecast), '||
13143 ' forecast_set DESGN , '||
13144 ' to_char(NULL) FSET,  '||
13145 ' 3 DESGN_IND, ' ||
13146 ' to_number(NULL), '||
13147 ' to_number(NULL), '||
13148 ' to_number(NULL) '||
13149 ' FROM fc_fcst_hdr'||pdblink ||
13150 ' WHERE delete_mark = 0 '||
13151 ' AND forecast_set is NOT NULL '||
13152 ' GROUP BY forecast_set '  ||
13153 ' ORDER BY FSET, 1 DESC , DESGN_IND ' ;
13154 -- Add fabricated forecast-set to the list
13155 /* Per discussions with Sam Tupe Forecast set name is NOT allowed to be changed
13156  Hence we should NOT collect the forecasts that do NOT have a forecast set */
13157 /*
13158 ' UNION ALL '||
13159 ' SELECT '||
13160 ' -1, '||
13161 ' forecast, '||
13162 ' substr(forecast,1,10) DESGN_IND , '||
13163 ' to_char(NULL) FSET, '||
13164 ' 2 DESGN_IND,  '||
13165 ' to_number(NULL), '||
13166 ' to_number(NULL), '||
13167 ' to_number(NULL) '||
13168 ' FROM fc_fcst_hdr'||pdblink ||
13169 ' WHERE delete_mark = 0 '||
13170 ' AND forecast_set is NULL '||
13171 --   With these changes some logic in designator generation has become redundant
13172 */
13173 
13174 OPEN  fcst_hdr for l_design_stmt ;
13175 LOOP
13176 FETCH fcst_hdr INTO fcst_hdr_tbl(l_cnt);
13177 EXIT WHEN fcst_hdr%NOTFOUND ;
13178 l_cnt := l_cnt + 1 ;
13179 END LOOP ;
13180 CLOSE fcst_hdr ;
13181 
13182 --Bug: 6030499
13183           SELECT st.VALUE INTO v_dummy from V$MYSTAT st, V$STATNAME sn
13184           where st.STATISTIC# = sn.STATISTIC#
13185           and sn.NAME in ('session pga memory');
13186           log_message('fcst_hdr Session pga memory = ' || TO_CHAR(v_dummy) );
13187 
13188 -- ===================== Logic ==============================
13189 LOOP
13190 EXIT  WHEN cnt + 1 > fcst_hdr_tbl.COUNT ;
13191 
13192 IF duplicate_found THEN
13193  cnt := cnt ;
13194  duplicate_found := FALSE ;
13195 ELSE
13196  IF temp_name is NOT NULL THEN
13197  IF (fcst_hdr_tbl(cnt).desgn_ind =  1
13198 	AND fcst_hdr_tbl(cnt).fcst_name <> temp_name )THEN
13199 --  	fcst_hdr_tbl(cnt).fcst_set := temp_name ;
13200    NULL ;
13201  ELSIF (fcst_hdr_tbl(cnt).desgn_ind =  3
13202 	AND fcst_hdr_tbl(cnt).fcst_name <> temp_name )THEN
13203   -- This means we changed a set name
13204   -- Now change the name in all resords of fcst that used this as set
13205   FOR y in 1..fcst_hdr_tbl.COUNT
13206   LOOP
13207    IF (fcst_hdr_tbl(y).fcst_set = fcst_hdr_tbl(cnt).fcst_name
13208 	AND fcst_hdr_tbl(y).desgn_ind =  1 ) THEN
13209 	fcst_hdr_tbl(y).fcst_set := temp_name  ;
13210    END IF ;
13211   END LOOP;
13212  ELSIF (fcst_hdr_tbl(cnt).desgn_ind = 2
13213             AND fcst_hdr_tbl(cnt).fcst_name <> temp_name )THEN
13214   -- This means we changed a set name that was "generated"
13215   -- Now change the name in the resord of fcst that used itself as set
13216   FOR y in 1..fcst_hdr_tbl.COUNT
13217   LOOP
13218    IF (fcst_hdr_tbl(y).orig_forecast = fcst_hdr_tbl(cnt).orig_forecast
13219 	AND fcst_hdr_tbl(y).desgn_ind  = 1 )THEN
13220         fcst_hdr_tbl(y).fcst_set := temp_name  ;
13221    END IF ;
13222   END LOOP;
13223  END IF ; -- desgn_ind check
13224  fcst_hdr_tbl(cnt).fcst_name := temp_name ;
13225 
13226  END IF ;
13227 
13228  cnt := cnt  + 1 ;
13229  j := 10 ;
13230  k := 0 ;
13231 END IF ;
13232 
13233  IF j < 10 THEN
13234     temp_name := substr(fcst_hdr_tbl(cnt).fcst_name,1,j)||to_char(k) ;
13235  ELSE
13236     temp_name := fcst_hdr_tbl(cnt).fcst_name ;
13237  END IF ;
13238 
13239 curr_cnt := cnt ;
13240 
13241 i := 1 ;
13242 
13243 LOOP
13244 EXIT WHEN i > fcst_hdr_tbl.COUNT ;
13245 
13246 IF i <> curr_cnt THEN
13247 -- so that record is not compared to itself
13248  IF temp_name  = fcst_hdr_tbl(i).fcst_name THEN
13249    duplicate_found := TRUE ;
13250    k := k + 1 ;
13251 
13252   IF k < 10 THEN
13253      j := 9 ;
13254   ELSIF k < 100 THEN
13255      j := 8 ;
13256   ELSIF k < 1000 THEN
13257      j := 7 ;
13258   ELSIF k < 10000 THEN
13259      j := 6 ;
13260   ELSIF k < 100000 THEN
13261      j := 5 ;
13262   END IF ;
13263 
13264   EXIT ;
13265 
13266  END IF ;
13267 END IF ; -- i <> curr_cnt
13268 
13269 i := i + 1 ;
13270 END LOOP ;
13271 
13272 
13273 END LOOP ; -- Outer loop
13274 
13275 /*
13276 FOR x in 1..fcst_hdr_tbl.COUNT
13277 LOOP
13278 log_message(fcst_hdr_tbl(x).fcst_id||
13279 		'='||fcst_hdr_tbl(x).orig_forecast ||
13280 		'='||fcst_hdr_tbl(x).desgn_ind ||
13281 		'='||fcst_hdr_tbl(x).fcst_name ||
13282 		'='||fcst_hdr_tbl(x).fcst_set ) ;
13283 END LOOP;
13284 */
13285 -- ===+++++++====++++ build designator++++=======++++=======
13286 
13287     OPEN cur_fcst_dtl FOR l_fcst_stmt;
13288     LOOP
13289 	write_fcst     := FALSE ;
13290 	write_fcst_set := FALSE ;
13291 
13292 	FETCH cur_fcst_dtl INTO fcst_dtl_rec;
13293 	EXIT WHEN cur_fcst_dtl%NOTFOUND;
13294 	IF fcst_dtl_rec.organization_id <> prev_org_id THEN
13295 	  -- Write an entry for forecast
13296 	  write_fcst     := TRUE ;
13297 	  write_fcst_set := TRUE ;
13298 	 prev_org_id := fcst_dtl_rec.organization_id ;
13299 	END IF ;
13300 	  -- also check if the set has changed ,if so write an entry for set
13301 	IF fcst_dtl_rec.forecast_id <> prev_fcst_id THEN
13302 	  write_fcst := TRUE ;
13303 	  -- get designator, forecast_name
13304 	  -- Temporarily putting a code - inefficient
13305 	  FOR i in 1..fcst_hdr_tbl.COUNT
13306 	  LOOP
13307 	    IF fcst_dtl_rec.forecast_id = fcst_hdr_tbl(i).fcst_id THEN
13308 		fcst_locn := i  ;
13309 		EXIT ;
13310 	    END IF ;
13311           END LOOP ;
13312 	  IF fcst_hdr_tbl(fcst_locn).fcst_set <> prev_fcst_set THEN
13313 	    -- insert set name for currrent org
13314 	    write_fcst_set := TRUE ;
13315 	  END IF ; -- end if for change of fcst_set
13316 	END IF ; -- endif of fcst_is change
13317 
13318 	prev_fcst	:= nvl(fcst_hdr_tbl(fcst_locn).fcst_name ,'-2');
13319 	prev_fcst_id := fcst_dtl_rec.forecast_id ;
13320 
13321 	IF write_fcst_set THEN
13322 
13323           i_index := i_index + 1 ;
13324           i_designator(i_index) :=  fcst_hdr_tbl(fcst_locn).fcst_set ;
13325           i_forecast_set(i_index) :=  to_char(NULL) ;
13326           i_organization_id(i_index) :=  fcst_dtl_rec.organization_id ;
13327           i_sr_instance_id(i_index) := pinstance_id ;
13328           i_description(i_index) :=  fcst_hdr_tbl(fcst_locn).fcst_set ;
13329           -- mps_relief(i_index) :=  0;  /* mps relief */
13330           -- inventory_atp_flag(i_index) := 0;  /* inventory atp flag */
13331           -- designator_type(i_index) := 6;  /* designator type */
13332           i_disable_date(i_index) := TO_DATE(NULL);  /* disable date */
13333           i_consume_forecast(i_index) := fcst_hdr_tbl(fcst_locn).consumption_ind ;
13334           -- update_type(i_index) := 6; /* Update type */
13335           i_backward_update_time_fence(i_index) :=  fcst_hdr_tbl(fcst_locn).backward_time_fence ;
13336           i_forward_update_time_fence(i_index) := fcst_hdr_tbl(fcst_locn).forward_time_fence ;
13337           -- bucket_type(i_index) := 1 ;  /* bucket type */ ;
13338           -- deleted_flag(i_index) := 2 ;
13339           -- refresh_id := 0 ; /* Refresh id */
13340 
13341 	  prev_fcst_set := fcst_hdr_tbl(fcst_locn).fcst_set ;
13342 
13343 	END IF ;
13344 
13345 	IF write_fcst THEN
13346 
13347           i_index := i_index + 1 ;
13348           i_designator(i_index) := fcst_hdr_tbl(fcst_locn).fcst_name ;
13349           i_forecast_set(i_index) := fcst_hdr_tbl(fcst_locn).fcst_set ;
13350           i_organization_id(i_index) := fcst_dtl_rec.organization_id ;
13351           i_sr_instance_id(i_index) := pinstance_id ;
13352           i_description(i_index) :=  fcst_hdr_tbl(fcst_locn).fcst_name ;
13353           -- mps_relief(i_index) :=  0;  /* mps relief */
13354           -- inventory_atp_flag(i_index) := 0;  /* inventory atp flag */
13355           -- designator_type(i_index) := 6;  /* designator type,For forecast the value will be 6 */
13356           i_disable_date(i_index) := TO_DATE(NULL);  /* disable date */
13357           i_consume_forecast(i_index) := fcst_hdr_tbl(fcst_locn).consumption_ind ;
13358           -- update_type(i_index) := 6; /* Update Type,For Process value will be 6 */
13359           i_backward_update_time_fence(i_index) :=  fcst_hdr_tbl(fcst_locn).backward_time_fence ;
13360           i_forward_update_time_fence(i_index) := fcst_hdr_tbl(fcst_locn).forward_time_fence ;
13361           -- bucket_type(i_index) := 1 ;  /* bucket type */ ;
13362           -- deleted_flag(i_index) := 2 ;
13363           -- refresh_id := 0 ; /* Refresh id */
13364 
13365 	END IF ;
13366 
13367 	  -- and now write the forecast details entry also.
13368          /* Demands Bulk inserts */
13369          d_index := d_index + 1 ;
13370          f_organization_id(d_index) := fcst_dtl_rec.organization_id ;
13371          f_inventory_item_id(d_index) := fcst_dtl_rec.inventory_item_id ;
13372          f_sr_instance_id(d_index) :=  pinstance_id ;
13373          f_assembly_item_id(d_index) := fcst_dtl_rec.inventory_item_id ;
13374          f_demand_date(d_index) := fcst_dtl_rec.trans_date ;
13375          f_requirement_quantity(d_index) :=  fcst_dtl_rec.trans_qty ;
13376          -- demand_class := null_value ;           /* Demand Class  */
13377          -- bucket_type(d_index) := 1 ;             /* Bucket type */
13378          -- demand_type(d_index) := 1 ;             /* demand type */
13379          -- origination_type(d_index) := 29 ;       /* origination type */
13380          -- wip_entity_id(d_index) := null_value ;  /* wip_entity id */
13381          -- demand_schedule(d_index) := null_value ; /* demand Schedule name */
13382 	 f_forecast_designator(d_index) :=
13383                 fcst_hdr_tbl(fcst_locn).fcst_name ; /* forecast designator */
13384          f_order_number(d_index)  := fcst_hdr_tbl(fcst_locn).fcst_name;  /* Order Number */
13385          -- wip_entity_name(d_index) := null_value ; /* wip entity name */
13386          f_sales_order_line_id(d_index) := fcst_dtl_rec.line_id ; /* Sales Order line Id */
13387          -- selling_price(d_index) :=  null_value ;   /* Selling Price */
13388          -- deleted_flag :=  2 ;
13389 
13390      END LOOP ;
13391      CLOSE cur_fcst_dtl;
13392 
13393 /* ----------------------- Demands Insert --------------------- */
13394       i := 1 ;
13395       log_message(f_organization_id.FIRST || ' *forecast*' || f_organization_id.LAST );
13396       IF f_organization_id.FIRST > 0 THEN
13397       FORALL i IN f_organization_id.FIRST..f_organization_id.LAST
13398         INSERT INTO msc_st_demands (
13399         organization_id,
13400         inventory_item_id,
13401         sr_instance_id,
13402         using_assembly_item_id,
13403         using_assembly_demand_date,
13404         using_requirement_quantity,
13405         demand_class,
13406         bucket_type,
13407         demand_type,
13408         origination_type,
13409         wip_entity_id,
13410         demand_schedule_name,
13411         forecast_designator,
13412         order_number,
13413         wip_entity_name,
13414         sales_order_line_id,
13415         selling_price,
13416         deleted_flag )
13417         VALUES (
13418         f_organization_id(i),
13419         f_inventory_item_id(i),
13420         f_sr_instance_id(i),
13421         f_assembly_item_id(i),
13422         f_demand_date(i),
13423         f_requirement_quantity(i),
13424         null_value,       /* demand_class  */
13425         1,                /* bucket_type  */
13426         1,                /* demand_type  */
13427         29,               /* origination_type */
13428         null_value,       /* wip_entity_id    */
13429         null_value,       /* demand_schedule_name */
13430         f_forecast_designator(i),
13431         f_order_number(i),
13432         null_value,                /* wip_entity_name */
13433         f_sales_order_line_id(i),
13434         null_value,                /* selling_price */
13435         2                          /* deleted_flag */
13436         ) ;
13437       END IF ;
13438 
13439 /* ----------------------- Designator Insert --------------------- */
13440       i := 1 ;
13441       log_message(i_organization_id.FIRST || ' *Designator*' || i_organization_id.LAST );
13442       IF i_organization_id.FIRST > 0 THEN
13443       FORALL i IN i_organization_id.FIRST..i_organization_id.LAST
13444           INSERT INTO msc_st_designators (
13445           designator,
13446           forecast_set,
13447           organization_id,
13448           sr_instance_id,
13449           description,
13450           mps_relief,
13451           inventory_atp_flag,
13452           designator_type,
13453           disable_date,
13454           consume_forecast,
13455           update_type,
13456           backward_update_time_fence,
13457           forward_update_time_fence,
13458           bucket_type,
13459           deleted_flag,
13460           refresh_id
13461           )
13462           VALUES (
13463           i_designator(i)     ,
13464           i_forecast_set(i)   ,
13465           i_organization_id(i),
13466           i_sr_instance_id(i) ,
13467           i_description(i)    ,
13468           0,           /* mps relief */
13469           0,           /* inventory atp flag  */
13470           6,           /* designator type,For forecast the value will be 6 */
13471           i_disable_date(i)    ,
13472           i_consume_forecast(i),
13473           6,           /* Update Type,For Process value will be 6 */
13474           i_backward_update_time_fence(i),
13475           i_forward_update_time_fence(i) ,
13476           1,           /* bucket_type */
13477           2,           /* deleted_flag */
13478           0            /* refresh_id  */
13479           ) ;
13480       END IF ;
13481 
13482       return_status := TRUE ;
13483 
13484 EXCEPTION
13485     WHEN invalid_string_value  THEN
13486         log_message('Organization string is Invalid ' );
13487         return_status := FALSE;
13488 
13489 	WHEN OTHERS THEN
13490 	log_message('Failure occured during the Forecast_extract');
13491 	log_message(sqlerrm);
13492         return_status := FALSE;
13493 
13494 END extract_forecasts ;
13495 
13496 
13497 /************************************************************************
13498 *   NAME
13499 *	 Log_message
13500 *
13501 *   DESCRIPTION
13502 *       Put the debug message in log file.
13503 *   HISTORY
13504 *       Created By : Rajesh Patangya
13505 ************************************************************************/
13506 PROCEDURE LOG_MESSAGE(pBUFF  IN  VARCHAR2) IS
13507 MSG VARCHAR2(32000) ;
13508 BEGIN
13509 MSG :='MSC_CL_GMP_UTILITY - ' ||pBUFF ;
13510   IF v_cp_enabled THEN
13511      IF fnd_global.conc_request_id > 0  THEN
13512          FND_FILE.PUT_LINE( FND_FILE.LOG, MSG);
13513      ELSE
13514          null;
13515      END IF;
13516   ELSE
13517     null ;
13518   END IF;
13519   EXCEPTION
13520      WHEN OTHERS THEN
13521         RETURN;
13522 END LOG_MESSAGE;
13523 
13524 /* **************************************************************************
13525 *   NAME
13526 *	 associate_forecasts
13527 *
13528 *   DESCRIPTION
13529 *         For each schedule forecast combination, mark the forecast table
13530 *   HISTORY
13531 *        Created By : Rajesh Patangya
13532 ************************************************************************/
13533 FUNCTION associate_forecasts (	pschd_fcst_cnt	IN NUMBER,
13534       				pschd_id	IN NUMBER ) return BOOLEAN
13535 IS
13536    found_fcst 	BOOLEAN ;
13537    schd_cnt	NUMBER ;
13538    i       	NUMBER ;
13539    f1       	NUMBER ;
13540 BEGIN
13541    found_fcst 	:= FALSE ;
13542    schd_cnt	:= 1 ;
13543    i       	:= 1 ;
13544    f1       	:= 1 ;
13545 
13546     -- Clean the earlier associations
13547     FOR f1 in 1..gfcst_size
13548     LOOP
13549        fcst_dtl_tab(f1).use_fcst_flag := 0 ;
13550     END LOOP;
13551 
13552     FOR schd_cnt in pschd_fcst_cnt..gschd_fcst_size
13553     LOOP
13554       IF pschd_id > schd_fcst_dtl_tab(schd_cnt).schedule_id THEN
13555         NULL ;
13556       ELSIF pschd_id = schd_fcst_dtl_tab(schd_cnt).schedule_id THEN
13557         FOR i in 1..gfcst_size
13558         LOOP
13559            IF fcst_dtl_tab(i).forecast_id =
13560               schd_fcst_dtl_tab(schd_cnt).forecast_id THEN
13561                   fcst_dtl_tab(i).use_fcst_flag := 1 ;
13562                   found_fcst := TRUE ;
13563            END IF;
13564         END LOOP;
13565       ELSE
13566          /*  pschd_id < schd_fcst_dtl_tab(schd_cnt).schedule_id THEN */
13567           gschd_fcst_cnt := schd_cnt ;
13568           EXIT ;
13569       END IF;
13570     END LOOP ;
13571     RETURN found_fcst ;
13572 
13573 END associate_forecasts;
13574 
13575 /* **************************************************************************
13576 *   NAME
13577 *	 check_forecast
13578 *
13579 *   DESCRIPTION
13580 *    Inventory item, Warehouse combination check, hence reached to the
13581 *    record for further processing
13582 *   HISTORY
13583 *        Created By : Rajesh Patangya
13584 ************************************************************************/
13585 FUNCTION check_forecast(pfcst_counter		IN  NUMBER,
13586   			pinventory_item_id	IN  NUMBER,
13587   			porganization_id	IN  NUMBER) return BOOLEAN
13588 IS
13589 fcst_i        NUMBER ;
13590 BEGIN
13591 fcst_i        := 1 ;
13592     /*  Loop through the forecast table for the matching inventory_item_id
13593         and organization_id (Process warehouse)  */
13594 
13595    FOR fcst_i in pfcst_counter..gfcst_size
13596    LOOP
13597      IF (fcst_dtl_tab(fcst_i).use_fcst_flag = 1) THEN
13598 
13599         IF fcst_dtl_tab(fcst_i).inventory_item_id > pinventory_item_id THEN
13600              return FALSE ;
13601         ELSIF fcst_dtl_tab(fcst_i).inventory_item_id = pinventory_item_id THEN
13602            IF fcst_dtl_tab(fcst_i).organization_id > porganization_id THEN
13603              return FALSE ;
13604            ELSIF fcst_dtl_tab(fcst_i).organization_id = porganization_id THEN
13605              return TRUE ;
13606            END IF;
13607         END IF;
13608 
13609      END IF;   /* Use Flag If   */
13610    END LOOP;
13611    -- If no rows were found after looping the whole table, return false
13612    return FALSE ;
13613 
13614 END check_forecast ;
13615 
13616 /* **************************************************************************
13617 *   NAME
13618 *	 check_so
13619 *
13620 *   DESCRIPTION
13621 *    Inventory item, Warehouse combination check, hence reached to the
13622 *    record for further processing
13623 *   HISTORY
13624 *        Created By : Rajesh Patangya
13625 ************************************************************************/
13626 FUNCTION check_so( pso_counter		IN  NUMBER,
13627 		   pinventory_item_id	IN  NUMBER,
13628 		   porganization_id	IN  NUMBER) return BOOLEAN
13629 IS
13630 
13631 so_i     NUMBER ;
13632 BEGIN
13633 so_i     := 0;
13634     /*  Loop through the Sales order table for the matching inventroy item_id
13635         and organization_id(whse)   */
13636 
13637    FOR so_i in pso_counter..gso_size
13638    LOOP
13639       IF sales_dtl_tab(so_i).inventory_item_id > pinventory_item_id THEN
13640            return FALSE ;
13641       ELSIF sales_dtl_tab(so_i).inventory_item_id = pinventory_item_id THEN
13642          IF sales_dtl_tab(so_i).organization_id > porganization_id THEN
13643            return FALSE ;
13644          ELSIF sales_dtl_tab(so_i).organization_id = porganization_id THEN
13645            return TRUE ;
13646          END IF;
13647       END IF;
13648    END LOOP ;
13649    -- If no rows were found after looping the whole table, return false
13650    return FALSE ;
13651 
13652 END check_so ;
13653 
13654 /* **************************************************************************
13655 *   NAME
13656 *	 consume_forecast
13657 *
13658 *   DESCRIPTION
13659 *       This procedure will consume the forecast for the values that are
13660 *	are loaded into the sales and forecast pl/sql tables. The occurences
13661 *	are passed in as paramaters. The sales orders that fall on or after
13662 *	a forecast for the same item/whse but before the next forecast for the
13663 *	same will decrease the value of the forecast by the amount of the
13664 * 	sales order line until it is zero.
13665 *   HISTORY
13666 *        Created By : Rajesh Patangya
13667 *     P Dong
13668 *     09/14/01 - Added api_mode to pass to insert_demands
13669 ************************************************************************/
13670 PROCEDURE consume_forecast( pinventory_item_id	IN  NUMBER,
13671 			    porganization_id	IN  NUMBER,
13672 			    papi_mode	        IN  BOOLEAN )
13673 AS
13674 cfcst_cnt      NUMBER ;
13675 cso_cnt        NUMBER ;
13676 found_forecast BOOLEAN ;
13677 
13678 BEGIN
13679 
13680 cfcst_cnt      := 0 ;
13681 cso_cnt        := 0 ;
13682 found_forecast := FALSE ;
13683 
13684  FOR cfcst_cnt in gfcst_cnt..gfcst_size
13685  LOOP
13686 
13687   IF (fcst_dtl_tab(cfcst_cnt).use_fcst_flag = 1 )  THEN
13688 
13689    IF fcst_dtl_tab(cfcst_cnt).inventory_item_id = pinventory_item_id AND
13690         fcst_dtl_tab(cfcst_cnt).organization_id = porganization_id THEN
13691     found_forecast := TRUE ;     /* B2922488 */
13692     FOR cso_cnt in gso_cnt..gso_size
13693     LOOP
13694      IF fcst_dtl_tab(cfcst_cnt).inventory_item_id =
13695                      sales_dtl_tab(cso_cnt).inventory_item_id AND
13696         fcst_dtl_tab(cfcst_cnt).organization_id =
13697                       sales_dtl_tab(cso_cnt).organization_id THEN
13698 
13699         IF fcst_dtl_tab(cfcst_cnt).trans_date <=
13700               sales_dtl_tab(cso_cnt).sched_shipdate THEN
13701 
13702 	    IF fcst_dtl_tab(cfcst_cnt).consumed_qty > 0 THEN
13703                  fcst_dtl_tab(cfcst_cnt).consumed_qty :=
13704                       fcst_dtl_tab(cfcst_cnt).consumed_qty -
13705                       sales_dtl_tab(cso_cnt).trans_qty ;
13706             END IF ; /* consumed_qty match */
13707                  write_this_so(cso_cnt,papi_mode) ;
13708 
13709         ELSE /* The fcst date is greater than so date, therefore write fcst */
13710             IF fcst_dtl_tab(cfcst_cnt).consumed_qty > 0 THEN
13711                write_this_fcst (cfcst_cnt,papi_mode);
13712             -- B2596464, Modified by Rajesh Patangya 26-SEP-2002
13713             -- Once forecast is written, make the quantity = 0,
13714             -- so that outside the loop it will not be written again.
13715                fcst_dtl_tab(cfcst_cnt).consumed_qty := 0 ;
13716             END IF ;
13717               EXIT ;
13718         END IF ; /* trans_date match */
13719 
13720      ELSIF (fcst_dtl_tab(cfcst_cnt).inventory_item_id <
13721             sales_dtl_tab(cso_cnt).inventory_item_id ) OR
13722         (   fcst_dtl_tab(cfcst_cnt).inventory_item_id =
13723             sales_dtl_tab(cso_cnt).inventory_item_id  AND
13724             fcst_dtl_tab(cfcst_cnt).organization_id <
13725             sales_dtl_tab(cso_cnt).organization_id
13726         )  THEN
13727             EXIT ;
13728      END IF ;
13729     END LOOP;  /* SO loop */
13730       -- After Looping through all SO , if the forecast remains
13731       -- unconsumed, write it to the table
13732          IF fcst_dtl_tab(cfcst_cnt).consumed_qty > 0 THEN
13733                    write_this_fcst (cfcst_cnt,papi_mode);
13734          END IF ;
13735     ELSIF
13736      (fcst_dtl_tab(cfcst_cnt).inventory_item_id > pinventory_item_id) OR
13737      (fcst_dtl_tab(cfcst_cnt).inventory_item_id = pinventory_item_id AND
13738      fcst_dtl_tab(cfcst_cnt).organization_id > porganization_id ) THEN
13739 	gfcst_cnt := cfcst_cnt ;
13740         write_so(gso_cnt,pinventory_item_id,porganization_id,papi_mode);
13741         EXIT ;
13742     END IF ;
13743   END IF ; /* use_fcst_flag */
13744  END LOOP ;    /* FCST loop */
13745 
13746   IF NOT (found_forecast) THEN
13747         -- At last, if there is no forecast at all, then you have to write
13748         -- all the sales orders
13749         write_so(gso_cnt,pinventory_item_id,porganization_id,papi_mode);
13750   END IF;
13751 
13752  EXCEPTION
13753     WHEN OTHERS THEN
13754         log_message('Failure occured during write_forecast');
13755         log_message(sqlerrm);
13756       RAISE;
13757 END consume_forecast ;
13758 
13759 /* **************************************************************************
13760 *   NAME
13761 *	 write_forecast
13762 *
13763 *   DESCRIPTION
13764 *     Loop through the forecast table for the matching inventory item_id
13765 *     and organization_id(whse)
13766 *     and insert into the destination table
13767 *     exit when item_id changes after noting down the counter position
13768 *   HISTORY
13769 *        Created By : Rajesh Patangya
13770 *     P Dong
13771 *     09/14/01 - Added api_mode to pass to insert_demands
13772 ************************************************************************/
13773 PROCEDURE write_forecast( pfcst_counter   	IN  NUMBER,
13774   			  pinventory_item_id	IN  NUMBER,
13775   			  porganization_id	IN  NUMBER,
13776 		          papi_mode	        IN BOOLEAN)
13777 AS
13778 fcst_i   NUMBER ;
13779 
13780 BEGIN
13781 fcst_i   := 0 ;
13782    -- A safety can be installed here
13783    IF gfcst_size >= pfcst_counter THEN
13784 
13785 
13786    FOR fcst_i in pfcst_counter..gfcst_size
13787    LOOP
13788      IF (fcst_dtl_tab(fcst_i).use_fcst_flag = 1 ) THEN
13789 
13790         IF fcst_dtl_tab(fcst_i).inventory_item_id > pinventory_item_id THEN
13791              gfcst_cnt := fcst_i ;
13792              EXIT ;
13793         ELSIF fcst_dtl_tab(fcst_i).inventory_item_id = pinventory_item_id THEN
13794            IF fcst_dtl_tab(fcst_i).organization_id > porganization_id THEN
13795              gfcst_cnt := fcst_i ;
13796              EXIT ;
13797            ELSIF fcst_dtl_tab(fcst_i).organization_id = porganization_id THEN
13798 		IF fcst_dtl_tab(fcst_i).consumed_qty > 0 THEN
13799                   write_this_fcst(fcst_i,papi_mode) ;
13800 		END IF ;
13801            END IF;
13802         END IF;
13803 
13804      END IF;   /* Use Flag If   */
13805    END LOOP;
13806 
13807    END IF;   /* Safety feature */
13808 
13809  EXCEPTION
13810     WHEN OTHERS THEN
13811         log_message('Failure occured during write_forecast');
13812         log_message(sqlerrm);
13813       RAISE;
13814 END write_forecast ;
13815 
13816 /* **************************************************************************
13817 *   NAME
13818 *	 write_so
13819 *
13820 *   DESCRIPTION
13821 *     Loop through the Sales order table for the matching inventory item_id
13822 *     and organization_id(whse)
13823 *     and insert into the destination table
13824 *     exit when item_id changes after noting down the counter position
13825 *   HISTORY
13826 *        Created By : Rajesh Patangya
13827 *     P Dong
13828 *     09/14/01 - Added api_mode to pass to insert_demands
13829 ************************************************************************/
13830 PROCEDURE write_so( pso_counter		IN  NUMBER,
13831 		    pinventory_item_id	IN  NUMBER,
13832 		    porganization_id	IN  NUMBER,
13833 		    papi_mode	        IN  BOOLEAN)
13834 AS
13835 so_i      NUMBER ;
13836 
13837 BEGIN
13838 so_i      := 0 ;
13839    -- A safety can be installed here
13840    IF gso_size >= pso_counter THEN
13841 
13842    FOR so_i in pso_counter..gso_size
13843    LOOP
13844       IF sales_dtl_tab(so_i).inventory_item_id > pinventory_item_id THEN
13845            gso_cnt := so_i ;
13846            EXIT ;
13847       ELSIF sales_dtl_tab(so_i).inventory_item_id = pinventory_item_id THEN
13848          IF sales_dtl_tab(so_i).organization_id > porganization_id THEN
13849            gso_cnt := so_i ;
13850            EXIT ;
13851          ELSIF sales_dtl_tab(so_i).organization_id = porganization_id THEN
13852            write_this_so(so_i,papi_mode) ;
13853          END IF;
13854       END IF;
13855    END LOOP ;
13856 
13857    END IF;   /* Safety feature */
13858 
13859  EXCEPTION
13860     WHEN OTHERS THEN
13861         log_message('Failure occured during write_so');
13862         log_message(sqlerrm);
13863       RAISE;
13864 END write_so ;
13865 
13866 /* **************************************************************************
13867 *   NAME
13868 *	 write_this_so
13869 *
13870 *   DESCRIPTION
13871 *    Call to build designator to get unique designator,
13872 *    insert sales order into msc_st_demand
13873 *   HISTORY
13874 *        Created By : Rajesh Patangya
13875 *     P Dong
13876 *     09/14/01 - Added api_mode to pass to insert_demands
13877 *     05/21/03 - B2971996 - Populating request_date in msc_st_demands table
13878 ************************************************************************/
13879 PROCEDURE write_this_so(pcounter      IN NUMBER,
13880                         sapi_mode     IN BOOLEAN)
13881 AS
13882   statement_demands_api  VARCHAR2(32000) ;
13883   statement_demands      VARCHAR2(32000) ;
13884 
13885 BEGIN
13886   statement_demands_api  := NULL ;
13887   statement_demands      := NULL ;
13888     g_delimiter  := '/';
13889     build_designator(g_item_tbl_position, g_delimiter, gcurrent_designator);
13890 
13891 IF sapi_mode
13892 THEN
13893   BEGIN
13894     statement_demands_api  :=
13895       ' INSERT INTO gmp_demands_api ( '
13896     ||'  organization_id, schedule_id, inventory_item_id, demand_date, '
13897     ||'  demand_quantity, origination_type, doc_id, selling_price ) '
13898     ||' VALUES '
13899     ||' ( :p1, :p2, :p3, :p4, '
13900     ||'   :p5, :p6, :p7, :p8 ) ';
13901 
13902     EXECUTE IMMEDIATE statement_demands_api USING
13903         sales_dtl_tab(pcounter).organization_id,
13904         sched_dtl_tab(g_item_tbl_position).schedule_id,
13905         sales_dtl_tab(pcounter).inventory_item_id,
13906         sales_dtl_tab(pcounter).sched_shipdate,
13907         sales_dtl_tab(pcounter).trans_qty,
13908         6,				/* origination type */
13909         null_value,				/* wip_entity id */
13910         sales_dtl_tab(pcounter).net_price  ;
13911 
13912         /* Global vairable Updation to next record */
13913         /*  B2929759, Rajesh Patangya 28-APR-2003 */
13914          gso_cnt := pcounter + 1 ;
13915 
13916   EXCEPTION
13917     WHEN OTHERS THEN
13918         log_message('Failure occured during the insert into gmp_demands_api');
13919         log_message(sqlerrm);
13920       RAISE;
13921   END;
13922 ELSE
13923   BEGIN
13924 
13925     statement_demands  :=
13926       ' INSERT INTO msc_st_demands ( '
13927     ||' organization_id, inventory_item_id, sr_instance_id, '
13928     ||' using_assembly_item_id, using_assembly_demand_date, '
13929     ||' using_requirement_quantity, demand_type, origination_type, '
13930     ||' wip_entity_id, demand_schedule_name, order_number, '
13931     ||' wip_entity_name, selling_price,request_date,deleted_flag ) '  /*B2971996*/
13932     ||' VALUES '
13933     ||' ( :p1, :p2, :p3,  '
13934     ||'   :p4, :p5,       '
13935     ||'   :p6, :p7, :p8 , '
13936     ||'   :p9, :p10,:p11, '
13937     ||'   :p12,:p13,:p14,:p15 )' ;
13938 
13939     EXECUTE IMMEDIATE statement_demands USING
13940 	sales_dtl_tab(pcounter).organization_id,
13941 	sales_dtl_tab(pcounter).inventory_item_id,
13942 	g_instance_id,
13943 	sales_dtl_tab(pcounter).inventory_item_id,
13944 	sales_dtl_tab(pcounter).sched_shipdate,
13945 	sales_dtl_tab(pcounter).trans_qty,
13946 	1,				/* demand type */
13947         6,				/* origination type */
13948 	null_value,			/* wip_entity id */
13949 	gcurrent_designator,
13950 	sales_dtl_tab(pcounter).orgn_code || g_delimiter ||
13951 		sales_dtl_tab(pcounter).order_no,
13952 	null_value,			/* wip entity name */
13953 	sales_dtl_tab(pcounter).net_price,
13954         sales_dtl_tab(pcounter).request_date,   /* B2971996 */
13955         2 ;
13956 
13957         /* Global vairable Updation to next record */
13958         /*  B2929759, Rajesh Patangya 28-APR-2003 */
13959          gso_cnt := pcounter + 1 ;
13960 
13961  EXCEPTION
13962     WHEN OTHERS THEN
13963         log_message('Failure occured during write_this_so');
13964         log_message(sqlerrm);
13965       RAISE;
13966   END;
13967 
13968   END IF;
13969 END write_this_so ;
13970 
13971 /* **************************************************************************
13972 *   NAME
13973 *	 write_this_fcst
13974 *
13975 *   DESCRIPTION
13976 *    Call to build designator to get unique designator,
13977 *    insert forecast into msc_st_demand
13978 *   HISTORY
13979 *        Created By : Rajesh Patangya
13980 *     P Dong
13981 *     09/14/01 - Added api_mode to pass to insert_demands
13982 ************************************************************************/
13983 PROCEDURE write_this_fcst(pcounter      IN NUMBER,
13984                           fapi_mode     IN BOOLEAN)
13985 AS
13986 
13987   statement_demands_api   VARCHAR2(32000) ;
13988   statement_demands       VARCHAR2(32000) ;
13989 
13990 BEGIN
13991   statement_demands_api  := NULL ;
13992   statement_demands      := NULL ;
13993     g_delimiter  := '/';
13994     build_designator(g_item_tbl_position, g_delimiter, gcurrent_designator);
13995 
13996 IF fapi_mode
13997 THEN
13998   BEGIN
13999     statement_demands_api  :=
14000       ' INSERT INTO gmp_demands_api ( '
14001     ||'  organization_id, schedule_id, inventory_item_id, demand_date, '
14002     ||'  demand_quantity, origination_type, doc_id, selling_price ) '
14003     ||' VALUES '
14004     ||' ( :p1, :p2, :p3, :p4, '
14005     ||'   :p5, :p6, :p7, :p8 ) ';
14006 
14007     EXECUTE IMMEDIATE statement_demands_api USING
14008         fcst_dtl_tab(pcounter).organization_id,
14009         sched_dtl_tab(g_item_tbl_position).schedule_id,
14010         fcst_dtl_tab(pcounter).inventory_item_id,
14011         fcst_dtl_tab(pcounter).trans_date,
14012         fcst_dtl_tab(pcounter).consumed_qty,
14013         7,				/* origination type */
14014         null_value,			/* wip_entity id */
14015         null_value ;
14016 
14017         /* Global vairable Updation to next record */
14018         /*  B2929759, Rajesh Patangya 28-APR-2003 */
14019            gfcst_cnt := pcounter + 1 ;
14020 
14021   EXCEPTION
14022     WHEN OTHERS THEN
14023         log_message('Failure occured during the insert into gmp_demands_api');
14024         log_message(sqlerrm);
14025       RAISE;
14026   END;
14027 ELSE
14028   BEGIN
14029     statement_demands  :=
14030       ' INSERT INTO msc_st_demands ( '
14031     ||' organization_id, inventory_item_id, sr_instance_id, '
14032     ||' using_assembly_item_id, using_assembly_demand_date, '
14033     ||' using_requirement_quantity, demand_type, origination_type, '
14034     ||' wip_entity_id, demand_schedule_name, order_number, '
14035     ||' wip_entity_name, selling_price, deleted_flag ) '
14036     ||' VALUES '
14037     ||' ( :p1, :p2, :p3,  '
14038     ||'   :p4, :p5,       '
14039     ||'   :p6, :p7, :p8 , '
14040     ||'   :p9, :p10,:p11, '
14041     ||'   :p12,:p13,:p14 )' ;
14042 
14043     EXECUTE IMMEDIATE statement_demands USING
14044         fcst_dtl_tab(pcounter).organization_id,
14045         fcst_dtl_tab(pcounter).inventory_item_id,
14046         g_instance_id,
14047         fcst_dtl_tab(pcounter).inventory_item_id,
14048         fcst_dtl_tab(pcounter).trans_date,
14049         fcst_dtl_tab(pcounter).consumed_qty,
14050         1,				/* demand type */
14051         7,				/* origination type */
14052         null_value, 			/* wip_entity id */
14053         gcurrent_designator,
14054         fcst_dtl_tab(pcounter).forecast ,
14055         null_value,			/* wip entity name */
14056         null_value,
14057         2 ;
14058 
14059         /* Global vairable Updation to next record */
14060         /*  B2929759, Rajesh Patangya 28-APR-2003 */
14061            gfcst_cnt := pcounter + 1 ;
14062 
14063  EXCEPTION
14064     WHEN OTHERS THEN
14065         log_message('Failure occured during write_this_fcst');
14066         log_message(sqlerrm);
14067       RAISE;
14068   END;
14069 
14070 END IF;
14071 END write_this_fcst ;
14072 
14073 /* **************************************************************************
14074 *   NAME
14075 *        insert_designator
14076 *
14077 *   DESCRIPTION
14078 *     Insert all the designator for schedule/item/warehouse combination
14079 *   HISTORY
14080 *        Created By : Rajesh Patangya
14081 ************************************************************************/
14082 PROCEDURE insert_designator IS
14083 
14084 i	       NUMBER ;
14085 st_designators VARCHAR2(32000) ;
14086 
14087 BEGIN
14088 
14089   i	         := 1 ;
14090   st_designators := NULL ;
14091   g_delimiter    := '/';
14092     st_designators  :=
14093         ' INSERT INTO msc_st_designators ( '
14094       ||' designator, organization_id, sr_instance_id, '
14095       ||' description, mps_relief, inventory_atp_flag, '
14096       ||' designator_type ) '
14097       ||' VALUES '
14098       ||' ( :p1, :p2, :p3, '
14099       ||'   :p4, :p5, :p6, '
14100       ||'   :p7 ) ';
14101 
14102       FOR i IN 1..desig_tab.COUNT LOOP
14103 
14104       EXECUTE IMMEDIATE st_designators USING
14105           desig_tab(i).designator,
14106           desig_tab(i).organization_id,
14107           g_instance_id,
14108           desig_tab(i).orgn_code || g_delimiter || desig_tab(i).schedule
14109                                  || g_delimiter || desig_tab(i).whse_code,
14110           2,
14111           2,
14112           1  ;
14113 
14114       END LOOP;
14115   EXCEPTION
14116     WHEN OTHERS THEN
14117         log_message('Failure occured in insert_designator');
14118         log_message(sqlerrm);
14119       RAISE;
14120 END insert_designator;
14121 
14122 /***********************************************************************
14123 *
14124 *   NAME
14125 *	process_resource_rows
14126 *
14127 *   DESCRIPTION
14128 *	This procedure will process al of the resource rows for a step then
14129 *       call the insert for resource requirements.
14130 *   HISTORY
14131 *	M Craig
14132 ************************************************************************/
14133 PROCEDURE process_resource_rows(
14134   pfirst_row    IN  NUMBER,
14135   plast_row     IN  NUMBER,
14136   pfound_mtl    IN  NUMBER,
14137   porgn_id      IN  NUMBER,
14138   pinstance_id  IN  NUMBER,
14139   pinflate_wip  IN  NUMBER,
14140   pmin_xfer_qty IN  NUMBER)
14141 IS
14142 
14143   v_resource_usage NUMBER ;
14144   v_res_seq        NUMBER ;
14145   v_schedule_flag  NUMBER ;
14146   v_parent_seq_num NUMBER ;
14147   v_rsrc_cnt       NUMBER ;
14148   v_start_date     DATE ;
14149   v_end_date       DATE ;
14150   old_activity     NUMBER ;
14151   j                NUMBER ;
14152 
14153 BEGIN
14154   v_resource_usage := 0;
14155   v_res_seq        := 0;
14156   v_schedule_flag  := 0;
14157   v_parent_seq_num := 0;
14158   v_rsrc_cnt       := 0;
14159   v_start_date     := NULL;
14160   v_end_date       := NULL;
14161   old_activity     := -1;
14162   j                := 0;
14163 
14164  FOR j IN pfirst_row..plast_row
14165  LOOP
14166    /* if the actual completion date is null then the resource
14167       is pending or WIP and needs to be written. otherwise the
14168       resource is completed and does not need to be reported. */
14169 
14170    IF old_activity <> rsrc_tab(j).bs_activity_id OR
14171       old_activity = -1 THEN
14172      v_res_seq := v_res_seq + 1;
14173      old_activity := rsrc_tab(j).bs_activity_id;
14174 
14175     /* B3421856 , Schedule flag needs to be populated correctly */
14176 
14177      IF pfound_mtl = 1 THEN
14178 
14179         IF rsrc_tab(j).material_ind = 1 THEN
14180                 v_schedule_flag := 4;
14181         ELSE
14182                 IF v_schedule_flag < 4 THEN
14183                         v_schedule_flag := 3 ;
14184                 END IF ;
14185         END IF ;
14186 
14187      END IF;  /* pfound_mtl */
14188    END IF;   /* old_activity */
14189 
14190    IF rsrc_tab(j).material_ind = 0 AND pfound_mtl = 1 THEN
14191      rsrc_tab(j).schedule_flag := v_schedule_flag;
14192    END IF;
14193 
14194    IF NVL(rsrc_tab(j).actual_cmplt_date,v_null_date) = v_null_date THEN
14195 
14196      /* when the actual start is null the resource has not started
14197         and the plan start will be used.  */
14198      IF rsrc_tab(j).tran_seq_dep = 1 THEN
14199        v_parent_seq_num := v_res_seq;
14200        v_resource_usage := rsrc_tab(j).resource_usage;
14201        v_start_date := rsrc_tab(j).act_start_date;
14202        v_end_date := rsrc_tab(j).plan_start_date;
14203      ELSE
14204        v_parent_seq_num := TO_NUMBER(NULL);
14205        v_start_date := rsrc_tab(j).plan_start_date;
14206        v_end_date := rsrc_tab(j).plan_cmplt_date;
14207        IF pinflate_wip = 1 THEN
14208          v_resource_usage := rsrc_tab(j).resource_usage / rsrc_tab(j).utl_eff;
14209        ELSE
14210          v_resource_usage := rsrc_tab(j).resource_usage;
14211        END IF;
14212      END IF;
14213 
14214      /* If no actual resource exists then the resource has not
14215         started and the planned value will be used */
14216 
14217      IF rsrc_tab(j).actual_rsrc_count IS NULL THEN
14218        v_rsrc_cnt := rsrc_tab(j).plan_rsrc_count;
14219      ELSE
14220        v_rsrc_cnt := rsrc_tab(j).actual_rsrc_count;
14221      END IF;
14222 
14223      /* write the current resource detail row asscoiating it with the
14224         batch through the product line */
14225 
14226      IF v_resource_usage > 0 THEN
14227 
14228         /* Bulk Insert for insert_resource_requirements */
14229           rr_index := rr_index + 1 ;
14230           rr_organization_id(rr_index) := porgn_id ;
14231           rr_sr_instance_id(rr_index) := pinstance_id ;
14232           rr_supply_id(rr_index) :=  rsrc_tab(j).x_batch_id ; /* B1177070 encoded key */
14233           /* B1224660 new value to write resource seq num */
14234           rr_resource_seq_num(rr_index) := v_res_seq ;
14235           rr_resource_id(rr_index) := rsrc_tab(j).x_resource_id ; /* B1177070 encoded key */
14236           rr_start_date(rr_index) := v_start_date ;
14237           rr_end_date(rr_index)  :=  v_end_date ;
14238           rr_opr_hours_required(rr_index) :=  v_resource_usage ;
14239           rr_assigned_units(rr_index) := v_rsrc_cnt ;
14240           rr_department_id(rr_index) := ((porgn_id * 2) + 1) ;  /* B1177070 encoded key */
14241           rr_wip_entity_id(rr_index) :=  rsrc_tab(j).x_batch_id ; /* B1177070 encoded key */
14242           /* B1224660 write the step number for oper seq num */
14243           rr_operation_seq_num(rr_index)  :=   rsrc_tab(j).batchstep_no ;
14244           rr_firm_flag(rr_index) :=    rsrc_tab(j).firm_type ;
14245           rr_minimum_transfer_quantity(rr_index) := pmin_xfer_qty ;
14246           rr_parent_seq_num(rr_index) := v_parent_seq_num ;
14247           rr_schedule_flag(rr_index) := rsrc_tab(j).schedule_flag ;
14248       END IF;
14249    END IF;
14250   END LOOP;
14251 
14252 END process_resource_rows;
14253 
14254 /*Sowmya - As Per latest FDD changes - Start*/
14255 /***********************************************************************
14256 *
14257 *   NAME
14258 *	production_reservations
14259 *
14260 *   DESCRIPTION
14261 *	This procedure will fetch all salesorders against which production
14262 *       batches are reserved.
14263 *   HISTORY
14264 *
14265 ************************************************************************/
14266 
14267 PROCEDURE production_reservations ( pdblink        IN  VARCHAR2,
14268                           pinstance_id   IN  NUMBER,
14269                           prun_date      IN  DATE,
14270                           pdelimiter     IN  VARCHAR2,
14271                           return_status  IN OUT NOCOPY BOOLEAN)
14272 IS
14273         v_stmt_alt_rsrc VARCHAR2(32000);
14274 BEGIN
14275 
14276 v_stmt_alt_rsrc :=  'INSERT INTO MSC_ST_RESERVATIONS'
14277                 ||'  (  '
14278                 ||'        TRANSACTION_ID , '
14279                 ||'        INVENTORY_ITEM_ID ,  '
14280                 ||'        ORGANIZATION_ID, '
14281                 ||'        SR_INSTANCE_ID ,  '
14282                 ||'        REQUIREMENT_DATE , '
14283                 ||'        PARENT_DEMAND_ID , '
14284                 ||'        REVISION  , '
14285                 ||'        DISPOSITION_ID , '
14286                 ||'        RESERVED_QUANTITY , '
14287                 ||'        DISPOSITION_TYPE ,  '
14288                 ||'        SUBINVENTORY , '
14289                 ||'        RESERVATION_TYPE , '
14290                 ||'        DEMAND_CLASS , '
14291                 ||'        AVAILABLE_TO_MRP , '
14292                 ||'        RESERVATION_FLAG , '
14293                 ||'        PROJECT_ID , '
14294                 ||'        TASK_ID , '
14295                 ||'        PLANNING_GROUP , '
14296                 ||'        SUPPLY_SOURCE_HEADER_ID , '
14297                 ||'        SUPPLY_SOURCE_TYPE_ID , '
14298                 ||'        DELETED_FLAG '
14299                 ||'  ) '
14300                 ||'  SELECT '
14301                 ||'        ((gbo.batch_res_id * 2) + 1), '
14302                 ||'        gia.aps_item_id , '
14303                 ||'        gbo.organization_id, '
14304                 ||'        :p1, '
14305                 ||'        gbo.scheduled_ship_date, '
14306                 ||'        gbo.so_line_id , '
14307                 ||'        NULL , '
14308                 ||'        gbo.order_id , '
14309                 ||'        gbo.reserved_qty , '
14310                 ||'        :p2 ,'
14311                 ||'        NULL , '
14312                 ||'        :p3 ,'
14313                 ||'        ool.demand_class_code , '
14314                 ||'        NULL  , '
14315                 ||'        :p4 ,'
14316                 ||'        ool.project_id, '
14317                 ||'        ool.task_id, '
14318                 ||'        ppp.planning_group, '
14319                 ||'        ((gbo.batch_id * 2) + 1) , '
14320                 ||'        :p5 ,'
14321                 ||'        :p6 '
14322                 ||'   FROM '
14323                 ||'         gml_batch_so_reservations'||pdblink||' gbo, '
14324                 ||'        (SELECT  '
14325                 ||'                DISTINCT item_id, aps_item_id, organization_id , whse_code '
14326                 ||'         FROM gmp_item_aps'||pdblink||')  gia, '
14327                 ||'        oe_order_lines_all'||pdblink||' ool, '
14328                 ||'        pjm_project_parameters'||pdblink||' ppp  '
14329                 ||'   WHERE '
14330                 ||'         gbo.item_id = gia.item_id '
14331                 ||'        AND gbo.organization_id = gia.organization_id '
14332                 ||'        AND gbo.delete_mark = 0 '
14333                 ||'        AND gbo.so_line_id = ool.line_id '
14334                 ||'        AND ool.project_id = ppp.project_id (+) ';
14335 
14336                 IF MSC_CL_GMP_UTILITY.g_in_str_org  IS NOT NULL THEN
14337                         v_stmt_alt_rsrc := v_stmt_alt_rsrc
14338                          ||'   AND EXISTS ( SELECT 1 FROM sy_orgn_mst'||pdblink||' som '
14339                          ||'   WHERE gia.whse_code = som.resource_whse_code )' ;
14340                 END IF;
14341 
14342                 EXECUTE IMMEDIATE v_stmt_alt_rsrc USING
14343                 pinstance_id,2,1,2,5,2 ;    /*Sowmya - As per latest FDD changes -
14344                                              Changed the supply source id from 13 to 5 */
14345         EXCEPTION
14346                 WHEN OTHERS THEN
14347 	        log_message('Failure occured during the insert into msc_st_reservations');
14348 	        log_message(sqlerrm);
14349               	return_status := FALSE;
14350 
14351 END production_reservations;
14352 /*Sowmya - As Per latest FDD changes - End*/
14353 
14354 /***********************************************************************
14355 *
14356 *   NAME
14357 *	update_last_setup_id
14358 *
14359 *   DESCRIPTION
14360 *	This procedure is triggered by the concurrent program for
14361 *       updating the last setup id.
14362 *
14363 *   HISTORY
14364 *	Namit           14-09-2004      Procedure Created
14365 ************************************************************************/
14366 
14367 PROCEDURE update_last_setup_id (
14368    effbuf   OUT NOCOPY VARCHAR2,
14369    retcode      OUT NOCOPY NUMBER,
14370    f_orgn_code    IN  VARCHAR2,
14371    t_orgn_code    IN  VARCHAR2
14372 )
14373 IS
14374    TYPE ref_cursor_typ IS REF CURSOR;
14375    cur_lsetup_id ref_cursor_typ;
14376    resources            VARCHAR2(30);
14377    v_last_setup_id      NUMBER;
14378    v_resource_id        NUMBER;
14379    v_plant_code         VARCHAR2(10);
14380    v_batch_id           NUMBER;
14381    v_instance_id        NUMBER;
14382    x_select             VARCHAR2(32000);
14383    old_resource_id      NUMBER;
14384    old_instance_id      NUMBER;
14385    lsetup_updated       BOOLEAN;
14386    l_user_id            NUMBER;
14387 
14388 BEGIN
14389 
14390    x_select        := NULL;
14391    old_resource_id := -1;
14392    old_instance_id := -1;
14393    lsetup_updated  := TRUE;
14394 
14395     l_user_id :=  to_number(FND_PROFILE.VALUE('USER_ID'));
14396 
14397     X_select := ' SELECT '
14398     ||' gbsr.sequence_dependent_id, '
14399     ||' crd.resource_id, '
14400     ||' grt.instance_id, '
14401     ||' crd.orgn_code, '
14402     ||' gbsr.batch_id '
14403     ||' FROM    gme_batch_step_resources gbsr, '
14404     ||'    gme_resource_txns grt, '
14405     ||'    sy_orgn_usr sou, '
14406     ||'    cr_rsrc_dtl crd, '
14407     ||'    gme_batch_header gbh '
14408     ||' WHERE   gbsr.batch_id = grt.doc_id '
14409     ||'    AND  gbh.batch_id = gbsr.batch_id '
14410     ||'    AND  gbh.plant_code = crd.orgn_code '
14411     ||'    AND  crd.orgn_code = sou.orgn_code '
14412     ||'    AND  sou.user_id = :user_id '
14413     ||'    AND  gbsr.batchstep_resource_id = grt.line_id '
14414     ||'    AND  grt.completed_ind = 1 '
14415     ||'    AND  crd.resources = gbsr.resources '
14416     ||'    AND  crd.resources = grt.resources '
14417     ||'    AND  crd.schedule_ind = 2 '
14418     ||'    AND   grt.instance_id IS NOT NULL '
14419     ||'    AND     crd.delete_mark = 0 ';
14420 
14421     IF f_orgn_code IS NOT NULL THEN
14422        x_select := x_select
14423        ||'    AND     crd.orgn_code >= :frm_orgn ' ;
14424     END IF;
14425     IF t_orgn_code IS NOT NULL THEN
14426        x_select := x_select
14427        ||'    AND     crd.orgn_code <= :to_orgn ' ;
14428     END IF;
14429 
14430     x_select := x_select
14431     ||'    ORDER BY grt.resources, grt.instance_id, '
14432     ||'       grt.end_date DESC, grt.poc_trans_id ' ;
14433 
14434    IF f_orgn_code IS NOT NULL AND t_orgn_code IS NOT NULL THEN
14435       OPEN cur_lsetup_id FOR x_select USING l_user_id, f_orgn_code, t_orgn_code;
14436    ELSIF f_orgn_code IS NOT NULL AND t_orgn_code IS NULL THEN
14437       OPEN cur_lsetup_id FOR x_select USING l_user_id, f_orgn_code;
14438    ELSIF f_orgn_code IS NULL AND t_orgn_code IS NOT NULL THEN
14439       OPEN cur_lsetup_id FOR x_select USING l_user_id, t_orgn_code;
14440    ELSE
14441       OPEN cur_lsetup_id FOR x_select USING l_user_id;
14442    END IF;
14443 
14444    LOOP
14445       FETCH cur_lsetup_id INTO v_last_setup_id, v_resource_id, v_instance_id,
14446         v_plant_code, v_batch_id;
14447       EXIT WHEN cur_lsetup_id%NOTFOUND;
14448 
14449       IF (old_resource_id <> v_resource_id OR old_instance_id <> v_instance_id) THEN
14450          old_resource_id := v_resource_id;
14451          old_instance_id := v_instance_id;
14452          lsetup_updated := FALSE;
14453       END IF;
14454 
14455       IF NOT (lsetup_updated) THEN
14456          lsetup_updated := TRUE;
14457             UPDATE gmp_resource_instances gri
14458             SET gri.last_setup_id = v_last_setup_id
14459             WHERE gri.resource_id = v_resource_id
14460               AND gri.instance_id = v_instance_id;
14461       END IF;
14462    END LOOP;
14463       CLOSE cur_lsetup_id ;
14464    COMMIT;
14465 EXCEPTION
14466     WHEN NO_DATA_FOUND THEN
14467         log_message(' NO_DATA_FOUND exception raised in Procedure: gmp_aps_ds_pull.update_last_setup_id ' );
14468       	RAISE;
14469 
14470     WHEN OTHERS THEN
14471         log_message('Error in Last Setup ID Program: '||SQLERRM);
14472         RAISE;
14473 
14474 END update_last_setup_id;
14475 
14476 FUNCTION GMP_APSDS_UTILITY1_R10
14477             (
14478                           p_dblink      IN VARCHAR2,
14479                           p_delimiter   IN VARCHAR2,
14480                           p_instance    IN INTEGER,
14481                           p_run_date    IN DATE,
14482                           p_num1        IN NUMBER,
14483                           p_num2        IN NUMBER,
14484                           p_num3        IN NUMBER,
14485                           p_num4        IN NUMBER,
14486                           p_varchar1    IN VARCHAR2,
14487                           p_varchar2    IN VARCHAR2,
14488                           p_varchar3    IN VARCHAR2,
14489                           p_varchar4    IN VARCHAR2
14490             ) RETURN INTEGER IS
14491 BEGIN
14492     return 0;
14493 END GMP_APSDS_UTILITY1_R10;
14494 
14495 PROCEDURE GMP_APSDS_PROC1_R10
14496             (
14497                           p_dblink      IN VARCHAR2,
14498                           p_delimiter   IN VARCHAR2,
14499                           p_instance    IN INTEGER,
14500                           p_run_date    IN DATE,
14501                           p_num1        IN NUMBER,
14502                           p_num2        IN NUMBER,
14503                           p_num3        IN NUMBER,
14504                           p_num4        IN NUMBER,
14505                           p_varchar1    IN VARCHAR2,
14506                           p_varchar2    IN VARCHAR2,
14507                           p_varchar3    IN VARCHAR2,
14508                           p_varchar4    IN VARCHAR2,
14509                           return_status  OUT NOCOPY BOOLEAN
14510             ) IS
14511 BEGIN
14512     return_status := TRUE;
14513 END GMP_APSDS_PROC1_R10;
14514 
14515 -- --------------------OPM Production Order Package End ------------
14516 
14517 /*
14518 REM+==========================================================================+
14519 REM| PROCEDURE NAME                                                           |
14520 REM|    rsrc_extract                                                          |
14521 REM|                                                                          |
14522 REM| Type                                                                     |
14523 REM|    public                                                                |
14524 REM|                                                                          |
14525 REM| DESCRIPTION                                                              |
14526 REM|    The following procedure rows into msc_st_department_resources         |
14527 REM|                                                                          |
14528 REM| Input Parameters                                                         |
14529 REM|    p_instance_id - Instance Id                                           |
14530 REM|    p_db_link - Database Link                                             |
14531 REM|    return_status - Status return variable                                |
14532 REM|                                                                          |
14533 REM| Output Parameters                                                        |
14534 REM|    None                                                                  |
14535 REM|                                                                          |
14536 REM|                                                                          |
14537 REM| HISTORY                                                                  |
14538 REM|    Created 5th Aug 1999 by Sridhar Gidugu (OPM Development Oracle US)    |
14539 REM|    8/17/99 - Changed to Dynamic SQL , added db_link                      |
14540 REM|    10/13/99 - Added deleted_flag in the insert statement                 |
14541 REM|    11/23/99 - Changed value of aggregate_resource_flag from 1 to 2       |
14542 REM|    01/12/00 - Added owning_department_id column in the Insert statement  |
14543 REM|             - Bug# 1140113                                               |
14544 REM|    4/03/00 - using mtl_organization_id from ic_whse_mst instead of       |
14545 REM|            - organization_id from sy_orgn_mst - Bug# 1252322             |
14546 REM|    4/18/00 - Fixed Bug# 1273557 - Department count is Zero               |
14547 REM|            - Changes made to the insert statement, changed               |
14548 REM|            - s.organization_id to w.mtl_organization_id                  |
14549 REM|    12/26/01 - Adding Code changes for Resource Utilization and Resource  |
14550 REM|               Efficiency - B2163006                                      |
14551 REM|    12/20/02 - Sridhar Gidugu  B2714583, Populated 3 new columns for      |
14552 REM|                               msc_st_department_resources                |
14553 REM|                               1.Resource_excess_type,                    |
14554 REM|                               2.Resource_shortage_type                   |
14555 REM|                               3.User_time_fence                          |
14556 REM|    01/09/03 - Sridhar Gidugu  Used mrp_planning_exception_sets           |
14557 REM|                               instead of mrp_planning_exception_sets_v   |
14558 REM|                               also added extra join with Organization_id |
14559 REM|    01/22/03 - Sridhar Gidugu  Insert statement for Resource Groups       |
14560 REM|    05/11/03 - Rajesh Patangya Used to_number(NULL) in palce of NULL      |
14561 REM|    05/20/03 - Sridhar Gidugu  B2971120 Populating new columns            |
14562 REM|                               Over_utilized_percent and                  |
14563 REM|                               under_utilized_percent in dept_rsc table   |
14564 REM|  04/21/2004   - Navin Sinha - B3577871 -ST:OSFME2: collections failing   |
14565 REM|                                in planning data pull.                    |
14566 REM|                                Added handling of NO_DATA_FOUND Exception.|
14567 REM|                                And return the return_status as TRUE.     |
14568 REM|  12/30/04 - Arvind Karuppasamy - B4081551, Modified query in rsrc_extract|
14569 REM|                                  to select the resource description from |
14570 REM|                                  cr_rsrc_mst.			      |
14571 REM|  02/17/05 - Teresa Wong - B4179616 Increased length of variables holding |
14572 REM|                                   dynamic sql stmts with string of org   |
14573 REM|                                   codes.                                 |
14574 REM+==========================================================================+
14575 */
14576 
14577 PROCEDURE rsrc_extract(p_instance_id IN NUMBER,
14578                        p_db_link     IN VARCHAR2,
14579                        return_status OUT NOCOPY BOOLEAN) is
14580 
14581 ins_dept_res     varchar2(32000);
14582 ins_res_group    varchar2(32000);
14583 ins_res_instance varchar2(32000);
14584 dep_ref_cursor   ref_cursor_typ;
14585 BEGIN
14586 stmt_no          := 0 ;
14587 
14588 /* Bug:6030499 Vpedarla added profile verification */
14589 
14590    log_message('Entered in department/Res RSRC_EXTRACT');
14591 
14592     collect_ps_data := TRUE;
14593 
14594 /*  New changes made for msc_st_department_resources - using mtl_organization_id
14595     from ic_whse_mst instead of organization_id from sy_orgn_mst
14596     table  - Bug # 1252322
14597     Commented the Where clause resource_whse_code is NOT NULL as whse code in
14598     ic_whse_mst is never NULL - 04/03/2000
14599 */
14600 
14601    log_message('Before v_cp_enabled call RSRC_EXTRACT');
14602 
14603 --    IF return_status THEN
14604 --       v_cp_enabled := TRUE;
14605 --    ELSE
14606 --       v_cp_enabled := FALSE;
14607 --    END IF;
14608 
14609    log_message('Before Org_string call RSRC_EXTRACT');
14610 
14611     /* populate the org_string */
14612      IF MSC_CL_GMP_UTILITY.org_string(p_instance_id) THEN
14613         NULL ;
14614      ELSE
14615         RAISE invalid_string_value  ;
14616      END IF;
14617 
14618    log_message('After Org_string call RSRC_EXTRACT');
14619 
14620     l_in_str_org := MSC_CL_GMP_UTILITY.g_in_str_org ;    /* 3491625 */
14621     log_message('Extract_items : l_in_str_org   =  '||l_in_str_org );
14622 
14623         /* note that we introduced substr(resources) as the
14624           final msc table has the column at 10 char only. If and when the MSC
14625           column width increases we shall remove substr */
14626 
14627     /* AKARUPPA 12/30/2004 B4081551 - Modified query to select resource description from cr_rsrc_mst */
14628 
14629     stmt_no := 10 ;
14630    log_message('stmt_no = 10 RSRC_EXTRACT');
14631 
14632     ins_dept_res := ' INSERT INTO msc_st_department_resources '
14633                || ' ( organization_id,  '
14634                || ' sr_instance_id, '
14635                || ' resource_id, '
14636                || ' department_id, '
14637                || ' resource_code, '
14638                || ' resource_description,  '
14639                || ' department_code, '
14640                || ' owning_department_id, '
14641                || ' line_flag, '
14642                || ' aggregated_resource_flag, '
14643                || ' capacity_units, '
14644                || ' available_24_hours_flag, '
14645                || ' resource_cost,  '
14646                || ' ctp_flag,     '
14647                || ' deleted_flag,  '
14648                || ' resource_excess_type,  '
14649                || ' resource_shortage_type,  '
14650                || ' user_time_fence,  '
14651                || ' over_utilized_percent,  '    /* B2971120 */
14652                || ' under_utilized_percent,  '   /* B2971120 */
14653                || ' efficiency,  '
14654                || ' utilization,  '
14655                || ' planning_exception_set,  '
14656                || ' resource_group_name,  '
14657                || ' bottleneck_flag,  '
14658                || ' chargeable_flag, '
14659                || ' capacity_tolerance, '
14660                || ' batchable_flag, '
14661                || ' batching_window, '
14662                || ' min_capacity, '
14663                || ' max_capacity, '
14664                || ' unit_of_measure, '
14665                || ' idle_time_tolerance, '
14666                || ' sds_scheduling_window, '
14667                || ' batching_penalty, '
14668                || ' schedule_to_instance, '
14669  /*B4487118 - HLINK GC:(RV): MULTIPLE ROWS ARE DISPALYED FOR A RESOURCE IN THE RV*/
14670                || ' resource_type '
14671                || ') '
14672                || '  SELECT /*+ DRIVING_SITE(r) DRIVING_SITE(rsm) DRIVING_SITE(mrp) DRIVING_SITE(p) '
14673                || 'DRIVING_SITE(w) DRIVING_SITE(sou) */ w.mtl_organization_id , '
14674                || '  :instance_id, '
14675                || '  ((r.resource_id * 2) + 1),'         /* B1177070 encoded */
14676                || '  ((w.mtl_organization_id * 2) + 1),' /* B1177070 encoded */
14677                || '  r.resources, '       /* B6522434 */
14678          --      || '  substrb(r.resources,1,10), '
14679                || '  rsm.resource_desc, '                /* B4081551 */
14680                || '  w.whse_code   , '
14681                || '  ((w.mtl_organization_id * 2) + 1)  , ' /* B1177070 */
14682                || '  2, '            /* Line Flag */
14683                || '  2, '      /* Yes = 1 and No = 2 resource Flag */
14684                || '  r.assigned_qty, '
14685                || '  2, '      /* Avail 24 hrs flag */
14686                || '  r.nominal_cost, '
14687                || '  1,'     /* for ATP to check Resources (RDP)*/
14688                || '  2, '
14689                || '  mrp.resource_excess_type, '      /*  B2714583 */
14690                || '  mrp.resource_shortage_type, '    /* B2714583 */
14691                || '  mrp.user_time_fence, '           /* B2714583 */
14692                || '  mrp.over_utilized_percent, '     /* B2971120 */
14693                || '  mrp.under_utilized_percent, '    /* B2971120 */
14694                || '  r.efficiency, '                  /* B2163006 */
14695                || '  r.utilization, '                 /* B2163006 */
14696                || '  r.planning_exception_set, '      /* B2714583 */
14697                || '  r.group_resource, '
14698                || '  NULL, '
14699                || '  decode(r.capacity_constraint,1,1,2), '
14700                || '  r.capacity_tolerance, '
14701                || '  2, ' /* batchable_flag */
14702                || '  NULL, '
14703                || '  r.min_capacity, '
14704                || '  r.max_capacity, '
14705                || '  sou.uom_code, '
14706                || '  idle_time_tolerence, '
14707                || '  sds_window, '
14708                || '  NULL, '
14709             /* If the Resource is scheduled to Instance, then value is Yes else No */
14710                || '  decode(r.schedule_ind,2,1,2), '
14711    /*B4487118 - HLINK GC:(RV): MULTIPLE ROWS ARE DISPALYED FOR A RESOURCE IN THE RV*/
14712                || '  1 '
14713                || '  FROM   cr_rsrc_dtl'||p_db_link||' r, '
14714 	       || '         cr_rsrc_mst'||p_db_link||' rsm, ' /* B4081551 */
14715                || '         mrp_planning_exception_sets'||p_db_link||' mrp, '
14716                || '         sy_orgn_mst'||p_db_link||' p, '
14717                || '         ic_whse_mst'||p_db_link||' w, '
14718 -- Bug 6467457 modified as below              ||'          sy_uoms_mst'||p_db_link||' sou '
14719                ||'          mtl_units_of_measure'||p_db_link||' sou '
14720                || '  WHERE  r.orgn_code = p.orgn_code '
14721                || '  AND    r.planning_exception_set = mrp.exception_set_name '
14722                || '  AND    w.mtl_organization_id = mrp.organization_id '
14723 	       || '  AND    r.resources = rsm.resources ' /* B4081551 */
14724                || '  AND    p.resource_whse_code = w.whse_code ' ;
14725 
14726         IF MSC_CL_GMP_UTILITY.g_in_str_org  IS NOT NULL THEN
14727          ins_dept_res := ins_dept_res
14728                    ||'   AND w.mtl_organization_id ' || l_in_str_org ;
14729         END IF;
14730 
14731          ins_dept_res := ins_dept_res
14732                || '  AND    r.delete_mark = 0 '
14733                || '  AND    rsm.delete_mark = 0 ' /* B4081551 */
14734                || '  AND    p.delete_mark = 0 '
14735                || '  AND    w.delete_mark = 0 '
14736 -- 6467457 modified as below    ||'   AND sou.delete_mark = 0 '
14737                ||'   AND NVL(sou.disable_date, sysdate+1) > sysdate '
14738 -- 6467457 modified as below              ||'   AND sou.um_code = r.capacity_uom '
14739                ||'   AND ( sou.unit_of_measure = r.capacity_uom OR sou.uom_code = r.capacity_uom) '
14740                || '  UNION ALL '
14741                || '  SELECT /*+ DRIVING_SITE(r) DRIVING_SITE(rsm) DRIVING_SITE(p) '
14742                || ' DRIVING_SITE(w) DRIVING_SITE(sou) */ w.mtl_organization_id , '
14743                || '  :instance_id1, '
14744                || '  ((r.resource_id * 2) + 1),'         /* B1177070 encoded */
14745                || '  ((w.mtl_organization_id * 2) + 1),' /* B1177070 encoded */
14746                || '  r.resources, '       /* B6522434 */
14747         --     || '  substrb(r.resources,1,10), '
14748                || '  rsm.resource_desc, '                /* B4081551 */
14749                || '  w.whse_code   , '
14750                || '  ((w.mtl_organization_id * 2) + 1)  , ' /* B1177070 */
14751                || '  2, '            /* Line Flag */
14752                || '  2, '      /* Yes = 1 and No = 2 resource Flag */
14753                || '  r.assigned_qty, '
14754                || '  2, '      /* Avail 24 hrs flag */
14755                || '  r.nominal_cost, '
14756                || '  1,'     /* for ATP to check Resources (RDP)*/
14757                || '  2, '
14758                || '  to_number(NULL), '      /*  B2714583 */
14759                || '  to_number(NULL), '      /*  B2714583 */
14760                || '  to_number(NULL), '      /*  B2714583 */
14761                || '  to_number(NULL), '      /*  B2971120 */
14762                || '  to_number(NULL), '      /*  B2971120 */
14763                || '  r.efficiency, '         /* B2163006 */
14764                || '  r.utilization, '        /* B2163006 */
14765                || '  r.planning_exception_set, ' /* B2714583 */
14766                || '  r.group_resource, '
14767                || '  NULL, '
14768                || '  decode(r.capacity_constraint,1,1,2), '
14769                || '  r.capacity_tolerance, '
14770                || '  2, ' /* batchable_flag */
14771                || '  NULL, '
14772                || '  r.min_capacity, '
14773                || '  r.max_capacity, '
14774                || '  sou.uom_code, '
14775                || '  idle_time_tolerence, '
14776                || '  sds_window, '
14777                || '  NULL, '
14778             /* If the Resource is scheduled to Instance, then value is Yes else No */
14779                || '  decode(r.schedule_ind,2,1,2), '
14780    /*B4487118 - HLINK GC:(RV): MULTIPLE ROWS ARE DISPALYED FOR A RESOURCE IN THE RV*/
14781                || '  1 '
14782                || '  FROM   cr_rsrc_dtl'||p_db_link||' r, '
14783 	       || '         cr_rsrc_mst'||p_db_link||' rsm, ' /* B4081551 */
14784                || '         sy_orgn_mst'||p_db_link||' p, '
14785                || '         ic_whse_mst'||p_db_link||' w, '
14786 -- Bug 6467457 modified as below                ||'          sy_uoms_mst'||p_db_link||' sou '
14787                ||'          mtl_units_of_measure'||p_db_link||' sou '
14788                || '  WHERE  r.orgn_code = p.orgn_code '
14789                || '  AND    r.planning_exception_set IS NULL '
14790                || '  AND    p.resource_whse_code = w.whse_code '
14791 	       || '  AND    r.resources = rsm.resources ' /* B4081551 */
14792                || '  AND    r.delete_mark = 0 '
14793                || '  AND    rsm.delete_mark = 0 ' /* B4081551 */
14794                || '  AND    p.delete_mark = 0 '
14795                || '  AND    w.delete_mark = 0 '
14796 -- Bug 6467457 modified as below               ||'   AND sou.delete_mark = 0 '
14797                ||'   AND NVL(sou.disable_date, sysdate+1) > sysdate '
14798 -- Bug 6467457 modified as below               ||'   AND sou.um_code = r.capacity_uom ';
14799                ||'   AND ( sou.unit_of_measure = r.capacity_uom OR sou.uom_code = r.capacity_uom) ';
14800 
14801         IF MSC_CL_GMP_UTILITY.g_in_str_org  IS NOT NULL THEN
14802          ins_dept_res := ins_dept_res
14803                ||'   AND w.mtl_organization_id ' || l_in_str_org ;
14804         END IF;
14805         log_message('msc_st_department_resources Insert statement '||ins_dept_res);
14806          EXECUTE IMMEDIATE  ins_dept_res USING p_instance_id, p_instance_id;
14807 
14808     /* Insert into MSC_ST_RESOURCE_GROUPS for Bottleneck Resources
14809        Sending only those resources that are used in Planning for APS
14810     */
14811     stmt_no := 20 ;
14812     ins_res_group := ' INSERT INTO msc_st_resource_groups '
14813                || ' ( group_code,  '
14814                || '   meaning, '
14815                || '   description,  '
14816                || '   from_date,  '
14817                || '   to_date,  '
14818                || '   enabled_flag,  '
14819                || '   sr_instance_id '
14820                || ' ) '
14821                || '  SELECT distinct '
14822                || '   crd.group_resource , '
14823                || '   crm.resource_desc,'
14824                || '   crm.resource_desc,'
14825                || '   sysdate,'
14826                || '   NULL,'
14827                || '   1,'
14828                || '   :instance_id '
14829                || '  FROM  sy_orgn_mst'||p_db_link||' sy, '
14830                || '        cr_rsrc_dtl'||p_db_link||' crd, '
14831                || '        cr_rsrc_mst'||p_db_link||' crm '
14832                || '  WHERE sy.orgn_code = crd.orgn_code  '
14833                || '    AND sy.resource_whse_code is NOT NULL '
14834                || '    AND crd.resources = crm.resources '
14835                || '    AND crd.group_resource = crm.resources '
14836                || '    AND crd.delete_mark = 0 ';
14837 
14838         IF MSC_CL_GMP_UTILITY.g_in_str_org  IS NOT NULL THEN
14839          ins_res_group := ins_res_group
14840                || '    AND EXISTS ( SELECT 1 FROM gmp_item_aps'||p_db_link||' gia '
14841                || '    WHERE gia.whse_code = sy.resource_whse_code )' ;
14842         END IF;
14843         log_message('msc_st_resource_groups Insert statement '||ins_res_group);
14844          EXECUTE IMMEDIATE  ins_res_group USING p_instance_id;
14845 
14846         /* Now extract the resource instances too -
14847         The instance extraction was put under resource avaialbility
14848         extraction but to keep it in synch with Discrete collection, it is being
14849         moved here. */
14850 
14851 /* Bug:6030499 Vpedarla conditionalised the following  */
14852 
14853   IF collect_ps_data THEN
14854 
14855      stmt_no := 30 ;
14856      ins_res_instance := ' INSERT INTO msc_st_dept_res_instances '
14857          ||' ( sr_instance_id, '
14858          ||'   res_instance_id, '
14859          ||'   resource_id, '
14860          ||'   department_id, '
14861          ||'   organization_id, '
14862          ||'   serial_number, '
14863          ||'   equipment_item_id, '
14864          ||'   last_known_setup, '
14865          ||'   effective_start_date, '
14866          ||'   effective_end_date, '
14867          ||'   deleted_flag '
14868          ||' ) '
14869          ||' SELECT :instance_id, '
14870          ||'   ((gri.instance_id * 2) + 1), '
14871          ||'   ((gri.resource_id * 2) + 1) x_resource_id,  '
14872          ||'   ((iwm.mtl_organization_id * 2) + 1) department_id,'  /* encoded */
14873          ||'   iwm.mtl_organization_id ,  '
14874          ||'   NVL(gri.eqp_serial_number, to_char(gri.instance_number)),  '
14875          ||'   gri.equipment_item_id,  '
14876          ||'   gri.last_setup_id, '  -- Conc Prog routine will populate this
14877          ||'   gri.eff_start_date,  '
14878          ||'   gri.eff_end_date, '
14879          ||'   2 '
14880          ||' FROM  '
14881          ||'   gmp_resource_instances'||p_db_link||' gri,  '
14882          ||'   cr_rsrc_dtl'||p_db_link||' crd, '
14883          ||'   sy_orgn_mst'||p_db_link||' som,'
14884          ||'   ic_whse_mst'||p_db_link||' iwm '
14885          ||' WHERE  '
14886          ||'       gri.resource_id = crd.resource_id '
14887          ||'   AND crd.schedule_ind = 2 '
14888          ||'   AND crd.orgn_code = som.orgn_code '
14889          ||'   AND gri.inactive_ind = 0  '
14890          ||'   AND crd.delete_mark = 0 '
14891          ||'   AND som.delete_mark = 0'
14892          ||'   AND iwm.delete_mark = 0'
14893          ||'   AND som.resource_whse_code = iwm.whse_code' ;
14894 
14895         IF MSC_CL_GMP_UTILITY.g_in_str_org  IS NOT NULL THEN
14896         ins_res_instance := ins_res_instance
14897          ||'   AND EXISTS ( SELECT 1 FROM gmp_item_aps'||p_db_link||' gia '
14898          ||'   WHERE gia.whse_code = som.resource_whse_code )' ;
14899      END IF;
14900 
14901      EXECUTE IMMEDIATE  ins_res_instance USING p_instance_id;
14902 
14903   END IF;
14904      /* Bug: 6030499 Vpedarla end of conditional code */
14905     return_status := TRUE;
14906 
14907 EXCEPTION
14908 
14909     WHEN invalid_string_value  THEN
14910         log_message('APS string is Invalid, check for Error condition' );
14911         return_status := FALSE;
14912     WHEN NO_DATA_FOUND THEN /* B3577871 */
14913         log_message(' NO_DATA_FOUND exception raised in Procedure: MSC_CL_GMP_UTILITY.Rsrc_extract ' );
14914         return_status := TRUE;
14915     WHEN  OTHERS THEN
14916         log_message('Error in department/Res Group Insert: '||p_instance_id);
14917         log_message('stmt_no: ' || stmt_no || '--' || sqlerrm);
14918         return_status := FALSE;
14919 
14920 END rsrc_extract;
14921 
14922 /*
14923 REM+==========================================================================+
14924 REM| PROCEDURE NAME                                                           |
14925 REM|    net_rsrc                                                              |
14926 REM|                                                                          |
14927 REM| Type                                                                     |
14928 REM|    public                                                                |
14929 REM|                                                                          |
14930 REM| DESCRIPTION                                                              |
14931 REM|    The following procedure inserts rows into                             |
14932 REM|    msc_st_net_rsrc_avail table                                           |
14933 REM|                                                                          |
14934 REM| Input Parameters                                                         |
14935 REM|    p_instance_id - Instance Id                                           |
14936 REM|    p_org_id - Organization id                                            |
14937 REM|    p_simulation_set - Simulation Set                                     |
14938 REM|    p_shift_no - Shift number                                             |
14939 REM|    p_cal_date - Calendar date                                            |
14940 REM|    p_from_time - shift starting time                                     |
14941 REM|    p_to_time - Shift Ending time                                         |
14942 REM|                                                                          |
14943 REM| Output Parameters                                                        |
14944 REM|    None                                                                  |
14945 REM|                                                                          |
14946 REM|                                                                          |
14947 REM| HISTORY                                                                  |
14948 REM|    Created 5th Aug 1999 by Sridhar Gidugu (OPM Development Oracle US)    |
14949 REM|    10/13/99 - Added deleted_flag in the insert statement                 |
14950 REM|    01/24/01 - Bug Fix - 1612090, Added new name to the unavailable view  |
14951 REM|                                                                          |
14952 REM|                                                                          |
14953 REM+==========================================================================+
14954 */
14955 
14956 PROCEDURE net_rsrc(p_instance_id    IN NUMBER,
14957                    p_org_id         IN NUMBER,
14958                    p_simulation_set IN VARCHAR2,
14959                    p_resource_id    IN NUMBER,
14960                    p_assigned_qty   IN NUMBER,
14961                    p_shift_num      IN NUMBER,
14962                    p_calendar_date  IN DATE,
14963                    p_from_time      IN NUMBER,
14964                    p_to_time        IN NUMBER ) IS
14965 BEGIN
14966 stmt_no          := 31;
14967     /*  Call Unavail_rsrc_proc */
14968       INSERT INTO msc_st_net_resource_avail
14969                             ( organization_id,
14970                             sr_instance_id,
14971                             resource_id,
14972                             department_id,
14973                             simulation_set,
14974                             shift_num,
14975                             shift_date,
14976                             from_time,
14977                             to_time,
14978                             capacity_units,
14979                             deleted_flag
14980                             )
14981                       values
14982                             ( p_org_id,
14983                             p_instance_id,
14984                             ((p_resource_id * 2) + 1), /* B1177070 */
14985                             ((p_org_id * 2) + 1),  /* B1177070 encoded key */
14986                             p_simulation_set,
14987                             p_shift_num,
14988                             p_calendar_date,
14989                             p_from_time,
14990                             p_to_time,
14991                             p_assigned_qty,
14992                             2
14993                             );
14994 EXCEPTION
14995     WHEN OTHERS THEN
14996       log_message('Failure:net_rsrc Occured ' || stmt_no);
14997 
14998 END net_rsrc;
14999 
15000 /*
15001 REM+==========================================================================+
15002 REM| PROCEDURE NAME                                                           |
15003 REM|    update_trading_partners                                               |
15004 REM|                                                                          |
15005 REM| Type                                                                     |
15006 REM|    public                                                                |
15007 REM|                                                                          |
15008 REM| DESCRIPTION                                                              |
15009 REM|                                                                          |
15010 REM|    This procedure updates the following table :                          |
15011 REM|                                                                          |
15012 REM|                      1. msc_st_trading_partners                          |
15013 REM|                                                                          |
15014 REM| Input Parameters                                                         |
15015 REM|    p_org_id - Organization_id                                            |
15016 REM|    p_cal_code - Calendar_code                                            |
15017 REM|                                                                          |
15018 REM| Output Parameters                                                        |
15019 REM|    None                                                                  |
15020 REM|                                                                          |
15021 REM|                                                                          |
15022 REM| HISTORY                                                                  |
15023 REM|    Created 5th Aug 1999 by Sridhar Gidugu (OPM Development Oracle US)    |
15024 REM|    8/30/99 - Removed the existing Trading Partner Procedure and changed  |
15025 REM|              to a single Update Procedure.                               |
15026 REM|    10/1/99 - Changed Updating Trading Partners,                          |
15027 REM|            - Updated Organization_typw with a value 2 and changed        |
15028 REM|            - partner_type = 3                                            |
15029 REM|                                                                          |
15030 REM|                                                                          |
15031 REM+==========================================================================+
15032 */
15033 PROCEDURE update_trading_partners(p_org_id      IN NUMBER,
15034                                   p_cal_code    IN VARCHAR2,
15035                                   return_status OUT NOCOPY BOOLEAN) IS
15036 BEGIN
15037 
15038     IF return_status THEN
15039        v_cp_enabled := TRUE;
15040     ELSE
15041        v_cp_enabled := FALSE;
15042     END IF;
15043 
15044       stmt_no  := 32;
15045     -- The Following Update statement the Trading Parters table with the
15046     -- Calendar Code for the Organization that uses the Calendar.
15047       UPDATE MSC_ST_TRADING_PARTNERS
15048       SET calendar_code = p_cal_code,
15049           organization_type = 2
15050       WHERE sr_tp_id = p_org_id
15051       AND partner_type = 3;
15052 
15053 
15054       return_status := TRUE;
15055 EXCEPTION
15056     WHEN OTHERS THEN
15057       log_message('Failure:Trading Partners Update Occured ' || stmt_no);
15058       return_status := FALSE;
15059 
15060 END update_trading_partners; /* End of Updating Trading partners */
15061 
15062 /*
15063 REM+==========================================================================+
15064 REM| PROCEDURE NAME                                                           |
15065 REM|    get_cal_no                                                            |
15066 REM|                                                                          |
15067 REM| Type                                                                     |
15068 REM|    public                                                                |
15069 REM|                                                                          |
15070 REM| DESCRIPTION                                                              |
15071 REM|    The following Procedure checks for the value of calendar no and       |
15072 REM|    assigns a new value if the lenght exceeds 10 characters               |
15073 REM|                                                                          |
15074 REM| Input Parameters                                                         |
15075 REM|    p_cal_id - Calendar Id                                                |
15076 REM|    p_cal_no - Calendar No                                                |
15077 REM|                                                                          |
15078 REM| Output Parameters                                                        |
15079 REM|    p_out_cal                                                             |
15080 REM|    p_already_prefixed                                                    |
15081 REM|                                                                          |
15082 REM|                                                                          |
15083 REM| HISTORY                                                                  |
15084 REM|    Created 24th Sep 1999 by Sridhar Gidugu (OPM Development Oracle US)   |
15085 REM|    05/03/2000 - Changed 14characters check to 10 Characters to include   |
15086 REM|                 Instance code as prefix to Calendar code which has       |
15087 REM|                 already has 4 Characters - Bug#1288143                   |
15088 REM|    07/07/2000 - Modified get_cal_no Function to a Procedure, comparisons |
15089 REM|                 with Calendar Code which has Instance Code Prefixes are  |
15090 REM|                 taken  care - Bug# 1337084                               |
15091 REM|                                                                          |
15092 REM|                                                                          |
15093 REM+==========================================================================+
15094 */
15095 
15096 PROCEDURE get_cal_no( p_cal_id           IN  NUMBER,
15097                       p_cal_no           IN  VARCHAR2,
15098                       p_icode            IN  VARCHAR2,
15099                       p_out_cal          OUT NOCOPY VARCHAR2,
15100                       p_already_prefixed OUT NOCOPY VARCHAR2 ) IS
15101 
15102   temp_cal_no          VARCHAR2(10) ;
15103   prefixed_temp_cal_no VARCHAR2(14) ;
15104   out_cal_no           VARCHAR2(14) ;
15105   i                    NUMBER;
15106   k                    NUMBER;
15107   j                    NUMBER;
15108   j_char               VARCHAR2(10) ;
15109   found                NUMBER ;
15110   already_prefixed     VARCHAR2(3) ;
15111 
15112 BEGIN
15113 
15114   temp_cal_no          := NULL;
15115   prefixed_temp_cal_no := NULL ;
15116   out_cal_no           := NULL;
15117   i                    := 0 ;
15118   k                    := 0 ;
15119   j                    := 0 ;
15120   j_char               := NULL;
15121   found                := 0;
15122   stmt_no              := 0;
15123   already_prefixed     := 'NO';
15124 
15125 /* If calendar no is less than 10 , return  */
15126 
15127   IF length(p_cal_no) < 10 or plsqltbl_rec.COUNT < 1 THEN
15128      out_cal_no := substrb(p_cal_no,1,10);
15129   ELSE
15130 
15131   /* The default name generation is the first 10 chars of the calendar no */
15132 
15133      temp_cal_no := substrb(p_cal_no,1,10);
15134 
15135  /* 07/07/2000 - Adding Instance code as a Prefix to the Calendar Code. */
15136 
15137      prefixed_temp_cal_no := p_icode||':'||temp_cal_no;
15138 
15139      out_cal_no := NULL;
15140 
15141   stmt_no   := 10;
15142   FOR i IN 1..plsqltbl_rec.COUNT
15143   LOOP
15144     /*  if a row has already been inserted for the calendar id
15145         use the value from that row and stop the loop  */
15146 
15147       IF plsqltbl_rec(i).calendar_id = p_cal_id
15148       THEN
15149 
15150      /* Commented the following statement and used substrb to pick first
15151         10 characters as it causes a buffer too small problem - Bug#1288143 */
15152 
15153           out_cal_no := substrb(plsqltbl_rec(i).calendar_no,1,14);
15154 
15155      /*
15156        07/07/2000 - Added a check flag to indicate the Instance is already prefixed
15157              and this check is being used at the time when the PLSQL table is
15158              constructed, where in it will not assign an Instance Prefix if the
15159              calendar_code is already prefixed - Bug# 1337084.
15160      */
15161 
15162           already_prefixed := 'YES';
15163           found := 1;
15164           EXIT;
15165       END IF;
15166 
15167   END LOOP; /* End loop for check in the PL/SQL tbl */
15168 
15169   IF found = 0 THEN
15170       k := 10;
15171       j := 0;
15172       j_char := NULL;
15173 
15174       /*
15175        the loop will try the default value then change it if necessary and
15176        until we have exhasted all of the values of 0-99999999999999 (10 chars of numbers)
15177       */
15178       stmt_no   := 20;
15179       LOOP
15180         /* { */
15181         temp_cal_no := j_char || substrb(p_cal_no,1,k);
15182       /*
15183          this loop goes through the current list to see if there is a duplicate
15184          if found we stop and generate a new value then try again
15185       */
15186 
15187         FOR i IN 1..plsqltbl_rec.COUNT LOOP
15188         /*  { */
15189 
15190 /*  07/07/00 - Comparing the Calendar number with Prefixed Calendar Code - Bug#1337084 */
15191 
15192           IF plsqltbl_rec(i).calendar_no = p_icode||':'||temp_cal_no THEN
15193             EXIT;
15194           END IF;
15195           IF i =  plsqltbl_rec.COUNT THEN
15196             found := 1;
15197             out_cal_no := temp_cal_no;
15198           END IF;
15199         /* }  */
15200         END LOOP ;
15201 
15202         /*  if we found a value or reached the max we stop */
15203         IF found = 1 or j = 9999999999 THEN
15204           EXIT;
15205         END IF;
15206 
15207         /*  to get a unique value we keep taking one char at a time from the
15208          the calendar_no.
15209         */
15210         j := j + 1;
15211         j_char := TO_CHAR(j);
15212         k := 10 - length(j_char);
15213 
15214       /* } */
15215       END LOOP;
15216   END IF;
15217 
15218   END IF ;
15219 
15220         p_out_cal := out_cal_no;
15221         p_already_prefixed := already_prefixed ;
15222 EXCEPTION
15223     WHEN OTHERS THEN
15224       log_message('Failure:get_cal_no Occured ' || stmt_no);
15225       p_out_cal := NULL ;
15226       p_already_prefixed := already_prefixed ;
15227 
15228 END get_cal_no; /* End of the Procedure GET_CAL_NO */
15229 /*
15230 REM+==========================================================================+
15231 REM| PROCEDURE NAME                                                           |
15232 REM|    retrieve_calendar_detail                                              |
15233 REM|                                                                          |
15234 REM| Type                                                                     |
15235 REM|    public                                                                |
15236 REM|                                                                          |
15237 REM| DESCRIPTION                                                              |
15238 REM|                                                                          |
15239 REM|                                                                          |
15240 REM| Input Parameters                                                         |
15241 REM|    p_orgn_code - Orgn Code                                               |
15242 REM|    p_org_id - Organization id                                            |
15243 REM|    p_cal_id - calendar_id                                                |
15244 REM|    p_instance_id - Instance Id                                           |
15245 REM|    p_delimiter - Delimiter                                               |
15246 REM|    p_db_link - Data Base Link                                            |
15247 REM|                                                                          |
15248 REM| Output Parameters                                                        |
15249 REM|    return_status                                                         |
15250 REM|                                                                          |
15251 REM|                                                                          |
15252 REM| HISTORY                                                                  |
15253 REM|    Created 5th Aug 1999 by Sridhar Gidugu (OPM Development Oracle US)    |
15254 REM|    9/20/99 - created the Retrieve calendar Procedure                     |
15255 REM|    10/13/99 - Added deleted_flag in the insert statement                 |
15256 REM|    10/18/99 - Changed value of Exception set Id from 1 to -1             |
15257 REM|    12/09/99 - Added Code to include all Calendar Days                    |
15258 REM|    12/17/99 - Fixed Code for Bug# 1117565                                |
15259 REM|    02/01/00 - next seq and prior seqs are made same as seq number in     |
15260 REM|             - msc_calendar_dates insert, bug#1175906                     |
15261 REM|             - similarly for next date and prior date are same as calendar|
15262 REM|             - dates                                                      |
15263 REM|    03/01/00 - Added Code to not to include rows which have               |
15264 REM|               shift_duration as zero seconds - Bug#1221285               |
15265 REM|    03/20/03 - Added Inserts to msc_st_shift_times table - 2213101        |
15266 REM|    03/20/03 - Added Inserts to msc_st_shift_dates table - 2213101        |
15267 REM|                                                                          |
15268 REM|                                                                          |
15269 REM+==========================================================================+
15270 */
15271 PROCEDURE retrieve_calendar_detail( p_cal_id      IN NUMBER,
15272                                     p_calendar_no IN VARCHAR2,
15273                                     p_cal_desc    IN VARCHAR2,
15274                                     p_run_date    IN DATE,
15275                                     p_db_link     IN VARCHAR2,
15276                                     p_instance_id IN NUMBER,
15277                                     p_usage       IN VARCHAR2,
15278                                     return_status OUT NOCOPY BOOLEAN) IS
15279 cal_cur             ref_cursor_typ;
15280 cal_count           NUMBER;
15281 cal_start_date      DATE;
15282 cal_end_date        DATE;
15283 sql_stmt2           VARCHAR2(32700);
15284 sql_stmt3           VARCHAR2(32700);
15285 v_cal_date          DATE;
15286 v_shift_num         NUMBER;
15287 v_from_time         NUMBER;
15288 v_to_time           NUMBER;
15289 old_occur           NUMBER;
15290 prior_occur         NUMBER;
15291 old_cal_date        DATE;
15292 seq_num             NUMBER;
15293 prior_seq_num       NUMBER;
15294 next_seq_num        NUMBER;
15295 shift_seq_num       NUMBER;
15296 shift_prior_seq_num NUMBER;
15297 shift_next_seq_num  NUMBER;
15298 shift_next_date     DATE;
15299 shift_prior_date    DATE;
15300 shift_old_date      DATE;
15301 v_prior_date        DATE;
15302 v_old_cal_date      DATE;
15303 v_seq_num           NUMBER;
15304 v_next_seq_num      NUMBER;
15305 v_prior_seq_num     NUMBER;
15306 i                   INTEGER;
15307 j                   INTEGER;
15308 x                   INTEGER;
15309 old_weekly          NUMBER ;
15310 prior_weekly        NUMBER ;
15311 old_period          NUMBER ;
15312 prior_period        NUMBER ;
15313 period_char         VARCHAR2(8);
15314 week_end            DATE;
15315 weekly_seq          NUMBER ;
15316 period_seq          NUMBER ;
15317 week_num            NUMBER ;
15318 /* 05-JAN-2002 Rajesh Patangya  */
15319 wps_index           INTEGER ;
15320 /* 12/13/02 - Rajesh Patangya B2710601, Added database link  */
15321 ins_stmt            VARCHAR2(32700) ;
15322 ins_stmt1           VARCHAR2(32700) ;
15323 shft_time           VARCHAR2(32700) ;
15324 temp_from_date      DATE ;
15325 temp_to_date        DATE ;
15326 temp_to_time        NUMBER ;
15327 temp_shift_num      NUMBER ;
15328 
15329 BEGIN
15330 
15331   cal_count         := 0;
15332   prior_occur       := 1;
15333   old_cal_date      :=  to_date('01/01/1959','DD/MM/YYYY');
15334   seq_num           := 0;
15335   prior_seq_num     := 1;
15336   shift_seq_num     := 0;
15337   shift_prior_seq_num := 1;
15338   shift_old_date    := to_date('01/01/1959','DD/MM/YYYY');
15339 
15340   i                 := 0;
15341   j                 := 0;
15342   x                 := 0;
15343   old_weekly        := 0;
15344   prior_weekly      := 0;
15345   old_period        := 0;
15346   prior_period      := 0;
15347   period_char       := NULL;
15348   weekly_seq        := 0;
15349   period_seq        := 0;
15350   week_num          := 0;
15351   wps_index         := 0;
15352   ins_stmt          := NULL;
15353   ins_stmt1         := NULL;
15354   shft_time         := NULL;
15355   temp_from_date    := NULL;
15356   temp_to_date      := NULL;
15357   temp_to_time      := 0 ;
15358   temp_shift_num    := 0 ;
15359   stmt_no           := 0;
15360 
15361        /* Insert for Net Resource starts here, The following select statement
15362           gets the period that are availble for a given calendar, From time
15363           and To Time are taken in seconds here.
15364        */
15365 
15366     IF return_status THEN
15367        v_cp_enabled := TRUE;
15368     ELSE
15369        v_cp_enabled := FALSE;
15370     END IF;
15371 
15372 --
15373        stmt_no := 10;
15374        sql_stmt3 := ' SELECT msd.calendar_date calendar_date,  '
15375                     || '      dd.shift_no  shift_no,                 '
15376                     || '      dd.shift_start  from_time,             '
15377                     || '      dd.shift_start + dd.shift_duration  to_time  '
15378                     || ' FROM   mr_shcl_dtl'||p_db_link||'  msd, '
15379                     || '        mr_shdy_hdr'||p_db_link||'  dh,  '
15380                     || '        mr_shdy_dtl'||p_db_link||'  dd   '
15381                     || ' WHERE msd.calendar_id = :curr_cal_id   '
15382                     || ' and   dh.shopday_no = msd.shopday_no   '
15383                     || ' AND dd.shopday_no = dh.shopday_no      '
15384                     || ' AND msd.delete_mark = 0                '
15385                     || ' AND dh.delete_mark  = 0                '
15386                     || ' AND dd.delete_mark  = 0                '
15387                     || ' AND dd.shift_duration  > 0             '
15388                     || ' ORDER BY  calendar_date,               '
15389                     || '           from_time,                   '
15390                     || '           to_time  ';
15391 
15392     /* The cursor is opened and the values are stored in a PL/SQL table
15393       for further processing If Pl/SQL Tbl new_rec  has any residual rows,
15394       we Need to clean before populating the New Table - 12/17/99 */
15395 
15396        IF new_rec.COUNT > 0 THEN
15397           new_rec.delete;
15398        END IF;
15399 
15400       /*      OPEN cal_cur FOR sql_stmt3 USING p_cal_id,trunc(p_run_date); */
15401 
15402        OPEN cal_cur FOR sql_stmt3 USING p_cal_id;
15403 
15404      stmt_no := 20;
15405      i := 0;
15406      LOOP
15407        FETCH cal_cur
15408        INTO  calendar_record;
15409        EXIT WHEN cal_cur%NOTFOUND;
15410 
15411        stmt_no := 30;
15412 
15413        /*  Check for the First record  */
15414        IF i = 0 THEN
15415          stmt_no := 40;
15416 
15417          /*  Check if the first row to time is spilling over  */
15418 
15419          IF calendar_record.to_time > no_of_secs THEN
15420            i := i + 1;
15421            new_rec(i).cal_date := calendar_record.cal_date ;
15422            new_rec(i).shift_num := calendar_record.shift_num ;
15423            new_rec(i).from_time := calendar_record.from_time;
15424            new_rec(i).to_time := no_of_secs ;
15425 
15426  /*           Add more record for the spilled over shift  */
15427            i := i +1 ;
15428 
15429            new_rec(i).cal_date := calendar_record.cal_date + 1 ;
15430            new_rec(i).shift_num := calendar_record.shift_num ;
15431            new_rec(i).from_time := 0 ;
15432            new_rec(i).to_time := calendar_record.to_time - no_of_secs ;
15433          ELSE
15434              /*  Else Store the values in the PL/sql table          */
15435 
15436            i := i + 1;
15437            new_rec(i).cal_date := calendar_record.cal_date ;
15438            new_rec(i).shift_num := calendar_record.shift_num ;
15439            new_rec(i).from_time := calendar_record.from_time;
15440            new_rec(i).to_time := calendar_record.to_time;
15441 
15442          END IF;
15443 
15444        /*   If not the first record, then check if the Calendar date
15445             is greater than the Previous cal date in the PL/sql table */
15446      ELSE
15447        IF calendar_record.cal_date >  new_rec(i).cal_date  THEN
15448 
15449           /*  Check if the Date, to_time is spilling over */
15450          IF calendar_record.to_time > no_of_secs THEN
15451            i := i + 1;
15452            new_rec(i).cal_date := calendar_record.cal_date;
15453            new_rec(i).from_time := calendar_record.from_time;
15454            new_rec(i).shift_num := calendar_record.shift_num;
15455            new_rec(i).to_time := no_of_secs;
15456 
15457        /*          Add more record for the spilled over shift  */
15458              i := i + 1;
15459              new_rec(i).cal_date := calendar_record.cal_date + 1;
15460              new_rec(i).shift_num := calendar_record.shift_num;
15461              new_rec(i).from_time := 0;
15462              new_rec(i).to_time := calendar_record.to_time - no_of_secs ;
15463          ELSE
15464              /*   Else Store the values in the PL/sql table          */
15465 
15466              i := i + 1 ;
15467              new_rec(i).cal_date := calendar_record.cal_date ;
15468              new_rec(i).shift_num := calendar_record.shift_num ;
15469              new_rec(i).from_time := calendar_record.from_time;
15470              new_rec(i).to_time := calendar_record.to_time;
15471 
15472          END IF;
15473 
15474        /*  If not the first record, then check if the Calendar date
15475            is equal to the Previous cal date in the PL/sql table */
15476 
15477      ELSIF calendar_record.cal_date =  new_rec(i).cal_date THEN
15478 
15479         /*  Checking if the Cursor from_time is greater than Previous record to_time */
15480 
15481           IF calendar_record.from_time >  new_rec(i).to_time  THEN
15482              /*  Check if the Date, to_time is spilling over */
15483              IF calendar_record.to_time > no_of_secs THEN
15484                i := i + 1;
15485                new_rec(i).cal_date := calendar_record.cal_date;
15486                new_rec(i).from_time := calendar_record.from_time;
15487                new_rec(i).shift_num := calendar_record.shift_num;
15488                new_rec(i).to_time := no_of_secs;
15489 
15490            /*  Add more record for the spilled over shift  */
15491                  i := i + 1;
15492                  new_rec(i).cal_date := calendar_record.cal_date + 1 ;
15493                  new_rec(i).from_time := 0 ;
15494                  new_rec(i).shift_num := calendar_record.shift_num;
15495                  new_rec(i).to_time := calendar_record.to_time - no_of_secs ;
15496              ELSE
15497                 i := i + 1;
15498                 new_rec(i).cal_date := calendar_record.cal_date ;
15499                 new_rec(i).shift_num := calendar_record.shift_num ;
15500                 new_rec(i).from_time := calendar_record.from_time;
15501                 new_rec(i).to_time := calendar_record.to_time;
15502             END IF ;
15503          ELSE      /* Merge time !!!
15504                       Shifts Merge is the start time of the shift is Less than
15505                       the Previous record to_time
15506                Checking if the record that is Merged is spilling Over to next day */
15507              IF calendar_record.to_time > no_of_secs THEN
15508                 new_rec(i).to_time := no_of_secs ;
15509                /* Add more record for the spilled over shift  */
15510                  i := i + 1;
15511                  new_rec(i).cal_date := calendar_record.cal_date + 1;
15512                  new_rec(i).from_time := 0 ;
15513                  new_rec(i).shift_num := calendar_record.shift_num;
15514                  new_rec(i).to_time := calendar_record.to_time - no_of_secs ;
15515               ELSE
15516                 IF  calendar_record.to_time > new_rec(i).to_time THEN
15517                   new_rec(i).to_time := calendar_record.to_time ;
15518                 END IF ;
15519               END IF  ;
15520           END IF ; /* End OF Merge time  */
15521 
15522        /*  checking if the Calendar date is less than the Previous cal date
15523            in the PL/sql table This check is useful when two shifts in a day
15524            are crossing Midnight Then in that case we need to compare the start
15525            time with the Previously completed shift end time and the dates too. */
15526 
15527         ELSIF calendar_record.cal_date <  new_rec(i).cal_date THEN
15528             IF calendar_record.to_time > no_of_secs THEN
15529               IF calendar_record.to_time - no_of_secs > new_rec(i).to_time THEN
15530                  new_rec(i).to_time := calendar_record.to_time - no_of_secs ;
15531               END IF;
15532             END IF ;
15533 
15534         END IF ; /* End if for date check */
15535      END IF; /* End if for i = 0 */
15536 
15537      END LOOP;
15538 
15539      /*  cal count gives the Number of rows after the Calendar is exploded */
15540      cal_count := new_rec.COUNT ;
15541      /*  Calendar Start date and End dates are Calculated here  */
15542      cal_start_date := new_rec(1).cal_date;
15543      cal_end_date := new_rec(cal_count).cal_date;
15544 
15545      CLOSE cal_cur;
15546 
15547 /*Bug: 6030499 Vpedarla added session pga memory */
15548 
15549      SELECT st.VALUE INTO v_dummy from V$MYSTAT st, V$STATNAME sn
15550      where st.STATISTIC# = sn.STATISTIC#
15551      and sn.NAME in ('session pga memory');
15552      log_message('Cal Cur Session pga memory = ' || TO_CHAR(v_dummy) );
15553 
15554    /* 05-JAN-2002 Rajesh Patangya  */
15555    /* Start writing the exploded Calendar dates into temp table */
15556    wps_index         := 1 ;
15557 
15558    /* 12/13/02 - Rajesh Patangya B2710601, Added database link  */
15559      ins_stmt := 'INSERT INTO gmp_calendar_detail_gtmp'||p_db_link
15560                           ||' ( '
15561                           ||'   calendar_id, '
15562                           ||'   shift_num, '
15563                           ||'   shift_date, '
15564                           ||'   from_time, '
15565                           ||'   to_time, '
15566                           ||'   from_date, '
15567                           ||'   to_date '
15568                           ||' ) '
15569                           ||' VALUES '
15570                           ||' ( :p1,:p2,:p3,:p4,:p5,:p6,:p7)';
15571 
15572 
15573      ins_stmt1 := 'INSERT INTO temp_cal'||p_db_link
15574                           ||' ( '
15575                           ||'   calendar_id, '
15576                           ||'   shift_num, '
15577                           ||'   shift_date, '
15578                           ||'   from_time, '
15579                           ||'   to_time, '
15580                           ||'   from_date, '
15581                           ||'   to_date '
15582                           ||' ) '
15583                           ||' VALUES '
15584                           ||' ( :p1,:p2,:p3,:p4,:p5,:p6,:p7)';
15585 --
15586    FOR wps_index IN 1..new_rec.COUNT
15587    LOOP
15588 
15589      temp_from_date := (new_rec(wps_index).cal_date +
15590                          (new_rec(wps_index).from_time/86400)) ;
15591 
15592      IF new_rec(wps_index).to_time = 86400 THEN
15593      temp_to_time   := new_rec(wps_index).to_time - 1 ;
15594      temp_shift_num := new_rec(wps_index).shift_num  + 99999 ;
15595      ELSE
15596      temp_to_time   := new_rec(wps_index).to_time  ;
15597      temp_shift_num := new_rec(wps_index).shift_num;
15598      END IF ;
15599 
15600      temp_to_date   := (new_rec(wps_index).cal_date + (temp_to_time /86400)) ;
15601 
15602      EXECUTE IMMEDIATE ins_stmt USING
15603                                 p_cal_id,
15604                                 temp_shift_num,
15605                                 new_rec(wps_index).cal_date,
15606                                 new_rec(wps_index).from_time,
15607                                 temp_to_time,
15608                                 temp_from_date,
15609                                 temp_to_date
15610                                ;
15611   /*
15612      EXECUTE IMMEDIATE ins_stmt1 USING
15613                                 p_cal_id,
15614                                 temp_shift_num,
15615                                 new_rec(wps_index).cal_date,
15616                                 new_rec(wps_index).from_time,
15617                                 temp_to_time,
15618                                 temp_from_date,
15619                                 temp_to_date
15620                                ;
15621   */
15622     END LOOP;
15623 --       log_message(to_char(sysdate,'MM/DD/YYYY HH24:MI:SS'));
15624 
15625    IF p_usage = 'APS' THEN
15626        /* Insert for msc_st_shift_times Starts Here - 2213101 */
15627        stmt_no := 41;
15628        shft_time := '  INSERT INTO msc_st_shift_times '
15629                     || ' (shift_num,                      '
15630                     || '  calendar_code,                  '
15631                     || '  from_time,                      '
15632                     || '  to_time,                        '
15633                     || '  deleted_flag,                   '
15634                     || '  sr_instance_id                  '
15635                     || ' )                                '
15636                     || ' SELECT distinct shift_num ,   '
15637                     || '  :calendar_no,                      '
15638                     || '  from_time,         '
15639                     || '  to_time,  '
15640                     || '  2  ,                    '
15641                     || '  :instance_id                      '
15642                     || ' FROM  gmp_calendar_detail_gtmp'||p_db_link||'  gtmp '
15643                     || ' WHERE calendar_id = :curr_cal_id   '
15644                     || ' ORDER BY shift_num,from_time, to_time ' ;
15645 
15646        EXECUTE IMMEDIATE shft_time USING p_calendar_no,
15647                                          p_instance_id,
15648                                          p_cal_id;
15649 
15650        /* Insert for msc_st_shift_times Ends Here - 2213101 */
15651 --
15652      /* Start writing the Calendar dates */
15653 
15654      old_occur := 1;
15655      old_cal_date := new_rec(1).cal_date;
15656 
15657      old_weekly := 1;
15658      prior_weekly := 1;
15659      old_period := 1;
15660      prior_period := 1;
15661 
15662      period_char := TO_CHAR(new_rec(old_period).cal_date,'MON-YYYY');
15663      weekly_seq := 0;
15664      period_seq := 0;
15665 
15666      SELECT to_char(new_rec(old_weekly).cal_date,'D') INTO week_num FROM dual;
15667      week_num := (week_num - 7) * -1;
15668      week_end := new_rec(old_weekly).cal_date + week_num;
15669 
15670      /*
15671       The PL/sql table thus Populated after exploding the Calendar is useful in
15672       Populating MSC_ST_CALENDAR_DATES here
15673      */
15674      stmt_no := 50;
15675      FOR j IN 1 ..cal_count
15676      LOOP
15677        IF new_rec(j).cal_date <> old_cal_date THEN
15678           seq_num := seq_num + 1;
15679           prior_seq_num := seq_num - 1;
15680           IF prior_seq_num < 1 THEN
15681              prior_seq_num := 1;
15682           END IF;
15683           next_seq_num := seq_num + 1;
15684          /* Code change to include all the Calendar Days in the
15685             Staging Calendar Table
15686          */
15687 
15688         /* After allowing the first row insert, check from the second row on
15689            if there are any gaps in the dates
15690         */
15691           IF seq_num >= 1 THEN
15692           /* using information from the Prior set values of sequences and dates */
15693 
15694              v_next_seq_num := next_seq_num;
15695              v_prior_seq_num := seq_num;
15696              v_old_cal_date := old_cal_date;
15697              v_prior_date := old_cal_date;
15698 
15699          /* Start of Code change to include all the Calendar Days in the
15700             Staging Calendar Table
15701          */
15702 
15703              stmt_no := 51;
15704              WHILE ( v_old_cal_date + 1 < new_rec(j).cal_date)
15705              LOOP
15706                   INSERT INTO msc_st_calendar_dates
15707                                   (calendar_date,
15708                                    calendar_code,
15709                                    exception_set_id,
15710                                    seq_num,
15711                                    next_seq_num,
15712                                    prior_seq_num,
15713                                    next_date,
15714                                    prior_date,
15715                                    calendar_start_date,
15716                                    calendar_end_date,
15717                                    description,
15718                                    sr_instance_id,
15719                                    deleted_flag
15720                                   )
15721                             values(v_old_cal_date + 1,
15722                                    p_calendar_no,
15723                                    -1,
15724                                    NULL,
15725                                    v_next_seq_num,
15726                                    v_prior_seq_num,
15727                                    new_rec(j).cal_date,
15728                                    v_prior_date,
15729                                    cal_start_date,
15730                                    cal_end_date,
15731                                    p_cal_desc,
15732                                    p_instance_id,
15733                                    2
15734                                    );
15735                  /* The Calendar Date needs to be incremented to check for
15736                     further gaps in the dates
15737                  */
15738                  v_old_cal_date := v_old_cal_date + 1;
15739              END LOOP;
15740           END IF;
15741 
15742          /* End of Code change to include all the Calendar Days in the
15743             Staging Calendar Table
15744          */
15745 
15746         /* New changes made to the calendar sequences, Bug#1175906
15747            nextseq, prior_seq are made same as seq number for working
15748            days, and similarly for next date and prior_dates are same as
15749            calendar_dates - 02/01/2000
15750         */
15751 
15752           stmt_no := 52;
15753           INSERT INTO msc_st_calendar_dates
15754                  (calendar_date,
15755                   calendar_code,
15756                   exception_set_id,
15757                   seq_num,
15758                   next_seq_num,
15759                   prior_seq_num,
15760                   next_date,
15761                   prior_date,
15762                   calendar_start_date,
15763                   calendar_end_date,
15764                   description,
15765                   sr_instance_id,
15766                   deleted_flag
15767                  )
15768            VALUES(new_rec(old_occur).cal_date,
15769                   p_calendar_no,
15770                   -1,
15771                   seq_num,
15772                   seq_num,
15773                   seq_num,
15774                   new_rec(old_occur).cal_date,
15775                   new_rec(old_occur).cal_date,
15776                   cal_start_date,
15777                   cal_end_date,
15778                   p_cal_desc,
15779                   p_instance_id,
15780                   2
15781                  );
15782 
15783              /*  write weekly bucket */
15784              stmt_no := 53;
15785              IF new_rec(j).cal_date > week_end THEN
15786                weekly_seq := weekly_seq + 1;
15787                INSERT INTO msc_st_cal_week_start_dates
15788                  ( CALENDAR_CODE         ,
15789                    EXCEPTION_SET_ID       ,
15790                    WEEK_START_DATE        ,
15791                    NEXT_DATE              ,
15792                    PRIOR_DATE             ,
15793                    SEQ_NUM                ,
15794                    DELETED_FLAG           ,
15795                    SR_INSTANCE_ID)
15796                VALUES
15797                  ( p_calendar_no ,
15798                    -1,
15799                    new_rec(old_weekly).cal_date,
15800                    new_rec(j).cal_date,
15801                    new_rec(prior_weekly).cal_date,
15802                    weekly_seq,
15803                    2,
15804                    p_INSTANCE_ID) ;
15805 
15806                week_num := 0;
15807                SELECT TO_CHAR(new_rec(j).cal_date,'D') INTO week_num FROM dual;
15808                week_num := (week_num - 7) * -1;
15809                prior_weekly := old_weekly;
15810                old_weekly := j;
15811                week_end := new_rec(old_weekly).cal_date + week_num;
15812 
15813                /*  write period bucket */
15814                IF period_char <> TO_CHAR(new_rec(j).cal_date,'MON-YYYY') THEN
15815                  period_seq := period_seq + 1;
15816 
15817                  stmt_no := 54;
15818                  INSERT INTO msc_st_period_start_dates
15819                  ( CALENDAR_CODE         ,
15820                    EXCEPTION_SET_ID       ,
15821                    PERIOD_START_DATE      ,
15822                    PERIOD_SEQUENCE_NUM    ,
15823                    PERIOD_NAME            ,
15824                    NEXT_DATE              ,
15825                    PRIOR_DATE             ,
15826                    DELETED_FLAG           ,
15827                    SR_INSTANCE_ID)
15828                  VALUES
15829                  ( p_calendar_no ,
15830                    -1,
15831                    new_rec(old_period).cal_date,
15832                    period_seq,
15833                    TO_CHAR(new_rec(old_period).cal_date, 'MON'),
15834                    new_rec(j).cal_date,
15835                    new_rec(prior_period).cal_date,
15836                    2,
15837                    p_INSTANCE_ID);
15838 
15839                  prior_period := old_period;
15840                  old_period := j;
15841                  period_char := TO_CHAR(new_rec(old_period).cal_date,'MON-YYYY');
15842                END IF;
15843              END IF;
15844 
15845              old_cal_date := new_rec(j).cal_date;
15846              prior_occur := old_occur;
15847              old_occur := j;
15848              prior_seq_num := seq_num;
15849        END IF;
15850      END LOOP;
15851 
15852      /* Insert for the last record */
15853 
15854      stmt_no := 60;
15855      INSERT INTO msc_st_calendar_dates
15856        ( calendar_date,
15857          calendar_code,
15858          exception_set_id,
15859          seq_num,
15860          next_seq_num,
15861          prior_seq_num,
15862          next_date,
15863          prior_date,
15864          calendar_start_date,
15865          calendar_end_date,
15866          description,
15867          sr_instance_id
15868          )
15869       VALUES
15870        ( new_rec(old_occur).cal_date,
15871          p_calendar_no,
15872          -1,
15873          seq_num + 1,
15874          seq_num + 1,
15875          seq_num + 1,
15876          new_rec(old_occur).cal_date,
15877          new_rec(old_occur).cal_date,
15878          cal_start_date,
15879          cal_end_date,
15880          p_cal_desc,
15881          p_instance_id
15882        );
15883 
15884      weekly_seq := weekly_seq + 1;
15885 
15886      stmt_no := 61;
15887      INSERT INTO msc_st_cal_week_start_dates
15888        ( CALENDAR_CODE         ,
15889          EXCEPTION_SET_ID       ,
15890          WEEK_START_DATE        ,
15891          NEXT_DATE              ,
15892          PRIOR_DATE             ,
15893          SEQ_NUM                ,
15894          DELETED_FLAG           ,
15895          SR_INSTANCE_ID)
15896      VALUES
15897        ( p_calendar_no ,
15898          -1,
15899          new_rec(old_weekly).cal_date,
15900          new_rec(old_weekly).cal_date,
15901          new_rec(prior_weekly).cal_date,
15902          weekly_seq,
15903          2,
15904          p_INSTANCE_ID) ;
15905 
15906 
15907      period_seq := period_seq + 1;
15908 
15909      stmt_no := 63;
15910      INSERT INTO msc_st_period_start_dates
15911      ( CALENDAR_CODE         ,
15912        EXCEPTION_SET_ID       ,
15913        PERIOD_START_DATE      ,
15914        PERIOD_SEQUENCE_NUM    ,
15915        PERIOD_NAME            ,
15916        NEXT_DATE              ,
15917        PRIOR_DATE             ,
15918        DELETED_FLAG           ,
15919        SR_INSTANCE_ID
15920      )
15921      VALUES
15922      (p_calendar_no ,
15923       -1,
15924       new_rec(old_period).cal_date,
15925       period_seq,
15926       TO_CHAR(new_rec(old_period).cal_date, 'MON'),
15927       new_rec(old_period).cal_date,
15928       new_rec(prior_period).cal_date,
15929       2,
15930       p_INSTANCE_ID);
15931 
15932       /* B2213101 - Code added for Insert into msc_st_shift_dates */
15933      stmt_no := 70;
15934      shift_prior_date := new_rec(1).cal_date;
15935 
15936      FOR h IN 1 ..new_rec.COUNT
15937      LOOP
15938 
15939          shift_seq_num := shift_seq_num + 1;
15940 
15941          shift_prior_seq_num := shift_seq_num - 1;
15942          IF shift_prior_seq_num < 1 THEN
15943              shift_prior_seq_num := 1;
15944          END IF;
15945 
15946          shift_next_seq_num := shift_seq_num + 1;
15947          IF shift_next_seq_num > new_rec.COUNT THEN
15948             shift_next_seq_num := shift_next_seq_num - 1;
15949          END IF;
15950 
15951          IF new_rec(1).shift_num = new_rec(h).shift_num THEN
15952             IF shift_seq_num = 1 THEN
15953                shift_prior_date := new_rec(h).cal_date;
15954                shift_next_date  := shift_prior_date + 1;
15955             ELSE
15956                shift_prior_date := new_rec(h-1).cal_date;
15957                shift_next_date  := new_rec(h).cal_date + 1;
15958             END IF;
15959          END IF;
15960 
15961 
15962          INSERT INTO msc_st_shift_dates
15963            ( calendar_code,
15964              exception_set_id,
15965              shift_num,
15966              shift_date,
15967              seq_num,
15968              next_seq_num,
15969              prior_seq_num,
15970              next_date,
15971              prior_date,
15972              deleted_flag,
15973              sr_instance_id
15974            )
15975          VALUES
15976            ( p_calendar_no,
15977              -1,
15978              new_rec(h).shift_num,
15979              new_rec(h).cal_date,
15980              shift_seq_num,
15981              shift_next_seq_num,
15982              shift_prior_seq_num,
15983              shift_next_date,
15984              shift_prior_date,
15985              2,
15986              p_instance_id
15987            );
15988 
15989      END LOOP;
15990 
15991       /* B2213101 - End of changes for  Insert into msc_st_shift_dates */
15992 
15993   END IF ; /*  End if for usage */
15994 
15995   return_status := TRUE;
15996 
15997 EXCEPTION
15998    WHEN NO_DATA_FOUND THEN
15999     log_message('Calendar has no days set in the Calendar Detail : '||p_calendar_no);
16000     log_message('stmt_no = ' || stmt_no || '--' || sqlerrm);
16001     return_status := FALSE;
16002 
16003    WHEN OTHERS THEN
16004     log_message('Error in retrieve Calendar Detail : ' || sqlerrm);
16005     return_status := FALSE;
16006 
16007 END retrieve_calendar_detail;
16008 
16009 /*
16010 REM+==========================================================================+
16011 REM| PROCEDURE NAME                                                           |
16012 REM|    net_rsrc_insert                                                       |
16013 REM|                                                                          |
16014 REM| Type                                                                     |
16015 REM|    public                                                                |
16016 REM|                                                                          |
16017 REM| DESCRIPTION                                                              |
16018 REM|                                                                          |
16019 REM|                                                                          |
16020 REM| Input Parameters                                                         |
16021 REM|    p_org_id - Organization id                                            |
16022 REM|    p_orgn_code - Orgn Code                                               |
16023 REM|    p_calendar_id - calendar_id                                           |
16024 REM|    p_instance_id - Instance Id                                           |
16025 REM|    p_usage - Used foir APS or WPS                                        |
16026 REM|    p_db_link - Data Base Link                                            |
16027 REM|                                                                          |
16028 REM| Output Parameters                                                        |
16029 REM|    return_status                                                         |
16030 REM|                                                                          |
16031 REM| HISTORY                                                                  |
16032 REM|    Created on 4th Jan 2002 By Rajesh Patangya                            |
16033 REM|    7th Mar 2003 -- Performance issue fix and B2671540 00:00 shift fix    |
16034 REM| B3161696 - 26-SEP-2003 TARGETTED RESOURCE AVAILABILITY PLACEHOLDER BUG   |
16035 REM| B4309093 - 20-APR-2005 Modified code to TO ADD TIME OR A SHIFT TO A      |
16036 REM|                        PLANT RESOURCE                                    |
16037 REM+==========================================================================+
16038 */
16039 PROCEDURE net_rsrc_insert(p_org_id         IN PLS_INTEGER,
16040                           p_orgn_code      IN VARCHAR2,
16041                           p_simulation_set IN VARCHAR2,
16042                           p_db_link        IN VARCHAR2,
16043                           p_instance_id    IN PLS_INTEGER,
16044                           p_run_date       IN DATE ,
16045                           p_calendar_id    IN PLS_INTEGER,
16046                           p_usage          IN VARCHAR2,
16047                           return_status    OUT NOCOPY BOOLEAN) IS
16048 
16049 ri_shift_interval	ref_cursor_typ;
16050 
16051 gsql_stmt		varchar2(10000) ;
16052 sql_stmt1		varchar2(32700) ;
16053 sql_shifts 		varchar2(32700) ;
16054 i         		INTEGER ;
16055 j         		INTEGER ;
16056 g_calendar_id 		PLS_INTEGER  ;
16057 
16058     /* B3347284, Performance Issue */
16059 first_index             NUMBER ;
16060 last_index              NUMBER ;
16061 end_index               NUMBER ;
16062 first_in                NUMBER ;
16063 last_in                 NUMBER ;
16064 
16065 TYPE rsrc_cnt IS TABLE OF cr_rsrc_dtl.assigned_qty%TYPE;
16066 resource_count rsrc_cnt ;
16067 
16068 TYPE rsrc_id  IS TABLE OF cr_rsrc_dtl.resource_id%TYPE;
16069 resource_id   rsrc_id ;
16070 
16071 TYPE inst_id  IS TABLE OF gmp_resource_instances.instance_id%TYPE;
16072 instance_id   inst_id ;
16073 
16074 TYPE inst_num  IS TABLE OF gmp_resource_instances.instance_number%TYPE;
16075 instance_number inst_num ;
16076 
16077 /* B3482001 - taking shift number from gmp_calendar_detail_gtmp */
16078 TYPE shift_no  IS TABLE OF gmp_calendar_detail_gtmp.shift_num%TYPE;
16079 shift_num  shift_no ;
16080 
16081 TYPE f_dt   IS TABLE OF bom_shift_dates.shift_date%TYPE;
16082 f_date f_dt ;
16083 
16084 TYPE t_dt   IS TABLE OF bom_shift_dates.shift_date%TYPE;
16085 t_date t_dt ;
16086 
16087 BEGIN
16088          /* 8i Database does not support BULK COLLECT - B3881832 */
16089   gsql_stmt	 := NULL;
16090   sql_stmt1	 := NULL;
16091   sql_shifts := NULL;
16092   stmt_no	   := 0;
16093   i     		 := 1;
16094   j     		 := 1;
16095   first_index           := 0 ;
16096   last_index            := 0 ;
16097   end_index             := 0 ;
16098   first_in              := 0 ;
16099   last_in               := 0 ;
16100 
16101 log_message(' net_rsrc_insert called '||p_org_id||'**'||p_orgn_code||'**'||
16102            p_simulation_set||'**'||p_db_link||'**'||p_instance_id
16103            ||'**'||p_calendar_id||'**'||p_usage);
16104 
16105          stmt_no := 72;
16106          -- Rajesh Patangya B4692705, When the calendar is not assigned to
16107          -- resource then organization calendar should be considered
16108 	       g_calendar_id 	:= 0 ;
16109          gsql_stmt :=  '  SELECT mfg_calendar_id '
16110                     || '  FROM  sy_orgn_mst'||p_db_link
16111                     || '  WHERE orgn_code = :orgn_code1 ';
16112 
16113          EXECUTE IMMEDIATE gsql_stmt INTO g_calendar_id USING p_orgn_code ;
16114 
16115          IF g_calendar_id = 0 THEN
16116             log_message('Warning : '||p_orgn_code||
16117                     ' does not have manufacturing calendar, continuing ...') ;
16118          END IF;
16119 
16120     /* Interval Cursor gives the all the point of inflections  */
16121 
16122        stmt_no := 73;
16123        -- HW B4309093 Check for calendar id in cr_rsrc_dtl
16124        sql_stmt1 :=  ' SELECT /*+ ALL_ROWS DRIVING_SITE (rt) */ '
16125                   || ' 	decode(rt.interval_date,rt.lead_idate,rt.assigned_qty,decode(rt.rsum,0,rt.assigned_qty,rt.assigned_qty-rt.rsum)) resource_count  '
16126                   || ' 	,rt.resource_id '
16127                   || ' 	,0 instance_id '
16128                   || ' 	,0 instance_number '
16129                   || ' 	,rt.shift_num '
16130                   || ' 	,rt.interval_date	from_date  '
16131                   || ' 	,rt.lead_idate		to_date '
16132                   || ' FROM '
16133                   || ' ( '
16134                   || ' SELECT '
16135                   || ' 	t.resource_id '
16136                   || ' 	,t.shift_num  '
16137                   || ' 	,t.interval_date '
16138                   || ' 	,t.assigned_qty  '
16139                   || ' 	,nvl(sum(u.resource_units),0) rsum  '
16140                   || ' 	,max(t.lead_idate) lead_idate '
16141                   || ' FROM '
16142                   || ' ( '
16143                   || ' SELECT unique resource_id,instance_number,from_date, '
16144                   || ' to_date to_date1,resource_units '
16145                   || ' FROM ( '
16146                   || ' SELECT un.resource_id, '
16147                   || '        gri.instance_number, '
16148                   || '        un.from_date,  '
16149                   || '        un.to_date,    '
16150                   || '        1 resource_units'
16151                   || ' FROM   cr_rsrc_dtl '||p_db_link||'  crd, '
16152                   || '        gmp_rsrc_unavail_dtl_v '||p_db_link||' un, '
16153                   || '        gmp_resource_instances '||p_db_link||' gri '
16154                   || ' WHERE  crd.resource_id = un.resource_id  '
16155                   || ' AND    crd.resource_id = gri.resource_id  '
16156                   || ' AND    un.instance_id  = gri.instance_id  '
16157                   || ' AND    crd.orgn_code = :orgn_code ' ;
16158 
16159     IF (p_usage = 'BASED') THEN   /* Usage APS */
16160     sql_stmt1 := sql_stmt1
16161                   || ' AND    crd.calendar_id = :l_cal_id ' ;
16162     ELSE
16163     sql_stmt1 := sql_stmt1
16164                   || ' AND    nvl(crd.calendar_id,:g_default_cal_id)=:l_cal_id';
16165     END IF ;
16166 
16167     sql_stmt1 := sql_stmt1
16168                   || ' AND    crd.schedule_ind = 2 '
16169                   || ' AND    crd.delete_mark = 0 ' ;
16170 
16171     IF (v_from_rsrc IS NOT NULL AND v_to_rsrc IS NOT NULL) THEN
16172     sql_stmt1 := sql_stmt1 || '  AND crd.resources BETWEEN :frsrc and :trsrc ' ;
16173     END IF ;
16174 
16175 -- HW B4309093 Check for calendar id in cr_rsrc_dtl
16176     sql_stmt1 := sql_stmt1
16177                   || ' AND    nvl(un.instance_id,0) <> 0  '
16178                   || ' UNION ALL '
16179                   || ' SELECT un.resource_id, '
16180                   || '        gri.instance_number, '
16181                   || '        un.from_date,  '
16182                   || '        un.to_date,    '
16183                   || '        1 resource_units'
16184                   || ' FROM   cr_rsrc_dtl '||p_db_link||'  crd, '
16185                   || '        gmp_rsrc_unavail_dtl_v '||p_db_link||' un, '
16186                   || '        gmp_resource_instances '||p_db_link||' gri '
16187                   || ' WHERE  crd.resource_id = un.resource_id  '
16188                   || ' AND    crd.resource_id = gri.resource_id  '
16189                   || ' AND    crd.orgn_code = :orgn_code1 ' ;
16190 
16191     IF (p_usage = 'BASED') THEN   /* Usage APS */
16192     sql_stmt1 := sql_stmt1
16193                   || ' AND    crd.calendar_id = :l_cal_id1 ' ;
16194     ELSE
16195     sql_stmt1 := sql_stmt1
16196                   || ' AND    nvl(crd.calendar_id ,:g_default_cal_id1)= :l_cal_id1 ';
16197     END IF ;
16198     sql_stmt1 := sql_stmt1
16199                   || ' AND    crd.delete_mark = 0 '
16200                   || ' AND    crd.schedule_ind = 2 '
16201                   || ' AND    nvl(un.instance_id,0) = 0  ' ;
16202 
16203     IF (v_from_rsrc IS NOT NULL AND v_to_rsrc IS NOT NULL) THEN
16204     sql_stmt1 := sql_stmt1 || '  AND crd.resources BETWEEN :frsrc and :trsrc ' ;
16205     END IF ;
16206 
16207 -- HW B4309093 Check for calendar id in cr_rsrc_dtl
16208     sql_stmt1 := sql_stmt1
16209                   || ' AND    gri.instance_number in '
16210                   || '      ( select tgri.instance_number '
16211                   || '      FROM gmp_resource_instances '||p_db_link||' tgri '
16212                   || '      WHERE tgri.resource_id = crd.resource_id '
16213                   || '      AND rownum <= un.resource_units '
16214                   || '      ) '
16215                   || ' UNION ALL  '
16216                   || ' SELECT un.resource_id, '
16217                   || '        0 instance_number,  '
16218                   || '        un.from_date,  '
16219                   || '        un.to_date,    '
16220                   || '        un.resource_units '
16221                   || ' FROM   cr_rsrc_dtl '||p_db_link||'  crd, '
16222                   || '        gmp_rsrc_unavail_dtl_v ' ||p_db_link||'  un'
16223                   || ' WHERE  crd.resource_id = un.resource_id  '
16224                   || ' AND    crd.orgn_code = :orgn_code2 ' ;
16225 
16226     IF (p_usage = 'BASED') THEN   /* Usage APS */
16227     sql_stmt1 := sql_stmt1
16228                   || ' AND    crd.calendar_id = :l_cal_id2 ' ;
16229     ELSE
16230     sql_stmt1 := sql_stmt1
16231                   || ' AND    nvl(crd.calendar_id ,:g_default_cal_id2)= :l_cal_id2 ' ;
16232     END IF;
16233     sql_stmt1 := sql_stmt1
16234                   || ' AND    crd.delete_mark = 0 ' ;
16235 
16236     IF (v_from_rsrc IS NOT NULL AND v_to_rsrc IS NOT NULL) THEN
16237     sql_stmt1 := sql_stmt1 || '  AND crd.resources BETWEEN :frsrc and :trsrc ' ;
16238     END IF ;
16239 
16240 -- HW B4309093 Check for calendar id in cr_rsrc_dtl
16241     sql_stmt1 := sql_stmt1
16242                   || ' AND NOT EXISTS '
16243                   || ' (SELECT 1 '
16244                   || '  FROM gmp_resource_instances  ' ||p_db_link||' gri '
16245                   || '  WHERE gri.resource_id = un.resource_id ) '
16246                   || ' ) '
16247                   || ' ) u, '
16248                   || ' 	( '
16249                   || ' 	SELECT resource_id,shift_num,interval_date, '
16250                   || '          assigned_qty,lead_idate '
16251                   || ' 	FROM '
16252                   || ' 		( '
16253                   || ' 	        SELECT resource_id,shift_num,interval_date, '
16254                   || '                 assigned_qty '
16255                   || ' 			,lead(resource_id,1) over(order by '
16256                   || '  resource_id,interval_date,shift_num) as lead_rid '
16257                   || ' 			,lead(interval_date,1) over(order by '
16258                   || '  resource_id,interval_date,shift_num) as lead_idate '
16259                   || ' 			,lead(shift_num,1) over(order by '
16260                   || '  resource_id,interval_date,shift_num) as lead_snum '
16261                   || ' 		FROM '
16262                   || ' 			( '
16263                   || ' SELECT unique cmd.resource_id, '
16264                   || ' 0 , '
16265                   || ' exp.shift_num, '
16266                   || ' 0 , '
16267                   || ' cmd.interval_date, '
16268                   || ' cmd.assigned_qty '
16269                   || ' FROM ( '
16270                   || ' SELECT un.resource_id resource_id, '
16271                   || '        gri.instance_number instance_number,'
16272                   || '        0 shift_num,'
16273                   || '        0 resource_count,'
16274                   || '        un.from_date interval_date, '
16275                   || '        crd.assigned_qty assigned_qty '
16276                   || ' FROM   cr_rsrc_dtl '||p_db_link||'  crd, '
16277                   || '        gmp_rsrc_unavail_dtl_v '||p_db_link||' un, '
16278                   || '        gmp_resource_instances '||p_db_link||' gri '
16279                   || ' WHERE  crd.resource_id = un.resource_id  '
16280                   || ' AND    crd.resource_id = gri.resource_id  '
16281                   || ' AND    un.instance_id  = gri.instance_id  '
16282                   || ' AND    crd.orgn_code = :orgn_code1 ' ;
16283 
16284     IF (p_usage = 'BASED') THEN   /* Usage APS */
16285     sql_stmt1 := sql_stmt1
16286                   || ' AND    crd.calendar_id = :l_cal_id2 ' ;
16287     ELSE
16288     sql_stmt1 := sql_stmt1
16289                   || ' AND    nvl(crd.calendar_id ,:g_default_cal_id4)= :l_cal_id4 ' ;
16290     END IF;
16291 
16292     sql_stmt1 := sql_stmt1
16293                   || ' AND    crd.schedule_ind = 2 '
16294                   || ' AND    crd.delete_mark = 0 '
16295                   || ' AND    nvl(un.instance_id,0) <> 0  ' ;
16296 
16297     IF (v_from_rsrc IS NOT NULL AND v_to_rsrc IS NOT NULL) THEN
16298     sql_stmt1 := sql_stmt1 || '  AND crd.resources BETWEEN :frsrc and :trsrc ' ;
16299     END IF ;
16300 
16301 -- HW B4309093 Check for calendar id in cr_rsrc_dtl
16302     sql_stmt1 := sql_stmt1
16303                   || ' UNION ALL '
16304                   || ' SELECT un.resource_id resource_id, '
16305                   || '        gri.instance_number instance_number,'
16306                   || '        0 shift_num,'
16307                   || '        0 resource_count,'
16308                   || '        un.to_date interval_date, '
16309                   || '        crd.assigned_qty assigned_qty '
16310                   || ' FROM   cr_rsrc_dtl '||p_db_link||'  crd, '
16311                   || '        gmp_rsrc_unavail_dtl_v '||p_db_link||' un, '
16312                   || '        gmp_resource_instances '||p_db_link||' gri '
16313                   || ' WHERE  crd.resource_id = un.resource_id  '
16314                   || ' AND    crd.resource_id = gri.resource_id  '
16315                   || ' AND    un.instance_id  = gri.instance_id  '
16316                   || ' AND    crd.orgn_code = :orgn_code2 ' ;
16317 
16318     IF (p_usage = 'BASED') THEN   /* Usage APS */
16319     sql_stmt1 := sql_stmt1
16320                   || ' AND    crd.calendar_id = :l_cal_id2 ' ;
16321     ELSE
16322     sql_stmt1 := sql_stmt1
16323                   || ' AND    nvl(crd.calendar_id ,:g_default_cal_id5)= :l_cal_id5 ' ;
16324     END IF;
16325 
16326     sql_stmt1 := sql_stmt1
16327                   || ' AND    crd.schedule_ind = 2 '
16328                   || ' AND    crd.delete_mark = 0 '
16329                   || ' AND    nvl(un.instance_id,0) <> 0  ' ;
16330 
16331     IF (v_from_rsrc IS NOT NULL AND v_to_rsrc IS NOT NULL) THEN
16332     sql_stmt1 := sql_stmt1 || '  AND crd.resources BETWEEN :frsrc and :trsrc ' ;
16333     END IF ;
16334 
16335 -- HW B4309093 Check for calendar id in cr_rsrc_dtl
16336     sql_stmt1 := sql_stmt1
16337                   || ' UNION ALL '
16338                   || ' SELECT un.resource_id resource_id, '
16339                   || '        gri.instance_number instance_number,'
16340                   || '        0 shift_num,'
16341                   || '        0 resource_count,'
16342                   || '        un.from_date interval_date, '
16343                   || '        crd.assigned_qty assigned_qty '
16344                   || ' FROM   cr_rsrc_dtl '||p_db_link||'  crd, '
16345                   || '        gmp_rsrc_unavail_dtl_v '||p_db_link||' un, '
16346                   || '        gmp_resource_instances '||p_db_link||' gri '
16347                   || ' WHERE  crd.resource_id = un.resource_id  '
16348                   || ' AND    crd.resource_id = gri.resource_id  '
16349                   || ' AND    crd.orgn_code = :orgn_code3 ' ;
16350 
16351     IF (p_usage = 'BASED') THEN   /* Usage APS */
16352     sql_stmt1 := sql_stmt1
16353                   || ' AND    crd.calendar_id = :l_cal_id2 ' ;
16354     ELSE
16355     sql_stmt1 := sql_stmt1
16356                   || ' AND    nvl(crd.calendar_id ,:g_default_cal_id6)= :l_cal_id6 ' ;
16357     END IF;
16358 
16359     sql_stmt1 := sql_stmt1
16360                   || ' AND    crd.schedule_ind = 2 '
16361                   || ' AND    crd.delete_mark = 0 '
16362                   || ' AND    nvl(un.instance_id,0) = 0  ' ;
16363 
16364     IF (v_from_rsrc IS NOT NULL AND v_to_rsrc IS NOT NULL) THEN
16365     sql_stmt1 := sql_stmt1 || '  AND crd.resources BETWEEN :frsrc and :trsrc ' ;
16366     END IF ;
16367 
16368 -- HW B4309093 Check for calendar id in cr_rsrc_dtl
16369     sql_stmt1 := sql_stmt1
16370                   || ' AND    gri.instance_number in '
16371                   || '      ( select tgri.instance_number '
16372                   || '      FROM gmp_resource_instances '||p_db_link||' tgri '
16373                   || '      WHERE tgri.resource_id = crd.resource_id '
16374                   || '      AND rownum <= un.resource_units '
16375                   || '      ) '
16376                   || ' UNION ALL '
16377                   || ' SELECT un.resource_id resource_id, '
16378                   || '        gri.instance_number instance_number,'
16379                   || '        0 shift_num,'
16380                   || '        0 resource_count,'
16381                   || '        un.to_date interval_date, '
16382                   || '        crd.assigned_qty assigned_qty '
16383                   || ' FROM   cr_rsrc_dtl '||p_db_link||'  crd, '
16384                   || '        gmp_rsrc_unavail_dtl_v '||p_db_link||' un, '
16385                   || '        gmp_resource_instances '||p_db_link||' gri '
16386                   || ' WHERE  crd.resource_id = un.resource_id  '
16387                   || ' AND    crd.resource_id = gri.resource_id  '
16388                   || ' AND    crd.orgn_code = :orgn_code4 ' ;
16389 
16390     IF (p_usage = 'BASED') THEN   /* Usage APS */
16391     sql_stmt1 := sql_stmt1
16392                   || ' AND    crd.calendar_id = :l_cal_id2 ' ;
16393     ELSE
16394     sql_stmt1 := sql_stmt1
16395                   || ' AND    nvl(crd.calendar_id ,:g_default_cal_id7)= :l_cal_id7 ';
16396     END IF ;
16397 
16398     sql_stmt1 := sql_stmt1
16399                   || ' AND    crd.delete_mark = 0 '
16400                   || ' AND    crd.schedule_ind = 2 '
16401                   || ' AND    nvl(un.instance_id,0) = 0  ' ;
16402 
16403     IF (v_from_rsrc IS NOT NULL AND v_to_rsrc IS NOT NULL) THEN
16404     sql_stmt1 := sql_stmt1 || '  AND crd.resources BETWEEN :frsrc and :trsrc ' ;
16405     END IF ;
16406 
16407     sql_stmt1 := sql_stmt1
16408                   || ' AND    gri.instance_number in '
16409                   || '      ( select tgri.instance_number '
16410                   || '      FROM gmp_resource_instances '||p_db_link||' tgri '
16411                   || '      WHERE tgri.resource_id = crd.resource_id '
16412                   || '      AND rownum <= un.resource_units '
16413                   || '      ) '
16414                   || ' UNION ALL '
16415                   || ' SELECT un.resource_id, '
16416                   || '        0 instance_number,  '
16417                   || '        0 shift_num,'
16418                   || '        0 resource_count,'
16419                   || '        un.from_date interval_date, '
16420                   || '        crd.assigned_qty assigned_qty '
16421                   || ' FROM   cr_rsrc_dtl '||p_db_link||'  crd, '
16422                   || '        gmp_rsrc_unavail_dtl_v '||p_db_link||' un '
16423                   || ' WHERE  crd.resource_id = un.resource_id  '
16424                   || ' AND    crd.orgn_code = :orgn_code44 ' ;
16425 
16426     IF (p_usage = 'BASED') THEN   /* Usage APS */
16427     sql_stmt1 := sql_stmt1
16428                   || ' AND    crd.calendar_id = :l_cal_id2 ' ;
16429     ELSE
16430     sql_stmt1 := sql_stmt1
16431                   || ' AND    nvl(crd.calendar_id ,:g_default_cal_id8)= :l_cal_id8 ' ;
16432     END IF;
16433 
16434     sql_stmt1 := sql_stmt1
16435                   || ' AND    crd.delete_mark = 0 ' ;
16436 
16437     IF (v_from_rsrc IS NOT NULL AND v_to_rsrc IS NOT NULL) THEN
16438     sql_stmt1 := sql_stmt1 || '  AND crd.resources BETWEEN :frsrc and :trsrc ' ;
16439     END IF ;
16440 
16441 -- HW B4309093 Check for calendar id in cr_rsrc_dtl
16442     sql_stmt1 := sql_stmt1
16443                   || ' AND NOT EXISTS '
16444                   || '       (SELECT 1 '
16445                   || '        FROM gmp_resource_instances '||p_db_link||' gri '
16446                   || '        WHERE gri.resource_id = un.resource_id ) '
16447                   || ' UNION ALL '
16448                   || ' SELECT un.resource_id, '
16449                   || '        0 instance_number,  '
16450                   || '        0 shift_num,'
16451                   || '        0 resource_count,'
16452                   || '        un.to_date interval_date, '
16453                   || '        crd.assigned_qty assigned_qty '
16454                   || ' FROM   cr_rsrc_dtl '||p_db_link||'  crd, '
16455                   || '        gmp_rsrc_unavail_dtl_v '||p_db_link||' un '
16456                   || ' WHERE  crd.resource_id = un.resource_id  '
16457                   || ' AND    crd.orgn_code = :orgn_code444 ' ;
16458 
16459     IF (p_usage = 'BASED') THEN   /* Usage APS */
16460     sql_stmt1 := sql_stmt1
16461                   || ' AND    crd.calendar_id = :l_cal_id2 ' ;
16462     ELSE
16463     sql_stmt1 := sql_stmt1
16464                   || ' AND    nvl(crd.calendar_id ,:g_default_cal_id9)= :l_cal_id9 ' ;
16465     END IF;
16466 
16467     sql_stmt1 := sql_stmt1
16468                   || ' AND    crd.delete_mark = 0 ' ;
16469 
16470     IF (v_from_rsrc IS NOT NULL AND v_to_rsrc IS NOT NULL) THEN
16471     sql_stmt1 := sql_stmt1 || '  AND crd.resources BETWEEN :frsrc and :trsrc ' ;
16472     END IF ;
16473 
16474     sql_stmt1 := sql_stmt1
16475                   || ' AND NOT EXISTS '
16476                   || '       (SELECT 1 '
16477                   || '        FROM gmp_resource_instances '||p_db_link||' gri '
16478                   || '        WHERE gri.resource_id = un.resource_id ) '
16479                   || '    )   cmd,  '
16480                   || '        gmp_calendar_detail_gtmp ' ||p_db_link||' exp  '
16481                   || '      WHERE  exp.calendar_id = :curr_cal1 '
16482                   || '        AND  cmd.interval_date  BETWEEN '
16483                   || '             exp.from_date AND exp.to_date '
16484                   || ' UNION ALL '
16485                   || ' SELECT crd.resource_id , '
16486                   || '        0 , '
16487                   || '        exp.shift_num,  '
16488                   || '        0 , '
16489                   || '        exp.from_date interval_date, '
16490                   || '        crd.assigned_qty assigned_qty '
16491                   || ' FROM   cr_rsrc_dtl '||p_db_link||'  crd, '
16492                   || '        gmp_calendar_detail_gtmp ' ||p_db_link||' exp  '
16493                   || ' WHERE  crd.orgn_code = :orgn_code5 ' ;
16494 
16495     IF (p_usage = 'BASED') THEN   /* Usage APS */
16496     sql_stmt1 := sql_stmt1
16497                   || ' AND    crd.calendar_id = :l_cal_id2 ' ;
16498     ELSE
16499     sql_stmt1 := sql_stmt1
16500                   || ' AND    nvl(crd.calendar_id ,:g_default_cal_id10)= :l_cal_id10 ' ;
16501     END IF;
16502 
16503     sql_stmt1 := sql_stmt1
16504                   || ' AND    crd.delete_mark = 0 ' ;
16505 
16506     IF (v_from_rsrc IS NOT NULL AND v_to_rsrc IS NOT NULL) THEN
16507     sql_stmt1 := sql_stmt1 || '  AND crd.resources BETWEEN :frsrc and :trsrc ' ;
16508     END IF ;
16509 
16510 -- HW B4309093 Check for calendar id in cr_rsrc_dtl
16511     sql_stmt1 := sql_stmt1
16512                   || ' AND    exp.calendar_id = :curr_cal2 '
16513                   || ' UNION ALL '
16514                   || ' SELECT crd.resource_id , '
16515                   || '        0 , '
16516                   || '        exp.shift_num,  '
16517                   || '        0 , '
16518                   || '        exp.to_date interval_date, '
16519                   || '        crd.assigned_qty assigned_qty '
16520                   || ' FROM   cr_rsrc_dtl '||p_db_link||'  crd, '
16521                   || '        gmp_calendar_detail_gtmp ' ||p_db_link||' exp  '
16522                   || ' WHERE  crd.orgn_code = :orgn_code6 ' ;
16523 
16524     IF (p_usage = 'BASED') THEN   /* Usage APS */
16525     sql_stmt1 := sql_stmt1
16526                   || ' AND    crd.calendar_id = :l_cal_id2 ' ;
16527     ELSE
16528     sql_stmt1 := sql_stmt1
16529                   || ' AND    nvl(crd.calendar_id ,:g_default_cal_id11)= :l_cal_id11 ' ;
16530     END IF;
16531 
16532     sql_stmt1 := sql_stmt1
16533                   || ' AND    crd.delete_mark = 0 ' ;
16534 
16535     IF (v_from_rsrc IS NOT NULL AND v_to_rsrc IS NOT NULL) THEN
16536     sql_stmt1 := sql_stmt1 || '  AND crd.resources BETWEEN :frsrc and :trsrc ' ;
16537     END IF ;
16538 
16539     sql_stmt1 := sql_stmt1
16540                   || ' AND    exp.calendar_id = :curr_cal3 '
16541                   || ' 			) '
16542                   || ' 		) '
16543                   || ' 	WHERE '
16544                   || ' 		resource_id = lead_rid '
16545                   || ' 	    AND trunc(interval_date) = trunc(lead_idate) '
16546                   || ' 	    AND interval_date < lead_idate '
16547                   || ' 	    AND shift_num = lead_snum  '
16548                   || ' 	) t '
16549                   || ' WHERE '
16550                   || ' 	    t.interval_date >= u.from_date(+) '
16551                   || '  AND t.lead_idate <= u.to_date1 (+) '
16552                   || ' 	AND t.resource_id = u.resource_id(+) '
16553                   || ' GROUP BY '
16554                   || ' 	 t.resource_id '
16555                   || ' 	,t.shift_num '
16556                   || ' 	,t.interval_date '
16557                   || ' 	,t.assigned_qty '
16558                   || ' ) rt '
16559                   || ' WHERE '
16560                   || ' 	(rt.interval_date = rt.lead_idate OR rt.rsum=0) '
16561                   || ' 	OR '
16562                   || ' 	(    rt.interval_date <> rt.lead_idate '
16563                   || '   AND rt.rsum <> 0 '
16564                   || '   AND rt.assigned_qty>rsum) '
16565                   || ' ORDER BY 2,6,5 ';
16566 
16567 log_message(' ri_shift_interval Sql statement = '||sql_stmt1);
16568 
16569     IF (v_from_rsrc IS NOT NULL AND v_to_rsrc IS NOT NULL) THEN
16570 -- HW B4309093 Pass correct parameters
16571     OPEN ri_shift_interval FOR sql_stmt1 USING
16572            p_orgn_code,p_calendar_id,p_calendar_id, V_FROM_RSRC, V_TO_RSRC ,
16573            p_orgn_code,p_calendar_id,p_calendar_id, V_FROM_RSRC, V_TO_RSRC ,
16574            p_orgn_code,p_calendar_id,p_calendar_id, V_FROM_RSRC, V_TO_RSRC ,
16575            p_orgn_code,p_calendar_id,p_calendar_id, V_FROM_RSRC, V_TO_RSRC ,
16576            p_orgn_code,p_calendar_id,p_calendar_id, V_FROM_RSRC, V_TO_RSRC ,
16577            p_orgn_code,p_calendar_id,p_calendar_id, V_FROM_RSRC, V_TO_RSRC ,
16578            p_orgn_code,p_calendar_id,p_calendar_id, V_FROM_RSRC, V_TO_RSRC ,
16579            p_orgn_code,p_calendar_id,p_calendar_id, V_FROM_RSRC, V_TO_RSRC ,
16580            p_orgn_code,p_calendar_id,p_calendar_id, V_FROM_RSRC, V_TO_RSRC ,
16581            p_calendar_id ,
16582            p_orgn_code,p_calendar_id,p_calendar_id, V_FROM_RSRC, V_TO_RSRC ,
16583            p_calendar_id ,
16584            p_orgn_code,p_calendar_id,p_calendar_id, V_FROM_RSRC, V_TO_RSRC ,
16585            p_calendar_id  ;
16586 
16587     ELSE
16588 
16589 -- HW B4309093 Pass correct parameters
16590       IF (p_usage = 'BASED') THEN   /* Usage APS */
16591        OPEN ri_shift_interval FOR sql_stmt1 USING
16592                 p_orgn_code,p_calendar_id,
16593 		p_orgn_code,p_calendar_id,
16594 		p_orgn_code,p_calendar_id,
16595                 p_orgn_code,p_calendar_id,
16596 		p_orgn_code,p_calendar_id,
16597                 p_orgn_code,p_calendar_id,
16598 		p_orgn_code,p_calendar_id,
16599                 p_orgn_code,p_calendar_id,
16600 		p_orgn_code,p_calendar_id, p_calendar_id,
16601                 p_orgn_code,p_calendar_id, p_calendar_id,
16602                 p_orgn_code,p_calendar_id, p_calendar_id ;
16603 
16604       ELSE
16605        OPEN ri_shift_interval FOR sql_stmt1 USING
16606                 p_orgn_code,g_calendar_id,p_calendar_id,
16607 		p_orgn_code,g_calendar_id,p_calendar_id,
16608 		p_orgn_code,g_calendar_id,p_calendar_id,
16609                 p_orgn_code,g_calendar_id,p_calendar_id,
16610 		p_orgn_code,g_calendar_id,p_calendar_id,
16611                 p_orgn_code,g_calendar_id,p_calendar_id,
16612 		p_orgn_code,g_calendar_id,p_calendar_id,
16613                 p_orgn_code,g_calendar_id,p_calendar_id,
16614 		p_orgn_code,g_calendar_id,p_calendar_id,
16615                 p_calendar_id,
16616                 p_orgn_code, g_calendar_id,p_calendar_id,
16617 		p_calendar_id,
16618                 p_orgn_code, g_calendar_id,p_calendar_id,
16619 		p_calendar_id ;
16620       END IF ;
16621     END IF;
16622 
16623     /* B3347284, Performance Issue */
16624     stmt_no := 73;
16625     LOOP
16626        FETCH ri_shift_interval BULK COLLECT INTO resource_count, resource_id,
16627              instance_id, instance_number, shift_num, f_date, t_date ;
16628        EXIT WHEN ri_shift_interval%NOTFOUND;
16629     END LOOP ;
16630     CLOSE ri_shift_interval;
16631 
16632     stmt_no := 74;
16633     IF (resource_id.FIRST > 0) THEN    /* Only if any resource */
16634 
16635        first_index :=  resource_id.FIRST ;
16636        last_index  :=  resource_id.LAST ;
16637        end_index   := ceil(last_index/50000) ;
16638 
16639        first_in  := first_index ;
16640        last_in   := 50000 ;
16641 
16642         IF last_index >=  last_in THEN
16643           NULL ;
16644         ELSE
16645          last_in := last_index ;
16646         END IF;
16647 
16648      FOR j IN first_index..end_index LOOP
16649 
16650        IF ((p_usage = 'APS') OR (p_usage = 'BASED')) THEN /* Usage APS/BASED */
16651 
16652         FORALL i IN first_in..last_in
16653           INSERT INTO msc_st_net_resource_avail
16654             ( organization_id,
16655               sr_instance_id,
16656               resource_id,
16657               department_id,
16658               simulation_set,
16659               shift_num,
16660               shift_date,
16661               from_time,
16662               to_time,
16663               capacity_units,
16664               deleted_flag
16665               )
16666            VALUES
16667             ( p_org_id,
16668               p_instance_id,
16669               ((resource_id(i) * 2) + 1), /* B1177070 */
16670               ((p_org_id * 2) + 1),  /* B1177070 encoded key */
16671               p_simulation_set,
16672               shift_num(i),
16673               trunc(f_date(i)),
16674               ((f_date(i) - trunc(f_date(i))) * 86400 ),
16675               ((t_date(i) - trunc(t_date(i))) * 86400 ),
16676               resource_count(i),
16677               2
16678               );
16679 
16680        ELSIF (p_usage = 'WPS') THEN   /* Usage WPS     */
16681 
16682         FORALL i IN first_in..last_in
16683          INSERT INTO gmp_resource_avail
16684          (
16685           instance_id, plant_code, resource_id,
16686           calendar_id, resource_instance_id, shift_num,
16687           shift_date, from_time, to_time,
16688           resource_units, creation_date, created_by,
16689           last_update_date, last_updated_by, last_update_login
16690          )  VALUES
16691          (
16692             p_instance_id,
16693             p_orgn_code,
16694             resource_id(i),
16695             p_calendar_id,
16696             instance_id(i),
16697             shift_num(i),
16698             trunc(f_date(i)),
16699             ((f_date(i) - trunc(f_date(i))) * 86400 ),
16700             ((t_date(i) - trunc(t_date(i))) * 86400 ),
16701             resource_count(i),
16702             sysdate,
16703             FND_GLOBAL.USER_ID,
16704             sysdate,
16705             FND_GLOBAL.USER_ID,
16706             FND_GLOBAL.USER_ID
16707           )           ;
16708 
16709        END IF;   /* APS or WPS */
16710 
16711         first_in  := last_in + 1;
16712         last_in   := last_in + 50000 ;
16713 
16714         IF last_index >=  last_in THEN
16715           NULL ;
16716         ELSE
16717          last_in := last_index ;
16718         END IF;
16719 
16720     -- B5083216, commit ends the session, if called remotely
16721     -- COMMIT;                 /* Save remaining records */
16722      END LOOP ;
16723 
16724     END IF;   /* Only if any resource */
16725 
16726  /* Bug: 6030499 Vpedarla added session pga memory */
16727 
16728     SELECT st.VALUE INTO v_dummy from V$MYSTAT st, V$STATNAME sn
16729     where st.STATISTIC# = sn.STATISTIC#
16730     and sn.NAME in ('session pga memory');
16731     log_message('ri_shift_interval Session pga memory = ' || TO_CHAR(v_dummy) );
16732 
16733     /* Insert for msc_st_resource_shifts Starts here - 2213101 */
16734     -- PK Bug 6330140 Modified query to remove ic_whse_mst to eliminate cartesian product
16735        stmt_no := 80;
16736        sql_shifts := '  INSERT INTO msc_st_resource_shifts '
16737             || '  ( department_id,                  '
16738             || '  shift_num,                      '
16739             || '  resource_id,                    '
16740             || '  deleted_flag,                   '
16741             || '  sr_instance_id,                 '
16742             || '  capacity_units                  '
16743             || '  )                                 '
16744             || ' SELECT /*+ DRIVING_SITE(gtmp) DRIVING_SITE(som) DRIVING_SITE(crd) */ unique '
16745             || '  ((:org_id*2)+1) organization_id, '
16746             || '  gtmp.shift_num,            '
16747             || '  ((crd.resource_id*2)+1),  '
16748             || '  2,                        '
16749             || '  :instance_id,             '
16750             || '  crd.assigned_qty          '
16751             || ' FROM gmp_calendar_detail_gtmp'||p_db_link||'  gtmp, '
16752             || '      sy_orgn_mst'||p_db_link||'  som,   '
16753             || '      cr_rsrc_dtl'||p_db_link||'  crd   '
16754             || ' WHERE gtmp.calendar_id = :curr_cal_id   '
16755             || ' AND NVL(crd.calendar_id,som.mfg_calendar_id)=gtmp.calendar_id '
16756             || ' AND som.orgn_code = crd.orgn_code   '
16757             || ' AND som.resource_whse_code IS NOT NULL  '
16758             || ' AND crd.delete_mark  = 0                '  ;
16759 
16760      IF ((p_usage = 'APS') OR (p_usage = 'BASED')) THEN /* Usage APS/BASED */
16761        EXECUTE IMMEDIATE sql_shifts USING p_org_id, p_instance_id,p_calendar_id;
16762      END IF;
16763 
16764     /* End of Inserts to msc_st_resource_shifts - 2213101  */
16765 
16766   return_status := TRUE;
16767 
16768 EXCEPTION
16769   WHEN NO_DATA_FOUND THEN
16770     log_message('NO DATA FOUND : MSC_CL_GMP_UTILITY.net_rsrc_insert' || stmt_no);
16771     return_status := TRUE;
16772   WHEN OTHERS THEN
16773     log_message('Error in Net Resource Insert: '||stmt_no);
16774     log_message(sqlerrm);
16775     return_status := FALSE;
16776 
16777 END net_rsrc_insert;
16778 
16779 /*
16780 REM+==========================================================================+
16781 REM| PROCEDURE NAME                                                           |
16782 REM|    insert_simulation_sets                                                |
16783 REM|                                                                          |
16784 REM| Type                                                                     |
16785 REM|    public                                                                |
16786 REM|                                                                          |
16787 REM| DESCRIPTION                                                              |
16788 REM|                                                                          |
16789 REM|                                                                          |
16790 REM| Input Parameters                                                         |
16791 REM|    p_org_id - Organization id                                            |
16792 REM|    p_rsrc_whse_code - Resource Whse Code                                 |
16793 REM|    p_instance_id - Instance Id                                           |
16794 REM|    p_delimiter - Delimiter                                               |
16795 REM|                                                                          |
16796 REM| Output Parameters                                                        |
16797 REM|    return_status                                                         |
16798 REM|                                                                          |
16799 REM|                                                                          |
16800 REM| HISTORY                                                                  |
16801 REM|    Created 23th Sep 1999 by Sridhar Gidugu (OPM Development Oracle US)   |
16802 REM|    10/01/1999 - Chaged passing of Parameters to insert_simulation_sets   |
16803 REM|               - Added p_simulation_sets as a parameter and removed       |
16804 REM|               - p_rsrc_whse_code parameter                               |
16805 REM|    10/13/1999 - Added deleted_flag in the insert statement               |
16806 REM|                                                                          |
16807 REM|                                                                          |
16808 REM+==========================================================================+
16809 */
16810 PROCEDURE insert_simulation_sets(p_org_id         IN NUMBER,
16811                                  p_instance_id    IN NUMBER,
16812                                  p_simulation_set IN VARCHAR2,
16813                                  return_status    OUT NOCOPY BOOLEAN) IS
16814 BEGIN
16815 
16816     IF return_status THEN
16817        v_cp_enabled := TRUE;
16818     ELSE
16819        v_cp_enabled := FALSE;
16820     END IF;
16821 
16822           INSERT INTO msc_st_simulation_sets
16823                                         (organization_id,
16824                                          sr_instance_id,
16825                                          simulation_set,
16826                                          description,
16827                                          use_in_wip_flag,
16828                                          deleted_flag
16829                                          )
16830                              values     (p_org_id,
16831                                          p_instance_id,
16832                                          p_simulation_set,
16833                                          p_simulation_set,
16834                                          2,
16835                                          2
16836                                         ); /* Simulation Set Insert ends here */
16837 
16838      return_status := TRUE;
16839 
16840 EXCEPTION
16841    WHEN  OTHERS THEN
16842       log_message('Error in insert simulation: ');
16843       log_message(sqlerrm);
16844       return_status := FALSE;
16845 
16846 END insert_simulation_sets;
16847 
16848 /*
16849 REM+==========================================================================+
16850 REM| PROCEDURE NAME                                                           |
16851 REM|    populate_rsrc_cal                                                     |
16852 REM|                                                                          |
16853 REM| Type                                                                     |
16854 REM|    public                                                                |
16855 REM|                                                                          |
16856 REM| DESCRIPTION                                                              |
16857 REM|                                                                          |
16858 REM|                                                                          |
16859 REM| Input Parameters                                                         |
16860 REM|    p_orgn_code - Orgn Code                                               |
16861 REM|    p_org_id - Organization id                                            |
16862 REM|    p_cal_id - calendar_id                                                |
16863 REM|    p_instance_id - Instance Id                                           |
16864 REM|    p_delimiter - Delimiter                                               |
16865 REM|    p_db_link - Data Base Link                                            |
16866 REM|    p_nra_enabled - flag to build net resource available                  |
16867 REM|                                                                          |
16868 REM| Output Parameters                                                        |
16869 REM|    return_status                                                         |
16870 REM|                                                                          |
16871 REM|                                                                          |
16872 REM| HISTORY                                                                  |
16873 REM|    Created 5th Aug 1999 by Sridhar Gidugu (OPM Development Oracle US)    |
16874 REM|    9/1/99 - Main Proc calls the populate_cal_dates                       |
16875 REM|             Update trading Partners and net_rsrc_insert procedure.       |
16876 REM|                                                                          |
16877 REM|    9/7/99 - Changed the Main Procedure, removed UNION ALL for main cursor|
16878 REM|    9/28/99 - Changed the main query ordering by Organization Id and      |
16879 REM|            - changed logic for populating plsqltbl                       |
16880 REM|    4/03/00 - using mtl_organization_id from ic_whse_mst instead of       |
16881 REM|            - organization_id from sy_orgn_mst - Bug# 1252322             |
16882 REM|    5/03/00 - Add instance code as a prefix to the calendar code          |
16883 REM|            - Bug # 1288143                                               |
16884 REM|    7/07/00 - Anchor Date Problem Fixed in the Calendar Code              |
16885 REM|            - Bug # 1337084.                                              |
16886 REM|    7/12/00 - Removed the Debugging Statement shcl.calendar_id in         |
16887 REM|            - (121,126) - bug#1353845                                     |
16888 REM|    10/18/01 - B2041247 - Modified the cursor to consider Calendars       |
16889 REM|            associated with the OPM Plants                                |
16890 REM|                                                                          |
16891 REM|    7th Mar 2003 -- Performance issue fix and B2671540 00:00 shift fix    |
16892 REM|  04/21/2004   - Navin Sinha - B3577871 -ST:OSFME2: collections failing   |
16893 REM|                                in planning data pull.                    |
16894 REM|                                Added handling of NO_DATA_FOUND Exception.|
16895 REM|                                And return the return_status as TRUE.     |
16896 REM|                                                                          |
16897 REM|   07-May-2004 - Sowmya - B3599089 - ST: ORG SPECIFIC COMPLETE COLLETION  |
16898 REM|                          FOR OPM ORGS TAKING MORE TIME.                  |
16899 REM|                          As the varaibale l_org_specific was not getting |
16900 REM|                          refreshed,the resource availability             |
16901 REM|                          was getting collected irrespective of whether or|
16902 REM|                          not the org is enabled. To overcome this, added |
16903 REM|                          if clause containing the l_cur%NOTFOUND.So when |
16904 REM|                          the no values are returned the l_org_specific= 0|
16905 REM|                                                                          |
16906 REM+==========================================================================+
16907 REM
16908 */
16909 
16910 PROCEDURE populate_rsrc_cal(p_run_date    IN DATE,
16911                             p_instance_id IN NUMBER,
16912                             p_delimiter   IN VARCHAR2,
16913                             p_db_link     IN VARCHAR2,
16914                             p_nra_enabled IN NUMBER,
16915                             return_status OUT NOCOPY BOOLEAN) IS
16916 
16917 /* Local Array Defintions */
16918 TYPE interval_typ_a is RECORD
16919 (
16920   organization_id 	PLS_INTEGER,
16921   simulation_set  	VARCHAR2(10),
16922   resource_id     	PLS_INTEGER,
16923   shift_date      	DATE,
16924   shift_num       	PLS_INTEGER,
16925   capacity_units  	PLS_INTEGER,
16926   from_time       	PLS_INTEGER,
16927   to_time         	PLS_INTEGER
16928 );
16929 
16930 TYPE interval_tab_a is table of interval_typ_a index by BINARY_INTEGER;
16931 interval_record_aps     interval_typ_a;
16932 
16933 TYPE interval_typ_b is RECORD
16934 (
16935   organization_id 	NUMBER,
16936   Department_id 	NUMBER,
16937   resource_id     	NUMBER,
16938   res_instance_id     	NUMBER,
16939   equipment_item_id    	NUMBER,
16940   serial_number  	VARCHAR2(30),
16941   shift_date      	DATE,
16942   shift_num       	NUMBER,
16943   from_time       	NUMBER,
16944   to_time         	NUMBER
16945 );
16946 
16947 TYPE interval_tab_b is table of interval_typ_b index by BINARY_INTEGER;
16948 inst_record_aps     interval_typ_b;
16949 
16950 union_cal_ref      ref_cursor_typ;
16951 l_cur              ref_cursor_typ;
16952 ri_assembly	   ref_cursor_typ;
16953 r_inst_assembly	   ref_cursor_typ;
16954 sql_allcal         VARCHAR2(32000);
16955 inst_stmt          VARCHAR2(32000);
16956 inst_resavl  	   VARCHAR2(32000);
16957 Upd_Process_Org    VARCHAR2(32000);
16958 sqlstmt  	   VARCHAR2(32000);
16959 upd_res_avl  	   VARCHAR2(32000);
16960 l_stmt             VARCHAR2(32700);/* Bug # 5086464 */
16961 ins_res_avl        VARCHAR2(32700);
16962 stmt_no            INTEGER;
16963 n                  INTEGER;
16964 i                  INTEGER;
16965 j                  INTEGER;
16966 k                  INTEGER;
16967 x                  INTEGER;
16968 y                  INTEGER;
16969 v_icode            VARCHAR2(4);
16970 fetch_cal          PLS_INTEGER;
16971 found              PLS_INTEGER;
16972 old_org_id         PLS_INTEGER;
16973 v_out_cal_no       VARCHAR2(16);
16974 v_already_prefixed VARCHAR2(3);
16975 instance_prefix    VARCHAR2(4);
16976 simulation_set     VARCHAR2(10);
16977 l_opm_org          VARCHAR2(2000);
16978 f_resource_id      PLS_INTEGER;
16979 l_org_specific     PLS_INTEGER;
16980 
16981 BEGIN
16982 
16983 /* Bug: 6030499 Vpedarla added profile verification */
16984 
16985 LOG_MESSAGE(' populate_rsrc_cal started ');
16986 
16987     collect_ps_data := TRUE;
16988 
16989 n              := 0;
16990 i              := 0;
16991 j              := 0;
16992 k              := 0;
16993 x              := 0;
16994 y              := 0;
16995 v_icode        := '';
16996 fetch_cal      := 0;
16997 found          := 0;
16998 old_org_id     := 0 ;
16999 v_out_cal_no   := '';
17000 v_already_prefixed := '';
17001 instance_prefix    := '';
17002 simulation_set     := NULL;
17003 
17004 inst_resavl  	:= NULL;
17005 sqlstmt  	:= NULL;
17006 f_resource_id   := 0;
17007 l_opm_org       := NULL;
17008 l_org_specific  := 0;
17009 l_stmt          := NULL;
17010 
17011      /* Following statements are added to include the instance Code as
17012         a Prefix to the Calendar Code, this done to maintain the uniqueness
17013         of a calendar code across instances, prior to this change the
17014         calendar code was not prefixed with Instance code and this caused
17015         unique constraint problems - Bug# 1288143
17016      */
17017 
17018     IF return_status THEN
17019        v_cp_enabled := TRUE;
17020     ELSE
17021        v_cp_enabled := FALSE;
17022     END IF;
17023 
17024     /* Retrieving the Instance code from MSC_APPS_INSTANCES - Bug#1288143 */
17025      stmt_no := 05;
17026      inst_stmt :=  ' SELECT instance_code '
17027                 || ' FROM msc_apps_instances WHERE instance_id = :instance_id ';
17028 
17029      EXECUTE IMMEDIATE inst_stmt INTO v_icode USING p_instance_id ;
17030 
17031      /* Cursor statement to retrieve the calendar_id and the plant that the
17032         calendar is asociated with and the Organization_id that uses the
17033         calendar, here the ordering is done by Organization_id,
17034         resource_whse_code and calendar_id, in that way the primary row
17035         is always retrieved first and the rest can be skipped
17036      */
17037      /* New changes made for main Calendar Cursor - using mtl_organization_id
17038         from ic_whse_mst instead of organization_id from sy_orgn_mst table
17039         - Bug# 1252322 */
17040      /* B2041247 - The following Calendar Cursor has been modified to reflect
17041         the design changes planned for WPS Process integration. Now The
17042         calendars that are associated with the OPM plant are considered */
17043 
17044      stmt_no := 10;
17045      sql_allcal :=  ' SELECT sy.mfg_calendar_id, '
17046                  || ' shcl.calendar_no, '
17047                  || ' shcl.calendar_desc, '
17048                  || ' sy.orgn_code,    '
17049                  || ' decode(whse.whse_code,sy.resource_whse_code, '
17050                  || '        sy.resource_whse_code,NULL) resource_whse_code, '
17051                  || ' ic.mtl_organization_id  organization_id,  '
17052                  || ' 0  '
17053                  || ' FROM ps_schd_hdr'||p_db_link||' h, '
17054                  || '      ps_schd_dtl'||p_db_link||' d, '
17055                  || '      mr_shcl_hdr'||p_db_link||' shcl, '
17056                  || '      (select distinct plant_code,whse_code '
17057                  || '       from ps_whse_eff'||p_db_link|| ') whse, '
17058                  || '      sy_orgn_mst'||p_db_link||' sy, '
17059                  || '      ic_whse_mst'||p_db_link||' ic  '
17060                  || ' WHERE  d.schedule_id = h.schedule_id '
17061                  || ' AND    d.orgn_code = sy.orgn_code '
17062                  || ' AND    shcl.calendar_id = sy.mfg_calendar_id ' /* B2041247 */
17063                  || ' AND    whse.plant_code = sy.orgn_code '
17064                  || ' AND    whse.whse_code = ic.whse_code '
17065                  || ' AND    h.active_ind = 1 '
17066                  || ' AND    shcl.active_ind = 1 '
17067                  || ' AND    h.delete_mark = 0 '
17068                  || ' AND    shcl.delete_mark = 0 '
17069                  || ' ORDER BY organization_id, '
17070                  || '          resource_whse_code, '
17071                  || '          mfg_calendar_id ';
17072 
17073      /* The following cursor fetch statement retrieves rows from the Main
17074         cursor and inserts rows into plsqltbl when the organization_id changes */
17075      stmt_no := 20;
17076      i := 0;
17077      OPEN  union_cal_ref FOR sql_allcal;
17078      LOOP
17079           FETCH union_cal_ref INTO cursor_rec;
17080           EXIT WHEN union_cal_ref%NOTFOUND;
17081           IF cursor_rec.organization_id <> old_org_id THEN
17082               i := i + 1;
17083      /* Prefixing the Instance Code to the calendar code - Bug#1288143 */
17084      /* Bug# 1337084 - Changed get_cal_no Function to a Procedure - 07/06/00 */
17085 
17086               stmt_no := 22;
17087               get_cal_no(cursor_rec.calendar_id,
17088                          cursor_rec.calendar_no,
17089                          v_icode,
17090                          v_out_cal_no,
17091                          v_already_prefixed);
17092 
17093      /* 07/07/2000 - Added a check flag to indicate the Instance is already prefixed
17094         and this check is being used at the time when the PLSQL table is
17095         constructed, where in it will not assign an Instance Prefix if the
17096         calendar_code is already prefixed. - Bug# 1337084. */
17097 
17098               stmt_no := 23;
17099               IF v_already_prefixed = 'YES' THEN
17100                    plsqltbl_rec(i).calendar_no := v_out_cal_no ;
17101               ELSE
17102                    plsqltbl_rec(i).calendar_no := v_icode||':'||v_out_cal_no ;
17103               END IF ;
17104 
17105               plsqltbl_rec(i).calendar_id := cursor_rec.calendar_id;
17106               plsqltbl_rec(i).calendar_desc := cursor_rec.calendar_desc;
17107               plsqltbl_rec(i).orgn_code := cursor_rec.orgn_code;
17108               plsqltbl_rec(i).resource_whse_code :=
17109                               cursor_rec.resource_whse_code;
17110               plsqltbl_rec(i).organization_id := cursor_rec.organization_id;
17111               plsqltbl_rec(i).posted := cursor_rec.posted;
17112           END IF;
17113 
17114           old_org_id := cursor_rec.organization_id;
17115           v_already_prefixed := 'NO';
17116           v_out_cal_no := '';
17117      END LOOP; /* End loop for Main Cursor */
17118      CLOSE union_cal_ref;
17119 
17120 /* Bug: 6030499 */
17121      SELECT st.VALUE INTO v_dummy from V$MYSTAT st, V$STATNAME sn
17122      where st.STATISTIC# = sn.STATISTIC#
17123      and sn.NAME in ('session pga memory');
17124      log_message('union_cal_ref Session pga memory = ' || TO_CHAR(v_dummy) );
17125 
17126 
17127      /* INSERT A LOOP TO SPIT OUT ALL THE ROWS IN PL/SQL TABLE HERE  */
17128 
17129    stmt_no := 30;
17130    WHILE y = 0 LOOP
17131 
17132      FOR k in 1 .. plsqltbl_rec.COUNT
17133      LOOP
17134 
17135      /* Checking if there are any rows in PL/SQL that were processed */
17136      IF plsqltbl_rec(k).posted = 0 THEN
17137         found := 1;
17138 
17139          IF fetch_cal = 0 THEN
17140 	    fetch_cal := plsqltbl_rec(k).calendar_id;
17141 
17142            /* Calling the retrieve Calendar Procedure,which explodes the calendar
17143               for a given Calendar Id */
17144 
17145            stmt_no := 40;
17146            retrieve_calendar_detail(plsqltbl_rec(k).calendar_id,
17147                                     plsqltbl_rec(k).calendar_no,
17148                                     plsqltbl_rec(k).calendar_desc,
17149                                     p_run_date,
17150                                     p_db_link,
17151                                     p_instance_id,
17152                                     V_APS,
17153                                     return_status
17154                                    );
17155          END IF;
17156 
17157        IF plsqltbl_rec(k).calendar_id = fetch_cal THEN
17158 
17159            /* Calling the Update Trading Partner Procedure,which updates the
17160               MSC_ST_TRADING_PARTNERS with the Calendar Code for a given Organization
17161               Id
17162            */
17163            stmt_no := 50;
17164            update_trading_partners(plsqltbl_rec(k).organization_id,
17165                                    plsqltbl_rec(k).calendar_no,
17166                                    return_status
17167                                    );
17168 
17169          IF plsqltbl_rec(k).resource_whse_code IS NOT NULL  THEN
17170 
17171           /* Check if the org string have the organization */
17172            BEGIN
17173             stmt_no := 51;
17174             IF MSC_CL_GMP_UTILITY.org_string(p_instance_id) THEN
17175                NULL ;
17176             ELSE
17177                RAISE invalid_string_value  ;
17178             END IF;
17179 
17180             l_opm_org := plsqltbl_rec(k).organization_id ;
17181 
17182             IF MSC_CL_GMP_UTILITY.g_in_str_org IS NOT NULL THEN
17183              l_stmt := 'SELECT 1 FROM dual WHERE '||
17184                         l_opm_org||MSC_CL_GMP_UTILITY.g_in_str_org ;
17185                 OPEN l_cur for l_stmt ;
17186                 FETCH l_cur INTO l_org_specific ;
17187                 IF l_cur%NOTFOUND THEN
17188                         l_org_specific := 0;
17189                 END IF;
17190                 /*B3599089 - sowsubra - When the organization is not in the list ,
17191                 the resource  availability was getting collected
17192                 irrespective of whether or not the org is enabled . So
17193                 added this to reset the value of l_org_specific. */
17194                 CLOSE l_cur ;
17195             END IF;
17196 
17197            EXCEPTION
17198               WHEN NO_DATA_FOUND THEN
17199                 l_org_specific := 0 ;
17200                 NULL ;
17201               WHEN OTHERS THEN
17202                 log_message('Error in org string decision:  '||stmt_no);
17203                 log_message(sqlerrm);
17204                 l_org_specific := 0 ;
17205                 return_status := FALSE;
17206            END;
17207 
17208              IF l_org_specific = 1 THEN
17209 
17210                /* B3452373, Simulation set should be null, as OPM stops sending this
17211                   information to APS and hence related code is commented */
17212                  simulation_set := NULL ;
17213 
17214                IF p_nra_enabled = V_YES THEN
17215                  /* Populating Net Resource Insert Table */
17216                  stmt_no := 65;
17217                  net_rsrc_insert(plsqltbl_rec(k).organization_id,
17218                                  plsqltbl_rec(k).orgn_code,
17219                                  simulation_set,
17220                                  p_db_link,
17221                                  p_instance_id,
17222                                  p_run_date,
17223                                  plsqltbl_rec(k).calendar_id,
17224                                  V_APS,
17225                                  return_status
17226                                  );
17227 
17228                 /* Bug:6030499 conditionalising the following calls */
17229 
17230                 IF collect_ps_data THEN
17231 
17232         /* Populate Net Resource Instance rows  PS Integration */
17233                   net_rsrc_avail_calculate(plsqltbl_rec(k).organization_id,
17234                                     plsqltbl_rec(k).orgn_code,
17235                                     plsqltbl_rec(k).calendar_id,
17236                                     p_instance_id,
17237                                     p_db_link,
17238                                     V_APS,
17239                                     return_status)  ;
17240                   END IF;   -- Bug: 6030499 end of conditionalising call
17241                END IF;
17242              END IF;  /* org_specific */
17243 
17244          END IF;  /* rsrc whse code not null */
17245 
17246          /* Marking that particular as being Posted, after making all the calls
17247             to the Procedure */
17248          plsqltbl_rec(k).posted := 1;
17249 
17250        END IF;  /* cal_id = fetch_cal */
17251 
17252      END IF;  /* postd = 0 */
17253      END LOOP;  /* End loop for PL/SQL table */
17254 
17255      IF found = 1 THEN
17256        fetch_cal := 0;
17257        found := 0;
17258      ELSE
17259        y := 1;
17260      END IF;
17261    END LOOP;  /* End Loop for While */
17262 
17263      /* B5001619 Rajesh All the process orgs should have organization_type=2 */
17264       BEGIN
17265        stmt_no := 67 ;
17266        Upd_Process_Org := 'UPDATE MSC_ST_TRADING_PARTNERS '
17267        ||' SET organization_type = 2 '
17268        ||' WHERE sr_tp_id in (SELECT organization_id '
17269        ||'                    FROM  mtl_parameters'||p_db_link
17270        ||'                    WHERE process_enabled_flag = '||''''||'Y'||'''' || ')'
17271        ||' AND partner_type = 3' ;
17272 
17273        EXECUTE IMMEDIATE  Upd_Process_Org;
17274        log_message('Trading Partner Update is Done' );
17275 
17276       EXCEPTION
17277         WHEN NO_DATA_FOUND THEN
17278            NULL ;
17279         WHEN OTHERS THEN
17280           log_message('Error in UPDATE TRADING_PARTNERS  '||stmt_no);
17281           log_message(SQLERRM);
17282           return_status := FALSE;
17283       END ;
17284 
17285    /* Addition of shifts/Datetime in resource calendar functionlality */
17286     IF p_nra_enabled = V_YES THEN
17287         log_message('Enter rsrcal_based_availability ');
17288         rsrcal_based_availability(p_run_date ,
17289                                   p_instance_id ,
17290                                   p_db_link ,
17291                                   return_status) ;
17292         log_message('Return From rsrcal_based_availability ');
17293     END IF;
17294 
17295    /* 7th Mar 2003 -- Performance issue fix and B2671540 00:00 shift fix */
17296    /* This logic introduced for Net resource availablility to
17297        write consolidated rows once final available rows are in place */
17298     stmt_no := 75;
17299 
17300    ins_res_avl :=  ' SELECT '
17301    || '        net.organization_id, '
17302    || '        net.simulation_set, '
17303    || '        net.resource_id , '
17304    || '        net.shift_date  , '
17305    || '        net.shift_num   , '
17306    || '        net.capacity_units , '
17307    || '        min(net.from_time) from_time, '
17308    || '        max(net.lead_tt) to_time '
17309    || ' FROM  ( '
17310    || '        SELECT organization_id , '
17311    || '               simulation_set, '
17312    || '               resource_id, '
17313    || '               shift_date  , '
17314    || '               shift_num , '
17315    || '               capacity_units , '
17316    || '               from_time , '
17317    || '               to_time , '
17318    || '  lead(organization_id,1) '
17319    || '  over(order by organization_id,simulation_set, '
17320    || '  resource_id,shift_date, shift_num,from_time,to_time,capacity_units) '
17321    || '  as lead_iid, '
17322    || '  lead(simulation_set,1) '
17323    || '  over(order by organization_id,simulation_set,'
17324    || '  resource_id,shift_date, shift_num,from_time,to_time,capacity_units) '
17325    || '  as lead_ss, '
17326    || '  lead(resource_id,1) '
17327    || '  over(order by organization_id,simulation_set,'
17328    || '  resource_id,shift_date, shift_num,from_time,to_time,capacity_units) '
17329    || '  as lead_rid, '
17330    || '  lead(shift_date,1) '
17331    || '  over(order by organization_id,simulation_set,'
17332    || '  resource_id,shift_date, shift_num,from_time,to_time,capacity_units) '
17333    || '  as lead_sdt, '
17334    || '  lead(shift_num,1) '
17335    || '  over(order by organization_id,simulation_set,'
17336    || '  resource_id,shift_date, shift_num,from_time,to_time,capacity_units) '
17337    || '  as lead_sn, '
17338    || '  lead(from_time,1) '
17339    || '  over(order by organization_id,simulation_set,'
17340    || '  resource_id,shift_date, shift_num,from_time,to_time,capacity_units) '
17341    || '  as lead_ft, '
17342    || '  lead(to_time,1) '
17343    || '  over(order by organization_id,simulation_set,'
17344    || '  resource_id,shift_date, shift_num,from_time,to_time,capacity_units) '
17345    || '  as lead_tt, '
17346    || '  lead(capacity_units,1) '
17347    || '  over(order by organization_id,simulation_set,'
17348    || '  resource_id,shift_date, shift_num,from_time,to_time,capacity_units) '
17349    || '  as lead_rc '
17350    || '          FROM msc_st_net_resource_avail '
17351    || '          WHERE sr_instance_id = :inst_id '
17352    || '              ) net '
17353    || '      WHERE net.resource_id     = net.lead_rid '
17354    || '        AND net.organization_id = net.lead_iid '
17355    || '        AND net.simulation_set  = net.lead_ss '
17356    || '        AND net.shift_num       = net.lead_sn '
17357    || '        AND net.shift_date      = net.lead_sdt '
17358    || '        AND net.to_time         = net.lead_ft '
17359    || '        AND net.capacity_units  = net.lead_rc '
17360    || ' GROUP BY '
17361    || '        net.organization_id , '
17362    || '        net.simulation_set , '
17363    || '        net.resource_id , '
17364    || '        net.shift_date , '
17365    || '        net.shift_num , '
17366    || '        net.capacity_units ' ;
17367 
17368     stmt_no := 76;
17369     OPEN ri_assembly FOR ins_res_avl  USING p_instance_id ;
17370     LOOP
17371        FETCH ri_assembly INTO  interval_record_aps;
17372        EXIT WHEN ri_assembly%NOTFOUND;
17373 
17374      sqlstmt := ' DELETE FROM msc_st_net_resource_avail '
17375              || ' WHERE organization_id  = :org_id '
17376              || '   AND simulation_set = :sim_set '
17377              || '   AND sr_instance_id = :inst_id '
17378              || '   AND resource_id = :prid '
17379              || '   AND shift_date = :psdt '
17380              || '   AND shift_num  = :psn  '
17381              || '   AND capacity_units = :prc '
17382              || '   AND from_time  >= :pft '
17383              || '   AND to_time  <= :ptt '  ;
17384 
17385     stmt_no := 77;
17386        EXECUTE immediate sqlstmt USING
17387        interval_record_aps.organization_id ,
17388        interval_record_aps.simulation_set ,
17389        p_instance_id ,
17390        interval_record_aps.resource_id,
17391        interval_record_aps.shift_date,
17392        interval_record_aps.shift_num,
17393        interval_record_aps.capacity_units,
17394        interval_record_aps.from_time,
17395        interval_record_aps.to_time  ;
17396 
17397        f_resource_id :=  (interval_record_aps.resource_id - 1 )/ 2 ;
17398 
17399     stmt_no := 78;
17400          net_rsrc(
17401             p_instance_id,
17402             interval_record_aps.organization_id,
17403             interval_record_aps.simulation_set,
17404             f_resource_id,
17405             interval_record_aps.capacity_units,
17406             interval_record_aps.shift_num,
17407             trunc(interval_record_aps.shift_date),
17408             interval_record_aps.from_time ,
17409             interval_record_aps.to_time
17410                   );
17411 
17412 	f_resource_id  := 0 ;
17413        COMMIT ;
17414     END LOOP;
17415     CLOSE ri_assembly;
17416 
17417     stmt_no := 79;
17418 
17419 /* Bug: 6030499 added session pga memory */
17420 
17421           SELECT st.VALUE INTO v_dummy from V$MYSTAT st, V$STATNAME sn
17422           where st.STATISTIC# = sn.STATISTIC#
17423           and sn.NAME in ('session pga memory');
17424           log_message('ri_assembly Session pga memory = ' || TO_CHAR(v_dummy) );
17425 
17426 
17427 /* Bug: 6030499 conditionalising the following code */
17428    IF collect_ps_data THEN
17429 
17430     upd_res_avl := null ;
17431     upd_res_avl := 'UPDATE msc_st_net_resource_avail '
17432             ||' SET to_time   = 86400 '
17433             ||' WHERE to_time = 86399 '
17434             ||'   AND shift_num >= 99999 ' ;
17435 
17436        EXECUTE immediate upd_res_avl;
17437 
17438     stmt_no := 80;
17439     upd_res_avl := null ;
17440     upd_res_avl := 'UPDATE msc_st_net_resource_avail '
17441             ||' SET shift_num = (shift_num - 99999) '
17442             ||' WHERE shift_num >= 99999 ' ;
17443 
17444        EXECUTE immediate upd_res_avl;
17445        COMMIT ;
17446 
17447    /* Final rows for msc_st_net_res_inst_avail */
17448    stmt_no := 81;
17449    inst_resavl :=  null;
17450 
17451    inst_resavl := ' SELECT '
17452    || '        net.organization_id, '
17453    || '        net.Department_id, '
17454    || '        net.resource_id , '
17455    || '        net.res_instance_id , '
17456    || '        net.equipment_item_id , '
17457    || '        net.serial_number, '
17458    || '        net.shift_date  , '
17459    || '        net.shift_num   , '
17460    || '        min(net.from_time) from_time, '
17461    || '        max(net.lead_tt) to_time '
17462    || ' FROM  ( '
17463    || '        SELECT organization_id , '
17464    || '               Department_id, '
17465    || '               resource_id, '
17466    || '               res_instance_id, '
17467    || '               equipment_item_id, '
17468    || '               serial_number, '
17469    || '               shift_date  , '
17470    || '               shift_num , '
17471    || '               from_time , '
17472    || '               to_time , '
17473    || '  lead(organization_id,1) '
17474    || '  over(order by organization_id,Department_id,resource_id,res_instance_id, '
17475    || '  equipment_item_id,serial_number, shift_date,shift_num,from_time,to_time) '
17476    || '  as lead_iid, '
17477    || '  lead(Department_id,1) '
17478    || '  over(order by organization_id,Department_id,resource_id,res_instance_id, '
17479    || '  equipment_item_id,serial_number, shift_date,shift_num,from_time,to_time) '
17480    || '  as lead_did, '
17481    || '  lead(resource_id,1) '
17482    || '  over(order by organization_id,Department_id,resource_id,res_instance_id, '
17483    || '  equipment_item_id,serial_number, shift_date,shift_num,from_time,to_time) '
17484    || '  as lead_rid, '
17485    || '  lead(res_instance_id,1) '
17486    || '  over(order by organization_id,Department_id,resource_id,res_instance_id, '
17487    || '  equipment_item_id,serial_number, shift_date,shift_num,from_time,to_time) '
17488    || '  as lead_r_inst_id, '
17489    || '  lead(equipment_item_id,1) '
17490    || '  over(order by organization_id,Department_id,resource_id,res_instance_id, '
17491    || '  equipment_item_id,serial_number, shift_date,shift_num,from_time,to_time) '
17492    || '  as lead_eid, '
17493    || '  lead(serial_number,1) '
17494    || '  over(order by organization_id,Department_id,resource_id,res_instance_id, '
17495    || '  equipment_item_id,serial_number, shift_date,shift_num,from_time,to_time) '
17496    || '  as lead_sr_no, '
17497    || '  lead(shift_date,1) '
17498    || '  over(order by organization_id,Department_id,resource_id,res_instance_id, '
17499    || '  equipment_item_id,serial_number, shift_date,shift_num,from_time,to_time) '
17500    || '  as lead_sdt, '
17501    || '  lead(shift_num,1) '
17502    || '  over(order by organization_id,Department_id,resource_id,res_instance_id, '
17503    || '  equipment_item_id,serial_number, shift_date,shift_num,from_time,to_time) '
17504    || '  as lead_sn, '
17505    || '  lead(from_time,1) '
17506    || '  over(order by organization_id,Department_id,resource_id,res_instance_id, '
17507    || '  equipment_item_id,serial_number, shift_date,shift_num,from_time,to_time) '
17508    || '  as lead_ft, '
17509    || '  lead(to_time,1) '
17510    || '  over(order by organization_id,Department_id,resource_id,res_instance_id, '
17511    || '  equipment_item_id,serial_number, shift_date,shift_num,from_time,to_time) '
17512    || '  as lead_tt '
17513    || '          FROM msc_st_net_res_inst_avail '
17514    || '          WHERE sr_instance_id = :inst_id '
17515    || '              ) net '
17516    || '      WHERE '
17517    || '            net.organization_id   = net.lead_iid '
17518    || '        AND net.Department_id     = net.lead_did '
17519    || '        AND net.resource_id       = net.lead_rid '
17520    || '        AND net.res_instance_id   = net.lead_r_inst_id '
17521    || '        AND net.equipment_item_id = net.lead_eid '
17522    || '        AND net.serial_number     = net.lead_sr_no '
17523    || '        AND net.shift_date        = net.lead_sdt '
17524    || '        AND net.shift_num         = net.lead_sn '
17525    || '        AND net.to_time           = net.lead_ft '
17526    || ' GROUP BY '
17527    || '        net.organization_id, '
17528    || '        net.Department_id, '
17529    || '        net.resource_id , '
17530    || '        net.res_instance_id , '
17531    || '        net.equipment_item_id , '
17532    || '        net.serial_number, '
17533    || '        net.shift_date  , '
17534    || '        net.shift_num   ' ;
17535 
17536     stmt_no := 82;
17537     OPEN r_inst_assembly FOR inst_resavl  USING p_instance_id ;
17538     LOOP
17539        FETCH r_inst_assembly INTO  inst_record_aps;
17540        EXIT WHEN r_inst_assembly%NOTFOUND;
17541 
17542      sqlstmt := ' DELETE FROM msc_st_net_res_inst_avail '
17543              || ' WHERE organization_id  = :org_id '
17544              || '   AND Department_id  = :dept_id '
17545              || '   AND sr_instance_id = :inst_id '
17546              || '   AND resource_id = :prid '
17547              || '   AND res_instance_id = :pr_inst_id '
17548              || '   AND equipment_item_id = :pe_id '
17549              || '   AND serial_number = :ps_no '
17550              || '   AND shift_date = :psdt '
17551              || '   AND shift_num  = :psn  '
17552              || '   AND from_time  >= :pft '
17553              || '   AND to_time  <= :ptt '  ;
17554 
17555     stmt_no := 83;
17556        EXECUTE immediate sqlstmt USING
17557        inst_record_aps.organization_id ,
17558        inst_record_aps.Department_id ,
17559        p_instance_id ,
17560        inst_record_aps.resource_id,
17561        inst_record_aps.res_instance_id,
17562        inst_record_aps.equipment_item_id,
17563        inst_record_aps.serial_number ,
17564        inst_record_aps.shift_date,
17565        inst_record_aps.shift_num,
17566        inst_record_aps.from_time,
17567        inst_record_aps.to_time  ;
17568 
17569     stmt_no := 84;
17570 
17571         INSERT INTO msc_st_net_res_inst_avail
17572           ( Organization_Id,
17573             Department_id,
17574             sr_instance_id,
17575             Resource_Id,
17576             res_instance_id,
17577             serial_number,
17578             equipment_item_id,
17579             Shift_Num,
17580             Shift_Date,
17581             From_Time,
17582             To_Time
17583          )  VALUES
17584          (  inst_record_aps.organization_id ,
17585             inst_record_aps.Department_id ,
17586             p_instance_id  ,
17587             inst_record_aps.resource_id,
17588             inst_record_aps.res_instance_id,
17589             inst_record_aps.equipment_item_id,
17590             inst_record_aps.serial_number ,
17591             inst_record_aps.shift_num,
17592             inst_record_aps.shift_date,
17593             inst_record_aps.from_time,
17594             inst_record_aps.to_time
17595          )  ;
17596 
17597        COMMIT ;
17598     END LOOP;
17599     CLOSE r_inst_assembly;
17600 
17601 END IF;
17602 /* Bug: 6030499 of conditionalised code */
17603 
17604     stmt_no := 85;
17605     sqlstmt := null ;
17606     sqlstmt := 'UPDATE msc_st_net_res_inst_avail '
17607             ||' SET to_time   = 86400 '
17608             ||' WHERE to_time = 86399 '
17609             ||'   AND shift_num >= 99999 ' ;
17610 
17611        EXECUTE immediate sqlstmt;
17612     sqlstmt := null ;
17613     stmt_no := 86;
17614     sqlstmt := 'UPDATE msc_st_net_res_inst_avail '
17615             ||' SET shift_num = (shift_num - 99999) '
17616             ||' WHERE shift_num >= 99999 ' ;
17617 
17618        EXECUTE immediate sqlstmt;
17619        COMMIT ;
17620 
17621    return_status := TRUE;
17622 
17623 EXCEPTION
17624     WHEN invalid_string_value  THEN
17625       log_message('APS string is Invalid, check for Error condition' );
17626       return_status := FALSE;
17627     WHEN NO_DATA_FOUND THEN /* B3577871 */
17628       log_message(' NO_DATA_FOUND exception : MSC_CL_GMP_UTILITY.Populate_rsrc_cal ' );
17629       return_status := TRUE;
17630     WHEN OTHERS THEN
17631       log_message('Error in Populate Rsrc cal construct: '||stmt_no);
17632       log_message('Error : '||v_icode);
17633       log_message(SQLERRM);
17634       return_status := FALSE;
17635 
17636 END populate_rsrc_cal;  /* End of Main Procedure */
17637 
17638 /*
17639 REM+==========================================================================+
17640 REM| PROCEDURE NAME                                                           |
17641 REM|    rsrcal_based_availability                                             |
17642 REM|                                                                          |
17643 REM| Type                                                                     |
17644 REM|    private                                                               |
17645 REM|                                                                          |
17646 REM| DESCRIPTION                                                              |
17647 REM|    This Procedure will calcaulate net resource availability              |
17648 REM|    for all the resources having their own calendars different            |
17649 REM|    from plant's manufacturing calendar                                   |
17650 REM| Input Parameters                                                         |
17651 REM|    p_run_date    - Running Date                                          |
17652 REM|    p_instance_id - Instance Id                                           |
17653 REM|    p_db_link - Data Base Link                                            |
17654 REM|                                                                          |
17655 REM| Output Parameters                                                        |
17656 REM|    return_status                                                         |
17657 REM|                                                                          |
17658 REM| HISTORY                                                                  |
17659 REM|    06/07/2005  by Rajesh Patangya (OPM Development Oracle US)            |
17660 REM+==========================================================================+
17661 REM
17662 */
17663 PROCEDURE rsrcal_based_availability(p_run_date    IN DATE,
17664                                     p_instance_id IN PLS_INTEGER,
17665                                     p_db_link     IN VARCHAR2,
17666                                     return_status OUT NOCOPY BOOLEAN) IS
17667 
17668   /*  Declare  Cursor Types */
17669   cur_get_cal      ref_cursor_typ;
17670 
17671   TYPE cal_org_typ is RECORD
17672   ( calendar_id      PLS_INTEGER,
17673     calendar_no      varchar2(16),
17674     calendar_desc    varchar2(40),
17675     orgn_code        varchar2(4),
17676     organization_id  PLS_INTEGER
17677   );
17678   calorg_record  cal_org_typ;
17679 
17680   sql_get_cal      VARCHAR2(32700);/* Bug # 5086464 */
17681   old_calendar_id  PLS_INTEGER ;
17682   stmt_no          PLS_INTEGER ;
17683 
17684 BEGIN
17685   old_calendar_id  := -1;
17686 
17687          stmt_no := 610;
17688          /* populate the org_string */
17689          IF MSC_CL_GMP_UTILITY.org_string(p_instance_id) THEN
17690             NULL ;
17691          ELSE
17692             RAISE invalid_string_value  ;
17693          END IF;
17694 
17695          sql_get_cal :=  ' SELECT distinct crd.calendar_id,  '
17696             ||' shcl.calendar_no, shcl.calendar_desc, '
17697             ||' sy.orgn_code, iwm.mtl_organization_id '
17698             ||' FROM mr_shcl_hdr'||p_db_link||' shcl, '
17699             ||'      sy_orgn_mst'||p_db_link||' sy,  '
17700             ||'      cr_rsrc_dtl'||p_db_link||' crd,  '
17701             ||'      ic_whse_mst'||p_db_link||' iwm  '
17702             ||' WHERE sy.orgn_code = crd.orgn_code '
17703 	    ||'   AND sy.mfg_calendar_id <> crd.calendar_id '
17704             ||'   AND crd.calendar_id IS NOT NULL '
17705             ||'   AND crd.calendar_id = shcl.calendar_id '
17706             ||'   AND iwm.whse_code = sy.resource_whse_code ' ;
17707 
17708         IF MSC_CL_GMP_UTILITY.g_in_str_org  IS NOT NULL THEN
17709          sql_get_cal := sql_get_cal
17710             ||'   AND iwm.mtl_organization_id '||MSC_CL_GMP_UTILITY.g_in_str_org;
17711         END IF;
17712 
17713          sql_get_cal := sql_get_cal
17714             ||'   AND shcl.delete_mark = 0 '
17715             ||'   AND crd.delete_mark = 0 '
17716             ||' ORDER BY crd.calendar_id  ' ;
17717 
17718      OPEN cur_get_cal FOR sql_get_cal ;
17719      LOOP
17720      FETCH cur_get_cal INTO calorg_record ;
17721      EXIT WHEN cur_get_cal%NOTFOUND ;
17722 
17723       log_message('BASED: ' || calorg_record.calendar_id );
17724       IF calorg_record.calendar_id <> old_calendar_id THEN
17725          stmt_no := 611 ;
17726          COMMIT;  -- To Empty the _GTMP Table
17727 
17728       log_message('BASED 1 ' );
17729          retrieve_calendar_detail(calorg_record.calendar_id,
17730                                   calorg_record.calendar_no,
17731                                   calorg_record.calendar_desc,
17732                                   p_run_date,
17733                                   p_db_link,
17734                                   p_instance_id,
17735                                   V_WPS,
17736                                   return_status
17737                                   );
17738       END IF ;
17739 
17740       log_message('BASED 2 ' );
17741          stmt_no := 622;
17742          /* Populating Net Resource Insert Table */
17743          net_rsrc_insert(calorg_record.organization_id,
17744                          calorg_record.orgn_code,
17745                          NULL,    -- simulation_set,
17746                          p_db_link,
17747                          p_instance_id,
17748                          p_run_date,
17749                          calorg_record.calendar_id,
17750                          V_BASED,
17751                          return_status
17752                          );
17753 
17754       log_message('BASED 3 ' );
17755         /* Populate Net Resource Instance rows  PS Integration */
17756 
17757 /* Bug: 6030499 conditionalising the following code */
17758 
17759 IF collect_ps_data THEN
17760         /* Populate Net Resource Instance rows  PS Integration */
17761            net_rsrc_avail_calculate(calorg_record.organization_id,
17762                                     calorg_record.orgn_code,
17763                                     calorg_record.calendar_id,
17764                                     p_instance_id,
17765                                     p_db_link,
17766                                     V_BASED,
17767                                     return_status)  ;
17768       log_message('BASED 4 ' );
17769 
17770 END IF;
17771 -- Bug: 6030499 end of conditional code
17772 
17773     COMMIT ;
17774 
17775       old_calendar_id := calorg_record.calendar_id ;
17776 
17777      END LOOP ;
17778      CLOSE cur_get_cal ;
17779 
17780  -- Bug: 6030499
17781           SELECT st.VALUE INTO v_dummy from V$MYSTAT st, V$STATNAME sn
17782           where st.STATISTIC# = sn.STATISTIC#
17783           and sn.NAME in ('session pga memory');
17784           log_message('cur_get_cal Session pga memory = ' || TO_CHAR(v_dummy) );
17785 
17786      return_status := TRUE;
17787 
17788 EXCEPTION
17789     WHEN invalid_string_value  THEN
17790       log_message('APS string is Invalid, check for Error condition' );
17791       return_status := FALSE;
17792     WHEN NO_DATA_FOUND THEN
17793       log_message('NO DATA FOUND exception: MSC_CL_GMP_UTILITY.rsrcal_based_availability');
17794       return_status := TRUE;
17795     WHEN OTHERS THEN
17796       log_message('Error in MSC_CL_GMP_UTILITY.rsrcal_based_availability '||p_instance_id);
17797       log_message(sqlerrm);
17798       return_status := FALSE;
17799 
17800 END rsrcal_based_availability;
17801 
17802 /*
17803 REM+==========================================================================+
17804 REM| PROCEDURE NAME                                                           |
17805 REM|    insert_gmp_resource_avail                                             |
17806 REM|                                                                          |
17807 REM| Type                                                                     |
17808 REM|    public                                                                |
17809 REM|                                                                          |
17810 REM| DESCRIPTION                                                              |
17811 REM|                                                                          |
17812 REM| Input Parameters                                                         |
17813 REM|    p_orgn_code - Orgn Code                                               |
17814 REM|                                                                          |
17815 REM| Output Parameters                                                        |
17816 REM|    errbuf and retcode                                                    |
17817 REM|                                                                          |
17818 REM| HISTORY                                                                  |
17819 REM|    Created on 4th Jan 2002 By Rajesh Patangya                            |
17820 REM| B3161696 - 26-SEP-2003 TARGETTED RESOURCE AVAILABILITY PLACEHOLDER BUG   |
17821 REM| B4309093 - 20-APR-2005 Modified code to TO ADD TIME OR A SHIFT TO A      |
17822 REM|                        PLANT RESOURCE                                    |
17823 REM+==========================================================================+
17824 */
17825 PROCEDURE insert_gmp_resource_avail( errbuf        OUT NOCOPY VARCHAR2,
17826                                      retcode       OUT NOCOPY NUMBER  ,
17827                                      p_orgn_code   IN VARCHAR2 ,
17828                                      p_from_rsrc   IN VARCHAR2 ,
17829                                      p_to_rsrc     IN VARCHAR2 ,
17830                                      p_calendar_id IN NUMBER   ) IS
17831 
17832   cal_detail_ref    ref_cursor_typ;
17833   cur_get_def_cal   ref_cursor_typ;
17834   cur_get_cal       ref_cursor_typ;
17835   l_calendar_no     varchar2(16) ;
17836   l_calendar_desc   varchar2(40) ;
17837   l_calendar_id     NUMBER  ;
17838   i                 integer ;
17839   l_message         varchar2(1000) ;
17840   ret_status        boolean ;
17841   sql_stmt1	    VARCHAR2(32000) ;
17842   sql_stmt2	    VARCHAR2(32000) ;
17843   delete_stmt	    VARCHAR2(32000) ;
17844   sql_get_cal	    VARCHAR2(32000) ;
17845   sql_get_def_cal   VARCHAR2(32000) ;
17846 
17847 BEGIN
17848   i                 := 1 ;
17849   stmt_no	    := 0 ;
17850   l_message         := NULL ;
17851   sql_stmt1         := NULL;
17852   sql_stmt2         := NULL;
17853   sql_get_cal       := NULL;
17854   delete_stmt       := NULL;
17855   l_calendar_id     := 0 ;
17856 
17857   V_FROM_RSRC := p_from_rsrc;
17858   V_TO_RSRC   := p_to_rsrc ;
17859   l_calendar_id := p_calendar_id ;
17860 
17861 
17862 --HW B4309093 Case I - Calendar is blank
17863 IF p_calendar_id is NULL THEN
17864 
17865 -- This also covers if From and To resources are blank
17866     sql_get_cal :=  ' SELECT '
17867          ||'  DISTINCT NVL(r.calendar_id,sy.mfg_calendar_id), '
17868          ||' shcl.calendar_no, shcl.calendar_desc '
17869          ||' FROM mr_shcl_hdr shcl, '
17870          ||'      sy_orgn_mst sy, '
17871          ||'      cr_rsrc_dtl r   '
17872          ||' WHERE sy.orgn_code = r.orgn_code '
17873 	 ||'   AND NVL(r.calendar_id,sy.mfg_calendar_id)=shcl.calendar_id '
17874 	 ||'   AND r.orgn_code = :lorgn_code '
17875          ||'   AND shcl.delete_mark = 0 ' ;
17876 
17877 -- Case A - From Resource is entered and To Resource is blank
17878 
17879    IF (v_from_rsrc IS NOT NULL AND v_to_rsrc IS NULL) THEN
17880      sql_get_cal := sql_get_cal  || ' AND r.resources >= :frsrc ' ;
17881      OPEN cur_get_cal FOR sql_get_cal USING p_orgn_code , p_from_rsrc;
17882 
17883 -- Case B - From and TO resources are entered
17884 
17885    ELSE
17886      IF (v_from_rsrc IS NOT NULL AND v_to_rsrc IS NOT NULL) THEN
17887        sql_get_cal := sql_get_cal  || ' AND resources BETWEEN :frsrc and :trsrc ';
17888        OPEN cur_get_cal FOR sql_get_cal USING p_orgn_code , p_from_rsrc, p_to_rsrc ;
17889 
17890 -- Case C - From and TO resources are blank
17891 -- Statement is already constrcut at top
17892      ELSIF ( v_from_rsrc IS NULL AND v_to_rsrc IS NULL) THEN
17893       OPEN cur_get_cal FOR sql_get_cal USING p_orgn_code ;
17894      END IF ;
17895 
17896    END IF;
17897 
17898 -- Case II Calendar is entered
17899 ELSE
17900 -- Case A- Both from and To resources are entered
17901       sql_get_cal := 'Select calendar_id, '
17902 		||' calendar_no,calendar_desc '
17903 		||' FROM mr_shcl_hdr '
17904 		||' WHERE calendar_id = :cal_id ' ;
17905       OPEN cur_get_cal FOR sql_get_cal USING p_calendar_id ;
17906 END IF ;
17907 
17908 -- HW B4309093 Loop through the calendars
17909 LOOP
17910 FETCH cur_get_cal INTO l_calendar_id, l_calendar_no, l_calendar_desc ;
17911 EXIT WHEN cur_get_cal%NOTFOUND ;
17912 
17913      stmt_no := 1 ;
17914      delete_stmt := 'DELETE FROM gmp_resource_avail '||
17915                     ' WHERE calendar_id = :cal_id '  ||
17916                     '   AND plant_code  = :Plant_code1 ';
17917 
17918     IF (v_from_rsrc IS NOT NULL AND v_to_rsrc IS NOT NULL) THEN
17919       delete_stmt := delete_stmt ||' AND resource_id in (select resource_id '
17920                             ||' FROM cr_rsrc_dtl '
17921                             ||' WHERE orgn_code = :Plant_code2 '
17922                             ||' AND resources BETWEEN :frsrc and :trsrc ) ';
17923      EXECUTE IMMEDIATE delete_stmt USING l_calendar_id, p_orgn_code,
17924                    p_orgn_code, v_from_rsrc, v_to_rsrc;
17925     ELSIF (v_from_rsrc IS NOT NULL AND v_to_rsrc IS NULL) THEN
17926       delete_stmt := delete_stmt ||' AND resource_id in (select resource_id '
17927                             ||' FROM cr_rsrc_dtl '
17928                             ||' WHERE orgn_code = :Plant_code2 '
17929                             ||' AND resources > :frsrc ) ';
17930      EXECUTE IMMEDIATE delete_stmt USING l_calendar_id, p_orgn_code,
17931                    p_orgn_code, v_from_rsrc;
17932 
17933     ELSIF (v_from_rsrc IS NULL AND v_to_rsrc IS NULL) THEN
17934      EXECUTE IMMEDIATE delete_stmt USING l_calendar_id, p_orgn_code ;
17935 
17936     END IF ;
17937 
17938     COMMIT;
17939 
17940     retrieve_calendar_detail(l_calendar_id,
17941                              l_calendar_no,
17942                              l_calendar_desc,
17943                              null,
17944                              null,
17945                              null,
17946                              V_WPS,
17947                              ret_status)  ;
17948 
17949     /* Summary rows for WPS */
17950     net_rsrc_insert(null,
17951                     p_orgn_code,
17952                     null,
17953                     null,
17954                     0,
17955                     sysdate,
17956                     l_calendar_id,
17957                     V_WPS,
17958                     ret_status)  ;
17959     COMMIT ;
17960 
17961     /* Instance number rows for WPS */
17962     net_rsrc_avail_calculate(null,
17963                              p_orgn_code,
17964                              l_calendar_id,
17965                              null,   /* MSC INSTANCE */
17966                              null,   /* DB LINK */
17967                              V_WPS,
17968                              ret_status)  ;
17969     COMMIT ;
17970 
17971 END LOOP ;
17972 CLOSE cur_get_cal ; -- HW B4309093
17973 
17974     retcode := 0 ;
17975 
17976 EXCEPTION
17977    WHEN NO_DATA_FOUND THEN
17978        l_message := 'Manufacturing Calendar is not assigned to '|| p_orgn_code ;
17979        log_message(l_message);
17980        retcode := 1 ;
17981    WHEN OTHERS THEN
17982        log_message(sqlerrm);
17983        retcode := 1 ;
17984 
17985 END insert_gmp_resource_avail;
17986 
17987 /*
17988 REM+==========================================================================+
17989 REM| PROCEDURE NAME                                                           |
17990 REM|    net_rsrc_avail_calculate                                              |
17991 REM|                                                                          |
17992 REM| Type                                                                     |
17993 REM|    public                                                                |
17994 REM|                                                                          |
17995 REM| DESCRIPTION                                                              |
17996 REM|                                                                          |
17997 REM| Input Parameters                                                         |
17998 REM|    p_nstance_id - Instance_id                                            |
17999 REM|    p_orgn_code - Orgn Code                                               |
18000 REM|    p_instance_id - Instance Id                                           |
18001 REM|    p_db_link - Data Base Link                                            |
18002 REM|                                                                          |
18003 REM| Output Parameters                                                        |
18004 REM|    return_status                                                         |
18005 REM|                                                                          |
18006 REM| HISTORY                                                                  |
18007 REM|    Created on 4th Jan 2002 By Rajesh Patangya                            |
18008 REM|    7th Mar 2003 -- Performance issue fix and B2671540 00:00 shift fix    |
18009 REM| B3161696 - 26-SEP-2003 TARGETTED RESOURCE AVAILABILITY PLACEHOLDER BUG   |
18010 REM| B4309093 - 20-APR-2005 Modified code to TO ADD TIME OR A SHIFT TO A      |
18011 REM|                        PLANT RESOURCE                                    |
18012 REM+==========================================================================+
18013 */
18014 
18015 PROCEDURE net_rsrc_avail_calculate(
18016                           p_org_id       IN PLS_INTEGER,
18017                           p_orgn_code    IN VARCHAR2,
18018                           p_calendar_id  IN PLS_INTEGER,
18019                           p_instance_id  IN PLS_INTEGER,
18020                           p_db_link      IN VARCHAR2,
18021                           p_usage        IN VARCHAR2,   /* OPM-PS */
18022                           return_status  OUT NOCOPY BOOLEAN) IS
18023 
18024 /* For GMP_RESOURCE_AVAIL array definition */
18025 TYPE interval_typ is RECORD
18026 (
18027   resource_id           PLS_INTEGER,
18028   resource_instance_id  PLS_INTEGER,
18029   shift_date            DATE,
18030   shift_num             PLS_INTEGER,
18031   resource_units        PLS_INTEGER,
18032   from_time             PLS_INTEGER,
18033   to_time               PLS_INTEGER
18034 );
18035 
18036 TYPE interval_tab is table of interval_typ index by BINARY_INTEGER;
18037 
18038 interval_record		interval_typ;
18039 interval_rec		interval_tab;
18040 
18041 ri_assembly	        ref_cursor_typ;
18042 ri_shift_interval	ref_cursor_typ;
18043 
18044 sqlstmt		        VARCHAR2(32700) ;
18045 sqlupt 		        VARCHAR2(32700) ;
18046 sql_stmt1		VARCHAR2(32700) ;
18047 sql_stmt2		VARCHAR2(32700) ;
18048 
18049 k         		INTEGER ;
18050 i         		INTEGER ;
18051 j         		INTEGER ;
18052 g_calendar_id           PLS_INTEGER  ;
18053 x_dept_id               PLS_INTEGER  ;
18054 
18055 BEGIN
18056 
18057          /* 8i Database does not support BULK COLLECT - B3881832 */
18058          sqlstmt	 := NULL;
18059          sqlupt 	 := NULL;
18060          sql_stmt1	 := NULL;
18061          sql_stmt2	 := NULL;
18062          stmt_no	 := 0 ;
18063          x_dept_id       := 0 ;
18064          k         	 := 1;
18065          i         	 := 1;
18066          j         	 := 1;
18067          resource_count  := empty_pls_table;
18068          resource_id     := empty_pls_table;
18069          instance_id     := empty_pls_table;
18070          instance_number := empty_pls_table;
18071          shift_num       := empty_pls_table;
18072          f_date          := empty_dat_table;
18073          t_date          := empty_dat_table;
18074          /* 8i Database does not support BULK COLLECT - B3881832 */
18075          dbms_session.free_unused_user_memory;
18076 
18077          stmt_no := 60;
18078          -- Rajesh Patangya B4692705, When the calendar is not assigned to
18079          -- resource then organization calendar should be considered
18080 	 g_calendar_id 	:= 0 ;
18081          sql_stmt1 :=  '  SELECT mfg_calendar_id '
18082                     || '  FROM sy_orgn_mst'||p_db_link
18083                     || '  WHERE orgn_code = :orgn_code1 ';
18084 
18085          EXECUTE IMMEDIATE sql_stmt1 INTO g_calendar_id USING p_orgn_code ;
18086 
18087          IF g_calendar_id = 0 THEN
18088             log_message('Warning : '||p_orgn_code||
18089                     ' does not have manufacturing calendar, continuing ...') ;
18090          END IF;
18091 
18092     /* Interval Cursor gives the all the point of inflections  */
18093 
18094     stmt_no := 63;
18095     /*  03/26/02 Rajesh Patangya B2282409, Filter extra resource information */
18096     -- HW B4309093 Check for calendar id in cr_rsrc_dtl
18097        sql_stmt1 :=  ' SELECT /*+ ALL_ROWS */ '
18098                   || '  decode(rt.interval_date,rt.lead_idate,rt.assigned_qty,'
18099                   || '  (rt.assigned_qty-nvl(rt.rsum,0))) resource_count '
18100                   || '  ,rt.resource_id '
18101                   || '  ,rt.instance_id '
18102                   || '  ,rt.shift_num '
18103                   || '  ,rt.interval_date '
18104                   || '  ,rt.lead_idate    '
18105                -- for OPM-PS
18106                   || '  ,NVL(gri.eqp_serial_number, to_char(gri.instance_number)) '
18107                   || '  ,gri.equipment_item_id '
18108                   || '  ,((rt.resource_id * 2) + 1) '
18109                   || '  ,((rt.instance_id * 2) + 1) '
18110                   || ' FROM '
18111                   || ' ( '
18112                   || ' SELECT '
18113                   || '  t.resource_id '
18114                   || '  ,t.instance_id '
18115                   || '  ,t.shift_num  '
18116                   || '  ,t.interval_date '
18117                   || '  ,t.assigned_qty  '
18118                   || '  ,nvl(u.resource_units,0) rsum  '
18119                   || '  ,max(t.lead_idate) lead_idate '
18120                   || ' FROM ( '
18121                   || ' SELECT unique resource_id,instance_id,from_date, '
18122                   || ' to_date to_date1,resource_units '
18123                   || ' FROM ( '
18124                   || ' SELECT un.resource_id, '
18125                   || '        gri.instance_id, '
18126                   || '        un.from_date,  '
18127                   || '        un.to_date,    '
18128                   || '        1 resource_units'
18129                   || ' FROM   cr_rsrc_dtl '||p_db_link||'  crd, '
18130                   || '        gmp_rsrc_unavail_dtl_v '||p_db_link||' un, '
18131                   || '        gmp_resource_instances '||p_db_link||' gri '
18132                   || ' WHERE  crd.resource_id = un.resource_id  '
18133                   || ' AND    crd.resource_id = gri.resource_id  '
18134                   || ' AND    un.instance_id  = gri.instance_id  '
18135                   || ' AND    crd.orgn_code = :orgn_code1 ' ;
18136 
18137     IF (p_usage = 'BASED') THEN   /* Usage APS */
18138     sql_stmt1 := sql_stmt1
18139                   || ' AND    crd.calendar_id = :l_cal_id1 ' ;
18140     ELSE
18141     sql_stmt1 := sql_stmt1
18142                   || ' AND    nvl(crd.calendar_id,:g_default_cal_id1)=:l_cal_id1 ';
18143     END IF ;
18144 
18145     sql_stmt1 := sql_stmt1
18146                   || ' AND    crd.schedule_ind = 2 '
18147                   || ' AND    crd.delete_mark = 0 '
18148                   || ' AND    nvl(un.instance_id,0) <> 0  ' ;
18149 
18150     IF (v_from_rsrc IS NOT NULL AND v_to_rsrc IS NOT NULL) THEN
18151     sql_stmt1 := sql_stmt1 || '  AND crd.resources BETWEEN :frsrc1 and :trsrc2 ' ;
18152     END IF ;
18153 
18154 -- HW B4309093 Check for calendar id in cr_rsrc_dtl
18155     sql_stmt1 := sql_stmt1
18156                   || ' UNION ALL '
18157                   || ' SELECT un.resource_id, '
18158                   || '        gri.instance_id, '
18159                   || '        un.from_date,  '
18160                   || '        un.to_date,    '
18161                   || '        1 resource_units'
18162                   || ' FROM   cr_rsrc_dtl '||p_db_link||'  crd, '
18163                   || '        gmp_rsrc_unavail_dtl_v '||p_db_link||' un, '
18164                   || '        gmp_resource_instances '||p_db_link||' gri '
18165                   || ' WHERE  crd.resource_id = un.resource_id  '
18166                   || ' AND    crd.resource_id = gri.resource_id  '
18167                   || ' AND    crd.orgn_code = :orgn_code2 ' ;
18168 
18169     IF (p_usage = 'BASED') THEN   /* Usage APS */
18170     sql_stmt1 := sql_stmt1
18171                   || ' AND    crd.calendar_id = :l_cal_id2 ' ;
18172     ELSE
18173     sql_stmt1 := sql_stmt1
18174                   || ' AND    nvl(crd.calendar_id ,:g_default_cal_id2)= :l_cal_id2 ' ;
18175     END IF;
18176 
18177     sql_stmt1 := sql_stmt1
18178                   || ' AND    crd.delete_mark = 0 '
18179                   || ' AND    crd.schedule_ind = 2 '
18180                   || ' AND    nvl(un.instance_id,0) = 0  ' ;
18181 
18182     IF (v_from_rsrc IS NOT NULL AND v_to_rsrc IS NOT NULL) THEN
18183     sql_stmt1 := sql_stmt1 || '  AND crd.resources BETWEEN :frsrc2 and :trsrc2 ' ;
18184     END IF ;
18185 -- HW B4309093 Check for calendar id in cr_rsrc_dtl
18186     sql_stmt1 := sql_stmt1
18187                   || ' AND    gri.instance_number in '
18188                   || '      ( select tgri.instance_number '
18189                   || '      FROM gmp_resource_instances '||p_db_link||' tgri '
18190                   || '      WHERE tgri.resource_id = crd.resource_id '
18191                   || '      AND rownum <= un.resource_units '
18192                   || '      ) '
18193                   || '   ) '
18194                   || ' ) u, '
18195                   || ' 	( '
18196                   || '  SELECT	resource_id,instance_id, shift_num, '
18197                   || '          interval_date,assigned_qty,lead_idate '
18198                   || ' 	FROM '
18199                   || ' 		( '
18200                   || ' 		SELECT '
18201                   || ' 			resource_id,instance_id,shift_num, '
18202                   || '                  interval_date,1 assigned_qty, '
18203                   || ' 			lead(resource_id,1) over(order by '
18204     || ' resource_id,instance_id,interval_date,shift_num) as lead_rid, '
18205                   || ' 			lead(instance_id,1) over(order by '
18206     || ' resource_id,instance_id,interval_date,shift_num) as lead_iid, '
18207                   || ' 			lead(interval_date,1) over(order by '
18208     || ' resource_id,instance_id,interval_date,shift_num) as lead_idate, '
18209                   || ' 			lead(shift_num,1) over(order by '
18210     || ' resource_id,instance_id,interval_date,shift_num) as lead_snum '
18211                   || ' 		FROM '
18212                   || ' 			( '
18213                   || ' SELECT unique cmd.resource_id, '
18214                   || ' cmd.instance_id, '
18215                   || ' exp.shift_num, '
18216                   || ' 1 , '
18217                   || ' cmd.interval_date '
18218                   || ' FROM ( '
18219                   || ' SELECT un.resource_id resource_id, '
18220                   || '        gri.instance_id instance_id,'
18221                   || '        0 shift_num,'
18222                   || '        1 resource_count,'
18223                   || '        un.from_date interval_date '
18224                   || ' FROM   cr_rsrc_dtl '||p_db_link||'  crd, '
18225                   || '        gmp_rsrc_unavail_dtl_v '||p_db_link||' un, '
18226                   || '        gmp_resource_instances '||p_db_link||' gri '
18227                   || ' WHERE  crd.resource_id = un.resource_id  '
18228                   || ' AND    crd.resource_id = gri.resource_id  '
18229                   || ' AND    un.instance_id  = gri.instance_id  '
18230                   || ' AND    crd.orgn_code = :orgn_code3 ' ;
18231 
18232     IF (p_usage = 'BASED') THEN   /* Usage APS */
18233     sql_stmt1 := sql_stmt1
18234                   || ' AND    crd.calendar_id = :l_cal_id3 ' ;
18235     ELSE
18236     sql_stmt1 := sql_stmt1
18237                   || ' AND    nvl(crd.calendar_id ,:g_default_cal_id3)= :l_cal_id3 ' ;
18238     END IF;
18239 
18240     sql_stmt1 := sql_stmt1
18241                   || ' AND    crd.schedule_ind = 2 '
18242                   || ' AND    crd.delete_mark = 0 '
18243                   || ' AND    nvl(un.instance_id,0) <> 0  ' ;
18244 
18245     IF (v_from_rsrc IS NOT NULL AND v_to_rsrc IS NOT NULL) THEN
18246     sql_stmt1 := sql_stmt1 || '  AND crd.resources BETWEEN :frsrc3 and :trsrc3 ' ;
18247     END IF ;
18248 
18249 -- HW B4309093 Check for calendar id in cr_rsrc_dtl
18250     sql_stmt1 := sql_stmt1
18251                   || ' UNION ALL '
18252                   || ' SELECT un.resource_id resource_id, '
18253                   || '        gri.instance_id instance_id,'
18254                   || '        0 shift_num,'
18255                   || '        1 resource_count,'
18256                   || '        un.to_date interval_date '
18257                   || ' FROM   cr_rsrc_dtl '||p_db_link||'  crd, '
18258                   || '        gmp_rsrc_unavail_dtl_v '||p_db_link||' un, '
18259                   || '        gmp_resource_instances '||p_db_link||' gri '
18260                   || ' WHERE  crd.resource_id = un.resource_id  '
18261                   || ' AND    crd.resource_id = gri.resource_id  '
18262                   || ' AND    un.instance_id  = gri.instance_id  '
18263                   || ' AND    crd.orgn_code = :orgn_code4 ' ;
18264     IF (p_usage = 'BASED') THEN   /* Usage APS */
18265     sql_stmt1 := sql_stmt1
18266                   || ' AND    crd.calendar_id = :l_cal_id4 ' ;
18267     ELSE
18268     sql_stmt1 := sql_stmt1
18269                   || ' AND    nvl(crd.calendar_id ,:g_default_cal_id4)= :l_cal_id4 ' ;
18270     END IF;
18271 
18272     sql_stmt1 := sql_stmt1
18273                   || ' AND    crd.schedule_ind = 2 '
18274                   || ' AND    crd.delete_mark = 0 '
18275                   || ' AND    nvl(un.instance_id,0) <> 0  ' ;
18276 
18277     IF (v_from_rsrc IS NOT NULL AND v_to_rsrc IS NOT NULL) THEN
18278     sql_stmt1 := sql_stmt1 || '  AND crd.resources BETWEEN :frsrc4 and :trsrc4 ' ;
18279     END IF ;
18280 
18281 -- HW B4309093 Check for calendar id in cr_rsrc_dtl
18282     sql_stmt1 := sql_stmt1
18283                   || ' UNION ALL '
18284                   || ' SELECT un.resource_id resource_id, '
18285                   || '        gri.instance_id instance_id,'
18286                   || '        0 shift_num,'
18287                   || '        1 resource_count,'
18288                   || '        un.from_date interval_date '
18289                   || ' FROM   cr_rsrc_dtl '||p_db_link||'  crd, '
18290                   || '        gmp_rsrc_unavail_dtl_v '||p_db_link||' un, '
18291                   || '        gmp_resource_instances '||p_db_link||' gri '
18292                   || ' WHERE  crd.resource_id = un.resource_id  '
18293                   || ' AND    crd.resource_id = gri.resource_id  '
18294                   || ' AND    crd.orgn_code = :orgn_code5 ' ;
18295     IF (p_usage = 'BASED') THEN   /* Usage APS */
18296     sql_stmt1 := sql_stmt1
18297                   || ' AND    crd.calendar_id = :l_cal_id5 ' ;
18298     ELSE
18299     sql_stmt1 := sql_stmt1
18300                   || ' AND    nvl(crd.calendar_id ,:g_default_cal_id5)= :l_cal_id5 ' ;
18301     END IF;
18302 
18303     sql_stmt1 := sql_stmt1
18304                   || ' AND    crd.schedule_ind = 2 '
18305                   || ' AND    crd.delete_mark = 0 '
18306                   || ' AND    nvl(un.instance_id,0) = 0  ' ;
18307 
18308     IF (v_from_rsrc IS NOT NULL AND v_to_rsrc IS NOT NULL) THEN
18309     sql_stmt1 := sql_stmt1 || '  AND crd.resources BETWEEN :frsrc5 and :trsrc5 ' ;
18310     END IF ;
18311 
18312 -- HW B4309093 Check for calendar id in cr_rsrc_dtl
18313     sql_stmt1 := sql_stmt1
18314                   || ' AND    gri.instance_number in '
18315                   || '      ( select tgri.instance_number '
18316                   || '      FROM gmp_resource_instances '||p_db_link||' tgri '
18317                   || '      WHERE tgri.resource_id = crd.resource_id '
18318                   || '      AND rownum <= un.resource_units '
18319                   || '      ) '
18320                   || ' UNION ALL '
18321                   || ' SELECT un.resource_id resource_id, '
18322                   || '        gri.instance_id instance_id,'
18323                   || '        0 shift_num,'
18324                   || '        1 resource_count,'
18325                   || '        un.to_date interval_date '
18326                   || ' FROM   cr_rsrc_dtl '||p_db_link||'  crd, '
18327                   || '        gmp_rsrc_unavail_dtl_v '||p_db_link||' un, '
18328                   || '        gmp_resource_instances '||p_db_link||' gri '
18329                   || ' WHERE  crd.resource_id = un.resource_id  '
18330                   || ' AND    crd.resource_id = gri.resource_id  '
18331                   || ' AND    crd.orgn_code = :orgn_code6 ' ;
18332 
18333     IF (p_usage = 'BASED') THEN   /* Usage APS */
18334     sql_stmt1 := sql_stmt1
18335                   || ' AND    crd.calendar_id = :l_cal_id6 ' ;
18336     ELSE
18337     sql_stmt1 := sql_stmt1
18338                   || ' AND    nvl(crd.calendar_id ,:g_default_cal_id6)= :l_cal_id6 ' ;
18339     END IF;
18340 
18341     sql_stmt1 := sql_stmt1
18342                   || ' AND    crd.delete_mark = 0 '
18343                   || ' AND    crd.schedule_ind = 2 '
18344                   || ' AND    nvl(un.instance_id,0) = 0  ' ;
18345 
18346     IF (v_from_rsrc IS NOT NULL AND v_to_rsrc IS NOT NULL) THEN
18347     sql_stmt1 := sql_stmt1 || '  AND crd.resources BETWEEN :frsrc6 and :trsrc6 ' ;
18348     END IF ;
18349 
18350 -- HW B4309093 Check for calendar id in cr_rsrc_dtl
18351     sql_stmt1 := sql_stmt1
18352                   || ' AND    gri.instance_number in '
18353                   || '      ( select tgri.instance_number '
18354                   || '      FROM gmp_resource_instances '||p_db_link||' tgri '
18355                   || '      WHERE tgri.resource_id = crd.resource_id '
18356                   || '      AND rownum <= un.resource_units '
18357                   || '      ) '
18358                   || '    )   cmd,  '
18359                   || '        gmp_calendar_detail_gtmp ' ||p_db_link||' exp  '
18360                   || '      WHERE  exp.calendar_id = :curr_cal1 '
18361                   || '        AND  cmd.interval_date  BETWEEN '
18362                   || '             exp.from_date AND exp.to_date '
18363                   || ' UNION ALL '
18364                   || ' SELECT crd.resource_id , '
18365                   || '        gri.instance_id, '
18366                   || '        exp.shift_num,  '
18367                   || '        1 , '
18368                   || '        (exp.shift_date + '
18369                   || '               (exp.from_time/86400)) interval_date '
18370                   || ' FROM   cr_rsrc_dtl '||p_db_link||'  crd, '
18371                   || '        gmp_calendar_detail_gtmp ' ||p_db_link||' exp, '
18372                   || '        gmp_resource_instances '||p_db_link||' gri '
18373                   || ' WHERE  crd.orgn_code = :orgn_code7 ' ;
18374 
18375     IF (p_usage = 'BASED') THEN   /* Usage APS */
18376     sql_stmt1 := sql_stmt1
18377                   || ' AND    crd.calendar_id = :l_cal_id7 ' ;
18378     ELSE
18379     sql_stmt1 := sql_stmt1
18380                   || ' AND    nvl(crd.calendar_id ,:g_default_cal_id7)= :l_cal_id7 ' ;
18381     END IF;
18382 
18383     sql_stmt1 := sql_stmt1
18384                   || ' AND    exp.calendar_id = :curr_cal2 '
18385                   || ' AND    crd.resource_id = gri.resource_id  '
18386                   || ' AND    crd.delete_mark = 0 '
18387                   || ' AND    crd.schedule_ind = 2 ' ;
18388 
18389     IF (v_from_rsrc IS NOT NULL AND v_to_rsrc IS NOT NULL) THEN
18390     sql_stmt1 := sql_stmt1 || '  AND crd.resources BETWEEN :frsrc7 and :trsrc7 ' ;
18391     END IF ;
18392 
18393 -- HW B4309093 Check for calendar id in cr_rsrc_dtl
18394     sql_stmt1 := sql_stmt1
18395                   || ' UNION ALL '
18396                   || ' SELECT crd.resource_id , '
18397                   || '        gri.instance_id, '
18398                   || '        exp.shift_num,  '
18399                   || '        1 , '
18400                   || '        (exp.shift_date + '
18401                   || '               (exp.to_time/86400)) interval_date '
18402                   || ' FROM   cr_rsrc_dtl '||p_db_link||'  crd, '
18403                   || '        gmp_calendar_detail_gtmp ' ||p_db_link||' exp, '
18404                   || '        gmp_resource_instances '||p_db_link||' gri '
18405                   || ' WHERE  crd.orgn_code = :orgn_code8 ' ;
18406 
18407     IF (p_usage = 'BASED') THEN   /* Usage APS */
18408     sql_stmt1 := sql_stmt1
18409                   || ' AND    crd.calendar_id = :l_cal_id8 ' ;
18410     ELSE
18411     sql_stmt1 := sql_stmt1
18412                   || ' AND    nvl(crd.calendar_id ,:g_default_cal_id8)= :l_cal_id8 ' ;
18413     END IF;
18414 
18415     sql_stmt1 := sql_stmt1
18416                   || ' AND    exp.calendar_id = :curr_cal3 '
18417                   || ' AND    crd.resource_id = gri.resource_id  '
18418                   || ' AND    crd.delete_mark = 0 ' ;
18419 
18420     IF (v_from_rsrc IS NOT NULL AND v_to_rsrc IS NOT NULL) THEN
18421     sql_stmt1 := sql_stmt1 || '  AND crd.resources BETWEEN :frsrc8 and :trsrc8 ' ;
18422     END IF ;
18423 
18424     sql_stmt1 := sql_stmt1
18425                   || ' AND    crd.schedule_ind = 2 '
18426                   || '                  ) '
18427                   || '          ) '
18428                   || '    WHERE resource_id = lead_rid '
18429                   || '      AND instance_id = lead_iid '
18430                   || '      AND trunc(interval_date) = trunc(lead_idate) '
18431                   || '      AND interval_date < lead_idate '
18432                   || '      AND shift_num = lead_snum  '
18433                   || '  ) t '
18434                   || ' WHERE '
18435                   || '      t.interval_date >= u.from_date(+) '
18436                   || '  AND t.lead_idate <= u.to_date1 (+) '
18437                   || '  AND t.resource_id = u.resource_id(+) '
18438                   || '  AND t.instance_id = u.instance_id(+) '
18439                   || ' GROUP BY '
18440                   || '   t.resource_id '
18441                   || '  ,t.instance_id '
18442                   || '  ,t.shift_num '
18443                   || '  ,t.interval_date '
18444                   || '  ,u.resource_units '
18445                   || '  ,t.assigned_qty '
18446                   || ' ) rt, '
18447                   || '   gmp_resource_instances '||p_db_link||' gri '
18448                   || ' WHERE '
18449                   || '  decode(rt.interval_date,rt.lead_idate,rt.assigned_qty,'
18450                   || '        (rt.assigned_qty - nvl(rt.rsum,0))) > 0 '
18451                   || '  AND rt.resource_id = gri.resource_id '
18452                   || '  AND rt.instance_id = gri.instance_id '
18453                   || ' ORDER BY rt.resource_id ,rt.instance_id, '
18454                   || '  rt.interval_date,rt.shift_num ' ;
18455 
18456     IF (v_from_rsrc IS NOT NULL AND v_to_rsrc IS NOT NULL) THEN
18457 
18458 -- HW B4309093 Pass correct parameters
18459     OPEN ri_shift_interval FOR sql_stmt1 USING
18460       p_orgn_code,p_calendar_id, p_calendar_id,V_FROM_RSRC, V_TO_RSRC,
18461       p_orgn_code, p_calendar_id,p_calendar_id,V_FROM_RSRC, V_TO_RSRC,
18462       p_orgn_code, p_calendar_id,p_calendar_id,V_FROM_RSRC, V_TO_RSRC,
18463       p_orgn_code, p_calendar_id,p_calendar_id,V_FROM_RSRC, V_TO_RSRC,
18464       p_orgn_code, p_calendar_id,p_calendar_id,V_FROM_RSRC, V_TO_RSRC,
18465       p_orgn_code, p_calendar_id,p_calendar_id,V_FROM_RSRC, V_TO_RSRC,
18466       p_calendar_id,
18467       p_orgn_code, p_calendar_id,p_calendar_id,p_calendar_id, V_FROM_RSRC, V_TO_RSRC,
18468       p_orgn_code, p_calendar_id,p_calendar_id,p_calendar_id, V_FROM_RSRC, V_TO_RSRC ;
18469 
18470     ELSE
18471 -- HW B4309093 Pass correct parameters
18472       IF (p_usage = 'BASED') THEN   /* Usage APS */
18473         OPEN ri_shift_interval FOR sql_stmt1 USING
18474 	    p_orgn_code,p_calendar_id,
18475     	    p_orgn_code,p_calendar_id,
18476 	    p_orgn_code,p_calendar_id,
18477 	    p_orgn_code,p_calendar_id,
18478 	    p_orgn_code,p_calendar_id,
18479             p_orgn_code,p_calendar_id, p_calendar_id,
18480             p_orgn_code,p_calendar_id,p_calendar_id,
18481             p_orgn_code,p_calendar_id, p_calendar_id ;
18482 
18483        ELSE
18484         OPEN ri_shift_interval FOR sql_stmt1 USING
18485 	    p_orgn_code,g_calendar_id,p_calendar_id,
18486     	    p_orgn_code,g_calendar_id,p_calendar_id,
18487 	    p_orgn_code,g_calendar_id,p_calendar_id,
18488 	    p_orgn_code,g_calendar_id,p_calendar_id,
18489 	    p_orgn_code,g_calendar_id,p_calendar_id,
18490             p_orgn_code,g_calendar_id,p_calendar_id, p_calendar_id,
18491             p_orgn_code,g_calendar_id, p_calendar_id,p_calendar_id,
18492             p_orgn_code,g_calendar_id,p_calendar_id, p_calendar_id ;
18493 
18494 
18495       END IF;
18496     END IF;
18497 
18498     /* B3347284, Performance Issue */
18499     stmt_no := 644;
18500     j := 1 ;
18501     LOOP
18502        FETCH ri_shift_interval INTO resource_count(j), resource_id(j),
18503              instance_id(j), shift_num(j), f_date(j), t_date(j), msc_serial_number(j),
18504              equipment_item_id(j), x_resource_id(j), x_instance_id(j);
18505 
18506        EXIT WHEN ri_shift_interval%NOTFOUND;
18507 
18508     stmt_no := 665;
18509     i := 1 ;
18510     x_dept_id := ((p_org_id * 2) + 1) ;
18511     IF (resource_id.FIRST > 0) AND (j = 75000) THEN  /* Only if any resource */
18512 
18513        IF ((p_usage = 'APS') OR (p_usage = 'BASED')) THEN /* Usage APS/BASED */
18514 
18515 /* bug: 6030499 conditionalising the following code */
18516 IF collect_ps_data THEN
18517 
18518         FORALL i IN resource_id.FIRST..resource_id.LAST
18519 
18520         INSERT INTO msc_st_net_res_inst_avail
18521           ( Organization_Id,
18522             Department_id,
18523             sr_instance_id ,
18524             Resource_Id,
18525             res_instance_id,
18526             serial_number,
18527             equipment_item_id,
18528             Shift_Num,
18529             Shift_Date,
18530             From_Time,
18531             To_Time
18532          )  VALUES
18533          (
18534             p_org_id,
18535             x_dept_id,
18536             p_instance_id ,
18537             x_resource_id(i),
18538             x_instance_id(i),
18539             msc_serial_number(i),
18540             equipment_item_id(i),
18541             shift_num(i),
18542             trunc(f_date(i)),
18543             ((f_date(i) - trunc(f_date(i))) * 86400 ),
18544             ((t_date(i) - trunc(t_date(i))) * 86400 )
18545           )                     ;
18546 END IF;  -- Bug: 6030499
18547        ELSIF (p_usage = 'WPS') THEN   /* Usage WPS     */
18548 
18549         FORALL i IN resource_id.FIRST..resource_id.LAST
18550         INSERT INTO gmp_resource_avail
18551          (
18552           instance_id, plant_code, resource_id,
18553           calendar_id, resource_instance_id, shift_num,
18554           shift_date, from_time, to_time,
18555           resource_units, creation_date, created_by,
18556           last_update_date, last_updated_by, last_update_login
18557          )  VALUES
18558          (
18559             p_instance_id,
18560             p_orgn_code,
18561             resource_id(i),
18562             p_calendar_id,
18563             instance_id(i),
18564             shift_num(i),
18565             trunc(f_date(i)),
18566             ((f_date(i) - trunc(f_date(i))) * 86400 ),
18567             ((t_date(i) - trunc(t_date(i))) * 86400 ),
18568             resource_count(i),
18569             sysdate,
18570             FND_GLOBAL.USER_ID,
18571             sysdate,
18572             FND_GLOBAL.USER_ID,
18573             FND_GLOBAL.USER_ID
18574           )                     ;
18575 
18576        END IF;   /* APS or WPS */
18577 
18578          resource_count     := empty_pls_table;
18579          resource_id        := empty_pls_table;
18580          x_resource_id      := empty_pls_table;
18581          instance_id        := empty_pls_table;
18582          x_instance_id      := empty_pls_table;
18583          shift_num          := empty_pls_table;
18584          msc_serial_number  := emp_serial_number;
18585          equipment_item_id  := empty_pls_table;
18586          f_date             := empty_dat_table;
18587          t_date             := empty_dat_table;
18588          j := 0 ;
18589          /* 8i Database does not support BULK COLLECT - B3881832 */
18590          dbms_session.free_unused_user_memory;
18591 
18592    END IF;   /* Only if any resource */
18593 
18594    j := j + 1 ;
18595    END LOOP ;
18596    CLOSE ri_shift_interval;
18597 
18598 -- Bug: 6030499
18599           SELECT st.VALUE INTO v_dummy from V$MYSTAT st, V$STATNAME sn
18600           where st.STATISTIC# = sn.STATISTIC#
18601           and sn.NAME in ('session pga memory');
18602           log_message('Session pga memory = ' || TO_CHAR(v_dummy) );
18603 
18604     stmt_no := 666;
18605     i := 1 ;
18606     x_dept_id := ((p_org_id * 2) + 1) ;
18607     IF (resource_id.FIRST > 0) THEN  /* Only if any resource */
18608 
18609        IF ((p_usage = 'APS') OR (p_usage = 'BASED')) THEN /* Usage APS/BASED */
18610 
18611 /* bug: 6030499 conditionalising the following code */
18612 IF collect_ps_data THEN
18613 
18614         FORALL i IN resource_id.FIRST..resource_id.LAST
18615         INSERT INTO msc_st_net_res_inst_avail
18616           ( Organization_Id,
18617             Department_id,
18618             sr_instance_id ,
18619             Resource_Id,
18620             res_instance_id,
18621             serial_number,
18622             equipment_item_id,
18623             Shift_Num,
18624             Shift_Date,
18625             From_Time,
18626             To_Time
18627          )  VALUES
18628          (
18629             p_org_id,
18630             x_dept_id,
18631             p_instance_id ,
18632             x_resource_id(i),
18633             x_instance_id(i),
18634             msc_serial_number(i),
18635             equipment_item_id(i),
18636             shift_num(i),
18637             trunc(f_date(i)),
18638             ((f_date(i) - trunc(f_date(i))) * 86400 ),
18639             ((t_date(i) - trunc(t_date(i))) * 86400 )
18640           )                     ;
18641    END IF; -- bug: 6030499
18642 
18643        ELSIF (p_usage = 'WPS') THEN   /* Usage WPS     */
18644 
18645         FORALL i IN resource_id.FIRST..resource_id.LAST
18646         INSERT INTO gmp_resource_avail
18647          (
18648           instance_id, plant_code, resource_id,
18649           calendar_id, resource_instance_id, shift_num,
18650           shift_date, from_time, to_time,
18651           resource_units, creation_date, created_by,
18652           last_update_date, last_updated_by, last_update_login
18653          )  VALUES
18654          (
18655             p_instance_id,
18656             p_orgn_code,
18657             resource_id(i),
18658             p_calendar_id,
18659             instance_id(i),
18660             shift_num(i),
18661             trunc(f_date(i)),
18662             ((f_date(i) - trunc(f_date(i))) * 86400 ),
18663             ((t_date(i) - trunc(t_date(i))) * 86400 ),
18664             resource_count(i),
18665             sysdate,
18666             FND_GLOBAL.USER_ID,
18667             sysdate,
18668             FND_GLOBAL.USER_ID,
18669             FND_GLOBAL.USER_ID
18670           )                     ;
18671 
18672        END IF;   /* APS or WPS */
18673 
18674          resource_count     := empty_pls_table;
18675          resource_id        := empty_pls_table;
18676          x_resource_id      := empty_pls_table;
18677          instance_id        := empty_pls_table;
18678          x_instance_id      := empty_pls_table;
18679          shift_num          := empty_pls_table;
18680          msc_serial_number  := emp_serial_number;
18681          equipment_item_id  := empty_pls_table;
18682          f_date             := empty_dat_table;
18683          t_date             := empty_dat_table;
18684          /* 8i Database does not support BULK COLLECT - B3881832 */
18685          dbms_session.free_unused_user_memory;
18686          COMMIT ;
18687 
18688    END IF;   /* Only if any resource */
18689 
18690    /* This logic introduced for Net resource availablility to
18691        write consolidated rows once final available rows are in place */
18692    stmt_no := 666;
18693    sql_stmt2 := NULL;
18694 
18695    sql_stmt2 :=  ' SELECT  /*+ ALL_ROWS */ '
18696    || '        net.resource_id , '
18697    || '        net.resource_instance_id, '
18698    || '        net.shift_date  , '
18699    || '        net.shift_num   , '
18700    || '        net.resource_units , '
18701    || '        min(net.from_time) from_time, '
18702    || '        max(net.lead_tt) to_time '
18703    || ' FROM  ( '
18704    || '        SELECT resource_id , '
18705    || '               resource_instance_id, '
18706    || '               shift_date  , '
18707    || '               shift_num , '
18708    || '               from_time , '
18709    || '               to_time , '
18710    || '               resource_units , '
18711    || '  lead(resource_id,1) over(order by resource_id,resource_instance_id, '
18712    || '  shift_date, shift_num,from_time,to_time,resource_units) as lead_rid, '
18713    || '  lead(resource_instance_id,1) over(order by resource_id, '
18714    || '  resource_instance_id, '
18715    || '  shift_date, shift_num,from_time,to_time,resource_units) as lead_iid, '
18716    || '  lead(shift_date,1) over(order by resource_id,resource_instance_id, '
18717    || '  shift_date, shift_num,from_time,to_time,resource_units) as lead_sdt, '
18718    || '  lead(shift_num,1) over(order by resource_id,resource_instance_id, '
18719    || '  shift_date, shift_num,from_time,to_time,resource_units) as lead_sn, '
18720    || '  lead(from_time,1) over(order by resource_id,resource_instance_id, '
18721    || '  shift_date, shift_num,from_time,to_time,resource_units) as lead_ft, '
18722    || '  lead(to_time,1) over(order by resource_id,resource_instance_id, '
18723    || '  shift_date, shift_num,from_time,to_time,resource_units) as lead_tt, '
18724    || '  lead(resource_units,1) over(order by resource_id, '
18725    || '  resource_instance_id, '
18726    || '  shift_date, shift_num,from_time,to_time,resource_units) as lead_rc '
18727    || '          FROM gmp_resource_avail'
18728    || '          WHERE plant_code = :orgn_code1 '
18729    || '            AND calendar_id = :cal_id ' ;
18730 
18731    IF (v_from_rsrc IS NOT NULL AND v_to_rsrc IS NOT NULL) THEN
18732 
18733    sql_stmt2 := sql_stmt2 ||' AND resource_id in (select resource_id '
18734                           ||' from cr_rsrc_dtl '||p_db_link
18735                           ||' WHERE orgn_code = :orgn_code2 '
18736                           ||' AND resources BETWEEN :frsrc and :trsrc )' ;
18737    END IF ;
18738 
18739    sql_stmt2 := sql_stmt2 || '              ) net '
18740    || '      WHERE net.resource_id          = net.lead_rid '
18741    || '        AND net.resource_instance_id = net.lead_iid '
18742    || '        AND net.shift_num      = net.lead_sn '
18743    || '        AND net.shift_date     = net.lead_sdt '
18744    || '        AND net.to_time        = net.lead_ft '
18745    || '        AND net.resource_units = net.lead_rc '
18746    || ' GROUP BY '
18747    || '        net.resource_id , '
18748    || '        net.resource_instance_id , '
18749    || '        net.shift_date , '
18750    || '        net.shift_num , '
18751    || '        net.resource_units ' ;
18752 
18753     stmt_no := 66;
18754 
18755     IF (v_from_rsrc IS NOT NULL AND v_to_rsrc IS NOT NULL) THEN
18756      OPEN ri_assembly FOR sql_stmt2 USING p_orgn_code, p_calendar_id,
18757           p_orgn_code, v_from_rsrc, v_to_rsrc ;
18758     ELSE
18759      OPEN ri_assembly FOR sql_stmt2 USING p_orgn_code, p_calendar_id ;
18760     END IF;
18761 
18762     LOOP
18763        FETCH ri_assembly INTO  interval_record;
18764        EXIT WHEN ri_assembly%NOTFOUND;
18765 
18766      sqlstmt := 'DELETE FROM gmp_resource_avail'
18767              || ' WHERE plant_code  = :Plant_code1 '
18768              || '   AND calendar_id = :cal_id '
18769              || '   AND resource_id = :prid '
18770              || '   AND resource_instance_id = :piid '
18771              || '   AND shift_date = :psdt '
18772              || '   AND shift_num  = :psn  '
18773              || '   AND from_time  >= :pft '
18774              || '   AND to_time  <= :ptt '
18775              || '   AND resource_units = :prc ' ;
18776 
18777    stmt_no := 67;
18778        EXECUTE immediate sqlstmt USING
18779        p_orgn_code , p_calendar_id ,
18780        interval_record.resource_id,
18781        interval_record.resource_instance_id,
18782        trunc(interval_record.shift_date),
18783        interval_record.shift_num,
18784        interval_record.from_time, interval_record.to_time,
18785        interval_record.resource_units  ;
18786 
18787    stmt_no := 68;
18788          net_rsrc_avail_insert(
18789             p_instance_id,
18790             p_orgn_code,
18791             interval_record.resource_instance_id,
18792             p_calendar_id,
18793             interval_record.resource_id,
18794             interval_record.resource_units,
18795             interval_record.shift_num,
18796             interval_record.shift_date,
18797             interval_record.from_time,
18798             interval_record.to_time
18799                   );
18800 
18801        COMMIT ;
18802     END LOOP;
18803     CLOSE ri_assembly;
18804 
18805 -- Bug: 6030499
18806           SELECT st.VALUE INTO v_dummy from V$MYSTAT st, V$STATNAME sn
18807           where st.STATISTIC# = sn.STATISTIC#
18808           and sn.NAME in ('session pga memory');
18809           log_message('ri_assembly Session pga memory = ' || TO_CHAR(v_dummy) );
18810 
18811 
18812    stmt_no := 69;
18813      sqlupt := 'UPDATE gmp_resource_avail'
18814             ||' SET to_time   = 86400 '
18815             ||' WHERE to_time = 86399 '
18816             ||'   AND shift_num >= 99999 ' ;
18817 
18818        EXECUTE immediate sqlupt ;
18819      sqlupt := null ;
18820      sqlupt := 'UPDATE gmp_resource_avail'
18821             ||' SET shift_num = (shift_num - 99999) '
18822             ||' WHERE shift_num >= 99999 ' ;
18823 
18824        EXECUTE immediate sqlupt ;
18825        COMMIT ;
18826 
18827     return_status := TRUE ;
18828   EXCEPTION
18829   WHEN NO_DATA_FOUND THEN
18830    log_message('NO DATA FOUND exception: MSC_CL_GMP_UTILITY.net_rsrc_avail_calculate');
18831    return_status := TRUE;
18832   WHEN  OTHERS THEN
18833    log_message('Error in Net Resource Instance Insert: '||stmt_no);
18834    log_message(sqlerrm);
18835    return_status := FALSE ;
18836 
18837 end net_rsrc_avail_calculate;
18838 
18839 /*
18840 REM+==========================================================================+
18841 REM| PROCEDURE NAME                                                           |
18842 REM|    net_rsrc_avail_insert                                                 |
18843 REM|                                                                          |
18844 REM| Type                                                                     |
18845 REM|    public                                                                |
18846 REM|                                                                          |
18847 REM| DESCRIPTION                                                              |
18848 REM|    The following procedure inserts rows into gmp_resource_avail          |
18849 REM|                                                                          |
18850 REM| Input Parameters                                                         |
18851 REM|    p_instance_id - Instance Id                                           |
18852 REM|    p_orgn_code - Plant Code                                              |
18853 REM|    p_resource_instance_id - Resource Instance Id                         |
18854 REM|    p_Calendar_id - Calendar id                                           |
18855 REM|    p_resource_id - Resource Id                                           |
18856 REM|    p_assigned_qty -  Resource units                                      |
18857 REM|    p_shift_num - Shift number                                            |
18858 REM|    p_calendar_date - Calendar date                                       |
18859 REM|    p_from_time - shift starting time                                     |
18860 REM|    p_to_time - Shift Ending time                                         |
18861 REM|                                                                          |
18862 REM| Output Parameters                                                        |
18863 REM|    None                                                                  |
18864 REM|                                                                          |
18865 REM| HISTORY                                                                  |
18866 REM|    Created on 4th Jan 2002 By Rajesh Patangya                            |
18867 REM|                                                                          |
18868 REM+==========================================================================+
18869 */
18870 
18871 PROCEDURE net_rsrc_avail_insert(p_instance_id          IN NUMBER,
18872                                 p_orgn_code            IN VARCHAR2,
18873                                 p_resource_instance_id IN NUMBER,
18874                                 p_calendar_id          IN NUMBER,
18875                                 p_resource_id          IN NUMBER,
18876                                 p_assigned_qty         IN NUMBER,
18877                                 p_shift_num            IN NUMBER,
18878                                 p_calendar_date        IN DATE,
18879                                 p_from_time            IN NUMBER,
18880                                 p_to_time              IN NUMBER ) IS
18881 
18882 BEGIN
18883    IF nvl(p_from_time,0) = 0  AND nvl(p_to_time,0) = 0 THEN
18884      NULL ;
18885    ELSE
18886      INSERT INTO gmp_resource_avail (
18887      instance_id, plant_code, resource_id,
18888      calendar_id, resource_instance_id, shift_num,
18889      shift_date, from_time, to_time,
18890      resource_units, creation_date, created_by,
18891      last_update_date, last_updated_by, last_update_login )
18892      VALUES (
18893              p_instance_id,
18894              p_orgn_code,
18895              p_resource_id,
18896              p_calendar_id,
18897              p_resource_instance_id,
18898              p_shift_num,
18899              p_calendar_date,
18900              p_from_time,
18901              p_to_time,
18902              p_assigned_qty,
18903              sysdate,
18904              FND_GLOBAL.USER_ID,
18905              sysdate,
18906              FND_GLOBAL.USER_ID,
18907              FND_GLOBAL.USER_ID ) ;
18908     END IF;
18909 EXCEPTION
18910   WHEN  OTHERS THEN
18911      log_message('Error in Net Resource Avail Insert ' || sqlerrm);
18912 
18913 END net_rsrc_avail_insert;
18914 
18915 /*
18916 REM+=========================================================================+
18917 REM| FUNCTION NAME                                                           |
18918 REM|    ORG_STRING                                                           |
18919 REM| DESCRIPTION                                                             |
18920 REM|    To find out the organization string                                  |
18921 REM| HISTORY                                                                 |
18922 REM| 12/21/2005   Rajesh Patangya                                            |
18923 REM+=========================================================================+
18924 */
18925 FUNCTION ORG_STRING(instance_id IN NUMBER) return BOOLEAN IS
18926 
18927  sql_stmt         varchar2(32000);
18928  c_str            ref_cursor_typ ;
18929  l_aps_compatible number ;
18930  org_str          varchar2(32767) ;
18931  in_position      number ;
18932 
18933 BEGIN
18934  sql_stmt           := NULL ;
18935  l_aps_compatible   := 0 ;
18936  org_str            := NULL ;
18937  in_position        := -10 ;
18938 
18939     SELECT MSC_CL_GMP_UTILITY.is_aps_compatible
18940     INTO l_aps_compatible  FROM DUAL ;
18941 
18942     IF l_aps_compatible = 1 THEN
18943 
18944        /*sql_stmt := 'SELECT MSC_CL_PULL.get_org_str(' || instance_id || ') FROM dual ' ;
18945        OPEN c_str FOR sql_stmt ;
18946        FETCH c_str INTO org_str ;
18947        log_message(' String From APS : ' || org_str);
18948        CLOSE c_str ;*/
18949 
18950        org_str := MSC_CL_PULL.get_org_str(instance_id); /* Bug # 5086464 Commented the code above and added this line */
18951 
18952 --  org_str := 'IN (1381,1382)' ;
18953          in_position := instr(org_str,'IN');
18954 
18955          /* B3450303, For all org or specific org, APS will provide valid org string
18956             We have to find the IN part in the string, otherwise have to raise
18957             Exception message for error condition */
18958 
18959          IF in_position > 0 THEN
18960          	MSC_CL_GMP_UTILITY.g_in_str_org  := org_str ;
18961         	return TRUE  ;
18962          ELSE
18963          	MSC_CL_GMP_UTILITY.g_in_str_org := NULL ;
18964         	return FALSE ;
18965          END IF;
18966 
18967 
18968     ELSE
18969      /* For older patchset This value should be TRUE */
18970         MSC_CL_GMP_UTILITY.g_in_str_org := NULL ;
18971         return TRUE  ;
18972     END IF;
18973 
18974    EXCEPTION
18975      WHEN OTHERS THEN
18976        log_message('Error in org_string ' || sqlerrm);
18977        MSC_CL_GMP_UTILITY.g_in_str_org := NULL ;
18978        return FALSE ;
18979 END ORG_STRING;
18980 
18981 FUNCTION GMP_CAL_UTILITY1_R10
18982             (
18983                           p_dblink      IN VARCHAR2,
18984                           p_delimiter   IN VARCHAR2,
18985                           p_instance    IN INTEGER,
18986                           p_run_date    IN DATE,
18987                           p_num1        IN NUMBER,
18988                           p_num2        IN NUMBER,
18989                           p_num3        IN NUMBER,
18990                           p_num4        IN NUMBER,
18991                           p_varchar1    IN VARCHAR2,
18992                           p_varchar2    IN VARCHAR2,
18993                           p_varchar3    IN VARCHAR2,
18994                           p_varchar4    IN VARCHAR2
18995             ) RETURN INTEGER IS
18996 BEGIN
18997     return 0;
18998 END GMP_CAL_UTILITY1_R10;
18999 
19000 PROCEDURE GMP_CAL_PROC1_R10
19001             (
19002                           p_dblink      IN VARCHAR2,
19003                           p_delimiter   IN VARCHAR2,
19004                           p_instance    IN INTEGER,
19005                           p_run_date    IN DATE,
19006                           p_num1        IN NUMBER,
19007                           p_num2        IN NUMBER,
19008                           p_num3        IN NUMBER,
19009                           p_num4        IN NUMBER,
19010                           p_varchar1    IN VARCHAR2,
19011                           p_varchar2    IN VARCHAR2,
19012                           p_varchar3    IN VARCHAR2,
19013                           p_varchar4    IN VARCHAR2,
19014                           return_status  OUT NOCOPY BOOLEAN
19015             ) IS
19016 BEGIN
19017     return_status := TRUE;
19018 END GMP_CAL_PROC1_R10;
19019 
19020 -- --------------------OPM Calendar Package End --------------
19021 
19022  FUNCTION is_aps_compatible RETURN NUMBER IS
19023  BEGIN
19024   RETURN 1 ;
19025  END is_aps_compatible ;
19026 
19027  END MSC_CL_GMP_UTILITY;