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.0.12010000.3 2008/08/18 07:06:26 sbyerram ship $ */
3 
4 
5           /*======== GLOBAL OPM Data Collection Declaration =========*/
6 
7 TYPE  ref_cursor_typ is REF CURSOR;
8 
9 invalid_string_value      EXCEPTION;
10 invalid_gmp_uom_profile   EXCEPTION;
11 stmt_no                   NUMBER := 0;
12 s		          INTEGER := 1;
13 p_location                VARCHAR2(300) := NULL;
14 g_aps_eff_id              NUMBER     := 0;  /* Global Aps Effectivity ID */
15 aps_fmeff_id              NUMBER     := 0 ; /* Generated effectivity Id */
16 x_aps_fmeff_id            NUMBER     := 0 ; /* encoded effectivity Id */
17 g_fm_dtl_start_loc        INTEGER := 0; /* Start detail location */
18 g_fm_dtl_end_loc          INTEGER := 0;  /* End detail location */
19 g_fm_hdr_loc              INTEGER := 1;  /* Starting for formula header */
20 g_formula_orgn_count_tab  INTEGER := 1;  /* Starting for formula orgn detail */
21 g_rstep_loc	 	  INTEGER := 1 ;  /* global rtg offset location */
22 g_curr_rstep_loc	  NUMBER  := -1 ; /* current r step offsetp locn */
23 g_prev_formula_id 	  NUMBER := -1 ;
24 g_prev_locn 		  NUMBER := 1;
25 g_dep_index               NUMBER := 1;
26 alt_rsrc_size             INTEGER;  /* Number of Alternate resources for BOM */
27 formula_headers_size      INTEGER;  /* Number of rows in formula_headers */
28 formula_details_size      INTEGER;  /* Number of rows in formula_details */
29 formula_orgn_size  	  INTEGER;  /* Number of detail rows for formula */
30 routing_headers_size      INTEGER;  /* Number of rows in routing_headers */
31 rtg_org_dtl_size      	  INTEGER;  /* Number of rows in routing_org_details */
32 rtg_gen_dtl_size          INTEGER;  /* Number of rows in generic routing_det */
33 material_assocs_size      INTEGER;  /* Number of rows in material_assocs */
34 setup_size                INTEGER;  /* Number of rows in Seq Dep Cursor */
35 opr_stpdep_size           INTEGER := 1;  /* Number of rows in step dependency */
36 recipe_orgn_over_size     INTEGER;  /* No. of rows in recipe orgn override */
37 recipe_override_size      INTEGER;  /* Number of rows in recipe override */
38 rtg_offsets_size 	  INTEGER := 1;  /* Number of rows in rtg offsets tbl */
39 current_date_time         DATE;	    /* For consistency writes */
40 b_instance_id             INTEGER;
41 delimiter                 VARCHAR2(1);  /* Used when filling in comment columns on BOM and ROUTING Tables */
42 l_in_str_org              VARCHAR2(32767) := null ;   /* B3491625 */
43 at_apps_link              VARCHAR2(31); /* Database link to APPS server from Planning server  */
44 g_instance_id             NUMBER;       /* Instance Id from Planning server  */
45 g_mat_assoc               INTEGER;  /* Glabal counter for materail assiciation */
46 g_gmp_uom_class           VARCHAR2(10); /* UOM Class */
47 g_setup_id                NUMBER; /* hold he last setup_id */
48 sd_index                  INTEGER := 0 ;
49 /* These variables store the MTQ related values that is last inserted. */
50 g_old_formula_id          NUMBER ; /* B3970993 */
51 g_old_recipe_id           NUMBER ; /* B3970993 */
52 g_old_rtg_id              NUMBER ; /* B3970993 */
53 g_old_rtgstep_id          NUMBER ; /* B3970993 */
54 g_old_aps_item_id         NUMBER ; /* B3970993 */
55 g_mtq_loc                 NUMBER ; /* B3970993 */
56 g_min_mtq                 NUMBER ; /* B3970993 */
57 /* Bug:5872693 Vpedarla 12-Feb-2007 */
58 k                         NUMBER;
59 orig_start_date           DATE;
60 substcount                NUMBER;
61 enddatenull               BOOLEAN:=FALSE;
62 /* Bug:5872693 Vpedarla end 12-Feb-2007 */
63 v_gmd_seq 		  varchar2(100);
64 v_gmd_formula_lineid 	  INTEGER := 0;
65 gmd_formline_cnt  	  INTEGER := 0 ;
66 op_formline_cnt 	  INTEGER := 0 ;
67 desig_count		  NUMBER  := 0;
68 gfcst_cnt		  NUMBER  := 0;
69 gso_cnt		          NUMBER  := 0;
70 gschd_fcst_cnt	          NUMBER  := 0;
71 gitem_size		  NUMBER  := 0;
72 gfcst_size		  NUMBER  := 0;
73 gso_size		  NUMBER  := 0;
74 gschd_fcst_size	          NUMBER  := 0;
75 g_item_tbl_position	  NUMBER  := 0;
76 gcurrent_designator	  VARCHAR2(10) := NULL;
77 g_delimiter               VARCHAR2(4) := '/' ;
78 gprod_size                NUMBER  := 0;
79 grsrc_size                NUMBER  := 0;
80 gonhand_balance_size      NUMBER  := 0; -- akaruppa B4287033
81 g_rsrc_cnt                INTEGER ;
82 stp_chg_num               NUMBER  ;
83 stp_chg_cursor            VARCHAR2(32700);
84 statement_alt_resource    VARCHAR2(32700):= NULL;
85 alt_prod_size             INTEGER;  /* NAVIN :- : Number of rows in Alternate Resource */
86 /* Sowmya - As per the latest FDD changes */
87 l_res_inst_process        NUMBER;
88 /*-------------------------- Operation Charges-----------------------------*/
89 v_orgn_id                      NUMBER;
90 r                              NUMBER;
91 p                              NUMBER ;
92 chg_res_index                  NUMBER; /* NAVIN :- Resource Charges */
93 resource_usage_flag            NUMBER;
94 resource_instance_usage_flag   NUMBER;
95 old_rsrc_batch_id              NUMBER;
96 old_rsrc_resources             VARCHAR2(16);
97 old_rsrc_original_seq_num      NUMBER;
98 old_instance_number            NUMBER;
99 old_rsrc_inst_batch_id         NUMBER;
100 old_rsrc_inst_resources        VARCHAR2(16);
101 old_rsrc_inst_original_seq_num NUMBER;
102 V_FROM_RSRC                    VARCHAR2(16) ;
103 V_TO_RSRC                      VARCHAR2(16) ;
104 
105 TYPE gmp_buffer_typ IS RECORD
106 (
107   fmeff_id            NUMBER,  /* OPM Effectivity ID         */
108   aps_fmeff_id        NUMBER,  /* APS Effectivity ID - B2989806  */
109   item_id             NUMBER,  /* OPM Effectivity Item ID    */
110   formula_id          NUMBER,  /* Formula ID                 */
111   plant_code          VARCHAR2(4), /* Effectivity Orgn code      */
112   organization_id     NUMBER    ,  /* ID for the Plant           */
113   start_date          DATE,        /* Effectivity Start Date     */
114   end_date            DATE,        /* Effectivity End Date       */
115   inv_min_qty         NUMBER,      /* Effectivity Minimum Qty    */
116   inv_max_qty         NUMBER,      /* Effectivity Maximum Qty    */
117   preference          NUMBER,      /* Effectivity Preference     B3437281 */
118   primary_um          VARCHAR2(4), /* Primary UOM of the Item    */
119   whse_code           VARCHAR2(4), /* Resource or Material Whse  */
120   routing_id          NUMBER    ,  /* Routing ID. Could be NULL  */
121   routing_no          VARCHAR2(32),/* Associated Routing No      */
122   routing_vers        NUMBER   ,   /* Associated Routing Version */
123   routing_desc        VARCHAR2(70),/* Associated Routing DEsc'n  */
124   routing_um          VARCHAR2(4), /* UOM from the Routing       */
125   routing_qty         NUMBER,      /* Qty from the Routing       */
126   prod_factor         NUMBER, /*B2870041 factor to convert prod to rout um */
127   product_index       NUMBER, /*B2870041 index of the product line */
128   aps_item_id         NUMBER    ,  /* OPM Effective Aps Item ID    */
129   recipe_id           NUMBER  ,  /* 1830940 New GMD Changes Recipe ID */
130   rtg_hdr_location    NUMBER    ,   /* index link to routing header */
131 /* NAMIT_CR */
132   calculate_step_quantity NUMBER ,
133   category_id         NUMBER,  /* SGIDUGU */
134   setup_id            NUMBER,   /* SGIDUGU */
135   seq_dpnd_class      VARCHAR2(8)   /* SGIDUGU */
136 );
137 effectivity           gmp_buffer_typ;
138 -- primary_bom_formulaline_id  NUMBER     ; -- Bug # 4879588
139 
140 TYPE gmp_formula_header_typ IS RECORD
141 (
142   formula_id          NUMBER    ,
143   valid_flag          NUMBER   ,
144   start_dtl_loc       NUMBER    ,
145   end_dtl_loc         NUMBER    ,
146   total_output        NUMBER, /* B2870041 total output for all prod/byp */
147   total_um            VARCHAR2(4) /*B2870041 um used to calculate qty */
148 );
149 TYPE gmp_formula_header_tbl IS TABLE OF gmp_formula_header_typ
150 INDEX BY BINARY_INTEGER;
151 formula_header_tab        gmp_formula_header_tbl;
152 
153 TYPE gmp_formula_detail_typ IS RECORD
154 (
155   formula_id          NUMBER,
156   formula_no          VARCHAR2(32),
157   formula_vers        NUMBER, --PK
158   formula_desc1       VARCHAR2(100),
159   x_formulaline_id    NUMBER,
160   line_type           NUMBER,
161   opm_item_id         NUMBER, --PK
162   formula_qty         NUMBER,
163   scrap_factor        NUMBER,
164   scale_type          NUMBER,
165   contribute_yield_ind VARCHAR2(1),      /* B2657068 Rajesh Patangya */
166   contribute_step_qty_ind NUMBER,      /* NAMIT_ASQC */
167   phantom_type        NUMBER,
168   aps_um              VARCHAR2(3),
169   orig_um             VARCHAR2(4), /*B2870041 formula um */
170   primary_um          VARCHAR2(4), /* B2870041 item primary um */
171   bom_scale_type      NUMBER,
172   primary_qty         NUMBER,
173   aps_item_id         NUMBER, --PK
174   scale_multiple      NUMBER, --PK       /* B2657068 Rajesh Patangya */
175   scale_rounding_variance NUMBER, --PK    /* B2657068 Rajesh Patangya */
176   rounding_direction  NUMBER,          /* B2657068 Rajesh Patangya */
177   release_type        NUMBER,       /* B3278466 LTC change */
178   /*sowmya - Item substitution - start*/
179   original_item_id    NUMBER, --PK
180   start_date          DATE,
181   end_date            DATE,
182   /*sowmya - Item substitution - end*/
183   /* venu */
184   formula_line_id     NUMBER, --PK
185   preference          NUMBER, --PK
186   lead_stdate         DATE,
187   lead_enddate        DATE,
188   lead_pref           NUMBER,
189   actual_end_date     DATE,
190   actual_end_flag     NUMBER,
191   original_item_flag  NUMBER,
192   formulaline_id      NUMBER --PK
193   /* venu */
194 );
195 
196 TYPE gmp_formula_detail_tbl IS TABLE OF gmp_formula_detail_typ
197 INDEX by BINARY_INTEGER;
198 formula_detail_tab   gmp_formula_detail_tbl ;
199 
200 /* Bug:5872693 Vpedarla start 12-Feb-2007 */
201 prev_detail_tab                   gmp_formula_detail_tbl ;
202 orig_detail_tab                   gmp_formula_detail_tbl ;
203 temp_detail_tab                   gmp_formula_detail_tbl ;
204 subst_tab                         gmp_formula_detail_tbl ;
205 /* Bug:5872693 Vpedarla end 12-Feb-2007 */
206 
207 TYPE gmp_formula_detail_count_typ IS RECORD
208 (
209   formula_id          NUMBER    ,
210   formula_dtl_count   NUMBER
211 );
212 TYPE gmp_formula_detail_count_tbl IS TABLE OF gmp_formula_detail_count_typ
213 INDEX BY BINARY_INTEGER;
214 formula_dtl_count_rec     gmp_formula_detail_count_typ ;
215 
216 TYPE gmp_formula_orgn_count_typ IS RECORD
217 (
218   formula_id          NUMBER    ,
219   plant_code          VARCHAR2(4),
220   organization_id     NUMBER    ,
221   orgn_count          NUMBER    ,  /* Count of formula details */
222   valid_flag          NUMBER
223 );
224 TYPE gmp_formula_orgn_count_tbl IS TABLE OF gmp_formula_orgn_count_typ
225 INDEX BY BINARY_INTEGER;
226 formula_orgn_count_tab  gmp_formula_orgn_count_tbl;
227 
228 TYPE gmp_routing_header_typ IS RECORD
229 (
230   routing_id          NUMBER    ,
231   plant_code          VARCHAR2(4),
232   valid_flag          NUMBER   ,
233   generic_start_loc   NUMBER    ,
234   generic_end_loc     NUMBER    ,
235   orgn_start_loc      NUMBER    ,
236   orgn_end_loc        NUMBER    ,
237   step_start_loc      NUMBER    ,
238   step_end_loc        NUMBER    ,
239   usage_start_loc     NUMBER    ,
240   usage_end_loc       NUMBER    ,
241   stpdep_start_loc    NUMBER    ,
242   stpdep_end_loc      NUMBER
243 );
244 TYPE gmp_routing_header_tbl IS TABLE OF gmp_routing_header_typ
245 INDEX BY BINARY_INTEGER;
246 rtg_org_hdr_tab      gmp_routing_header_tbl;
247 
248 TYPE gmp_routing_detail_typ IS RECORD
249 (
250   routing_id          NUMBER    ,
251   orgn_code           VARCHAR2(4),
252   routingstep_no      NUMBER   ,
253   seq_dep_ind         NUMBER, /*B2870041 sequence dependent indicator */
254   prim_rsrc_ind_order NUMBER   ,
255   resources           VARCHAR2(16),
256   prim_rsrc_ind       NUMBER   ,
257   capacity_constraint NUMBER   ,
258   min_capacity        NUMBER,
259   max_capacity        NUMBER,
260   schedule_ind        NUMBER,
261 
262   routingstep_id      NUMBER    ,
263   x_routingstep_id    NUMBER    ,
264 --  routingstep_no      NUMBER   ,
265   step_qty            NUMBER,
266   minimum_transfer_qty NUMBER,
267   oprn_desc           VARCHAR2(70),
268   oprn_id             NUMBER  ,   /* SGIDUGU - Seq Dep changes */
269   oprn_no             VARCHAR2(32),
270   process_qty_um      VARCHAR2(4),
271   activity            VARCHAR2(16),
272   oprn_line_id        NUMBER    ,
273 --  resources           VARCHAR2(16),
274   resource_count      NUMBER   ,
275   resource_usage      NUMBER,
276   usage_um            VARCHAR2(4),
277   scale_type          NUMBER   ,
278 --  prim_rsrc_ind       NUMBER   ,
279   offset_interval     NUMBER,
280   resource_id         NUMBER    ,
281   x_resource_id       NUMBER    ,   /* B1177070 added encoded key */
282   rtg_scale_type      NUMBER   ,
283   aps_usage_um        VARCHAR2(3),
284   activity_factor     NUMBER,       /* GMD New Additional Columns */
285   process_qty         NUMBER,       /* GMD New Additional Columns */
286 --  seq_dep_ind         NUMBER, /*B2870041 sequence dependent indicator */
287   material_ind        NUMBER, /*B2870041 material indicator for next/prior*/
288   schedule_flag       NUMBER, /*B2870041 default value for APS*/
289   mat_found           NUMBER, /* Indicator is any activity is scheduled in operation. */
290   include_rtg_row     NUMBER, /* Do Not Plan Resource rows will have value 0 */
291   break_ind           NUMBER, /* Flag denoting whether activity is breakable or not. */
292   o_min_capacity      NUMBER,  /* Overrides */
293   o_max_capacity      NUMBER,  /* Overrides */
294   o_resource_usage    NUMBER,  /* Overrides */
295   o_activity_factor   NUMBER,  /* Overrides */
296   o_process_qty       NUMBER,  /* Overrides */
297   o_step_qty          NUMBER,  /* Overrides */
298   is_sds_rout         NUMBER,   /* B4918786 SDS */
299   is_unique           NUMBER,   /* B4918786 SDS */
300   is_nonunique        NUMBER,   /* B4918786 SDS */
301   setup_id            NUMBER    /* B4918786 SDS */
302 );
303 TYPE gmp_routing_detail_tbl IS TABLE OF gmp_routing_detail_typ
304 INDEX BY BINARY_INTEGER;
305 rtg_org_dtl_tab    gmp_routing_detail_tbl;
306 
307 TYPE gen_routing_detail_typ IS RECORD
308 (
309   routing_id          NUMBER    ,
310   routingstep_no      NUMBER   ,
311   seq_dep_ind         NUMBER, /*B2870041 sequence dependent indicator */
312   prim_rsrc_ind_order NUMBER   ,
313   resources           VARCHAR2(16),
314   routingstep_id      NUMBER    ,
315   oprn_no             VARCHAR2(32),
316   oprn_line_id        NUMBER    ,
317   activity            VARCHAR2(16),
318   prim_rsrc_ind       NUMBER   ,
319 --  resources           VARCHAR2(16),
320 --  prim_rsrc_ind       NUMBER   ,
321 --  seq_dep_ind         NUMBER, /*B2870041 sequence dependent indicator */
322   offset_interval     NUMBER,
323   uom_code            VARCHAR2(3) /* NAMIT_RD */
324 );
325 TYPE gen_routing_detail_tbl IS TABLE OF gen_routing_detail_typ
326 INDEX BY BINARY_INTEGER;
327 rtg_gen_dtl_tab       gen_routing_detail_tbl;
328 
329 /* B4918786 SDS */
330 TYPE gmp_sds_typ IS RECORD
331 (
332   oprn_id             NUMBER,
333   category_id         NUMBER,
334   seq_dpnd_class      VARCHAR2(100),
335   resources           VARCHAR2(16),
336   resource_id         NUMBER,
337   setup_id            NUMBER
338 );
339 TYPE gmp_sds_tbl IS TABLE OF gmp_sds_typ INDEX BY BINARY_INTEGER;
340 sds_tab    gmp_sds_tbl;
341 sds_tab_init gmp_sds_tbl;
342 
343 TYPE gmp_alt_resource_typ IS RECORD
344 (
345   prim_resource_id    NUMBER    ,
346   alt_resource_id     NUMBER    ,
347   min_capacity        NUMBER,  /* SGIDUGU - min capacity for alternate rsrc */
348   max_capacity        NUMBER,  /* SGIDUGU - max capacity for alternate rsrc */
349   runtime_factor      NUMBER,  /* B2353759,alternate runtime_factor */
350   preference	      NUMBER, /* Prod spec alternates */
351   item_id 	      NUMBER  /* Prod spec alternates */
352 );
353 TYPE gmp_alt_resource_tbl IS TABLE OF gmp_alt_resource_typ
354 INDEX BY BINARY_INTEGER;
355 rtg_alt_rsrc_tab       gmp_alt_resource_tbl;
356 
357 TYPE gmp_material_assoc_typ IS RECORD
358 (
359   formula_id          NUMBER    ,
360   recipe_id           NUMBER    ,
361   line_type           NUMBER   ,
362   line_no             NUMBER   ,
363   x_formulaline_id    NUMBER    ,   /* B1177070 added encoded key */
364   x_routingstep_id    NUMBER    ,  /* B1177070 added encoded key */
365 /* NAMIT_MTQ */
366   item_id             NUMBER  ,
367   routingstep_no      NUMBER   ,
368   aps_item_id         NUMBER,
369   uom_conv_factor     NUMBER,
370   min_trans_qty       NUMBER,
371   min_delay           NUMBER,
372   max_delay           NUMBER
373 );
374 TYPE gmp_material_assoc_tbl IS TABLE OF gmp_material_assoc_typ
375 INDEX BY BINARY_INTEGER;
376 mat_assoc_tab    gmp_material_assoc_tbl;
377 
378 /* NAMIT_CR Define Step Dependency Record Type */
379 
380 TYPE gmp_opr_stpdep_typ IS RECORD
381 (
382   routing_id          NUMBER  ,
383   x_dep_routingstep_id NUMBER    ,
384   x_routingstep_id    NUMBER    ,
385   dep_type            NUMBER   ,
386   standard_delay      NUMBER,
387   max_delay           NUMBER,
388   transfer_pct        NUMBER,
389   dep_routingstep_no  NUMBER   ,
390   routingstep_no      NUMBER   ,
391   chargeable_ind      NUMBER
392 );
393  TYPE gmp_opr_stepdep_tab IS TABLE OF gmp_opr_stpdep_typ
394  INDEX BY BINARY_INTEGER;
395 gmp_opr_stpdep_tbl gmp_opr_stepdep_tab;
396 
397 /* GMD New Declaration of PL/SQL Tables for Activity and Resources Overrides */
398 TYPE recipe_orgn_override_typ IS RECORD
399 (
400   routing_id          NUMBER    ,
401   orgn_code           VARCHAR2(4),
402   routingstep_id      NUMBER    ,
403   oprn_line_id        NUMBER    ,
404   recipe_id           NUMBER    ,
405   activity_factor     NUMBER,
406   resources           VARCHAR2(16),
407   resource_usage      NUMBER,
408   process_qty         NUMBER,
409 /* NAMIT_OC */
410   min_capacity        NUMBER,
411   max_capacity        NUMBER
412 );
413 TYPE recipe_orgn_override_tbl IS TABLE OF recipe_orgn_override_typ
414 INDEX BY BINARY_INTEGER;
415 rcp_orgn_override    recipe_orgn_override_tbl;
416 
417 TYPE recipe_override_typ IS RECORD
418 (
419   routing_id          NUMBER    ,
420   routingstep_id      NUMBER    ,
421   recipe_id           NUMBER    ,
422   step_qty            NUMBER
423 );
424 TYPE recipe_override_tbl IS TABLE OF recipe_override_typ
425 INDEX BY BINARY_INTEGER;
426 recipe_override      recipe_override_tbl;
427 -- Routing steps offsets
428 TYPE gmp_routing_step_offsets_typ IS RECORD
429 (
430 plant_code 	VARCHAR2(4),
431 fmeff_id 	NUMBER,
432 formula_id	NUMBER,
433 routingstep_id	NUMBER,
434 start_offset	NUMBER,
435 end_offset	NUMBER,
436 formulaline_id	NUMBER
437 );
438 TYPE rtgstep_offsets_tbl IS TABLE OF gmp_routing_step_offsets_typ
439 INDEX BY BINARY_INTEGER ;
440 rstep_offsets	rtgstep_offsets_tbl;
441 --
442 /* SGIDUGU Seq Dep Table Definition */
443 TYPE gmp_sequence_typ IS RECORD
444 (
445   oprn_id      NUMBER,
446   category_id  NUMBER,
447   seq_dep_id   NUMBER
448 );
449 
450 seq_rec  gmp_sequence_typ;
451 
452 TYPE gmp_setup_tbl  IS TABLE OF gmp_sequence_typ INDEX BY BINARY_INTEGER;
453 setupid_tab   gmp_setup_tbl ;
454 
455 /* End of SGIDUGU Seq Dep Table Definition */
456 
457 /* === OPM PLD Declaraion =====*/
458 
459 /* Record definition for the a line in a production order. */
460   TYPE product_typ IS RECORD(
461     batch_no                    VARCHAR2(32),
462     plant_code                  VARCHAR2(4),
463     batch_id                    NUMBER,
464     x_batch_id                  NUMBER,  /* B1177070 added encoded key */
465     wip_whse_code               VARCHAR2(4),
466     mtl_org_id                  NUMBER,
467     routing_id                  NUMBER,
468     start_date                  DATE,
469     end_date                    DATE,
470     trans_date                  DATE,
471     batch_status                NUMBER,
472     batch_type                  NUMBER,
473     organization_id             NUMBER,
474     whse_code                   VARCHAR2(4),
475     item_id                     NUMBER,   /* Give a Unique Item Id Name */
476     line_id                     NUMBER,
477     line_no                     NUMBER,   /* B2919303 */
478     tline_no                    NUMBER,   /* B2953953 - CoProducts */
479     line_type                   NUMBER,
480     tline_type                  NUMBER,   /* B2953953 - CoProducts */
481     qty                         NUMBER,
482     matl_item_id                NUMBER,   /* B1992371 for GME Changes */
483     recipe_item_id              NUMBER,   /* B1992371 for GME Changes */
484     poc_ind                     VARCHAR2(1),   /* B1992371, B2239948 for GME Changes */
485     firmed_ind                  NUMBER,      /* B2821248 - Firmed Ind is added */
486     batchstep_no                NUMBER,     /* B2919303 StepNo */
487     matl_qty                    NUMBER,
488     uom_conv_factor             NUMBER,
489     requested_completion_date   DATE,
490     schedule_priority		NUMBER,
491     from_op_seq_id 		NUMBER,
492     Minimum_Transfer_Qty	NUMBER,
493     Minimum_Time_Offset	        NUMBER,
494     Maximum_Time_Offset	        NUMBER,
495     from_op_seq_num		NUMBER
496    );
497   TYPE product_tbl IS TABLE OF product_typ INDEX by BINARY_INTEGER;
498   prod_tab   product_tbl;
499 
500 /* definition for the resource data of a production order */
501   TYPE rsrc_rec IS RECORD(
502     batch_id                  NUMBER,
503     x_batch_id                NUMBER,  /* B1177070 added encoded key */
504     batchstep_no              NUMBER,  /* B1224660 added batchstep to record */
505     seq_dep_ind               NUMBER,
506     prim_rsrc_ind_order       NUMBER,
507     resources                 VARCHAR2(16),
508     instance_number           NUMBER,
509     tran_seq_dep              NUMBER,
510     plan_start_date           DATE,
511     plant_code                VARCHAR2(4),
512 --    activity                VARCHAR2(16),	/* NAVIN: Remove this column. */
513     prim_rsrc_ind             NUMBER,
514     resource_id               NUMBER,
515     x_resource_id             NUMBER,  /* B1177070 added encoded key */
516     plan_rsrc_count           NUMBER,
517     actual_rsrc_count         NUMBER,
518     actual_start_date         DATE,
519     plan_cmplt_date           DATE,
520     actual_cmplt_date         DATE,
521     step_status               NUMBER,
522     resource_usage            NUMBER,
523     resource_instance_usage   NUMBER,
524     eqp_serial_number         VARCHAR2(30),   -- Bug 5713355
525     scale_type                NUMBER,
526     capacity_constraint       NUMBER ,
527     plan_step_qty             NUMBER,
528     min_xfer_qty              NUMBER,
529     material_ind              NUMBER,
530     schedule_flag             NUMBER,
531 --    offset_interval         NUMBER,
532     act_start_date            DATE,
533     utl_eff                   NUMBER,
534     bs_activity_id            NUMBER,
535     --NAVIN: START new field (added for 11.1.1.3 of Process Execution APS Patchset J.1 TDD)
536     group_sequence_id	      NUMBER,
537     group_sequence_number     NUMBER,
538     firm_type	              NUMBER,
539     setup_id	              NUMBER,
540     minimum_capacity          NUMBER,
541     maximum_capacity          NUMBER,
542     sequence_dependent_usage  NUMBER,
543     original_seq_num          NUMBER,
544     org_step_status	      NUMBER,
545     plan_charges	      NUMBER,
546     plan_rsrc_usage	      NUMBER,
547     actual_rsrc_usage	      NUMBER,
548     batchstep_id              NUMBER,   /* Navin 6/23/2004 Added for resource charges*/
549     mat_found                 NUMBER,
550     breakable_activity_flag   NUMBER,
551     usage_uom                 VARCHAR2(4), /*Sowmya - As Per the latest FDD changes */
552     step_qty_uom              VARCHAR2(3),
553     equp_item_id              NUMBER ,
554     gmd_rsrc_count            NUMBER,
555     step_start_date           DATE, /* msc_st_job_operations.reco_start_date */
556     step_end_date             DATE,  /* msc_st_job_operations.reco_completion_date */
557     efficiency                NUMBER /*B4320561 - sowsubra */
558     );
559   TYPE rsrc_dtl_tbl IS TABLE OF rsrc_rec INDEX by BINARY_INTEGER;
560   rsrc_tab   rsrc_dtl_tbl;
561 
562 /* Record and table definition for the MPS schedule details and the items and
563    orgs that are associated by plant/whse eff. The schedule are used for MDS
564    demand
565 */
566   TYPE sched_dtl_rec IS RECORD(
567     schedule        	VARCHAR2(16),
568     schedule_id     	NUMBER,
569     order_ind       	NUMBER,
570     stock_ind       	NUMBER,
571     whse_code       	VARCHAR2(4),
572     orgn_code       	VARCHAR2(4),
573     organization_id 	NUMBER,
574     inventory_item_id	NUMBER);
575 
576   TYPE sched_dtl_tbl IS TABLE OF sched_dtl_rec INDEX by BINARY_INTEGER;
577   sched_dtl_tab     sched_dtl_tbl;
578 
579   /* Record and table definition for forecast detals */
580   TYPE fcst_dtl_rec IS RECORD(
581     inventory_item_id   NUMBER,
582     organization_id     NUMBER,
583     forecast_id         NUMBER,
584     forecast            VARCHAR2(17),
585     orgn_code           VARCHAR2(4),
586     trans_date          DATE,
587     trans_qty           NUMBER,
588     consumed_qty        NUMBER,
589     use_fcst_flag	NUMBER);
590 
591   TYPE fcst_dtl_tbl IS TABLE OF fcst_dtl_rec INDEX by BINARY_INTEGER;
592   fcst_dtl_tab      fcst_dtl_tbl;
593 
594   /* Record and table definition for sales order detals */
595   TYPE sales_dtl_rec IS RECORD(
596     inventory_item_id   NUMBER,
597     organization_id 	NUMBER,
598     orgn_code           VARCHAR2(4),
599     order_no            VARCHAR2(32),
600     line_id             NUMBER,
601     net_price           NUMBER,
602     sched_shipdate      DATE,
603     request_date        DATE,       /* B2971996 */
604     trans_qty           NUMBER);
605 
606   TYPE sales_dtl_tbl IS TABLE OF sales_dtl_rec INDEX by BINARY_INTEGER;
607   sales_dtl_tab     sales_dtl_tbl;
608 
609   /* Record and table definition for schedule forecast association */
610   TYPE fcst_assoc_rec IS RECORD(
611     schedule_id         NUMBER,
612     forecast_id         NUMBER);
613 
614   TYPE fcst_assoc_tbl IS TABLE OF fcst_assoc_rec INDEX by BINARY_INTEGER;
615   SCHD_FCST_DTL_TAB     fcst_assoc_tbl;
616 
617   /* Record and table definition for designators */
618   TYPE desig_rec IS RECORD(
619     designator      VARCHAR2(15),
620     schedule        VARCHAR2(17),
621     orgn_code       VARCHAR2(4),
622     whse_code       VARCHAR2(4),
623     organization_id NUMBER);
624 
625   TYPE desig_tbl IS TABLE OF desig_rec INDEX by BINARY_INTEGER;
626   desig_tab         desig_tbl;
627 
628 TYPE stp_chg_typ is RECORD(
629   wip_entity_id	        NUMBER  ,
630   operation_seq_id      NUMBER	,
631   resource_id	        NUMBER	,
632   charge_num	        NUMBER  ,
633   organization_id       NUMBER  ,
634   operation_seq_no      NUMBER	,
635   resource_seq_num      NUMBER  ,
636   charge_quantity       NUMBER	,
637   charge_start_dt_time	DATE    ,
638   charge_end_dt_time    DATE
639   );
640 
641 TYPE stp_chg_tab IS TABLE OF stp_chg_typ INDEX by BINARY_INTEGER;
642 stp_chg_tbl stp_chg_tab;
643 
644 /* NAVIN :- Alternate Resource */
645 /* NAVIN: Alternate Resource selection   */
646 TYPE prod_alt_resource_typ IS RECORD
647 (
648     prim_resource_id    NUMBER,
649     alt_resource_id     NUMBER,
650     runtime_factor      NUMBER,  /* B2353759,alternate runtime_factor */
651     preference          NUMBER, /* B5688153 Prod spec alternates */
652     item_id             NUMBER  /* B5688153 Prod spec alternates */
653 );
654 TYPE prod_alt_resource_tbl IS TABLE OF prod_alt_resource_typ INDEX by BINARY_INTEGER;
655 prod_alt_rsrc_tab       prod_alt_resource_tbl;
656 
657 /* ---------------------------  Global declarations ------------------------ */
658 TYPE number_idx_tbl IS TABLE OF NUMBER INDEX BY BINARY_INTEGER;
659 TYPE date_idx_tbl IS TABLE OF DATE INDEX BY BINARY_INTEGER;
660 TYPE uom_code_tbl IS TABLE OF VARCHAR2(3) INDEX BY BINARY_INTEGER;
661 empty_number_table      number_idx_tbl;
662 empty_date_table       	date_idx_tbl ;
663 empty_uom_code_tbl	uom_code_tbl ;
664 
665 bom_sr_instance_id  	number_idx_tbl;
666 bomc_sr_instance_id 	number_idx_tbl;
667 pef_sr_instance_id 	number_idx_tbl;
668 rtg_sr_instance_id 	number_idx_tbl;
669 or_sr_instance_id 	number_idx_tbl;
670 opr_sr_instance_id 	number_idx_tbl;
671 rs_sr_instance_id 	number_idx_tbl;
672 oc_sr_instance_id 	number_idx_tbl;
673 itm_mtq_sr_instance_id 	number_idx_tbl; /* NAMIT_MTQ */
674 opr_stpdep_sr_instance_id  number_idx_tbl; /* NAMIT_CR */
675 
676 bom_organization_id  	   number_idx_tbl;
677 bomc_organization_id 	   number_idx_tbl;
678 pef_organization_id 	   number_idx_tbl;
679 rtg_organization_id 	   number_idx_tbl;
680 oc_organization_id 	   number_idx_tbl;
681 gt_organization_id 	   number_idx_tbl;
682 itm_mtq_organization_id    number_idx_tbl ; /* NAMIT_MTQ */
683 opr_stpdep_organization_id number_idx_tbl ;
684 opr_organization_id   	   number_idx_tbl ;
685 or_organization_id    	   number_idx_tbl ;
686 rs_organization_id    	   number_idx_tbl ;
687 
688 bom_bill_sequence_id 	number_idx_tbl;
689 bomc_bill_sequence_id 	number_idx_tbl;
690 pef_bill_sequence_id 	number_idx_tbl;
691 oc_bill_sequence_id 	number_idx_tbl;
692 
693 bom_last_update_date 	date_idx_tbl ;
694 bomc_last_update_date 	date_idx_tbl ;
695 pef_last_update_date 	date_idx_tbl ;
696 rtg_last_update_date 	date_idx_tbl ;
697 or_last_update_date 	date_idx_tbl ;
698 opr_last_update_date 	date_idx_tbl ;
699 rs_last_update_date 	date_idx_tbl ;
700 oc_last_update_date 	date_idx_tbl ;
701 
702 bom_creation_date 	date_idx_tbl ;
703 bomc_creation_date 	date_idx_tbl ;
704 pef_creation_date 	date_idx_tbl ;
705 rtg_creation_date 	date_idx_tbl ;
706 or_creation_date 	date_idx_tbl ;
707 opr_creation_date 	date_idx_tbl ;
708 rs_creation_date 	date_idx_tbl ;
709 oc_creation_date 	date_idx_tbl ;
710 
711 pef_effectivity_date 	date_idx_tbl   ;
712 bomc_effectivity_date 	date_idx_tbl   ;
713 opr_effectivity_date 	date_idx_tbl   ;
714 bomc_disable_date 	date_idx_tbl   ;
715 
716 rtg_routing_sequence_id 	number_idx_tbl   ;
717 pef_routing_sequence_id 	number_idx_tbl   ;
718 or_routing_sequence_id 		number_idx_tbl   ;
719 opr_routing_sequence_id 	number_idx_tbl   ;
720 rs_routing_sequence_id 		number_idx_tbl   ;
721 oc_routing_sequence_id 		number_idx_tbl   ;
722 /* NAMIT_MTQ */
723 itm_mtq_routing_sequence_id 	number_idx_tbl   ;
724 /* NAMIT_CR */
725 opr_stpdep_routing_sequence_id 	number_idx_tbl   ;
726 
727 bomc_uom_code  uom_code_tbl  ;
728 rtg_uom_code   uom_code_tbl ;
729 or_uom_code    uom_code_tbl ;
730 opr_uom_code   uom_code_tbl ;
731 
732 bom_assembly_item_id 	number_idx_tbl ;
733 rtg_assembly_item_id 	number_idx_tbl ;
734 
735 bomc_component_sequence_id 	number_idx_tbl;
736 oc_component_sequence_id 	number_idx_tbl;
737 
738 or_operation_sequence_id  	number_idx_tbl   ;
739 opr_operation_sequence_id 	number_idx_tbl   ;
740 rs_operation_sequence_id 	number_idx_tbl   ;
741 oc_operation_sequence_id 	number_idx_tbl   ;
742 
743 or_resource_seq_num 		number_idx_tbl   ;
744 rs_resource_seq_num 		number_idx_tbl   ;
745 /* SGIDUGU - Seq Dep */
746 or_setup_id     		number_idx_tbl   ;
747 gt_setup_id     		number_idx_tbl   ;
748 --
749 TYPE seq_dep_class_typ IS TABLE OF ic_item_mst.seq_dpnd_class%TYPE INDEX BY
750 BINARY_INTEGER;
751 gt_seq_dep_class     seq_dep_class_typ   ;
752 empty_seq_dep_class	seq_dep_class_typ ;
753 --
754 TYPE oprn_no_typ IS TABLE OF gmd_operations.oprn_no%TYPE INDEX BY
755 BINARY_INTEGER;
756 gt_oprn_no     oprn_no_typ ;
757 empty_oprn_no     oprn_no_typ ;
758 
759 /* End of changes SGIDUGU - Seq Dep */
760 
761 /* -------------------------------  BOM declarations --------------------------- */
762 TYPE alternate_bom_designator IS TABLE OF msc_st_boms.alternate_bom_designator%TYPE
763 INDEX BY BINARY_INTEGER;
764 bom_alternate_bom_designator alternate_bom_designator ;
765 empty_alternate_bom_designator alternate_bom_designator ;
766 
767 TYPE specific_assembly_comment IS TABLE OF msc_st_boms.specific_assembly_comment%TYPE
768 INDEX BY BINARY_INTEGER;
769 bom_specific_assembly_comment specific_assembly_comment ;
770 empty_bom_assembly_comment specific_assembly_comment ;
771 
772 bom_scaling_type 	number_idx_tbl ;
773 bom_assembly_quantity 	number_idx_tbl ;
774 
775 TYPE uom IS TABLE OF msc_st_boms.uom%TYPE INDEX BY BINARY_INTEGER;
776 bom_uom 	uom ;
777 empty_bom_uom 	uom ;
778 
779 /* NAMIT_CR For Step Material Assoc */
780 bom_op_seq_number 	number_idx_tbl;
781 
782 /* NAMIT_OC For ingredients contribute_to_step_qty will
783         store 1 for YES and 0 for NO */
784 bomc_contribute_to_step_qty 	number_idx_tbl;
785 
786 bom_index INTEGER := 0 ;   /* BOM Global counter */
787 
788 /* ---------------------------  BOM Components declarations ------------------------ */
789 bomc_Inventory_item_id 		number_idx_tbl;
790 bomc_using_assembly_id 		number_idx_tbl    ;
791 bomc_component_type 		number_idx_tbl    ;
792 bomc_scaling_type  		number_idx_tbl;
793 bomc_usage_quantity 		number_idx_tbl;
794 bomc_opr_offset_percent  	number_idx_tbl ;
795 bomc_optional_component  	number_idx_tbl ;
796 bomc_wip_supply_type 		number_idx_tbl ;
797 bomc_scale_multiple  		number_idx_tbl;
798 bomc_scale_rounding_variance 	number_idx_tbl ;
799 bomc_rounding_direction  	number_idx_tbl ;
800 
801 bomc_index INTEGER := 0 ;   /* BOM component Global counter */
802 
803 /* ---------------------------  Effectivity declarations ------------------------ */
804 pef_process_sequence_id 	number_idx_tbl   ;
805 pef_item_id             	number_idx_tbl ;
806 pef_disable_date 		date_idx_tbl   ;
807 pef_minimum_quantity 		number_idx_tbl   ;
808 pef_maximum_quantity 		number_idx_tbl   ;
809 pef_preference 			number_idx_tbl ;
810 
811 pef_index INTEGER := 0 ;   /* Process Effectivity Global counter */
812 
813 /* -------------------------------  Routng declarations  --------------------------- */
814 TYPE routing_comment IS TABLE OF msc_st_routings.routing_comment%TYPE
815 INDEX BY BINARY_INTEGER;
816 rtg_routing_comment routing_comment ;
817 empty_rtg_comment routing_comment ;
818 
819 
820 TYPE alt_routing_designator  IS TABLE OF msc_st_routings.alternate_routing_designator%TYPE
821 INDEX BY BINARY_INTEGER;
822 rtg_alt_routing_designator alt_routing_designator   ;
823 empty_rtg_designator alt_routing_designator   ;
824 
825 TYPE routing_quantity IS TABLE OF msc_st_routings.routing_quantity%TYPE
826 INDEX BY BINARY_INTEGER;
827 rtg_routing_quantity 		number_idx_tbl   ;
828 
829 /* NAMIT_CR For Calculate Step Dependency Flag */
830 rtg_auto_step_qty_flag 		number_idx_tbl  ;
831 
832 rtg_index INTEGER := 0 ;   /* Routing Global counter */
833 
834 /* -------------------------- Routng operations declarations  ------------------------ */
835 or_resource_id 		number_idx_tbl   ;
836 gt_resource_id 		number_idx_tbl   ;
837 
838 or_alternate_number 		number_idx_tbl   ;
839 or_principal_flag 		number_idx_tbl   ;
840 or_basis_type 			number_idx_tbl   ;
841 or_resource_usage 		number_idx_tbl   ;
842 or_max_resource_units 		number_idx_tbl   ;
843 or_resource_units 		number_idx_tbl   ;
844 or_orig_rs_seq_num 		number_idx_tbl ;
845 or_break_ind 			number_idx_tbl;
846 
847 or_index INTEGER := 0 ;   /* Operation Resource Global counter */
848 gt_index INTEGER := 0 ;   /* Operation Resource Global counter */
849 
850 /* -------------------------- Operations declarations  ------------------------ */
851 opr_operation_seq_num 		number_idx_tbl   ;
852 opr_mtransfer_quantity 		number_idx_tbl   ;
853 opr_department_id 		number_idx_tbl ;
854 rs_department_id 		number_idx_tbl ;
855 rs_schedule_flag 	        number_idx_tbl ;
856 /* NAMIT_MTQ */
857 itm_mtq_from_op_seq_id 	        number_idx_tbl ;
858 /* NAMIT_CR */
859 opr_stpdep_frm_seq_id 	        number_idx_tbl ;
860 opr_stpdep_to_seq_id 	        number_idx_tbl ;
861 opr_stpdep_dependency_type      number_idx_tbl ;
862 /* NAMIT_CR */
863 itm_mtq_min_time_offset 	number_idx_tbl ;
864 itm_mtq_max_time_offset 	number_idx_tbl ;
865 rs_activity_group_id 		number_idx_tbl ;
866 opr_stpdep_min_time_offset 	number_idx_tbl ;
867 opr_stpdep_max_time_offset 	number_idx_tbl ;
868 opr_stpdep_trans_pct 		number_idx_tbl ;
869 itm_mtq_frm_op_seq_num 		number_idx_tbl ;
870 opr_stpdep_frm_op_seq_num 	number_idx_tbl ;
871 opr_stpdep_to_op_seq_num 	number_idx_tbl ;
872 opr_stpdep_app_to_chrg 		number_idx_tbl ;
873 itm_mtq_from_item_id 		number_idx_tbl ;
874 itm_mtq_min_tran_qty 		number_idx_tbl ;
875 or_minimum_capacity 		number_idx_tbl ;
876 or_maximum_capacity 		number_idx_tbl ;
877 opr_step_qty 			number_idx_tbl;
878 
879 opr_step_qty_uom 		uom_code_tbl;
880 
881 TYPE operation_description IS TABLE OF msc_st_routing_operations.operation_description%TYPE
882 INDEX BY BINARY_INTEGER;
883 opr_operation_description    operation_description   ;
884 empty_opr_description        operation_description   ;
885 TYPE department_code IS TABLE OF msc_st_routing_operations.department_code%TYPE
886 INDEX BY BINARY_INTEGER;
887 opr_department_code          department_code ;
888 empty_opr_department_code    department_code ;
889 
890 opr_index INTEGER := 0 ;   /* Operation Global counter */
891 rs_index  INTEGER := 0 ;   /* Operation Global counter */
892 oc_index  INTEGER := 0 ;   /* Operation component Global counter */
893 /* NAMIT_MTQ */
894 mtq_index INTEGER := 0 ;   /* MTQ Global counter */
895 
896 /* ------------------- Requirement declaration ---------------------*/
897 
898 /* akaruppa B5007729 */
899 empty_num_table      number_idx_tbl;
900 rr_organization_id   number_idx_tbl;
901 s_organization_id    number_idx_tbl;
902 d_organization_id    number_idx_tbl;
903 f_organization_id    number_idx_tbl;
904 i_organization_id    number_idx_tbl;
905 o_organization_id    number_idx_tbl; -- akaruppa B4287033
906 arr_organization_id  number_idx_tbl; /* alternate resource declaration */
907 rr_activity_group_id number_idx_tbl; /* B3995361 rpatangy */
908 
909 rr_sr_instance_id   number_idx_tbl;
910 s_sr_instance_id    number_idx_tbl;
911 d_sr_instance_id    number_idx_tbl;
912 f_sr_instance_id    number_idx_tbl;
913 i_sr_instance_id    number_idx_tbl;
914 o_sr_instance_id    number_idx_tbl; -- akaruppa B4287033
915 stp_instance_id     number_idx_tbl;
916 arr_sr_instance_id  number_idx_tbl; /* alternate resource declaration */
917 
918 rr_supply_id         number_idx_tbl;
919 rr_resource_seq_num  number_idx_tbl;
920 rr_resource_id       number_idx_tbl;
921 
922 rr_opr_hours_required number_idx_tbl ;
923 rr_usage_rate         number_idx_tbl ;
924 rr_assigned_units     number_idx_tbl ;
925 rr_department_id      number_idx_tbl ;
926 
927 rr_wip_entity_id      number_idx_tbl ;
928 d_wip_entity_id       number_idx_tbl ;
929 f_wip_entity_id       number_idx_tbl ;
930 
931 rr_operation_seq_num  number_idx_tbl;
932 s_operation_seq_num   number_idx_tbl;
933 d_operation_seq_num   number_idx_tbl;
934 
935 rr_firm_flag                 number_idx_tbl ;
936 rr_minimum_transfer_quantity number_idx_tbl ;
937 rr_parent_seq_num            number_idx_tbl ;
938 rr_schedule_flag             number_idx_tbl ;
939 /* akaruppa B5007729 End*/
940 
941 empty_dat_table  date_idx_tbl;
942 rr_start_date    date_idx_tbl;
943 rr_end_date      date_idx_tbl;
944 
945 rr_hours_expended          number_idx_tbl ;
946 rr_breakable_activity_flag number_idx_tbl ;
947 rr_unadjusted_resource_hrs number_idx_tbl ; /* B4320561 - sowsubra */
948 rr_touch_time              number_idx_tbl; /* B4320561 - sowsubra */
949 rr_plan_step_qty           number_idx_tbl; /*Sowmya - As per latest FDD changes */
950 
951 TYPE res_step_qty_uom IS TABLE OF VARCHAR2(3)
952 INDEX BY BINARY_INTEGER;
953 rre_step_qty_uom           res_step_qty_uom;
954 rr_step_qty_uom            res_step_qty_uom;  /*Sowmya - As per latest FDD changes */
955 
956 rr_gmd_rsrc_cnt              number_idx_tbl; /*Sowmya - As per latest FDD changes */
957 rr_operation_sequence_id     number_idx_tbl ; /* B5461922 rpatangy */
958 jo_wip_entity_id             number_idx_tbl;
959 jo_instance_id               number_idx_tbl;
960 jo_operation_seq_num         number_idx_tbl;
961 jo_operation_sequence_id     number_idx_tbl;
962 jo_organization_id           number_idx_tbl;
963 jo_department_id             number_idx_tbl;
964 jo_minimum_transfer_quantity number_idx_tbl;
965 
966 TYPE recommended_typ IS TABLE OF VARCHAR2(1) INDEX BY BINARY_INTEGER;
967 jo_recommended         recommended_typ;
968 jo_network_start_end   recommended_typ;
969 joe_recommended        recommended_typ;
970 joe_network_start_end  recommended_typ;
971 
972 jo_reco_start_date      date_idx_tbl ;
973 jo_reco_completion_date date_idx_tbl ;
974 
975 rr_index      NUMBER := 0 ;
976 arr_index     NUMBER := 0 ;
977 si_index      NUMBER := 0 ;
978 inst_indx     NUMBER := 0 ; /* NAVIN :- - For Resource Instance */
979 jo_index      NUMBER := 0; /* NAMIT :- For msc_st_job_operations */
980 
981 /* ------------------- Supply declaration ---------------------*/
982 
983 /* akaruppa B5007729 */
984 s_plan_id               number_idx_tbl  ;
985 o_plan_id               number_idx_tbl  ; -- akaruppa B4287033
986 s_inventory_item_id     number_idx_tbl ;
987 d_inventory_item_id     number_idx_tbl ;
988 f_inventory_item_id     number_idx_tbl ;
989 o_inventory_item_id     number_idx_tbl ; -- akaruppa B4287033
990 rr_inventory_item_id    number_idx_tbl ; -- HW B4902328
991 
992 s_new_schedule_date     date_idx_tbl ;
993 o_new_schedule_date     date_idx_tbl ; -- akaruppa B4287033
994 s_old_schedule_date     date_idx_tbl ;
995 s_new_wip_start_date    date_idx_tbl ;
996 s_old_wip_start_date    date_idx_tbl ;
997 s_lunit_completion_date date_idx_tbl ;
998 s_disposition_id        number_idx_tbl ;
999 s_order_type            number_idx_tbl ;
1000 o_order_type            number_idx_tbl ; -- akaruppa B4287033
1001 /* akaruppa B5007729 End*/
1002 
1003 TYPE order_number IS TABLE OF msc_st_supplies.order_number%TYPE INDEX BY BINARY_INTEGER;
1004 s_order_number  order_number ;
1005 se_order_number order_number ;/* akaruppa B5007729 */
1006 
1007 /* akaruppa B5007729 */
1008 s_new_order_quantity number_idx_tbl ;
1009 o_new_order_quantity number_idx_tbl ; -- akaruppa B4287033
1010 s_old_order_quantity number_idx_tbl ;
1011 s_firm_planned_type  number_idx_tbl ;
1012 o_firm_planned_type  number_idx_tbl ; -- akaruppa B4287033
1013 /* akaruppa B5007729 End*/
1014 
1015 TYPE wip_entity_name IS TABLE OF msc_st_supplies.wip_entity_name%TYPE INDEX BY BINARY_INTEGER;
1016 s_wip_entity_name  wip_entity_name   ;
1017 se_wip_entity_name wip_entity_name ;/* akaruppa B5007729 */
1018 
1019 TYPE lot_number IS TABLE OF msc_st_supplies.lot_number%TYPE INDEX BY BINARY_INTEGER;
1020 s_lot_number lot_number ;
1021 o_lot_number lot_number ; -- akaruppa B4287033
1022 e_lot_number lot_number ; /* akaruppa B5007729 */
1023 
1024 /* akaruppa B5007729 */
1025 s_expiration_date          date_idx_tbl ;
1026 o_expiration_date          date_idx_tbl ; -- akaruppa B4287033
1027 s_firm_quantity            number_idx_tbl ;
1028 s_firm_date                date_idx_tbl ;
1029 s_by_product_using_assy_id number_idx_tbl ;
1030 /* akaruppa B5007729 End*/
1031 
1032 s_requested_completion_date     date_idx_tbl ;
1033 
1034 TYPE stp_schedule_priority IS TABLE OF msc_st_supplies.schedule_priority%TYPE
1035 INDEX BY BINARY_INTEGER;
1036 s_schedule_priority  stp_schedule_priority;
1037 
1038 /*B5100481 - 16 for pending, 3 for wip*/
1039 s_wip_status_code            number_idx_tbl;
1040 
1041 /* NAVIN: MTQ with Hardlinks */
1042 stp_var_itm_instance_id      number_idx_tbl;
1043 stp_var_itm_from_op_seq_id   number_idx_tbl;
1044 stp_var_itm_wip_entity_id    number_idx_tbl;
1045 stp_var_itm_from_item_id     number_idx_tbl;
1046 stp_var_min_tran_qty         number_idx_tbl;
1047 stp_var_itm_min_tm_off       number_idx_tbl;
1048 stp_var_itm_max_tm_off       number_idx_tbl;
1049 stp_var_itm_from_op_seq_num  number_idx_tbl;
1050 stp_var_itm_organization_id  number_idx_tbl;
1051 
1052 s_index      NUMBER := 0 ;
1053 
1054 /* ---------------- Demands declaration ----------------------*/
1055 
1056 /* akaruppa B5007729 */
1057 d_assembly_item_id number_idx_tbl ;
1058 f_assembly_item_id number_idx_tbl ;
1059 
1060 d_demand_date date_idx_tbl ;
1061 f_demand_date date_idx_tbl ;
1062 
1063 d_requirement_quantity number_idx_tbl;
1064 f_requirement_quantity number_idx_tbl;
1065 
1066 d_demand_type number_idx_tbl ;
1067 f_demand_type number_idx_tbl ;
1068 
1069 d_origination_type number_idx_tbl ;
1070 f_origination_type number_idx_tbl ;
1071 /* akaruppa B5007729 End*/
1072 
1073 TYPE demand_schedule IS TABLE OF msc_st_demands.demand_schedule_name%TYPE
1074 INDEX BY BINARY_INTEGER;
1075 d_demand_schedule demand_schedule;
1076 f_demand_schedule demand_schedule;
1077 e_demand_schedule demand_schedule;/* akaruppa B5007729 */
1078 
1079 TYPE dorder_number IS TABLE OF msc_st_demands.order_number%TYPE INDEX BY BINARY_INTEGER;
1080 d_order_number dorder_number ;
1081 f_order_number dorder_number ;
1082 e_order_number dorder_number ;/* akaruppa B5007729 */
1083 
1084 TYPE dwip_entity_name IS TABLE OF msc_st_demands.wip_entity_name%TYPE INDEX BY BINARY_INTEGER;
1085 d_wip_entity_name     dwip_entity_name   ;
1086 f_wip_entity_name     dwip_entity_name   ;
1087 e_wip_entity_name     dwip_entity_name   ;/* akaruppa B5007729 */
1088 
1089 /* akaruppa B5007729 */
1090 d_selling_price    number_idx_tbl;
1091 f_selling_price    number_idx_tbl;
1092 
1093 d_request_date     date_idx_tbl ;
1094 f_request_date     date_idx_tbl ;
1095 
1096 TYPE forecast_designator IS TABLE OF msc_st_demands.forecast_designator%TYPE
1097 INDEX BY BINARY_INTEGER;
1098 f_forecast_designator  forecast_designator ;
1099 e_forecast_designator  forecast_designator ;/* akaruppa B5007729 */
1100 
1101 f_sales_order_line_id  number_idx_tbl; /* akaruppa B5007729 */
1102 
1103 /*B5100481 - 16 for pending, 3 for wip*/
1104 d_wip_status_code      number_idx_tbl;
1105 
1106 d_index      NUMBER := 0 ;
1107 
1108 /* ---------------- Designator declaration ----------------------*/
1109 TYPE designator IS TABLE OF msc_st_designators.designator%TYPE INDEX BY BINARY_INTEGER;
1110 i_designator designator ;
1111 e_designator designator ;/* akaruppa B5007729 */
1112 
1113 TYPE forecast_set IS TABLE OF msc_st_designators.forecast_set%TYPE INDEX BY BINARY_INTEGER;
1114 i_forecast_set forecast_set;
1115 e_forecast_set forecast_set;/* akaruppa B5007729 */
1116 
1117 TYPE description IS TABLE OF msc_st_designators.description%TYPE INDEX BY BINARY_INTEGER;
1118 i_description description ;
1119 e_description description ;/* akaruppa B5007729 */
1120 
1121 i_disable_date               date_idx_tbl ;/* akaruppa B5007729 */
1122 i_consume_forecast           number_idx_tbl;/* akaruppa B5007729 */
1123 i_backward_update_time_fence number_idx_tbl;/* akaruppa B5007729 */
1124 i_forward_update_time_fence  number_idx_tbl;/* akaruppa B5007729 */
1125 
1126 i_index      NUMBER := 0 ;
1127 
1128 /* akaruppa B4287033  OnHand Declarations */
1129 o_new_dock_date   date_idx_tbl ;/* akaruppa B5007729 */
1130 
1131 o_deleted_flag    number_idx_tbl;/* akaruppa B5007729 */
1132 
1133 TYPE subinventory_code IS TABLE OF msc_st_supplies.subinventory_code%TYPE
1134 INDEX BY BINARY_INTEGER;
1135 o_subinventory_code subinventory_code   ;
1136 e_subinventory_code subinventory_code   ;/* akaruppa B5007729 */
1137 
1138 o_non_nettable_qty number_idx_tbl;/* akaruppa B5007729 */
1139 
1140 -- Rajesh Patangya 02-MAY-2006 Starts
1141 
1142 stp_chg_department_id      number_idx_tbl ;
1143 stp_chg_resource_id        number_idx_tbl ;
1144 stp_chg_organization_id    number_idx_tbl ;
1145 stp_chg_wip_entity_id      number_idx_tbl ;
1146 stp_chg_operation_seq_id   number_idx_tbl ;
1147 stp_chg_operation_seq_no   number_idx_tbl ;
1148 stp_chg_resource_seq_num   number_idx_tbl ;
1149 stp_chg_charge_num         number_idx_tbl ;
1150 stp_chg_charge_quanitity   number_idx_tbl ;
1151 
1152 -- Rajesh Patangya 02-MAY-2006 Ends
1153 
1154 TYPE stp_charge_start_dt_time IS TABLE OF msc_st_resource_charges.charge_start_datetime%TYPE
1155 INDEX BY BINARY_INTEGER;
1156 stpe_chg_charge_start_dt_time stp_charge_start_dt_time ;
1157 stp_chg_charge_start_dt_time  stp_charge_start_dt_time ;
1158 
1159 TYPE stp_charge_end_dt_time IS TABLE OF msc_st_resource_charges.charge_end_datetime%TYPE
1160 INDEX BY BINARY_INTEGER;
1161 stpe_chg_charge_end_dt_time stp_charge_end_dt_time ;
1162 stp_chg_charge_end_dt_time  stp_charge_end_dt_time ;
1163 
1164 --------------------------NAVIN: Sequence Dependencies--------------------------
1165 
1166 -- Rajesh Patangya 02-MAY-2006 Starts
1167 
1168 rr_sequence_id           number_idx_tbl ;
1169 rr_sequence_number       number_idx_tbl ;
1170 rr_setup_id              number_idx_tbl ;
1171 
1172 TYPE rsrc_firm_type IS TABLE OF msc_st_resource_requirements.firm_flag %TYPE
1173 INDEX BY BINARY_INTEGER;
1174 rr_firm_type rsrc_firm_type;
1175 
1176 /* NAVIN: new column for Operation Charges*/
1177 rr_min_capacity               number_idx_tbl;
1178 rr_max_capacity               number_idx_tbl;
1179 rr_original_seq_num           number_idx_tbl;
1180 rr_sequence_dependent_usage   number_idx_tbl;
1181 rr_alternate_number           number_idx_tbl;
1182 rr_basis_type                 number_idx_tbl;
1183 
1184 /* NAVIN :- Resource Instances start */
1185 
1186 rec_inst_supply_id            number_idx_tbl;
1187 rec_inst_organization_id      number_idx_tbl;
1188 rec_inst_sr_instance_id       number_idx_tbl;
1189 rec_inst_rec_resource_seq_num number_idx_tbl;
1190 rec_inst_resource_id          number_idx_tbl;
1191 rec_inst_instance_id          number_idx_tbl;
1192 rec_inst_start_date           date_idx_tbl ;
1193 rec_inst_end_date             date_idx_tbl ;
1194 rec_inst_rsrc_instance_hours  number_idx_tbl;
1195 rec_inst_operation_seq_num    number_idx_tbl;
1196 rec_inst_department_id        number_idx_tbl;
1197 rec_inst_wip_entity_id        number_idx_tbl;
1198 
1199 -- Begin Bug 5713355
1200 TYPE rec_serial_number IS TABLE OF msc_st_resource_instance_reqs.serial_number%TYPE
1201 INDEX BY BINARY_INTEGER;
1202 empty_inst_serial_number      rec_serial_number ;
1203 rec_inst_serial_number        rec_serial_number;
1204 -- End Bug 5713355
1205 rec_inst_parent_seq_num       number_idx_tbl;
1206 rec_inst_original_seq_num     number_idx_tbl;
1207 rec_inst_equp_item_id         number_idx_tbl;
1208 
1209 /* NAVIN :- Resource Instances end */
1210 
1211 /*-------------------------- Alternate Resources -----------------------------*/
1212 
1213 /* Sowmya - As Per the latest FDD changes :- Alternate resources declaration Start */
1214 
1215 TYPE alt_resource_varchar_typ IS TABLE OF VARCHAR2(4)
1216 INDEX BY BINARY_INTEGER;
1217 arre_uom_code              alt_resource_varchar_typ;
1218 arr_uom_code               alt_resource_varchar_typ;
1219 
1220 arr_wip_entity_id          number_idx_tbl;
1221 arr_operation_seq_num      number_idx_tbl;
1222 arr_res_seq_num            number_idx_tbl;
1223 arr_resource_id            number_idx_tbl;
1224 arr_alternate_num          number_idx_tbl;
1225 arr_usage_rate             number_idx_tbl;
1226 arr_assigned_units         number_idx_tbl;
1227 arr_department_id          number_idx_tbl;
1228 arr_activity_group_id      number_idx_tbl;
1229 arr_basis_type             number_idx_tbl;
1230 arr_setup_id               number_idx_tbl;
1231 arr_schedule_seq_num       number_idx_tbl;
1232 arr_maximum_assigned_units number_idx_tbl;
1233 
1234 /* Sowmya - As Per latest FDD changes :- Alternate resources declaration Ends */
1235 
1236 /*===== Calendar Declaration ===========*/
1237 
1238 TYPE cal_shift_typ is RECORD
1239 ( cal_date    DATE,
1240   shift_num   NUMBER,
1241   from_time   NUMBER,
1242   to_time     NUMBER
1243 );
1244 calendar_record  cal_shift_typ;
1245 TYPE cal_tab is table of cal_shift_typ index by BINARY_INTEGER;
1246 new_rec  cal_tab;
1247 
1248 TYPE cal_detail_typ is RECORD
1249 (calendar_id        NUMBER,
1250  calendar_no        VARCHAR2(16),
1251  calendar_desc      VARCHAR2(40),
1252  orgn_code          VARCHAR2(4),
1253  resource_whse_code VARCHAR2(4),
1254  organization_id    NUMBER,
1255  posted             NUMBER
1256 );
1257 cursor_rec  cal_detail_typ;
1258 TYPE tab_cal_typ is table of cal_detail_typ INDEX BY BINARY_INTEGER;
1259 plsqltbl_rec  tab_cal_typ;
1260 
1261 resource_count    number_idx_tbl;
1262 resource_id       number_idx_tbl;
1263 instance_id       number_idx_tbl;
1264 x_resource_id     number_idx_tbl;
1265 x_instance_id     number_idx_tbl;
1266 instance_number   number_idx_tbl;
1267 shift_num         number_idx_tbl;
1268 equipment_item_id number_idx_tbl;
1269 
1270 f_date           date_idx_tbl;
1271 t_date           date_idx_tbl;
1272 
1273 TYPE serial_number IS TABLE OF msc_st_net_res_inst_avail.serial_number%TYPE
1274 INDEX BY BINARY_INTEGER;
1275 emp_serial_number  serial_number;
1276 msc_serial_number  serial_number;
1277 
1278 /*
1279 REM+=========================================================================+
1280 REM| PROCEDURE NAME                                                          |
1281 REM|    retrieve_effectivities                                               |
1282 REM|                                                                         |
1283 REM| TYPE                                                                    |
1284 REM|    Private                                                              |
1285 REM|                                                                         |
1286 REM| DESCRIPTION                                                             |
1287 REM|    The majority of the logic in this procedure is contained in the four |
1288 REM|    cursors. There is one for each type of effectivity as follows:       |
1289 REM|      case 1: Effectivity has an organisation and a routing              |
1290 REM|      case 2: Effectivity has an organisation but no routing             |
1291 REM|      case 3: Effectivity has no organisation but has a routing          |
1292 REM|      case 4: Effectivity has no organisation and no routing             |
1293 REM|    Depending on each case above, the retrieval logic differs slightly   |
1294 REM|    as does the source of some the values which come back. To make it    |
1295 REM|    simpler to understand (and maintain) each case was dealt             |
1296 REM|    with on its own. By putting as much logic as possible in the SQL it  |
1297 REM|    was hoped to optimise the database accesses and make the code itself |
1298 REM|    simpler.                                                             |
1299 REM|                                                                         |
1300 REM| INPUT PARAMETERS                                                        |
1301 REM|    none                                                                 |
1302 REM|                                                                         |
1303 REM| OUTPUT PARAMETERS                                                       |
1304 REM|    return_status  TRUE=> OK                                             |
1305 REM|                                                                         |
1306 REM| INPUT/OUTPUT PARAMETERS                                                 |
1307 REM|    None                                                                 |
1308 REM|                                                                         |
1309 REM| HISTORY                                                                 |
1310 REM|    Created 12th July 1999 by P.J.Schofield (OPM Development Oracle UK)  |
1311 REM|    04/03/2000 - Using organization_id from gmp_item_aps , instead of    |
1312 REM|                 organization_id from sy_orgn_mst, Bug# 1252322          |
1313 REM| 07/14/2002   Rajesh Patangya - Reorgnized the complete code B2314052    |
1314 REM| 01/14/2003   Sridhar Gidugu  - Using gia.uom_code instead of gia.item_um|
1315 REM|                                Bug# 2739627                             |
1316 REM| 06/02/2003   Sridhar Gidugu  - B2989806 - Forward port fix for          |
1317 REM|                                Bug#2916619 - Rewrote Effectivity Cursor |
1318 REM+=========================================================================+
1319 */
1320 PROCEDURE retrieve_effectivities
1321 (
1322   return_status  OUT NOCOPY BOOLEAN
1323 )
1324 IS
1325   c_formula_effectivity   ref_cursor_typ;
1326   cur_routing_hdr     ref_cursor_typ;
1327   cur_routing_dtl     ref_cursor_typ;
1328   cur_formula_dtl     ref_cursor_typ;
1329   cur_formula_hdr     ref_cursor_typ;
1330   cur_mat_assoc       ref_cursor_typ;
1331   cur_alt_resource    ref_cursor_typ;
1332   c_recipe_override   ref_cursor_typ;
1333   c_recipe_orgn       ref_cursor_typ;
1334   c_uom_conv          ref_cursor_typ; /*B2870041 uom conversion cursor*/
1335   cur_rtg_offsets     ref_cursor_typ;
1336   cur_opr_stpdep      ref_cursor_typ;
1337   seq_dep_dtl         ref_cursor_typ;
1338   setup_id_dtl        ref_cursor_typ;
1339   uom_code_ref        ref_cursor_typ;
1340   um_code_ref         ref_cursor_typ;
1341   v_gmd_cursor 	      ref_cursor_typ;
1342 
1343   routing_dtl_cursor      VARCHAR2(32700) ;
1344   validation_statement    VARCHAR2(32700) ;
1345   retrieval_cursor        VARCHAR2(32700) ;
1346   effectivity_cursor      VARCHAR2(32700) ;
1347   formula_hdr_cursor      VARCHAR2(32700) ;
1348   formula_dtl_cursor      VARCHAR2(32700) ;
1349   routing_hdr_cursor      VARCHAR2(32700) ;
1350   mat_assoc_cursor        VARCHAR2(32700) ;
1351   recipe_orgn_statement   VARCHAR2(32700) ;
1352   recipe_statement        VARCHAR2(32700) ;
1353   uom_conv_cursor         VARCHAR2(32700) ; /*B2870041 hold sql for uom conv*/
1354   rtg_offset_cur_stmt     VARCHAR2(32700) ;
1355   opr_stpdep_cursor       VARCHAR2(32700) ;
1356   seq_dep_cursor          VARCHAR2(32700) ;
1357   setup_id_cursor         VARCHAR2(32700) ;
1358   uom_code_cursor         VARCHAR2(4000);
1359   um_code_cursor          VARCHAR2(4000);
1360 
1361   valid                   BOOLEAN ;
1362   routing_valid           BOOLEAN ;
1363   old_fmeff_id            NUMBER ;
1364   old_organization_id     NUMBER ;
1365   old_formula_id          NUMBER ;
1366   mat_start_indx          NUMBER ;
1367   mat_end_indx            NUMBER ;
1368   eff_counter		  INTEGER ;
1369   old_plant_code          VARCHAR2(4) ;
1370   s                       INTEGER ;
1371   temp_total_qty          NUMBER ; /*B2870041 temp var to calculate total output*/
1372   v_matl_qty              NUMBER ; /*B2870041 cursor var to get uom conv qty */
1373   spl_cnt                 NUMBER ;
1374   j                       NUMBER ; /*B2870041 for loop index*/
1375   end_index               NUMBER ; /*B2870041 for loop index*/
1376   old_route               NUMBER ; /*B2870041 for loop index*/
1377   old_orgn                VARCHAR2(4); /*B2870041 for loop index*/
1378   old_step                NUMBER ; /*B2870041 for loop index*/
1379   ri                      NUMBER ; /*B2870041 for loop index*/
1380   found                   NUMBER ; /*B2870041 for loop index*/
1381 /* NAMIT_OC */
1382   found_chrg_rsrc         NUMBER ;
1383   chrg_activity           VARCHAR2(16) ;
1384   first_step_row          NUMBER ; /*B2870041 for loop index*/
1385   l_gmp_um_code           VARCHAR2(25) ;
1386   v_dummy                 NUMBER ;
1387   nullenddatefound        BOOLEAN;  /* bug: 5872693 Vpedarla 12-Feb-2007 */
1388 
1389 BEGIN
1390 g_fm_dtl_start_loc        := 0; /* Start detail location */
1391 g_fm_dtl_end_loc          := 0; /* End detail location */
1392 g_fm_hdr_loc              := 1; /* Starting for formula header */
1393 g_formula_orgn_count_tab  := 1; /* Starting for formula orgn detail */
1394 
1395 g_rstep_loc               := 1 ;
1396 g_curr_rstep_loc	  := -1 ;
1397 g_prev_formula_id         := -1 ;
1398 g_prev_locn               := 1;
1399 
1400   routing_dtl_cursor      := NULL;
1401   validation_statement    := NULL;
1402   retrieval_cursor        := NULL;
1403   effectivity_cursor      := NULL;
1404   formula_hdr_cursor      := NULL;
1405   formula_dtl_cursor      := NULL;
1406   routing_hdr_cursor      := NULL;
1407   mat_assoc_cursor        := NULL;
1408   recipe_orgn_statement   := NULL;
1409   recipe_statement        := NULL;
1410   uom_conv_cursor         := NULL;
1411   rtg_offset_cur_stmt     := NULL;
1412   opr_stpdep_cursor       := NULL ;
1413   seq_dep_cursor          := NULL ;
1414   setup_id_cursor         := NULL ;
1415   old_plant_code          := NULL ;
1416   old_orgn                := NULL;
1417   chrg_activity           := NULL ;
1418   l_gmp_um_code           := NULL ;
1419   uom_code_cursor         := NULL ;
1420   um_code_cursor          := NULL ;
1421 
1422   valid                   := FALSE;
1423   routing_valid           := FALSE ;
1424   nullenddatefound        := FALSE;  /* bug: 5872693 Vpedarla 12-Feb-2007 */
1425 
1426   old_fmeff_id            := 0  ;
1427   old_organization_id     := 0  ;
1428   old_formula_id          := 0  ;
1429   mat_start_indx          := 0  ;
1430   mat_end_indx            := 0  ;
1431   eff_counter		  := 0 ;
1432   temp_total_qty          := 0  ;
1433   v_matl_qty              := 0  ;
1434   spl_cnt                 := 0 ;
1435   j                       := 0 ;
1436   end_index               := 0 ;
1437   old_route               := 0 ;
1438   old_step                := 0 ;
1439   ri                      := 0 ;
1440   found                   := 0 ;
1441   found_chrg_rsrc         := 0 ;
1442   first_step_row          := 0 ;
1443   v_dummy                 := 0 ;
1444   s                       := 1 ;
1445 
1446 dbms_session.free_unused_user_memory;/* akaruppa B5007729 */
1447 
1448 /* populate the org_string    */
1449      IF MSC_CL_GMP_UTILITY.org_string(g_instance_id) THEN
1450         NULL ;
1451      ELSE
1452         log_message(MSC_CL_GMP_UTILITY.g_in_str_org);
1453         RAISE invalid_string_value  ;
1454      END IF;
1455 
1456 --       l_in_str_org := 'IN (1381,1382,1383,1383,5172)' ;
1457     l_in_str_org := MSC_CL_GMP_UTILITY.g_in_str_org ;  /* B3491625 */
1458 
1459 /*B2870041 changed cursor to retrieve the just the routing qty no uom conv,
1460 added uom conv of the product to the routing uom for a qty of 1 to get the
1461 factor. The factor will be used later. added product index to allow access
1462 when we are writing out the routing */
1463     /* The query is being modified to incorporate changes for 1830940 */
1464 /* B2989806 Added inline tables and outer joins to select aps_fmeff_id */
1465 
1466 /* NAMIT UOM Change, This should come from source */
1467     um_code_cursor   := ' select fnd_profile.VALUE' ||at_apps_link
1468                       ||' (''SY$UOM_HOURS'') from dual ' ; /* OPM UOM */
1469 
1470        OPEN um_code_ref FOR um_code_cursor ;
1471        FETCH um_code_ref INTO l_gmp_um_code;
1472        CLOSE um_code_ref;
1473 
1474     IF l_gmp_um_code IS NOT NULL THEN
1475 /* Get the UOM code and UOM Class corresponding to "GMP: UOM for Hour" Profile */
1476        uom_code_cursor :=
1477                       ' select um_type '
1478                       ||' from sy_uoms_mst'||at_apps_link
1479                       ||' where um_code = :gmp_um_code ';
1480 /* mattt the comparison is done against um_code not unit_of_measure */
1481 -- ||' where unit_of_measure = :gmp_um_code ';
1482 
1483        OPEN uom_code_ref FOR uom_code_cursor USING l_gmp_um_code;
1484        FETCH uom_code_ref INTO g_gmp_uom_class;
1485        CLOSE uom_code_ref;
1486     ELSE
1487          RAISE invalid_gmp_uom_profile  ;
1488     END IF;
1489     IF (g_gmp_uom_class IS NULL) THEN
1490          RAISE invalid_gmp_uom_profile  ;
1491     END IF;
1492 
1493     effectivity_cursor :=
1494                    ' SELECT eff.recipe_validity_rule_id, '
1495                    ||' nvl(gfe.aps_fmeff_id,-1),eff.item_id, '
1496                    ||' eff.formula_id,eff.lorgn_code, eff.organization_id, '
1497                    ||' eff.start_date, eff.end_date, eff.inv_min_qty, '
1498                    ||' eff.inv_max_qty, eff.preference, eff.uom_code, '
1499                    ||' eff.wcode, eff.routing_id, '
1500                    ||' eff.routing_no, eff.routing_vers, eff.routing_desc, '
1501                    ||' eff.item_um, eff.routing_qty, '
1502                    ||' eff.prd_fct  , eff.prd_ind, '
1503                    ||' eff.aps_item_id, eff.recipe_id, eff.rhdr_loc, '
1504                    ||' decode(eff.calculate_step_quantity,0,2,1) calculate_step_quantity, '
1505                    ||' eff.category_id,NULL , '
1506                    ||' eff.seq_dpnd_class '
1507                    ||' FROM (  '
1508                    ||' SELECT ffe.recipe_validity_rule_id, ffe.item_id, '
1509                    ||' grb.formula_id, ffe.orgn_code lorgn_code, gia.organization_id, '
1510 		   ||' ffe.start_date, ffe.end_date, ffe.inv_min_qty, '
1511 		   ||' ffe.inv_max_qty, ffe.preference, gia.uom_code, '
1512                    ||' som.resource_whse_code wcode , grb.routing_id, '
1513 		   ||' frh.routing_no, frh.routing_vers, frh.routing_desc, '
1514                    ||' frh.item_um, frh.routing_qty, ' /*B2870041*/
1515                    ||' DECODE(frh.item_um,gia.item_um ,1, '
1516                    ||'        GMICUOM.uom_conversion'||at_apps_link
1517                    ||'                 (ffe.item_id, '
1518                    ||'                 0, '
1519                    ||'                 1, '
1520                    ||'                 gia.item_um , '   /* primary */
1521                    ||'                 frh.item_um , '   /* routing um */
1522                    ||'                 0 '
1523                    ||'                 ) '
1524                    ||'         ) prd_fct, -1 prd_ind, '
1525                    ||' gia.aps_item_id, grb.recipe_id, 0 rhdr_loc, '
1526                    ||' grb.calculate_step_quantity,'
1527 		   || ' gia.category_id,NULL, '
1528                    ||' gia.seq_dpnd_class '
1529 		   ||' FROM  gmd_recipes_b'||at_apps_link||' grb,'
1530 		   ||'       gmd_recipe_validity_rules'||at_apps_link||' ffe,'
1531 		   ||'       fm_form_mst'||at_apps_link||' ffm,'
1532 		   ||'       fm_rout_hdr'||at_apps_link||' frh,'
1533 		   ||'       sy_orgn_mst'||at_apps_link||' som,'
1534 		   ||'       gmp_item_aps'||at_apps_link||' gia,'
1535 		   ||'       gmd_status_b'||at_apps_link||' gs1,'
1536 		   ||'       gmd_status_b'||at_apps_link||' gs2,'
1537 		   ||'       gmd_status_b'||at_apps_link||' gs3,'
1538 		   ||'       gmd_status_b'||at_apps_link||' gs4 '
1539                    ||' WHERE grb.delete_mark = 0 '
1540                    ||'   AND grb.recipe_id = ffe.recipe_id '
1541                    ||'   AND grb.recipe_status = gs1.status_code '
1542                    ||'   AND gs1.status_type IN (' ||'''700'''|| ',' ||''' 900'''|| ') '
1543                    ||'   AND gs1.delete_mark = 0 '
1544                    ||'   AND ffe.delete_mark = 0 '
1545                    ||'   AND ffe.validity_rule_status = gs2.status_code '
1546                    ||'   AND gs2.status_type IN (' ||'''700'''|| ',' ||''' 900'''|| ') '
1547                    ||'   AND gs2.delete_mark = 0 '
1548                    ||'   AND frh.delete_mark = 0 '
1549                    ||'   AND ffm.delete_mark = 0 '
1550                    ||'   AND som.delete_mark = 0 '
1551                    ||'   AND frh.inactive_ind = 0 '
1552                    ||'   AND ffm.inactive_ind = 0 '
1553                    ||'   AND grb.routing_id IS NOT NULL '
1554                    ||'   AND ffe.orgn_code IS NOT NULL '
1555                    ||'   AND ffe.recipe_use IN (0,1) '
1556                    ||'   AND nvl(ffe.end_date,(SYSDATE + 1)) > SYSDATE '
1557                    ||'   AND ffe.orgn_code = som.orgn_code '
1558                    ||'   AND grb.formula_id = ffm.formula_id '
1559                    ||'   AND ffm.formula_status = gs3.status_code '
1560                    ||'   AND gs3.status_type IN (' ||'''700'''|| ',' ||''' 900'''|| ') '
1561                    ||'   AND gs3.delete_mark = 0 '
1562                    ||'   AND grb.routing_id =  frh.routing_id '
1563                    ||'   AND frh.routing_status =  gs4.status_code '
1564                    ||'   AND gs4.status_type IN (' ||'''700'''|| ',' ||''' 900'''|| ') '
1565                    ||'   AND gs4.delete_mark = 0 '
1566                    ||'   AND gia.plant_code =  ffe.orgn_code '
1567                    ||'   AND gia.item_id =  ffe.item_id '
1568                    ||'   AND gia.whse_code = som.resource_whse_code '
1569                    ||'   AND gia.replen_ind = 1 '
1570                    ||'   AND EXISTS ( SELECT 1 '
1571                    ||'          FROM  fm_matl_dtl'||at_apps_link||' '
1572                    ||'          WHERE formula_id = grb.formula_id '
1573                    ||'            AND line_type = 1 '
1574                    ||'            AND item_id = ffe.item_id ) '
1575                    ||' UNION ALL '
1576                    ||' SELECT ffe.recipe_validity_rule_id, ffe.item_id, '
1577                    ||' grb.formula_id, ffe.orgn_code lorgn_code, gia.organization_id, '
1578                    ||' ffe.start_date, ffe.end_date, ffe.inv_min_qty, '
1579                    ||' ffe.inv_max_qty, ffe.preference, gia.uom_code, '
1580                    ||' gia.whse_code wcode , to_number(null) , '
1581 		   ||' NULL, to_number(null), NULL, '
1582                    ||' NULL, to_number(null), to_number(null) prd_fct, -1 prd_ind, '
1583                    ||' gia.aps_item_id, grb.recipe_id, 0 rhdr_loc, '
1584 /* NAMIT_CR,SGIDUGU */
1585                    ||' 0 calculate_step_quantity, '
1586                    ||' gia.category_id,NULL, '
1587                    ||' gia.seq_dpnd_class '
1588 		   ||' FROM  gmd_recipes_b'||at_apps_link||' grb,'
1589 		   ||'       gmd_recipe_validity_rules'||at_apps_link||' ffe,'
1590 		   ||'       fm_form_mst'||at_apps_link||' ffm, '
1591 		   ||'       sy_orgn_mst'||at_apps_link||' som, '
1592 		   ||'       gmp_item_aps'||at_apps_link||' gia, '
1593 		   ||'       gmd_status_b'||at_apps_link||' gs1,'
1594 		   ||'       gmd_status_b'||at_apps_link||' gs2,'
1595 		   ||'       gmd_status_b'||at_apps_link||' gs3 '
1596                    ||' WHERE  grb.delete_mark = 0 '
1597                    ||'   AND grb.recipe_id = ffe.recipe_id '
1598                    ||'   AND grb.recipe_status = gs1.status_code '
1599                    ||'   AND gs1.status_type IN (' ||'''700'''|| ',' ||''' 900'''|| ') '
1600                    ||'   AND gs1.delete_mark = 0 '
1601                    ||'   AND ffe.delete_mark = 0 '
1602                    ||'   AND ffe.validity_rule_status = gs2.status_code '
1603                    ||'   AND gs2.status_type IN (' ||'''700'''|| ',' ||''' 900'''|| ') '
1604                    ||'   AND gs2.delete_mark = 0 '
1605                    ||'   AND ffm.delete_mark = 0 '
1606                    ||'   AND som.delete_mark = 0 '
1607                    ||'   AND ffm.inactive_ind = 0 '
1608                    ||'   AND grb.routing_id IS NULL '
1609                    ||'   AND ffe.orgn_code IS NOT NULL '
1610                    ||'   AND ffe.orgn_code = som.orgn_code '
1611                    ||'   AND ffe.recipe_use IN (0,1) '
1612                    ||'   AND nvl(ffe.end_date,(SYSDATE + 1)) > SYSDATE '
1613                    ||'   AND grb.formula_id = ffm.formula_id '
1614                    ||'   AND ffm.formula_status = gs3.status_code '
1615                    ||'   AND gs3.status_type IN (' ||'''700'''|| ',' ||''' 900'''|| ') '
1616                    ||'   AND gs3.delete_mark = 0 '
1617                    ||'   AND gia.plant_code =  ffe.orgn_code '
1618                    ||'   AND gia.item_id =  ffe.item_id '
1619                    ||'   AND gia.whse_code = som.resource_whse_code '
1620                    ||'   AND gia.replen_ind = 1 '
1621                    ||'   AND EXISTS ( SELECT 1 '
1622                    ||'          FROM  fm_matl_dtl'||at_apps_link||' '
1623                    ||'          WHERE formula_id = grb.formula_id '
1624                    ||'            AND line_type = 1 '
1625                    ||'            AND item_id = ffe.item_id ) '
1626                    ||' UNION ALL '
1627                    ||' SELECT ffe.recipe_validity_rule_id, ffe.item_id, '
1628                    ||' grb.formula_id, gia.plant_code lorgn_code, gia.organization_id, '
1629                    ||' ffe.start_date, ffe.end_date, ffe.inv_min_qty, '
1630                    ||' ffe.inv_max_qty, ffe.preference, gia.uom_code, '
1631                    ||' som.resource_whse_code wcode , grb.routing_id, '
1632                    ||' frh.routing_no, frh.routing_vers, frh.routing_desc, '
1633                    ||' frh.item_um, frh.routing_qty,' /*B2870041*/
1634                    ||' DECODE(frh.item_um,gia.item_um, 1, '
1635                    ||'        GMICUOM.uom_conversion'||at_apps_link
1636                    ||'                 (ffe.item_id, '
1637                    ||'                 0, '
1638                    ||'                 1, '
1639                    ||'                 gia.item_um , '   /* primary */
1640                    ||'                 frh.item_um , '   /* routing um */
1641                    ||'                 0 '
1642                    ||'                 ) '
1643                    ||'         ) prd_fct, -1 prd_ind, '
1644                    ||' gia.aps_item_id, grb.recipe_id, 0 rhdr_loc, '
1645 /* NAMIT_CR,SGIDUGU */
1646                    ||' grb.calculate_step_quantity, '
1647                    ||' gia.category_id,NULL, '
1648                    ||' gia.seq_dpnd_class '
1649 		   ||' FROM  gmd_recipes_b'||at_apps_link||' grb,'
1650 		   ||'       gmd_recipe_validity_rules'||at_apps_link||' ffe,'
1651 		   ||'       fm_form_mst'||at_apps_link||' ffm,'
1652 		   ||'       fm_rout_hdr'||at_apps_link||' frh,'
1653 		   ||'       sy_orgn_mst'||at_apps_link||' som,'
1654 		   ||'       gmp_item_aps'||at_apps_link||' gia,'
1655 		   ||'       gmd_status_b'||at_apps_link||' gs1,'
1656 		   ||'       gmd_status_b'||at_apps_link||' gs2,'
1657 		   ||'       gmd_status_b'||at_apps_link||' gs3,'
1658 		   ||'       gmd_status_b'||at_apps_link||' gs4 '
1659                    ||' WHERE grb.delete_mark = 0 '
1660                    ||'   AND grb.recipe_id = ffe.recipe_id '
1661                    ||'   AND grb.recipe_status = gs1.status_code '
1662                    ||'   AND gs1.status_type IN (' ||'''700'''|| ',' ||''' 900'''|| ') '
1663                    ||'   AND gs1.delete_mark = 0 '
1664                    ||'   AND ffe.delete_mark = 0 '
1665                    ||'   AND ffe.validity_rule_status = gs2.status_code '
1666                    ||'   AND gs2.status_type IN (' ||'''700'''|| ',' ||''' 900'''|| ') '
1667                    ||'   AND gs2.delete_mark = 0 '
1668                    ||'   AND frh.delete_mark = 0 '
1669                    ||'   AND ffm.delete_mark = 0 '
1670                    ||'   AND som.delete_mark = 0 '
1671                    ||'   AND frh.inactive_ind = 0 '
1672                    ||'   AND ffm.inactive_ind = 0 '
1673                    ||'   AND grb.routing_id IS NOT NULL '
1674                    ||'   AND ffe.orgn_code IS NULL '
1675                    ||'   AND ffe.recipe_use IN (0,1) '
1676                    ||'   AND nvl(ffe.end_date,(SYSDATE + 1)) > SYSDATE '
1677                    ||'   AND grb.formula_id = ffm.formula_id '
1678                    ||'   AND ffm.formula_status = gs3.status_code '
1679                    ||'   AND gs3.status_type IN (' ||'''700'''|| ',' ||''' 900'''|| ') '
1680                    ||'   AND gs3.delete_mark = 0 '
1681                    ||'   AND grb.routing_id =  frh.routing_id '
1682                    ||'   AND frh.routing_status =  gs4.status_code '
1683                    ||'   AND gs4.status_type IN (700,900) '
1684                    ||'   AND gs4.delete_mark = 0 '
1685                    ||'   AND gia.plant_code =  som.orgn_code '
1686                    ||'   AND gia.item_id =  ffe.item_id '
1687                    ||'   AND gia.whse_code = som.resource_whse_code '
1688                    ||'   AND gia.replen_ind = 1 '
1689                    ||'   AND EXISTS ( SELECT 1 '
1690                    ||'          FROM  fm_matl_dtl'||at_apps_link||' '
1691                    ||'          WHERE formula_id = grb.formula_id '
1692                    ||'            AND line_type = 1 '
1693                    ||'            AND item_id = ffe.item_id ) '
1694                    ||' UNION ALL '
1695                    ||' SELECT ffe.recipe_validity_rule_id, ffe.item_id, '
1696                    ||' grb.formula_id, gia.plant_code lorgn_code, gia.organization_id, '
1697                    ||' ffe.start_date, ffe.end_date, ffe.inv_min_qty, '
1698                    ||' ffe.inv_max_qty, ffe.preference, gia.uom_code, '
1699                    ||' gia.whse_code wcode , to_number(null) , '
1700                    ||' NULL, to_number(null), NULL, '
1701                    ||' NULL, to_number(null), to_number(null) prd_fct, -1 prd_ind, ' /*B2870041*/
1702                    ||' gia.aps_item_id, grb.recipe_id, 0 rhdr_loc, '
1703 /* NAMIT_CR,SGIDUGU */
1704                    ||' 0 calculate_step_quantity, '
1705                    ||' gia.category_id,NULL, '
1706                    ||' gia.seq_dpnd_class '
1707 		   ||' FROM  gmd_recipes_b'||at_apps_link||' grb,'
1708 		   ||'       gmd_recipe_validity_rules'||at_apps_link||' ffe,'
1709                    ||'       sy_orgn_mst'||at_apps_link||' som, '
1710                    ||'       fm_form_mst'||at_apps_link||' ffm, '
1711                    ||'       gmp_item_aps'||at_apps_link||' gia,'
1712 		   ||'       gmd_status_b'||at_apps_link||' gs1,'
1713 		   ||'       gmd_status_b'||at_apps_link||' gs2,'
1714 		   ||'       gmd_status_b'||at_apps_link||' gs3 '
1715                    ||' WHERE grb.delete_mark = 0 '
1716                    ||'   AND grb.recipe_id = ffe.recipe_id '
1717                    ||'   AND grb.recipe_status = gs1.status_code '
1718                    ||'   AND gs1.status_type IN (' ||'''700'''|| ',' ||''' 900'''|| ') '
1719                    ||'   AND gs1.delete_mark = 0 '
1720                    ||'   AND ffe.delete_mark = 0 '
1721                    ||'   AND ffe.validity_rule_status = gs2.status_code '
1722                    ||'   AND gs2.status_type IN (' ||'''700'''|| ',' ||''' 900'''|| ') '
1723                    ||'   AND gs2.delete_mark = 0 '
1724                    ||'   AND ffm.delete_mark = 0 '
1725                    ||'   AND som.delete_mark = 0 '
1726                    ||'   AND ffm.inactive_ind = 0 '
1727                    ||'   AND grb.routing_id IS NULL '
1728                    ||'   AND ffe.orgn_code IS NULL '
1729                    ||'   AND ffe.recipe_use IN (0,1) '
1730                    ||'   AND nvl(ffe.end_date,(SYSDATE + 1)) > SYSDATE '
1731                    ||'   AND grb.formula_id = ffm.formula_id '
1732                    ||'   AND ffm.formula_status = gs3.status_code '
1733                    ||'   AND gs3.status_type IN (' ||'''700'''|| ',' ||''' 900'''|| ') '
1734                    ||'   AND gs3.delete_mark = 0 '
1735 		   ||'   AND gia.plant_code = som.orgn_code '  ;
1736          IF l_in_str_org  IS NOT NULL THEN
1737          effectivity_cursor := effectivity_cursor
1738                    ||'   AND gia.organization_id ' || l_in_str_org
1739                    ||'   AND gia.whse_code = som.resource_whse_code ' ;
1740         END IF;
1741          /* B3837959 MMK Issue, Database link added for form_eff */
1742          effectivity_cursor := effectivity_cursor
1743 		   ||'   AND gia.item_id = ffe.item_id '
1744                    ||'   AND gia.replen_ind = 1 '
1745                    ||'   AND EXISTS ( SELECT 1 '
1746                    ||'          FROM  fm_matl_dtl'||at_apps_link||' '
1747                    ||'          WHERE formula_id = grb.formula_id '
1748                    ||'            AND line_type = 1 '
1749                    ||'            AND item_id = ffe.item_id )  ) eff,'
1750                    ||'( SELECT plant_code, whse_code, fmeff_id, '
1751                    ||'             max(aps_fmeff_id) aps_fmeff_id '
1752                    ||'             FROM gmp_form_eff'||at_apps_link||' '
1753                    ||'      GROUP BY plant_code, whse_code, fmeff_id '
1754                    ||'    ) gfe '
1755                    ||'WHERE eff.lorgn_code = gfe.plant_code (+) '
1756                    ||' AND eff.wcode = gfe.whse_code (+) '
1757                    ||' AND eff.recipe_validity_rule_id = gfe.fmeff_id (+) '
1758 		   ||' ORDER BY 4,5,6  ' ;
1759 
1760     formula_hdr_cursor :=
1761                      ' SELECT unique ffm.formula_id, 0, 0, 0, -1, NULL '
1762                    ||' FROM fm_form_mst'||at_apps_link||' ffm, '
1763                    ||'      gmd_recipes_b'||at_apps_link||' grb, '
1764                    ||'      gmd_recipe_validity_rules'||at_apps_link||' ffe, '
1765                    ||'      gmd_status_b'||at_apps_link||' gs '
1766                    ||' WHERE grb.recipe_id = ffe.recipe_id '
1767                    ||'   AND ffe.validity_rule_status = gs.status_code '
1768                    ||'   AND gs.status_type IN (' ||'''700'''|| ',' ||''' 900'''|| ') '
1769                    ||'   AND gs.delete_mark = 0 '
1770                    ||'   AND nvl(ffe.end_date,(SYSDATE + 1)) > SYSDATE '
1771                    ||'   AND ffm.formula_id = grb.formula_id '
1772                    ||'   AND ffe.delete_mark = 0 '
1773                    ||'   AND ffm.delete_mark = 0 '
1774                    ||' ORDER BY formula_id  ' ;
1775 
1776     -- gmp_putline('Started at '|| TO_CHAR(SYSDATE,'DD-MON-YYYY HH24:MI:SS'),'a');
1777     OPEN cur_formula_hdr FOR formula_hdr_cursor;
1778     LOOP
1779       FETCH cur_formula_hdr INTO formula_header_tab(formula_headers_size);
1780       EXIT WHEN cur_formula_hdr%NOTFOUND;
1781       formula_headers_size := formula_headers_size + 1;
1782     END LOOP;
1783     CLOSE cur_formula_hdr;
1784     formula_headers_size := formula_headers_size -1 ;
1785     time_stamp;
1786     log_message('Formula Header size is = ' || to_char(formula_headers_size)) ;
1787 
1788      v_gmd_seq := 'SELECT MAX(formulaline_id) FROM fm_matl_dtl'||at_apps_link;
1789 
1790      OPEN v_gmd_cursor FOR v_gmd_seq;
1791      FETCH v_gmd_cursor INTO v_gmd_formula_lineid;
1792      CLOSE v_gmd_cursor;
1793 
1794 /* Bug: 5872693 Vpedarla 12-Feb-2007 Start */
1795     prev_detail_tab(1) := NULL;
1796     orig_detail_tab(1) := NULL;
1797     formula_details_size := 0;
1798 /* Bug: 5872693 Vpedarla 12-Feb-2007 end */
1799 
1800 /* Bug: 5872693 Vpedarla 12-Mar-2007 Start */
1801 
1802    formula_dtl_cursor :=
1803          '  SELECT ffm.formula_id, '
1804        ||'  ffm.formula_no, '
1805        ||'  ffm.formula_vers, '
1806        ||'  ffm.formula_desc1, '
1807        ||'  ((fmd.formulaline_id * 2) + 1) x_formulaline_id, '
1808        ||'  fmd.line_type, '
1809        ||'  fmd.item_id, '
1810        ||'  decode(fmd.original_item_flag,1,fmd.qty,(( fmd.sub_replace_qty / fmd.sub_original_qty) * fmd.line_item_qty)) qty, '
1811        /*B5176291 - for substitute items fmd.qty will be null, in those case subsittute qty should be used*/
1812        ||'  fmd.scrap_factor, '
1813        ||'  fmd.scale_type, '
1814        ||'  fmd.contribute_yield_ind, '
1815        ||'  decode(fmd.line_type, -1, decode(nvl(fmd.contribute_step_qty_ind, '''||'N'||''''||'),'
1816        ||    ''''||'Y'||''''||',1,2), 1) contribute_step_qty_ind,'
1817        ||'  DECODE(fmd.phantom_type,0,null,6) phantom_type, '
1818        ||'  gia.uom_code, ' --akaruppa changed gia.uom_code to msi.primary_uom_code
1819        ||'  fmd.item_um ,  ' /*B2870041*/ --akaruppa changed fmd.item_um to fmd.detail_uom and gia.item_um to msi.primary_uom_code
1820        ||'  gia.uom_code, '
1821        ||'  DECODE(fmd.scale_type,0,0,1,2) scale_type, '
1822        ||'  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)), '
1823        ||'        GMICUOM.uom_conversion'||at_apps_link
1824        ||'                  ( fmd.item_id, '
1825        ||'                   0, '
1826        ||'                   decode(fmd.original_item_flag,1,fmd.qty,((fmd.sub_replace_qty / fmd.sub_original_qty) * fmd.line_item_qty)), '
1827        ||'                   fmd.item_um , '
1828        ||'                   gia.item_um , '
1829        ||'                   0)) primary_qty, '
1830        ||'  gia.aps_item_id, '
1831        ||'  fmd.scale_multiple, '
1832        ||'  (fmd.scale_rounding_variance * 100) scale_rounding_variance, '
1833 /* B3703430 - sowsubra - rounding variance multiplied by 100 */
1834        ||'  decode(fmd.rounding_direction,1,2,2,1,fmd.rounding_direction) ,'
1835        ||'  fmd.release_type, '
1836        ||'  fmd.line_item_id, '
1837        ||'  fmd.start_date, '
1838        ||'  fmd.end_date, '
1839        ||'  fmd.formulaline_id formula_line_id , '
1840        ||'  fmd.preference preference, '
1841        ||'  to_date(NULL) lead_stdate ,'
1842        ||'  to_date(NULL) lead_enddate ,'
1843        ||'  to_number(NULL) lead_pref ,'
1844        ||'  null actual_end_date ,'
1845        ||'  0 actual_end_flag ,'
1846        ||'  fmd.original_item_flag original_item_flag  , '
1847        ||'  fmd.formulaline_id formula_line_id '
1848        ||'  FROM  gmd_material_effectivities_vw'||at_apps_link||' fmd,'
1849        ||'        fm_form_mst'||at_apps_link||' ffm, '
1850        ||'        (SELECT  a.item_id, a.aps_item_id, a.item_um, a.uom_code '
1851        ||'            FROM (SELECT item_id, aps_item_id, item_um, uom_code, '
1852        ||'           ROW_NUMBER() OVER ( PARTITION BY item_id ORDER BY item_id,aps_item_id ) AS first_row '
1853        ||'           FROM gmp_item_aps'||at_apps_link ||' ) a where a.first_row = 1 ) gia '
1854        ||'  WHERE gia.item_id = fmd.item_id '
1855        ||'  AND ffm.formula_id = fmd.formula_id '
1856        ||'  AND ffm.delete_mark = 0 '
1857        ||'  AND ( fmd.qty <> 0 OR (( fmd.sub_replace_qty / fmd.sub_original_qty) * fmd.line_item_qty) <> 0) '
1858        ||'  ORDER BY ffm.formula_id ,fmd.line_type, fmd.formulaline_id, '
1859        ||'  fmd.original_item_flag desc,fmd.start_date,fmd.preference ';
1860 
1861 	OPEN cur_formula_dtl FOR formula_dtl_cursor;
1862 	-- { L1
1863 	LOOP
1864 	FETCH cur_formula_dtl INTO temp_detail_tab(1);
1865 	-- Bug 5955251 Vpedarla 29-Mar-2007  COLLECTION ISSUE CREATES DUMMY CO-PRODUCT CREATION IN ODS
1866 	EXIT WHEN cur_formula_dtl%NOTFOUND;
1867 	--end of bug 5955251
1868 	   -- { 1
1869 	   IF  (temp_detail_tab(1).original_item_flag = 1 ) THEN         /* If original item */
1870 	     -- { 2
1871 	     IF substcount <> 0 THEN              --processing the previous original item's substituion records
1872 	        FOR i in 1..substcount
1873 	        -- { L2
1874 	        loop
1875 	           -- { 3
1876 	           IF (subst_tab(i).start_date <= NVL(subst_tab(i).end_date,subst_tab(i).start_date)) THEN
1877 	              FOR j in 1..substcount
1878 	              -- { L3
1879 	              LOOP
1880 	                  -- { 4
1881 	                  IF ((I <> J) and
1882 	                      (subst_tab(j).start_date <= NVL(subst_tab(j).end_date,subst_tab(j).start_date))) THEN
1883 	                        -- { 5
1884 	                        IF (subst_tab(i).preference < subst_tab(j).preference) THEN
1885 	                             -- { 6
1886 	                             IF ((subst_tab(j).start_date >= subst_tab(i).start_date) and
1887 	                                  (subst_tab(i).end_date IS NULL)) THEN
1888 		       		                subst_tab(j).end_date := (subst_tab(j).start_date - 1/1440) ;
1889 
1890 	                             ELSIF ((subst_tab(j).start_date < subst_tab(i).start_date) and
1891 	                                      (subst_tab(i).end_date IS NULL) AND
1892 		                                ((subst_tab(j).end_date >= subst_tab(i).start_date) OR
1893 		                                (subst_tab(j).end_date IS NULL))) THEN
1894 	       		                     subst_tab(j).end_date := (subst_tab(i).start_date - 1/1440) ;
1895 
1896 	                             ELSIF ((subst_tab(j).start_date < subst_tab(i).end_date) and
1897 	                                    (subst_tab(j).end_date <= subst_tab(i).end_date) and
1898 	                                    (subst_tab(i).start_date <= subst_tab(j).start_date)) THEN
1899 	                                subst_tab(j).end_date := (subst_tab(j).start_date - 1/1440) ;
1900 
1901 	                             ELSIF (subst_tab(j).start_date > subst_tab(i).start_date)  and
1902 	                                  (subst_tab(j).start_date < subst_tab(i).end_date)  and
1903 	                                   (subst_tab(j).end_date > subst_tab(i).end_date) THEN
1904 		                         	  log_message('entered into condition--4');
1905 	                                subst_tab(j).start_date := subst_tab(i).end_date + 1/1440 ;
1906 
1907 	                             ELSIF (subst_tab(i).start_date > subst_tab(j).start_date)  and
1908 	                                    (subst_tab(i).start_date < subst_tab(j).end_date)  and
1909 	                                    (subst_tab(i).end_date > subst_tab(j).end_date)  THEN
1910 	                        		 subst_tab(j).end_date := subst_tab(i).start_date - 1/1440 ;
1911                                 --Swapna Bug#5975883 below eslif condition was added
1912 	                             ELSIF(subst_tab(i).start_date <= subst_tab(j).start_date) and
1913                                       (subst_tab(i).end_date is NOT NULL) and (subst_tab(j).start_date < subst_tab(i).end_date) and
1914 	                	                 (subst_tab(j).end_date is NULL) THEN
1915 	                                 subst_tab(j).start_date := subst_tab(i).end_date + 1/1440;
1916 	                             ELSIF(subst_tab(i).start_date > subst_tab(j).start_date)  and
1917 	                	                 (subst_tab(j).end_date is NULL)
1918 	                	                 and (subst_tab(i).end_date is NOT NULL) THEN
1919 	                                 subst_tab(j).end_date := subst_tab(i).start_date - 1/1440;
1920 	                                 substcount := substcount + 1;	--Swapna Bug#5975883
1921 	                                 subst_tab(substcount) := subst_tab(j);
1922 	                           		 subst_tab(substcount).start_date := subst_tab(i).end_date +1/1440 ;
1923 	                                 subst_tab(substcount).end_date := NULL;
1924 
1925 	                             ELSIF (subst_tab(i).start_date > subst_tab(j).start_date) and
1926 		                               (subst_tab(i).end_date < subst_tab(j).end_date) THEN
1927 	                                 substcount := substcount + 1;
1928 	                                 subst_tab(substcount) := subst_tab(j);
1929 	                                 subst_tab(substcount).start_date := subst_tab(i).end_date +1/1440 ;
1930 	                                 subst_tab(substcount).end_date := subst_tab(j).end_date;
1931 	                                 subst_tab(j).end_date := subst_tab(i).start_date - 1/1440 ;
1932 
1933 	                            END IF;
1934 	                            -- } 6
1935 	                        END IF;
1936 	                        -- } 5
1937 	                   END IF;
1938 	                   -- } 4
1939 	                END LOOP;
1940 	                -- } L3
1941 	            END IF;
1942 	            -- } 3
1943 	        END LOOP;
1944 	        -- } L2
1945 	      /* insert processed substitutes now */
1946 	        FOR k in 1..substcount
1947 	        LOOP
1948 	           formula_details_size := formula_details_size + 1 ;
1949 	           formula_detail_tab(formula_details_size) := subst_tab(k) ;
1950 	           formula_detail_tab(formula_details_size).x_formulaline_id := NULL;
1951 	        END LOOP;
1952 	        /*insert trailing records if there is no substitue which has a null end date*/
1953 	        FOR k in 1..substcount
1954 	        LOOP
1955 	        If subst_tab(k).end_date is null then
1956 	           enddatenull := TRUE;
1957 	        ELSIF subst_tab(k).end_date > NVL(orig_detail_tab(1).start_date,sysdate) THEN
1958 	           orig_detail_tab(1).start_date:= subst_tab(k).end_date + 1/1440 ;
1959 	        END IF;
1960 	     END LOOP;
1961 	     IF NOT(enddatenull) THEN
1962 	        formula_details_size := formula_details_size + 1 ;
1963 	        formula_detail_tab(formula_details_size) := orig_detail_tab(1) ;
1964 	        formula_detail_tab(formula_details_size).original_item_id := orig_detail_tab(1).opm_item_id;
1965 	        formula_detail_tab(formula_details_size).x_formulaline_id := NULL;
1966 	        formula_detail_tab(formula_details_size).end_date:=NULL;
1967 	     END IF;
1968 	  END IF; /* end of substitute record processing */
1969 	  -- } 2 substcount <> 0
1970 	     orig_detail_tab(1) := temp_detail_tab(1) ;
1971 		 prev_detail_tab(1) := temp_detail_tab(1) ;
1972 	        /* This is to insert original item */
1973 	     IF  nvl(temp_detail_tab(1).end_date,(SYSDATE +1)) > sysdate THEN
1974 	        formula_details_size := formula_details_size + 1 ;
1975 		    formula_detail_tab(formula_details_size) := temp_detail_tab (1) ;
1976 		    formula_detail_tab(formula_details_size).end_date := temp_detail_tab(1).end_date - 1/1440 ;
1977 	      END IF ;
1978 	        substcount := 0;
1979 	        orig_start_date:=orig_detail_tab(1).end_date;
1980 	   -- } IF of 1
1981 	   ELSE /* ELSE of original item - not an original item */
1982 	   -- { ELSE of 1
1983 	       IF substcount > 0 THEN /* from the second record onwards */
1984 	       /* comparing with prevoious record to check if there is any gap so that we insert
1985 	          the original item record in the gap. */
1986 	          IF ( temp_detail_tab(1).start_date > orig_start_date ) and NOT(nullenddatefound) THEN
1987 	         /* store the previous record' end date */
1988 	               substcount := substcount + 1 ;
1989 	               subst_tab(substcount) := orig_detail_tab(1) ;
1990 	               subst_tab(substcount).original_item_id := orig_detail_tab(1).opm_item_id;
1991 	               subst_tab(substcount).x_formulaline_id := NULL;
1992 	               subst_tab(substcount).start_date := orig_start_date;
1993 	               subst_tab(substcount).end_date := temp_detail_tab (1).start_date - 1/1440;
1994 	               subst_tab(substcount).preference:=99999;
1995 	           END IF;
1996 	       END IF;
1997 	       substcount := substcount + 1 ;
1998 	       subst_tab(substcount) := temp_detail_tab (1) ;
1999 	       IF (temp_detail_tab (1).end_date IS NULL) AND NOT (nullenddatefound)  THEN
2000 	          nullenddatefound := TRUE;
2001 	       ELSIF (temp_detail_tab(1).end_date > orig_start_date ) AND NOT (nullenddatefound) THEN
2002 	          orig_start_date := temp_detail_tab(1).end_date +1/1440;
2003 	       END IF;
2004 
2005 	   END IF;
2006 	   -- }  1
2007 	EXIT WHEN cur_formula_dtl%NOTFOUND;
2008 	END LOOP;
2009 	-- } L1
2010 CLOSE cur_formula_dtl;
2011 
2012 /* Bug: 5872693 Vpedarla 12-Mar-2007 END */
2013 
2014     time_stamp ;
2015     log_message('Formula detail size is = ' || to_char(formula_details_size)) ;
2016 
2017 -- =========== rtg offset data selection start ========================
2018    rtg_offset_cur_stmt := ' SELECT '||
2019 		' gro.plant_code, '||
2020 		' gro.fmeff_id, '||
2021 		' gro.formula_id, '||
2022 		' gro.routingstep_id, '||
2023 		' gro.start_offset, '||
2024 		' gro.end_offset, '||
2025 		' (rsm.formulaline_id *2 )+ 1'||
2026 		' from '||
2027 		' gmd_recipe_step_materials'||at_apps_link||' rsm, '||
2028 		' gmp_routing_offsets'||at_apps_link||' gro '||
2029 		' WHERE '||
2030 		' gro.recipe_id = rsm.recipe_id '||
2031 		' AND gro.routingstep_id = rsm.routingstep_id '||
2032 		' ORDER BY gro.formula_id,gro.plant_code, rsm.formulaline_id ' ;
2033 
2034     OPEN cur_rtg_offsets  FOR rtg_offset_cur_stmt ;
2035     LOOP
2036       FETCH cur_rtg_offsets INTO rstep_offsets(rtg_offsets_size);
2037 
2038       EXIT WHEN cur_rtg_offsets%NOTFOUND;
2039       rtg_offsets_size := rtg_offsets_size + 1;
2040     END LOOP;
2041     CLOSE cur_rtg_offsets;
2042 
2043     rtg_offsets_size := rtg_offsets_size -1 ;
2044     time_stamp ;
2045     log_message('Routing Offsets size is = ' || to_char(rtg_offsets_size)) ;
2046 
2047 -- =========== rtg offset data selection end ========================
2048 
2049     -- Validate formula for uom conversion, for planned items
2050     validate_formula ;
2051 
2052     routing_hdr_cursor :=
2053                      ' SELECT unique frh.routing_id, som.orgn_code, '
2054 /* NAMIT_CR 2 more zeros added for Linking Step Dependency to Routing Header */
2055                    ||'        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 '
2056                    ||' FROM sy_orgn_mst'||at_apps_link||' som, '
2057                    ||'      fm_rout_hdr'||at_apps_link||' frh, '
2058                    ||'      gmd_recipes_b'||at_apps_link||' grb, '
2059                    ||'      gmd_recipe_validity_rules'||at_apps_link||' ffe, '
2060                    ||'      gmd_status_b'||at_apps_link||' gs '
2061                    ||' WHERE grb.recipe_id = ffe.recipe_id '
2062                    ||'   AND ffe.validity_rule_status = gs.status_code '
2063                    ||'   AND gs.status_type IN (' ||'''700'''|| ',' ||''' 900'''|| ') '
2064                    ||'   AND gs.delete_mark = 0 '
2065                    ||'   AND nvl(ffe.end_date,(SYSDATE + 1)) > SYSDATE '
2066                    ||'   AND frh.routing_id = grb.routing_id '
2067                    ||'   AND som.delete_mark = 0 '
2068                    ||'   AND som.resource_whse_code is NOT NULL '
2069                    ||'   AND nvl(ffe.orgn_code, som.orgn_code) = som.orgn_code' ;
2070             IF l_in_str_org  IS NOT NULL THEN
2071                routing_hdr_cursor := routing_hdr_cursor
2072                    ||'   AND EXISTS ( SELECT 1 FROM gmp_item_aps'||at_apps_link||' gia '
2073                    ||'   WHERE gia.whse_code = som.resource_whse_code )' ;
2074             END IF;
2075 
2076          routing_hdr_cursor := routing_hdr_cursor
2077                    ||'   AND ffe.delete_mark = 0 '
2078                    ||'   AND frh.delete_mark = 0 '
2079                    ||'   AND frh.inactive_ind = 0 '
2080                    ||' ORDER BY frh.routing_id, som.orgn_code ' ;
2081 
2082     OPEN cur_routing_hdr FOR routing_hdr_cursor;
2083     LOOP
2084       FETCH cur_routing_hdr INTO rtg_org_hdr_tab(routing_headers_size);
2085       EXIT WHEN cur_routing_hdr%NOTFOUND;
2086       routing_headers_size := routing_headers_size + 1;
2087     END LOOP;
2088     CLOSE cur_routing_hdr;
2089     routing_headers_size := routing_headers_size -1 ;
2090     time_stamp ;
2091     log_message('Routing Header size is = ' || to_char(routing_headers_size)) ;
2092     /* 2582849 minimum_transfer_qty selected */
2093 
2094     /*  Select Seq Dep rows SGIDUGU
2095        Construct PL/Sql table used in bsearch
2096       Select Setup id rows for oprn_id <> -1 SGIDUGU */
2097    setup_id_cursor :=
2098           ' SELECT oprn_id, '
2099               ||'  category_id,   '
2100               ||'  seq_dep_id   '
2101               ||'  FROM  gmp_sequence_types'||at_apps_link||' gst  '
2102               ||'  WHERE oprn_id <> -1  '
2103               ||'  ORDER BY oprn_id,category_id  ' ;
2104 --
2105      setup_size := 1;
2106      OPEN setup_id_dtl FOR setup_id_cursor;
2107      LOOP
2108         FETCH setup_id_dtl INTO setupid_tab(setup_size);
2109         EXIT WHEN setup_id_dtl%NOTFOUND;
2110         setup_size := setup_size + 1;
2111      END LOOP;
2112      CLOSE setup_id_dtl;
2113      setup_size := setup_size - 1;
2114      time_stamp ;
2115      log_message('Setup id size is = ' || to_char(setup_size)) ;
2116 --
2117     /*  End of Select Seq Dep rows SGIDUGU */
2118 --
2119     routing_dtl_cursor :=
2120           ' SELECT frd.routing_id, '
2121               ||'  crd.orgn_code, '
2122               ||'  frd.routingstep_no,  '
2123               ||'  NVL(goa.sequence_dependent_ind,0), '
2124               /* This will ensure that ordering will always have primary first */
2125               ||'  DECODE(gor.prim_rsrc_ind, 1,1,2,2,0,3), '
2126               ||'  gor.resources, '
2127               ||'  gor.prim_rsrc_ind, '
2128               ||'  decode(crd.capacity_constraint,1,1,2), '
2129               ||'  crd.min_capacity, '
2130               ||'  crd.max_capacity, '
2131               ||'  crd.schedule_ind, '
2132               ||'  frd.routingstep_id, '
2133               ||'  ((frd.routingstep_id * 2) + 1) x_routingstep_id,  '
2134               ||'  frd.step_qty, '
2135               ||'  NVL(frd.minimum_transfer_qty,0) minimum_transfer_qty, '
2136               ||'  fom.oprn_desc,  '
2137               ||'  fom.oprn_id,  '     /* SGIDUGU Seq Dep */
2138               ||'  fom.oprn_no,  '
2139               ||'  sou2.uom_code,'
2140               ||'  goa.activity, '
2141               ||'  goa.oprn_line_id, '
2142               ||'  gor.resource_count, '
2143               ||'  gor.resource_usage, '
2144               ||'  gor.usage_um, '
2145               ||'  gor.scale_type,'
2146               ||'  goa.offset_interval, '
2147               ||'  crd.resource_id, '
2148               ||'  ((crd.resource_id * 2) + 1) x_resource_id, '
2149 --              ||'  -- DECODE(gor.scale_type,0,2,1,1,2,1) , ' /* B2967464 */
2150               ||'  DECODE(gor.scale_type,0,2,1,1,2,3) , ' /* B2967464 */
2151               ||'  sou.uom_code, '
2152               ||'  goa.activity_factor, '
2153               ||'  gor.process_qty, '
2154 --              ||'  NVL(goa.sequence_dependent_ind,0), '
2155               ||'  NVL(goa.material_ind,0), '
2156               ||'  1 , '
2157               || '  SUM(NVL(goa.material_ind,0))  OVER (PARTITION BY '
2158               || '  frd.routing_id, crd.orgn_code, frd.routingstep_no) mat_found, '
2159               || '  1, ' /* flag for including rows */
2160               || '  decode(goa.break_ind,NULL,2,0,2,1,1) brk_ind'
2161               || ' ,-1, -1, -1, -1, -1, -1, '
2162               ||' (SUM(DECODE(NVL(goa.sequence_dependent_ind,0),1,1,0)) OVER '
2163               ||' (PARTITION BY '
2164               ||' frd.routing_id, crd.orgn_code)) is_sds_rout,'
2165               ||' DECODE(NVL(goa.sequence_dependent_ind,0),1,DECODE(gor.prim_rsrc_ind,1,1,0),0) is_unique, '
2166               ||' DECODE(NVL(goa.sequence_dependent_ind,0),1,0,DECODE(gor.prim_rsrc_ind,1,1,0)) is_nonunique, '
2167               ||' NULL setup_id '
2168               ||' FROM  sy_uoms_mst'||at_apps_link||' sou, '
2169               ||'       sy_uoms_mst'||at_apps_link||' sou2, '
2170               ||'       cr_rsrc_dtl'||at_apps_link||' crd, '
2171               ||'       fm_rout_dtl'||at_apps_link||' frd, '
2172               ||'       gmd_operations'||at_apps_link||' fom, '
2173               ||'       gmd_operation_activities'||at_apps_link||' goa, '
2174               ||'       gmd_operation_resources'||at_apps_link||' gor '
2175               ||' WHERE frd.oprn_id = fom.oprn_id '
2176               ||'   AND fom.oprn_id = goa.oprn_id '
2177               ||'   AND goa.oprn_line_id = gor.oprn_line_id '
2178               ||'   AND crd.resources = gor.resources '
2179               ||'   AND sou.um_code = gor.usage_um '
2180               ||'   AND sou2.um_code = fom.process_qty_um '
2181               ||'   AND sou.delete_mark = 0 '
2182               ||'   AND fom.delete_mark = 0 '
2183               ||'   AND goa.activity_factor > 0 '
2184               ||'   AND sou.um_type = :gmp_uom_class '
2185               ||' ORDER BY  '
2186               ||'         1, 2, 3, 4, 5, 6 ';
2187 
2188     OPEN cur_routing_dtl FOR routing_dtl_cursor USING g_gmp_uom_class;
2189     LOOP
2190       FETCH cur_routing_dtl INTO rtg_org_dtl_tab(rtg_org_dtl_size);
2191       EXIT WHEN cur_routing_dtl%NOTFOUND;
2192       /*B2870041 The activities have to be properly marked for the schedule
2193          flag. This only needs to be done once for the route. The index is
2194          copied for ease of use. */
2195 
2196       ri := rtg_org_dtl_size;
2197 
2198       /* since the select includes orgn_code we need to track when the route
2199          org or step changes. If any of them change this means the step has
2200          changed. when there is a new step the process needs to reset. The
2201          new values are saved and the first row of the step is saved to be
2202          used to loop later. found will be used to indicate that an activity
2203          has the material ind set to 1 */
2204 
2205       IF old_route <> rtg_org_dtl_tab(ri).routing_id OR
2206          old_orgn <> rtg_org_dtl_tab(ri).orgn_code OR
2207          old_step <> rtg_org_dtl_tab(ri).routingstep_no THEN
2208 
2209         found := 0;
2210         /* NAMIT_OC */
2211         found_chrg_rsrc := 0;
2212         chrg_activity   := NULL;
2213         first_step_row := ri;
2214 
2215         old_route := rtg_org_dtl_tab(ri).routing_id;
2216         old_orgn := rtg_org_dtl_tab(ri).orgn_code;
2217         old_step := rtg_org_dtl_tab(ri).routingstep_no;
2218 
2219       END IF;
2220       /* if we found an activity with the material ind = 1 and one has not
2221          found yet we need to go back and set all the activities before this
2222          one in the step as PRIOR. the rows are looped though using the first
2223          step row index to the row before this current row. All rows with
2224          the material ind = 1 will have the schedule flag set to 1 as part
2225          of the query by default. If no activity has a material ind = 1
2226          all of the activities will be considered as schedule_flag=1
2227          by default in the query */
2228 
2229       IF rtg_org_dtl_tab(ri).material_ind = 1 AND found = 0 THEN
2230         found := 1;
2231         IF first_step_row < ri THEN
2232           end_index := ri -1;
2233           FOR j IN first_step_row..end_index
2234           LOOP
2235             rtg_org_dtl_tab(j).schedule_flag := 3;
2236           END LOOP;
2237         END IF;
2238 
2239       /* if the material ind is 0 but another activity was found with 1
2240          then this row will be considered as NEXT. */
2241       ELSIF rtg_org_dtl_tab(ri).material_ind = 0 AND found = 1 THEN
2242         rtg_org_dtl_tab(ri).schedule_flag := 4;
2243       END IF;
2244 
2245         /* NAMIT_OC */
2246 
2247         /* If an operation has been found to have more than one activity with chargeable resources the first
2248         activity will be used and all other activities will have the scale type changed to be linear. If any
2249         activity found with chargeable resource, other activities in the operation having resource with
2250         scale_type "By Charge", will be changed to scale_type "Proportional" */
2251 
2252       IF rtg_org_dtl_tab(ri).mat_found = 0 OR rtg_org_dtl_tab(ri).material_ind = 1
2253       THEN
2254 
2255         IF rtg_org_dtl_tab(ri).rtg_scale_type = 3
2256         AND rtg_org_dtl_tab(ri).capacity_constraint = 1
2257         AND found_chrg_rsrc = 0 THEN
2258           found_chrg_rsrc := 1;
2259           chrg_activity := rtg_org_dtl_tab(ri).activity;
2260         /* if the rtg_scale_type is 3 but another activity was found with 3
2261            then this row will be assigned scale_type = 1. */
2262         ELSIF rtg_org_dtl_tab(ri).rtg_scale_type = 3
2263         AND rtg_org_dtl_tab(ri).capacity_constraint = 1
2264         AND found_chrg_rsrc = 1
2265         AND chrg_activity <> rtg_org_dtl_tab(ri).activity THEN
2266           rtg_org_dtl_tab(ri).rtg_scale_type := 1;
2267           rtg_org_dtl_tab(ri).scale_type := 1;
2268         END IF;
2269       END IF;
2270 
2271       rtg_org_dtl_size := rtg_org_dtl_size + 1;
2272 
2273     END LOOP;
2274     CLOSE cur_routing_dtl;
2275     rtg_org_dtl_size := rtg_org_dtl_size -1 ;
2276     time_stamp ;
2277     log_message('Routing Org detail size is = ' || to_char(rtg_org_dtl_size)) ;
2278 
2279      /* New GMD Changes - B1830940 */
2280     validation_statement := 'SELECT '
2281               ||'  frd.routing_id, '
2282               ||'  frd.routingstep_no, '
2283 /* NAMIT_RD */
2284               ||'  NVL(goa.sequence_dependent_ind,0), '
2285               ||'  DECODE(gor.prim_rsrc_ind, 1,1,2,2,0,3), ' /* This will ensure that ordering will
2286                                                                 always have primary firsr*/
2287               ||'  gor.resources, '
2288               ||'  frd.routingstep_id, '
2289               ||'  fom.oprn_no, '
2290               ||'  goa.oprn_line_id, '
2291               ||'  goa.activity, '
2292               ||'  gor.prim_rsrc_ind, '
2293 --              ||'  gor.resources, '
2294 --              ||'  decode(gor.prim_rsrc_ind,1,1,2) prim_rsrc_ind, '
2295 --              ||'  NVL(goa.sequence_dependent_ind,0), '
2296               ||'  goa.offset_interval, '
2297 /* NAMIT_RD */
2298               ||'  sou.uom_code '
2299               ||' FROM  fm_rout_dtl'||at_apps_link||' frd, '
2300               ||'       gmd_operations'||at_apps_link||' fom, '
2301               ||'       gmd_operation_activities'||at_apps_link||' goa, '
2302               ||'       gmd_operation_resources'||at_apps_link||' gor, '
2303 /* NAMIT_RD */
2304               ||'       sy_uoms_mst'||at_apps_link||' sou '
2305               ||' WHERE frd.oprn_id = fom.oprn_id '
2306               ||'   AND fom.oprn_id = goa.oprn_id '
2307 /* NAMIT_RD */
2308 --              ||'   AND gor.prim_rsrc_ind in (1,2) '
2309               ||'   AND fom.delete_mark = 0'
2310               ||'   AND goa.oprn_line_id = gor.oprn_line_id '
2311 /* NAMIT_RD */
2312               ||'   AND sou.um_code = gor.usage_um '
2313               ||'   AND sou.delete_mark = 0 '
2314               ||'   AND sou.um_type = :gmp_uom_class '
2315 /* NAMIT_RD */
2316               ||' ORDER BY 1, 2, 3, 4, 5 ' ;
2317 /*              ||' ORDER BY frd.routing_id, '
2318               ||'          frd.routingstep_no, '
2319               ||'          fom.oprn_no, '
2320               ||'          NVL(goa.sequence_dependent_ind,0) DESC, '
2321               ||'          goa.offset_interval,'
2322               ||'          goa.activity,'
2323               ||'          goa.oprn_line_id,'
2324               ||'          decode(gor.prim_rsrc_ind,1,1,2), '
2325               ||'          gor.resources ' ;*/
2326 
2327     OPEN cur_routing_dtl FOR validation_statement USING g_gmp_uom_class;
2328     LOOP
2329       FETCH cur_routing_dtl INTO rtg_gen_dtl_tab(rtg_gen_dtl_size);
2330       EXIT WHEN cur_routing_dtl%NOTFOUND;
2331       rtg_gen_dtl_size := rtg_gen_dtl_size + 1;
2332     END LOOP;
2333     CLOSE cur_routing_dtl;
2334     rtg_gen_dtl_size := rtg_gen_dtl_size -1 ;
2335     time_stamp ;
2336     log_message('Generic Routing size is = ' || to_char(rtg_gen_dtl_size)) ;
2337 
2338     recipe_orgn_statement := ' SELECT '
2339                ||'  grb.routing_id, gc.orgn_code, '
2340                ||'  gc.routingstep_id, gc.oprn_line_id, gc.recipe_id, '
2341                ||'  gc.activity_factor, '
2342                ||'  gc.resources, gc.resource_usage, gc.process_qty, '
2343                ||'  gc.min_capacity, gc.max_capacity  '
2344                ||' FROM gmd_recipes'||at_apps_link||' grb, '
2345                ||'      gmd_status_b'||at_apps_link||' gs, ' /* B5114783*/
2346                ||' ( '
2347                ||' SELECT '
2348                ||'  gor.recipe_id, '
2349                ||'  gor.orgn_code, '
2350                ||'  gor.oprn_line_id, '
2351                ||'  gor.routingstep_id, '
2352                ||'  goa.activity_factor, '
2353                ||'  gor.resources, '
2354                ||'  gor.resource_usage , '
2355                ||'  gor.process_qty,  '
2356                ||'  gor.min_capacity, '
2357                ||'  gor.max_capacity  '
2358                ||' FROM  gmd_recipe_orgn_activities'||at_apps_link||' goa, '
2359                ||'       gmd_recipe_orgn_resources'||at_apps_link||' gor '
2360                ||' WHERE gor.recipe_id = goa.recipe_id '
2361                ||'   AND gor.orgn_code = goa.orgn_code '
2362                ||'   AND gor.oprn_line_id = goa.oprn_line_id '
2363                ||'   AND gor.routingstep_id = goa.routingstep_id '
2364                ||' UNION ALL '
2365                ||' SELECT goa.recipe_id, '
2366                ||'  goa.orgn_code, '
2367                ||'  goa.oprn_line_id, '
2368                ||'  goa.routingstep_id, '
2369                ||'  goa.activity_factor,  '
2370                ||'  NULL resources,  '
2371                ||'  -1 resource_usage, '
2372                ||'  -1 process_qty, '
2373                ||'  -1 min_capacity, '
2374                ||'  -1 max_capacity '
2375 
2376                ||' FROM  gmd_recipe_orgn_activities'||at_apps_link||' goa '
2377                ||' WHERE NOT EXISTS( SELECT 1 '
2378                ||'       FROM gmd_recipe_orgn_resources'||at_apps_link||' gor '
2379                ||'       WHERE gor.recipe_id = goa.recipe_id '
2380                ||'         AND gor.orgn_code = goa.orgn_code '
2381                ||'         AND gor.oprn_line_id = goa.oprn_line_id '
2382                ||'         AND gor.routingstep_id = goa.routingstep_id ) '
2383                ||' UNION ALL '
2384                ||' SELECT gor.recipe_id, '
2385                ||'  gor.orgn_code, '
2386                ||'  gor.oprn_line_id, '
2387                ||'  gor.routingstep_id, '
2388                ||'  -1 activity_factor, '
2389                ||'  gor.resources, '
2390                ||'  gor.resource_usage , '
2391                ||'  gor.process_qty,  '
2392                ||'  gor.min_capacity, '
2393                ||'  gor.max_capacity '
2394                ||' FROM  gmd_recipe_orgn_resources'||at_apps_link||' gor  '
2395                ||' WHERE NOT EXISTS( SELECT 1 '
2396                ||'       FROM gmd_recipe_orgn_activities'||at_apps_link||' goa'
2397                ||'       WHERE goa.recipe_id = gor.recipe_id '
2398                ||'         AND goa.orgn_code = gor.orgn_code '
2399                ||'         AND goa.oprn_line_id = gor.oprn_line_id '
2400                ||'         AND goa.routingstep_id = gor.routingstep_id ) '
2401                ||' ) gc '
2402                ||' WHERE grb.recipe_id = gc.recipe_id '
2403                ||'   AND grb.delete_mark = 0 '
2404             /* B5114783 start */
2405                ||'   AND grb.recipe_status =  gs.status_code '
2406                ||'   AND gs.status_type IN (' ||'''700'''|| ',' ||''' 900'''|| ') '
2407                ||'   AND gs.delete_mark = 0 '
2408             /* B5114783 End */
2409                ||' ORDER BY 1,2,3,4,5 ' ;
2410 
2411     OPEN c_recipe_orgn FOR recipe_orgn_statement;
2412     LOOP
2413       FETCH c_recipe_orgn INTO rcp_orgn_override(recipe_orgn_over_size);
2414       EXIT WHEN c_recipe_orgn%NOTFOUND;
2415       recipe_orgn_over_size := recipe_orgn_over_size + 1;
2416     END LOOP;
2417     CLOSE c_recipe_orgn;
2418     recipe_orgn_over_size := recipe_orgn_over_size -1 ;
2419     time_stamp ;
2420     log_message('recipe_orgn_over_size is= '|| to_char(recipe_orgn_over_size));
2421 
2422    recipe_statement :=
2423               ' SELECT grb.routing_id, grs.routingstep_id, grs.recipe_id, '
2424              ||'        grs.step_qty '
2425              ||' FROM gmd_recipes'||at_apps_link||' grb, '
2426              ||'      gmd_status_b'||at_apps_link||' gs, ' /* B5114783*/
2427              ||'      gmd_recipe_routing_steps'||at_apps_link||' grs '
2428              ||' WHERE grb.recipe_id = grs.recipe_id '
2429              ||'   AND grb.delete_mark = 0 '
2430           /* B5114783 start */
2431              ||'   AND grb.recipe_status =  gs.status_code '
2432              ||'   AND gs.status_type IN (' ||'''700'''|| ',' ||''' 900'''|| ') '
2433              ||'   AND gs.delete_mark = 0 '
2434           /* B5114783 End */
2435              ||' ORDER BY 1,2,3 ' ;
2436 
2437     OPEN c_recipe_override FOR recipe_statement ;
2438     LOOP
2439       FETCH c_recipe_override INTO recipe_override(recipe_override_size);
2440       EXIT WHEN c_recipe_override%NOTFOUND;
2441       recipe_override_size := recipe_override_size + 1;
2442     END LOOP;
2443     CLOSE c_recipe_override;
2444     recipe_override_size := recipe_override_size -1 ;
2445     time_stamp ;
2446     log_message('recipe Override size is = '||to_char(recipe_override_size)) ;
2447 
2448      /* Alternate Resource selection   */
2449      /* B5688153, Rajesh Patangya prod spec alt*/
2450         statement_alt_resource :=
2451                      ' SELECT pcrd.resource_id, acrd.resource_id, '
2452                    ||' acrd.min_capacity, acrd.max_capacity, '
2453                    ||' cam.runtime_factor, '
2454 /*prod spec alt*/  ||' nvl(cam.preference,-1), nvl(prod.item_id,-1)   '
2455                    ||' FROM  cr_rsrc_dtl'||at_apps_link||' acrd, '
2456                    ||'       cr_rsrc_dtl'||at_apps_link||' pcrd, '
2457                    ||'       cr_ares_mst'||at_apps_link||' cam, '
2458 		   ||'       gmp_altresource_products'||at_apps_link||' prod'
2459                    ||' WHERE cam.alternate_resource = acrd.resources '
2460                    ||'   AND cam.primary_resource = pcrd.resources '
2461                    ||'   AND acrd.orgn_code = pcrd.orgn_code '
2462                    ||'   AND cam.primary_resource = prod.primary_resource(+) '
2463                    ||'   AND cam.alternate_resource = prod.alternate_resource(+)  '
2464                    ||'   AND acrd.delete_mark = 0  '
2465                    ||' ORDER BY pcrd.resource_id, '
2466                    ||'   DECODE(cam.preference,NULL,cam.runtime_factor,cam.preference),'
2467                    ||'   prod.item_id ' ;
2468 
2469     alt_rsrc_size := 1;
2470     OPEN cur_alt_resource FOR statement_alt_resource ;
2471     LOOP
2472       FETCH cur_alt_resource INTO rtg_alt_rsrc_tab(alt_rsrc_size);
2473       EXIT WHEN cur_alt_resource%NOTFOUND;
2474       alt_rsrc_size := alt_rsrc_size + 1;
2475     END LOOP;
2476     CLOSE cur_alt_resource;
2477     alt_rsrc_size := alt_rsrc_size -1 ;
2478     time_stamp ;
2479     log_message('Alternate Routing size is = ' || to_char(alt_rsrc_size)) ;
2480 
2481 /* NAMIT_CR Get Step Dependency data */
2482 
2483    opr_stpdep_cursor := '    SELECT frdp.routing_id, '
2484               ||'          ((frd2.routingstep_id * 2) + 1) x_dep_routingstep_id, '
2485               ||'          ((frd1.routingstep_id * 2) + 1) x_routingstep_id, '
2486               ||'          decode(frdp.dep_type,0,1,2) dependency_type, '
2487               ||'          frdp.standard_delay, '
2488               ||'          frdp.max_delay, '
2489               ||'          frdp.transfer_pct, '
2490               ||'          frdp.dep_routingstep_no, '
2491               ||'          frdp.routingstep_no, '
2492               ||'          decode(nvl(frdp.chargeable_ind, 0),0,2,1,1) '
2493               ||'      FROM '
2494               ||'          fm_rout_dtl'||at_apps_link||' frd1, '
2495               ||'          fm_rout_dtl'||at_apps_link||' frd2, '
2496               ||'          fm_rout_dep'||at_apps_link||' frdp '
2497               ||'      WHERE '
2498               ||'          frd1.routing_id = frdp.routing_id '
2499               ||'          AND frd1.routingstep_no = frdp.routingstep_no '
2500               ||'          AND frd2.routing_id = frdp.routing_id '
2501               ||'          AND frd2.routingstep_no = frdp.dep_routingstep_no '
2502               ||'      ORDER BY 1,3,2 ' ;
2503 
2504     OPEN cur_opr_stpdep FOR opr_stpdep_cursor ;
2505     LOOP
2506       FETCH cur_opr_stpdep INTO gmp_opr_stpdep_tbl(opr_stpdep_size);
2507       EXIT WHEN cur_opr_stpdep%NOTFOUND;
2508       opr_stpdep_size := opr_stpdep_size + 1;
2509     END LOOP;
2510     CLOSE cur_opr_stpdep;
2511     opr_stpdep_size := opr_stpdep_size -1 ;
2512     time_stamp ;
2513     log_message('Operation Step Dependency size is = ' || to_char(opr_stpdep_size)) ;
2514 
2515     /* ------------------------------------------------------- */
2516     /* PROCESSING STARTS AFTER SELECTION OF THE DATA IN MEMORY */
2517     /* ------------------------------------------------------- */
2518 
2519     -- Link the routing header and detail
2520     link_routing ;
2521 /* Now spool the routing Header data for debugging */
2522 /*
2523   log_message ('Routing is ');
2524   log_message ('RTG_ID Plnt Valid GStart GEnd OStart OEnd StStart StEND UsgSt
2525   UsgEnd StpDepSt StpDepEnd  ');
2526   For spl_cnt in 1..rtg_org_hdr_tab.COUNT
2527   LOOP
2528      log_message ( rtg_org_hdr_tab(spl_cnt).routing_id ||'*'||
2529      rtg_org_hdr_tab(spl_cnt).plant_code         ||'*'||
2530      rtg_org_hdr_tab(spl_cnt).valid_flag         ||'*'||
2531      rtg_org_hdr_tab(spl_cnt).generic_start_loc  ||'*'||
2532      rtg_org_hdr_tab(spl_cnt).generic_end_loc    ||'*'||
2533      rtg_org_hdr_tab(spl_cnt).orgn_start_loc     ||'*'||
2534      rtg_org_hdr_tab(spl_cnt).orgn_end_loc       ||'*'||
2535      rtg_org_hdr_tab(spl_cnt).step_start_loc     ||'*'||
2536      rtg_org_hdr_tab(spl_cnt).step_end_loc       ||'*'||
2537      rtg_org_hdr_tab(spl_cnt).usage_start_loc    ||'*'||
2538      rtg_org_hdr_tab(spl_cnt).usage_end_loc      ||'*'||
2539      rtg_org_hdr_tab(spl_cnt).stpdep_start_loc   ||'*'||
2540      rtg_org_hdr_tab(spl_cnt).stpdep_end_loc );
2541   END LOOP ;
2542   */
2543 
2544     -- Link the routing header and detail overrides
2545     link_override_routing ;
2546 
2547     /*  New GMD Changes B1830940 */
2548     /*  B2800311, APS SHOULD SEE INGREDIENTS RELEASED AS AUTO-BY-STEP */
2549     /* B3054460 OPM/APS TO CATER FOR CHANGE TO TIME PHASED PLANNING OF
2550        MANUAL CONSUMPTION TYPE
2551     */
2552 
2553     mat_assoc_cursor  :=
2554                 ' SELECT  fmd.formula_id, frm.recipe_id, '
2555               ||'  DECODE(fmd.line_type, 1,1,2,2,-1,3), fmd.line_no, '
2556               ||'  ((frm.formulaline_id * 2) + 1) x_formulaline_id, '
2557               ||'  ((frm.routingstep_id * 2) + 1) x_routingstep_id, '
2558 /* NAMIT_MTQ */
2559               ||'   fmd.item_id, frd.routingstep_no, '
2560               ||'   gia.aps_item_id, '
2561               || '   DECODE(fmd.item_um, gia.item_um, 1, '
2562               || '     GMICUOM.uom_conversion'||at_apps_link
2563               || '       (fmd.item_id, 0, 1, fmd.item_um, gia.item_um, 0)) uom_conv_factor, '
2564               /*Sowmya - As per Latest FDD changes - Changes as per Matt's review comments-
2565               Fetch the conversion factor for a unit item, needed for converting the MTQ.
2566               MTQ value to be passed as promary UOM.*/
2567               ||'   decode(fmd.line_type, 1, frm.minimum_transfer_qty, null) minimum_transfer_qty, '
2568               ||'   decode(fmd.line_type, 1, frm.minimum_delay, null) minimum_delay, '
2569               ||'   decode(fmd.line_type, 1, frm.maximum_delay, null) maximum_delay '
2570              ||' FROM gmd_recipes'||at_apps_link||' r ,' /* added for asqc flg*/
2571 	      ||' gmd_recipe_step_materials'||at_apps_link||' frm, '
2572               ||'       fm_matl_dtl'||at_apps_link||' fmd, '
2573 /* NAMIT_MTQ */
2574               ||'       fm_rout_dtl'||at_apps_link||' frd,  '
2575               ||'      ( SELECT item_id, aps_item_id, item_um, uom_code '
2576               ||'        FROM (SELECT item_id, aps_item_id, item_um, uom_code,'
2577               ||'  		ROW_NUMBER() OVER ( PARTITION BY item_id '
2578               ||'      		ORDER BY item_id,aps_item_id ) AS first_row '
2579               ||'              	FROM gmp_item_aps '||at_apps_link
2580               ||'       	) '
2581               ||'        WHERE first_row = 1 '
2582               ||'       ) gia ' /*Sowmya - Added*/
2583               ||' WHERE fmd.formulaline_id = frm.formulaline_id '
2584               ||'   AND frm.recipe_id = r.recipe_id '  /* B3054460 */
2585               ||'   AND (fmd.release_type in (1,2,3) OR '  /* B3054460 */
2586               ||' NVL(r.calculate_step_quantity,0) = 1 ) '  /* xfer for ASQC */
2587 /* NAMIT_MTQ */
2588               ||'   AND frd.routingstep_id = frm.routingstep_id '
2589               ||'   AND gia.item_id = fmd.item_id '
2590 /* B3970993 nsinghi. Changed order by clause from 1,2,3,4,5 to 1,2,3,6,7 */
2591               ||' ORDER BY 1,2,3,6,7 ';
2592 
2593     OPEN cur_mat_assoc FOR mat_assoc_cursor ;
2594     LOOP
2595       FETCH cur_mat_assoc INTO mat_assoc_tab(material_assocs_size);
2596       EXIT WHEN cur_mat_assoc%NOTFOUND;
2597       material_assocs_size := material_assocs_size + 1;
2598     END LOOP;
2599     CLOSE cur_mat_assoc;
2600     material_assocs_size := material_assocs_size -1 ;
2601     time_stamp ;
2602     log_message('Material assoc size is = ' || to_char(material_assocs_size)) ;
2603 
2604  -- The cursor for effectivity opened and then the details processed
2605  OPEN c_formula_effectivity FOR effectivity_cursor;
2606 
2607   LOOP
2608   FETCH c_formula_effectivity INTO effectivity;
2609   EXIT WHEN c_formula_effectivity%NOTFOUND;
2610    IF ((effectivity.formula_id <> old_formula_id) OR
2611        (effectivity.plant_code <> old_plant_code) OR
2612        (effectivity.organization_id <> old_organization_id) OR
2613        (effectivity.fmeff_id <> old_fmeff_id)
2614       )  THEN   /* Old values */
2615 
2616     valid := check_formula(effectivity.plant_code,
2617                   effectivity.organization_id, effectivity.formula_id);
2618     /* routing check for effectivity */
2619     IF (valid) AND effectivity.routing_id IS NOT NULL THEN
2620         /* Locate_org_routing through Bsearch */
2621          valid := find_routing_header (effectivity.routing_id,
2622                                        effectivity.plant_code);
2623 
2624        IF (valid) AND effectivity.rtg_hdr_location > 0 AND
2625                       effectivity.routing_qty >= 0 THEN
2626 
2627            g_setup_id  := NULL;
2628            sd_index    := 0 ;
2629            validate_routing( effectivity.routing_id,
2630                              effectivity.plant_code,
2631                              effectivity.rtg_hdr_location,
2632                              routing_valid);
2633 
2634             IF (routing_valid) THEN /* Valid routing  */
2635                   valid := TRUE ;
2636              ELSE
2637                     valid := FALSE ;
2638              END IF;  /* Valid routing  */
2639 
2640        END IF ;   /* routing header location */
2641 
2642        /*B2870041 this logic will get the total output qty in the routing uom
2643           if the formula or route fails validation the effectivity is skipped*/
2644        IF (valid) THEN
2645 
2646          /* if the total output was already calculated for this formula in
2647             the routing um there is no need to do it again */
2648          IF formula_header_tab(g_fm_hdr_loc).total_um <>
2649               effectivity.routing_um  OR
2650             formula_header_tab(g_fm_hdr_loc).total_um IS NULL THEN
2651 
2652            /* if the factor was not calculated then the uom conversion failed
2653               and if it failed the effectivity can not be used */
2654            IF effectivity.prod_factor <= 0 THEN
2655              valid := FALSE;
2656            ELSE
2657              /* reset the total ouput accumulator and loop through all of the
2658                 material details to find all products and byproducts */
2659              temp_total_qty := 0;
2660 
2661              FOR j IN g_fm_dtl_start_loc..g_fm_dtl_end_loc
2662              LOOP
2663 
2664                /* if the line is either a product or byproduct then we need
2665                   to process it */
2666                IF formula_detail_tab(j).line_type > 0 THEN
2667 
2668                  /* if the item is the same as the item in the effectivity
2669                     we have the factor to get the item from base uom to the
2670                     route uom */
2671                  IF (formula_detail_tab(j).opm_item_id = effectivity.item_id)
2672                  THEN
2673                    temp_total_qty := temp_total_qty +
2674                      (effectivity.prod_factor *
2675                       formula_detail_tab(j).primary_qty);
2676                  /* if the item is different but the item base uom is the
2677                     same as the route the primary_qty will be used */
2678                  ELSIF
2679                    formula_detail_tab(j).opm_item_id <> effectivity.item_id AND
2680                    formula_detail_tab(j).primary_um = effectivity.routing_um
2681                  THEN
2682                    temp_total_qty := temp_total_qty +
2683                       formula_detail_tab(j).primary_qty;
2684                  /* if the item is different but the item base uom is the
2685                     same as the route the primary_qty will be used */
2686                  ELSIF
2687                    formula_detail_tab(j).opm_item_id <> effectivity.item_id AND
2688                    formula_detail_tab(j).orig_um = effectivity.routing_um
2689                  THEN
2690                    temp_total_qty := temp_total_qty +
2691                       formula_detail_tab(j).formula_qty;
2692                  /* no uom can be matched or the item is not the same as the
2693                     product thus a uom conversion will need to be done. If the
2694                     qty is 0 there is no need to do the conversion */
2695                  ELSIF formula_detail_tab(j).formula_qty > 0 THEN
2696                    uom_conv_cursor :=
2697                        'SELECT '
2698                      ||'  GMICUOM.uom_conversion'||at_apps_link
2699                      ||'  (:pitem, 0, :pqty, :pfrom_um, :pto_um, 0) '
2700                      ||'FROM dual';
2701                    v_matl_qty := -1;
2702                    OPEN c_uom_conv FOR uom_conv_cursor USING
2703                      formula_detail_tab(j).opm_item_id,
2704                      formula_detail_tab(j).primary_qty,
2705                      formula_detail_tab(j).primary_um,
2706                      effectivity.routing_um;
2707 
2708                    FETCH c_uom_conv INTO v_matl_qty;
2709                    CLOSE c_uom_conv;
2710 
2711                    /* as long as the qty is >0 then the uom conversion was
2712                       successful. If negative then it failed so reject the
2713                       effectivity and stop the current loop */
2714                    IF v_matl_qty > 0 THEN
2715                      temp_total_qty := temp_total_qty + v_matl_qty;
2716                    ELSE
2717                      valid := FALSE;
2718                      EXIT;
2719                    END IF;
2720                  END IF;
2721                END IF;
2722              END LOOP;
2723              /* if there was no failure and the qty is >0 save the values in
2724                 the formula header */
2725              IF (valid) AND temp_total_qty > 0 THEN
2726                formula_header_tab(g_fm_hdr_loc).total_output :=
2727                  temp_total_qty;
2728                formula_header_tab(g_fm_hdr_loc).total_um :=
2729                  effectivity.routing_um;
2730              END IF;
2731            END IF;
2732          END IF;
2733        END IF;
2734 
2735 
2736     END IF;   /* routing check for effectivity */
2737 
2738     IF valid THEN
2739 
2740       g_curr_rstep_loc := find_routing_offsets(effectivity.formula_id,
2741                                effectivity.plant_code);
2742 
2743       export_effectivities (valid);
2744 
2745     END IF ;
2746 
2747    END IF ;   /* Old Values */
2748 
2749     old_formula_id      := effectivity.formula_id ;
2750     old_organization_id := effectivity.organization_id ;
2751     old_fmeff_id        := effectivity.fmeff_id ;
2752     old_plant_code      := effectivity.plant_code ;
2753     valid               := FALSE ;
2754     routing_valid       := FALSE ;
2755 
2756   END LOOP;
2757   CLOSE c_formula_effectivity;
2758 
2759   log_message('Before MSC Inserts' ) ;
2760   time_stamp ;
2761   /* If all is OK, Bulk Insert the data into MSC tables */
2762    msc_inserts(valid);
2763        IF valid THEN
2764           COMMIT;
2765 	ELSE
2766 	NULL ;
2767        END IF;
2768    write_setups_and_transitions(valid) ;  /* SGIDUGU - Seq Dependencies */
2769 
2770        IF valid THEN
2771           COMMIT;
2772 	ELSE
2773 	NULL ;
2774        END IF;
2775 
2776   log_message('End of process' ) ;
2777   time_stamp ;
2778   -- gmp_putline('End at '|| TO_CHAR(SYSDATE,'DD-MON-YYYY HH24:MI:SS'),'a');
2779 /* akaruppa B5007729 Start*/
2780          /* Free memory used by PL/SQL tables used by program  */
2781            IF formula_header_tab.COUNT > 0 THEN
2782            formula_header_tab.delete ;
2783            END IF;
2784            IF formula_header_tab.COUNT > 0 THEN
2785            formula_header_tab.delete ;
2786            END IF;
2787            IF formula_detail_tab.COUNT > 0 THEN
2788            formula_detail_tab.delete ;
2789            END IF;
2790            IF formula_orgn_count_tab.COUNT > 0 THEN
2791            formula_orgn_count_tab.delete ;
2792            END IF;
2793            IF rtg_org_hdr_tab.COUNT > 0 THEN
2794            rtg_org_hdr_tab.delete ;
2795            END IF;
2796            IF rtg_org_dtl_tab.COUNT > 0 THEN
2797            rtg_org_dtl_tab.delete ;
2798            END IF;
2799            IF rtg_gen_dtl_tab.COUNT > 0 THEN
2800            rtg_gen_dtl_tab.delete ;
2801            END IF;
2802            IF rtg_alt_rsrc_tab.COUNT > 0 THEN
2803            rtg_alt_rsrc_tab.delete ;
2804            END IF;
2805            IF mat_assoc_tab.COUNT > 0 THEN
2806            mat_assoc_tab.delete;
2807            END IF;
2808            IF rcp_orgn_override.COUNT > 0 THEN
2809            rcp_orgn_override.delete ;
2810            END IF;
2811            IF recipe_override.COUNT > 0 THEN
2812            recipe_override.delete ;
2813            END IF;
2814            IF rstep_offsets.COUNT > 0 THEN
2815            rstep_offsets.delete ;
2816            END IF;
2817 
2818           dbms_session.free_unused_user_memory;
2819 
2820           SELECT st.VALUE INTO v_dummy from V$MYSTAT st, V$STATNAME sn
2821           WHERE st.STATISTIC# = sn.STATISTIC#
2822           AND sn.NAME in ('session pga memory max');
2823           log_message('Session pga memory max = ' || to_char(v_dummy) );
2824 
2825           SELECT st.VALUE INTO v_dummy from V$MYSTAT st, V$STATNAME sn
2826           where st.STATISTIC# = sn.STATISTIC#
2827           and sn.NAME in ('session pga memory');
2828           log_message('Session pga memory = ' || TO_CHAR(v_dummy) );
2829 
2830 	  /* akaruppa B5007729 End*/
2831 
2832   return_status := TRUE;
2833 
2834   EXCEPTION
2835     WHEN invalid_string_value  THEN
2836         log_message('Organization string is Invalid ' );
2837         return_status := FALSE;
2838     WHEN invalid_gmp_uom_profile THEN
2839         log_message('Profile "GMP: UOM for Hour" is Invalid ' );
2840         return_status := FALSE;
2841     WHEN OTHERS THEN
2842 	log_message('Error retrieving effectivities: '||sqlerrm);
2843 	return_status := FALSE;
2844 
2845 END retrieve_effectivities;
2846 
2847 /*
2848 REM+=========================================================================+
2849 REM| PROCEDURE NAME                                                          |
2850 REM|    link_override_routing                                                |
2851 REM| DESCRIPTION                                                             |
2852 REM|    Link the override based on routing and organization code             |
2853 REM|                                                                         |
2854 REM| HISTORY                                                                 |
2855 REM| 08/23/2002   Created Rajesh Patangya                                    |
2856 REM|                                                                         |
2857 REM+=========================================================================+
2858 */
2859 PROCEDURE link_override_routing IS
2860   i              NUMBER ;
2861   j              NUMBER ;
2862   k              NUMBER ;
2863   lgr_loc        NUMBER ;
2864   lgr_start_loc  NUMBER ;
2865   lgr_end_loc    NUMBER ;
2866   lorg_loc       NUMBER ;
2867   old_routing_id NUMBER ;
2868   gen_start_pos  NUMBER ;
2869   org_start_pos  NUMBER ;
2870   start_gen_pos_written NUMBER  ;
2871   start_org_pos_written NUMBER  ;
2872 
2873 BEGIN
2874   i              := 1 ;
2875   j              := 1 ;
2876   k              := 1 ;
2877   lgr_loc        := 0 ;
2878   lgr_start_loc  := 0 ;
2879   lgr_end_loc    := 0 ;
2880   lorg_loc       := 0 ;
2881   old_routing_id := 0 ;
2882   gen_start_pos  := 1  ;
2883   org_start_pos  := 1  ;
2884   start_gen_pos_written := 0 ;
2885   start_org_pos_written := 0 ;
2886 
2887 
2888   -- gmp_putline(' Begin Link Override Rtg ','a');
2889   FOR i IN 1..routing_headers_size
2890   LOOP
2891    IF rtg_org_hdr_tab(i).routing_id = old_routing_id THEN /* old rtg */
2892 
2893         rtg_org_hdr_tab(i).step_start_loc := lgr_start_loc ;
2894         rtg_org_hdr_tab(i).step_end_loc   := lgr_end_loc ;
2895    ELSE
2896         start_gen_pos_written := 0 ;
2897         FOR j IN gen_start_pos..recipe_override_size
2898         LOOP
2899         IF recipe_override(j).routing_id = rtg_org_hdr_tab(i).routing_id THEN
2900             IF start_gen_pos_written = 0 THEN
2901                 lgr_start_loc := j ;  /* Used for other org in org header */
2902                 rtg_org_hdr_tab(i).step_start_loc := j ;
2903                 start_gen_pos_written := 1 ;
2904             END IF ;
2905             IF j = recipe_override_size THEN
2906                 rtg_org_hdr_tab(i).step_end_loc := j ;
2907                 lgr_end_loc     := j ;
2908             END IF ;
2909 
2910         ELSIF recipe_override(j).routing_id > rtg_org_hdr_tab(i).routing_id
2911         THEN
2912 
2913             IF start_gen_pos_written <> 1 THEN
2914                 rtg_org_hdr_tab(i).step_start_loc := -1 ;
2915                 rtg_org_hdr_tab(i).step_end_loc   := -1 ;
2916                 lgr_start_loc   := - 1;
2917                 lgr_end_loc     := - 1;
2918             ELSE
2919                 lgr_end_loc   := j - 1;
2920                 rtg_org_hdr_tab(i).step_end_loc := lgr_end_loc ;
2921             END IF ;
2922             gen_start_pos := j ;
2923             EXIT ;
2924 
2925         /* ELSE - no need to write, continue looping. */
2926         END IF ;
2927      END LOOP ;   /* Generic loop */
2928    END IF ;   /* old rtg */
2929 
2930      --  For organization recipe
2931      start_org_pos_written := 0 ;
2932      FOR k IN org_start_pos..recipe_orgn_over_size
2933      LOOP
2934       IF rcp_orgn_override(k).routing_id = rtg_org_hdr_tab(i).routing_id AND
2935          rcp_orgn_override(k).orgn_code  = rtg_org_hdr_tab(i).plant_code THEN
2936 
2937           IF start_org_pos_written = 0 THEN
2938               rtg_org_hdr_tab(i).usage_start_loc := k ;
2939               start_org_pos_written := 1 ;
2940           END IF ;
2941           IF k = recipe_orgn_over_size THEN
2942               rtg_org_hdr_tab(i).usage_end_loc := k ;
2943           END IF ;
2944 
2945       ELSIF (rcp_orgn_override(k).routing_id>rtg_org_hdr_tab(i).routing_id) OR
2946           (
2947           (rcp_orgn_override(k).routing_id = rtg_org_hdr_tab(i).routing_id) AND
2948           (rcp_orgn_override(k).orgn_code  > rtg_org_hdr_tab(i).plant_code)
2949           )  THEN
2950 
2951             IF start_org_pos_written <> 1 THEN
2952               rtg_org_hdr_tab(i).usage_start_loc := -1 ;
2953               rtg_org_hdr_tab(i).usage_end_loc :=  -1 ;
2954             ELSE
2955               rtg_org_hdr_tab(i).usage_end_loc := k - 1 ;
2956             END IF ;
2957             org_start_pos := k ;
2958             EXIT ;
2959 
2960       /* ELSE - no need to write, continue looping. */
2961       END IF ;
2962      END LOOP ;   /* recipe organization loop */
2963 
2964      old_routing_id := rtg_org_hdr_tab(i).routing_id ;
2965   END LOOP ;  /* routing header loop */
2966 
2967   -- gmp_putline(' End Link Override Rtg ','a');
2968 END link_override_routing;
2969 
2970 /*
2971 REM+=========================================================================+
2972 REM| FUNCTION NAME                                                           |
2973 REM|    find_routing_header                                                  |
2974 REM| DESCRIPTION                                                             |
2975 REM|                                                                         |
2976 REM| HISTORY                                                                 |
2977 REM| 07/14/2002   Rajesh Patangya - Reorgnized the complete code B2314052    |
2978 REM+=========================================================================+
2979 */
2980 FUNCTION find_routing_header ( prouting_id   IN NUMBER,
2981                                pplant_code   IN VARCHAR2)
2982                                RETURN BOOLEAN IS
2983 
2984 routing_header_loc   NUMBER     ;
2985 BEGIN
2986 routing_header_loc   := 0 ;
2987       routing_header_loc := bsearch_routing (prouting_id,
2988                                              pplant_code);
2989 
2990        IF routing_header_loc > 0 THEN  /* routing header location */
2991 
2992           IF (rtg_org_hdr_tab(routing_header_loc).valid_flag < 0) OR
2993              (rtg_org_hdr_tab(routing_header_loc).generic_start_loc < 0) OR
2994              (rtg_org_hdr_tab(routing_header_loc).orgn_start_loc < 0)  THEN
2995 
2996                 effectivity.rtg_hdr_location :=  -1 ;
2997                 return FALSE ;
2998            ELSE
2999                 effectivity.rtg_hdr_location := routing_header_loc ;
3000                 return TRUE ;
3001           END IF ;
3002        ELSE
3003                 log_message('Bsearch returned negative for Routing Plant ');
3004                 effectivity.rtg_hdr_location :=  -1 ;
3005                 return FALSE ;
3006        END IF ; /* routing header location */
3007 
3008 END find_routing_header;
3009 
3010 /*
3011 REM+=========================================================================+
3012 REM| PROCEDURE NAME                                                          |
3013 REM|    link_routing                                                         |
3014 REM| DESCRIPTION                                                             |
3015 REM|                                                                         |
3016 REM| HISTORY                                                                 |
3017 REM| 07/14/2002   Rajesh Patangya - Reorgnized the complete code B2314052    |
3018 REM+=========================================================================+
3019 */
3020 PROCEDURE link_routing IS
3021   i              NUMBER ;
3022   j              NUMBER ;
3023   k              NUMBER ;
3024   lgr_loc        NUMBER ;
3025   lgr_start_loc  NUMBER ;
3026   lgr_end_loc    NUMBER ;
3027   lorg_loc       NUMBER ;
3028   old_routing_id NUMBER ;
3029   gen_start_pos  NUMBER ;
3030   org_start_pos  NUMBER ;
3031   start_gen_pos_written NUMBER  ;
3032   start_org_pos_written NUMBER  ;
3033 /* NAMIT_CR To link step dependency to routing header */
3034   lstpdep_start_loc  NUMBER ;
3035   lstpdep_end_loc    NUMBER ;
3036   stpdep_start_pos  NUMBER ;
3037   start_stpdep_pos_written NUMBER  ;
3038 
3039 BEGIN
3040   i              := 1 ;
3041   j              := 1 ;
3042   k              := 1 ;
3043   lgr_loc        := 0 ;
3044   lgr_start_loc  := 0 ;
3045   lgr_end_loc    := 0 ;
3046   lorg_loc       := 0 ;
3047   old_routing_id := 0 ;
3048   gen_start_pos  := 1  ;
3049   org_start_pos  := 1  ;
3050   start_gen_pos_written := 0 ;
3051   start_org_pos_written := 0 ;
3052   lstpdep_start_loc  := 0 ;
3053   lstpdep_end_loc    := 0 ;
3054   stpdep_start_pos  := 1  ;
3055   start_stpdep_pos_written := 0 ;
3056 
3057 
3058   -- gmp_putline(' Start Link Rtg ','a');
3059   FOR i IN 1..routing_headers_size
3060   LOOP
3061    IF rtg_org_hdr_tab(i).routing_id = old_routing_id THEN /* old rtg */
3062 
3063         rtg_org_hdr_tab(i).generic_start_loc := lgr_start_loc ;
3064         rtg_org_hdr_tab(i).generic_end_loc   := lgr_end_loc ;
3065 /* NAMIT_CR Link the Step Dependency to the routing header */
3066         rtg_org_hdr_tab(i).stpdep_start_loc := lstpdep_start_loc ;
3067         rtg_org_hdr_tab(i).stpdep_end_loc   := lstpdep_end_loc ;
3068 
3069    ELSE
3070         start_gen_pos_written := 0 ;
3071         FOR j IN gen_start_pos..rtg_gen_dtl_size
3072         LOOP
3073         IF rtg_gen_dtl_tab(j).routing_id = rtg_org_hdr_tab(i).routing_id THEN
3074             IF start_gen_pos_written = 0 THEN
3075                 lgr_start_loc := j ;  /* Used for other org in org header */
3076                 rtg_org_hdr_tab(i).generic_start_loc := j ;
3077                 start_gen_pos_written := 1 ;
3078             END IF ;
3079             IF j = rtg_gen_dtl_size THEN
3080                 rtg_org_hdr_tab(i).generic_end_loc := j ;
3081                 lgr_end_loc     := j ;
3082             END IF ;
3083 
3084         ELSIF rtg_gen_dtl_tab(j).routing_id > rtg_org_hdr_tab(i).routing_id
3085         THEN
3086 
3087             IF start_gen_pos_written <> 1 THEN
3088                 rtg_org_hdr_tab(i).generic_start_loc := -1 ;
3089                 rtg_org_hdr_tab(i).generic_end_loc   := -1 ;
3090                 lgr_start_loc   := - 1;
3091                 lgr_end_loc     := - 1;
3092             ELSE
3093                 lgr_end_loc   := j - 1;
3094                 rtg_org_hdr_tab(i).generic_end_loc := lgr_end_loc ;
3095             END IF ;
3096             gen_start_pos := j ;
3097             EXIT ;
3098 
3099         /* ELSE - no need to write, continue looping. */
3100         END IF ;
3101      END LOOP ;   /* Generic loop */
3102 /* NAMIT_CR Code To Link Step Dependency to Routing Header Start */
3103 
3104      start_stpdep_pos_written := 0 ;
3105      FOR j IN stpdep_start_pos..opr_stpdep_size
3106      LOOP
3107         IF gmp_opr_stpdep_tbl(j).routing_id = rtg_org_hdr_tab(i).routing_id THEN
3108             IF start_stpdep_pos_written = 0 THEN
3109                 lstpdep_start_loc := j ;  /* Used for other routes in route header */
3110                 rtg_org_hdr_tab(i).stpdep_start_loc := j ;
3111                 start_stpdep_pos_written := 1 ;
3112             END IF ;
3113             IF j = opr_stpdep_size THEN
3114                 rtg_org_hdr_tab(i).stpdep_end_loc := j ;
3115                 lstpdep_end_loc     := j ;
3116             END IF ;
3117 
3118         ELSIF gmp_opr_stpdep_tbl(j).routing_id > rtg_org_hdr_tab(i).routing_id
3119         THEN
3120 
3121             IF start_stpdep_pos_written <> 1 THEN
3122                 rtg_org_hdr_tab(i).stpdep_start_loc := -1 ;
3123                 rtg_org_hdr_tab(i).stpdep_end_loc   := -1 ;
3124                 lstpdep_start_loc   := - 1;
3125                 lstpdep_end_loc     := - 1;
3126             ELSE
3127                 lstpdep_end_loc   := j - 1;
3128                 rtg_org_hdr_tab(i).stpdep_end_loc := lstpdep_end_loc ;
3129             END IF ;
3130             stpdep_start_pos := j ;
3131             EXIT ;
3132 
3133         /* ELSE - no need to write, continue looping. */
3134         END IF ;
3135      END LOOP ;   /* Step Dependency loop */
3136 
3137 /* NAMIT_CR Code To Link Step Dependency to Routing Header End */
3138 
3139    END IF ;   /* old rtg */
3140 
3141      --  For organization routing
3142      start_org_pos_written := 0 ;
3143      For k IN org_start_pos..rtg_org_dtl_size
3144      LOOP
3145       IF rtg_org_dtl_tab(k).routing_id = rtg_org_hdr_tab(i).routing_id AND
3146          rtg_org_dtl_tab(k).orgn_code  = rtg_org_hdr_tab(i).plant_code THEN
3147 
3148           IF start_org_pos_written = 0 THEN
3149               rtg_org_hdr_tab(i).orgn_start_loc := k ;
3150               start_org_pos_written := 1 ;
3151           END IF ;
3152           IF k = rtg_org_dtl_size THEN
3153               rtg_org_hdr_tab(i).orgn_end_loc := k ;
3154           END IF ;
3155 
3156       ELSIF (rtg_org_dtl_tab(k).routing_id > rtg_org_hdr_tab(i).routing_id) OR
3157           (
3158           (rtg_org_dtl_tab(k).routing_id = rtg_org_hdr_tab(i).routing_id) AND
3159           (rtg_org_dtl_tab(k).orgn_code  > rtg_org_hdr_tab(i).plant_code)
3160           )  THEN
3161 
3162             IF start_org_pos_written <> 1 THEN
3163               rtg_org_hdr_tab(i).orgn_start_loc := -1 ;
3164               rtg_org_hdr_tab(i).orgn_end_loc :=  -1 ;
3165             ELSE
3166               rtg_org_hdr_tab(i).orgn_end_loc := k - 1 ;
3167             END IF ;
3168             org_start_pos := k ;
3169             EXIT ;
3170 
3171       /* ELSE - no need to write, continue looping. */
3172       END IF ;
3173      END LOOP ;   /* Organization loop */
3174 
3175      old_routing_id := rtg_org_hdr_tab(i).routing_id ;
3176 
3177   END LOOP ;  /* routing header loop */
3178 
3179   -- gmp_putline(' End Link Rtg ','a');
3180 END link_routing;
3181 
3182 /*
3183 REM+=========================================================================+
3184 REM| PROCEDURE NAME                                                          |
3185 REM|    validate_routing                                                     |
3186 REM| DESCRIPTION                                                             |
3187 REM|   1. ALL Items in effectivity needs to be convertible to Routing UOM    |
3188 REM|   2. ALL details are present in gmp_item_aps with appropriate flags     |
3189 REM|                                                                         |
3190 REM| HISTORY                                                                 |
3191 REM| 07/14/2002   Rajesh Patangya - Reorgnized the complete code B2314052    |
3192 REM+=========================================================================+
3193 */
3194 PROCEDURE validate_routing (prouting_id IN NUMBER ,
3195                            porgn_code   IN VARCHAR2,
3196                            pheader_loc  IN NUMBER,
3197                            prout_valid  OUT NOCOPY BOOLEAN)
3198 IS
3199 
3200   uom_statement           VARCHAR2(2000) ;
3201   old_routingstep_id      NUMBER   ;
3202   old_oprn_no             VARCHAR2(32)  ;
3203   old_activity            NUMBER ;
3204   i                       INTEGER ;
3205   j                       INTEGER ;
3206   start_genric_count      NUMBER ;
3207   end_genric_count        NUMBER ;
3208   start_orgn_count        NUMBER ;
3209   end_orgn_count          NUMBER ;
3210   rtg_org_loc             NUMBER ;
3211   prim_rsrc_cnt           NUMBER ;
3212   p_uom_qty               NUMBER ;
3213   rtg_valid               BOOLEAN ;
3214   found_match             BOOLEAN ;
3215 
3216 --
3217   k                       INTEGER;
3218   step_start_index        INTEGER;
3219   step_end_index          INTEGER;
3220   usage_start_index       INTEGER;
3221   usage_end_index         INTEGER;
3222   prev_routingstep_id     NUMBER;
3223   l_setup_id              NUMBER;
3224 
3225 BEGIN
3226   uom_statement           := NULL ;
3227   old_routingstep_id      := 0 ;
3228   old_oprn_no             := ' ' ;
3229   old_activity            := -1 ;
3230   i                       := 1 ;
3231   j                       := 1 ;
3232   start_genric_count      := 0 ;
3233   end_genric_count        := 0 ;
3234   start_orgn_count        := 0 ;
3235   end_orgn_count          := 0 ;
3236   rtg_org_loc             := 0 ;
3237   prim_rsrc_cnt           := 0 ;
3238   p_uom_qty               := -1 ;
3239   rtg_valid               := TRUE ;
3240   found_match             := TRUE ;
3241   prim_rsrc_cnt      := 0 ;
3242   found_match        := TRUE ;
3243   prev_routingstep_id     := NULL ;
3244   l_setup_id              := NULL;
3245 
3246    rtg_org_loc        := pheader_loc;
3247    start_genric_count := rtg_org_hdr_tab(rtg_org_loc).generic_start_loc;
3248    end_genric_count   := rtg_org_hdr_tab(rtg_org_loc).generic_end_loc;
3249    start_orgn_count   := rtg_org_hdr_tab(rtg_org_loc).orgn_start_loc;
3250    end_orgn_count     := rtg_org_hdr_tab(rtg_org_loc).orgn_end_loc;
3251 
3252 -- Overrides Rajesh {
3253    rtg_valid                 := TRUE ;
3254    k                         := 1;
3255 
3256    step_start_index :=
3257       rtg_org_hdr_tab(effectivity.rtg_hdr_location).step_start_loc ;
3258    step_end_index :=
3259       rtg_org_hdr_tab(effectivity.rtg_hdr_location).step_end_loc ;
3260    usage_start_index :=
3261       rtg_org_hdr_tab(effectivity.rtg_hdr_location).usage_start_loc ;
3262    usage_end_index :=
3263       rtg_org_hdr_tab(effectivity.rtg_hdr_location).usage_end_loc ;
3264 
3265 -- Changes for Overrides Rajesh }
3266 
3267    /* Generic routing check */
3268    IF (start_genric_count > 0) AND (end_genric_count > 0 ) THEN
3269    FOR i IN start_genric_count..end_genric_count
3270    LOOP
3271      /* { */
3272       IF (rtg_gen_dtl_tab(i).routing_id = prouting_id) THEN
3273 
3274          /* If operation, activity, step change then */
3275          IF (i = start_genric_count) OR
3276             (rtg_gen_dtl_tab(i).routingstep_id <> old_routingstep_id) OR
3277             (rtg_gen_dtl_tab(i).oprn_no <> old_oprn_no) OR
3278             (rtg_gen_dtl_tab(i).oprn_line_id <>  old_activity)  THEN
3279               prim_rsrc_cnt := 0 ;
3280           END IF ;
3281 
3282           IF rtg_gen_dtl_tab(i).prim_rsrc_ind = 1 THEN
3283              prim_rsrc_cnt := prim_rsrc_cnt + 1 ;
3284           END IF ;
3285 
3286           /* If no primary/ multiple primary resource exit and invalidate
3287              the rtg_header for all the organization */
3288           IF prim_rsrc_cnt <> 1 THEN
3289               --  Routing INVALID We should not do any further processing
3290               prim_rsrc_cnt := 0 ;
3291               invalidate_rtg_all_org(prouting_id) ;
3292               rtg_valid := FALSE;
3293               EXIT ;
3294           END IF ;
3295 
3296           old_routingstep_id := rtg_gen_dtl_tab(i).routingstep_id ;
3297           old_oprn_no        := rtg_gen_dtl_tab(i).oprn_no ;
3298           old_activity       := rtg_gen_dtl_tab(i).oprn_line_id ;
3299 
3300        /* organization check */
3301        IF (start_orgn_count > 0) AND (end_orgn_count > 0 ) AND
3302              (start_orgn_count <= end_orgn_count)
3303        THEN
3304        FOR j IN start_orgn_count..end_orgn_count
3305        LOOP
3306         /* {{ */
3307          IF (rtg_org_dtl_tab(j).orgn_code = porgn_code)  AND
3308             (rtg_org_dtl_tab(j).routing_id = prouting_id) THEN
3309 
3310 -- ------------------
3311          IF (rtg_org_dtl_tab(j).routingstep_id <> nvl(prev_routingstep_id,-1)) THEN
3312 
3313            IF (rtg_org_dtl_tab(j).is_unique = 1) AND (effectivity.category_id > 0)
3314 	   THEN
3315                l_setup_id := bsearch_setupid(rtg_org_dtl_tab(j).oprn_id,
3316                                  effectivity.category_id);
3317                IF l_setup_id > 0 THEN
3318                   rtg_org_dtl_tab(j).setup_id := l_setup_id ;
3319                ELSE
3320                  /* The actual SDS changeover data is not established */
3321                  rtg_org_dtl_tab(j).setup_id := NULL ;
3322                END IF;
3323            END IF;
3324            prev_routingstep_id := rtg_org_dtl_tab(j).routingstep_id ;
3325          END IF;
3326          IF (rtg_org_dtl_tab(j).is_unique = 1) AND (effectivity.category_id > 0) THEN
3327             sd_index := sd_index + 1 ;
3328             sds_tab(sd_index).oprn_id        := rtg_org_dtl_tab(j).oprn_id ;
3329             sds_tab(sd_index).category_id    := effectivity.category_id    ;
3330             sds_tab(sd_index).seq_dpnd_class := effectivity.seq_dpnd_class ;
3331             sds_tab(sd_index).resources      := rtg_org_dtl_tab(j).resources ;
3332             sds_tab(sd_index).resource_id    := rtg_org_dtl_tab(j).resource_id ;
3333             sds_tab(sd_index).setup_id       := rtg_org_dtl_tab(j).setup_id ;
3334          END IF;
3335 -- ------------------
3336           /* -------- Get step qty override (RDP) ------------------*/
3337 
3338             rtg_org_dtl_tab(j).o_resource_usage  := -1 ;
3339             rtg_org_dtl_tab(j).o_activity_factor := -1 ;
3340             rtg_org_dtl_tab(j).o_step_qty        := -1 ;
3341             rtg_org_dtl_tab(j).o_process_qty     := -1 ;
3342             rtg_org_dtl_tab(j).o_max_capacity    := -1 ;
3343             rtg_org_dtl_tab(j).o_min_capacity    := -1 ;
3344 
3345             IF (step_start_index > 0) AND (step_end_index > 0) THEN
3346             k := 1 ;
3347             FOR k IN step_start_index..step_end_index
3348             LOOP
3349              IF (effectivity.recipe_id =
3350                    recipe_override(k).recipe_id) THEN
3351 
3352              IF (rtg_org_dtl_tab(j).routing_id =
3353                    recipe_override(k).routing_id) AND
3354                 (rtg_org_dtl_tab(j).routingstep_id =
3355                    recipe_override(k).routingstep_id) THEN
3356 
3357                  rtg_org_dtl_tab(j).o_step_qty :=
3358                     recipe_override(k).step_qty ;
3359                  EXIT ;
3360              END IF ;
3361             ELSE
3362                  rtg_org_dtl_tab(j).o_step_qty := -1 ;
3363                  EXIT ;
3364             END IF; /* Get step qty override */
3365 
3366             END LOOP ;   /* Step Qty Override */
3367             END IF; /* Get step qty override */
3368            /* -------- step qty override Ends (RDP) ------------------*/
3369 
3370             IF (rtg_gen_dtl_tab(i).routingstep_id =
3371                                rtg_org_dtl_tab(j).routingstep_id) AND
3372                (rtg_gen_dtl_tab(i).oprn_line_id =
3373                                rtg_org_dtl_tab(j).oprn_line_id) AND
3374                (rtg_gen_dtl_tab(i).resources =
3375                                 rtg_org_dtl_tab(j).resources) THEN
3376 
3377       /* ------------ Override Calculation Code start ----------------------*/
3378 
3379             IF ((usage_start_index > 0) AND (usage_end_index > 0)) THEN
3380             k := 1 ;
3381               FOR k IN usage_start_index..usage_end_index
3382               LOOP
3383                /* { */
3384                IF (rtg_org_dtl_tab(j).routing_id =
3385                       rcp_orgn_override(k).routing_id) AND
3386                      (rtg_org_dtl_tab(j).orgn_code =
3387                       rcp_orgn_override(k).orgn_code) AND
3388                      (rtg_org_dtl_tab(j).routingstep_id =
3389                       rcp_orgn_override(k).routingstep_id) AND
3390                      (rtg_org_dtl_tab(j).oprn_line_id =
3391                       rcp_orgn_override(k).oprn_line_id) AND
3392                      (effectivity.recipe_id =
3393                       rcp_orgn_override(k).recipe_id) THEN
3394 
3395                    -- Activity factor override
3396                      rtg_org_dtl_tab(j).o_activity_factor :=
3397                                rcp_orgn_override(k).activity_factor;
3398                    -- Resource Overrides
3399                  /* { */
3400                  IF (rtg_org_dtl_tab(j).resources =
3401                          rcp_orgn_override(k).resources) THEN
3402 
3403                      rtg_org_dtl_tab(j).o_resource_usage :=
3404                             rcp_orgn_override(k).resource_usage;
3405                    -- Process Qty override
3406                      rtg_org_dtl_tab(j).o_process_qty :=
3407                              rcp_orgn_override(k).process_qty ;
3408                    -- Min / Max Capacity Overrides
3409                      rtg_org_dtl_tab(j).o_min_capacity :=
3410                              rcp_orgn_override(k).min_capacity ;
3411                      rtg_org_dtl_tab(j).o_max_capacity :=
3412                              rcp_orgn_override(k).max_capacity ;
3413                  END IF ; /* } Resource Overrides */
3414 
3415                END IF ;  /* }check for routing/step/oprn/recipe */
3416 
3417               END LOOP;  /* Override Loop Ends here */
3418             END IF; /* } check for Override presence */
3419 
3420             IF (rtg_org_dtl_tab(j).prim_rsrc_ind = 1) THEN
3421 
3422                      IF (rtg_org_dtl_tab(j).o_resource_usage = -1 ) THEN
3423 
3424                        IF (rtg_org_dtl_tab(j).resource_usage = 0) THEN
3425                         rtg_valid := FALSE ;
3426         		rtg_org_hdr_tab(rtg_org_loc).valid_flag := -1 ;
3427                         log_message('Recipe ' || effectivity.recipe_id ||' '||
3428                                rtg_org_dtl_tab(j).resources|| ' has usage 0');
3429                         EXIT ;
3430                        END IF;
3431                      ELSIF (rtg_org_dtl_tab(j).o_resource_usage = 0) THEN
3432                         rtg_valid := FALSE ;
3433                         log_message('Recipe ' || effectivity.recipe_id ||' '||
3434                                rtg_org_dtl_tab(j).resources|| ' has usage 0');
3435                         EXIT ;
3436                      END IF ;
3437 
3438                      IF (rtg_org_dtl_tab(j).o_activity_factor = -1 ) THEN
3439                        IF (rtg_org_dtl_tab(j).activity_factor = 0) THEN
3440                         rtg_valid := FALSE ;
3441         		rtg_org_hdr_tab(rtg_org_loc).valid_flag := -1 ;
3442                         log_message('Recipe ' || effectivity.recipe_id ||
3443                          ' has ZERO activity factor');
3444                         EXIT;
3445                        END IF;
3446                      ELSIF (rtg_org_dtl_tab(j).o_activity_factor = 0) THEN
3447                         rtg_valid := FALSE ;
3448                         log_message('Recipe ' || effectivity.recipe_id ||
3449                          ' has ZERO Override activity factor');
3450                         EXIT ;
3451                      END IF ;
3452 
3453                      IF (rtg_org_dtl_tab(j).o_step_qty = -1 ) THEN
3454                        IF (rtg_org_dtl_tab(j).step_qty = 0) THEN
3455                         rtg_valid := FALSE ;
3456         		rtg_org_hdr_tab(rtg_org_loc).valid_flag := -1 ;
3457                         log_message('Recipe ' || effectivity.recipe_id ||
3458                          ' has ZERO step qty');
3459                         EXIT ;
3460                        END IF;
3461                      ELSIF (rtg_org_dtl_tab(j).o_step_qty = 0) THEN
3462                         rtg_valid := FALSE ;
3463                         log_message('Recipe ' || effectivity.recipe_id ||
3464                          ' has ZERO override step qty');
3465                         EXIT ;
3466                      END IF ;
3467             END IF;  /* For primary resource chack */
3468 /*
3469     IF rtg_org_dtl_tab(j).routing_id = 58 THEN
3470      log_message (
3471      rtg_org_dtl_tab(j).routing_id ||'*'||
3472      effectivity.recipe_id ||'*'||
3473      rtg_org_dtl_tab(j).prim_rsrc_ind      ||'*'||
3474      rtg_org_dtl_tab(j).routingstep_id         ||' Us '||
3475      rtg_org_dtl_tab(j).resources     ||'* '||
3476      rtg_org_dtl_tab(j).resource_usage      ||' *'||
3477      rtg_org_dtl_tab(j).o_resource_usage      ||' AF '||
3478      rtg_org_dtl_tab(j).activity_factor      ||' *'||
3479      rtg_org_dtl_tab(j).o_activity_factor      ||' SQ '||
3480      rtg_org_dtl_tab(j).step_qty      ||' *'||
3481      rtg_org_dtl_tab(j).o_step_qty     ||' PQ '||
3482      rtg_org_dtl_tab(j).process_qty      ||' *'||
3483      rtg_org_dtl_tab(j).o_process_qty      ||' M '||
3484      rtg_org_dtl_tab(j).min_capacity   ||' *'||
3485      rtg_org_dtl_tab(j).o_min_capacity   ||' X '||
3486      rtg_org_dtl_tab(j).max_capacity   ||' *'||
3487      rtg_org_dtl_tab(j).o_max_capacity);
3488      END IF;
3489 */
3490       /* ------------ Override Calculation Code start ----------------------*/
3491 
3492                 IF (rtg_org_dtl_tab(j).prim_rsrc_ind = 1
3493                     AND rtg_org_dtl_tab(j).schedule_ind = 3) THEN
3494 
3495                     rtg_valid := FALSE;
3496         	    rtg_org_hdr_tab(rtg_org_loc).valid_flag := -1 ;
3497                     log_message('Primary Resource '||rtg_org_dtl_tab(j).resources||
3498                         ' is defined as Do Not Plan ');
3499                     EXIT;
3500                 ELSIF (rtg_org_dtl_tab(j).prim_rsrc_ind <> 1
3501                     AND rtg_org_dtl_tab(j).schedule_ind = 3) THEN
3502 
3503                     start_orgn_count := j + 1 ;
3504                     rtg_org_dtl_tab(j).include_rtg_row := 0;
3505                     EXIT;
3506                 ELSE
3507                     rtg_valid := TRUE ;
3508         	    rtg_org_hdr_tab(rtg_org_loc).valid_flag := 1 ;
3509                     start_orgn_count := j + 1 ;
3510                     EXIT ;
3511                 END IF;
3512 
3513             ELSE
3514               -- Make the rtg invalid ONLY if the Primary or Auxilary
3515               -- resources for any activity is missing
3516               IF rtg_gen_dtl_tab(i).prim_rsrc_ind <> 0 THEN
3517                  rtg_valid := FALSE ;
3518                 log_message('Missing Plant Resource '||rtg_org_dtl_tab(j).resources);
3519       -- gmp_putline('Missing resource ' || rtg_org_dtl_tab(j).resources,'a');
3520               END IF ;
3521               EXIT;
3522             END IF ;
3523 
3524          END IF;
3525          /* }} */
3526        END LOOP;   /* Orgnization  Loop */
3527        ELSE
3528           -- If there are no organization details , the rtg is invalid
3529           rtg_valid := FALSE ;
3530        END IF;  /* organization check */
3531 
3532          IF rtg_valid = FALSE THEN
3533             EXIT ;
3534          END IF ;
3535      END IF;
3536      /* } */
3537    END LOOP ;  /* Generic Loop */
3538    ELSE
3539         -- If no generic routing details present, make routing invalid
3540         rtg_valid := FALSE ;
3541         invalidate_rtg_all_org(prouting_id) ;
3542    END IF;  /* Generic routing check */
3543 
3544    IF rtg_valid THEN
3545         rtg_org_hdr_tab(rtg_org_loc).valid_flag := 1 ;
3546    ELSE
3547         rtg_org_hdr_tab(rtg_org_loc).valid_flag := -1 ;
3548    END IF ;
3549 
3550      prout_valid := rtg_valid ;
3551 
3552 END validate_routing ;
3553 
3554 /*
3555 REM+=========================================================================+
3556 REM| PROCEDURE NAME                                                          |
3557 REM|    invalidate_rtg_all_org                                               |
3558 REM| DESCRIPTION                                                             |
3559 REM|                                                                         |
3560 REM| HISTORY                                                                 |
3561 REM| 07/14/2002   Rajesh Patangya - Reorgnized the complete code B2314052    |
3562 REM+=========================================================================+
3563 */
3564 PROCEDURE invalidate_rtg_all_org (p_routing_id IN NUMBER) IS
3565 
3566   i INTEGER ;
3567 BEGIN
3568   i := 1  ;
3569    FOR i IN 1..routing_headers_size
3570    LOOP
3571      IF rtg_org_hdr_tab(i).routing_id = p_routing_id THEN
3572            rtg_org_hdr_tab(i).valid_flag := -1 ;
3573      ELSIF rtg_org_hdr_tab(i).routing_id > p_routing_id THEN
3574            EXIT ;
3575      /* ELSE
3576            NULL ;  */
3577      END IF;
3578    END LOOP ;
3579 END invalidate_rtg_all_org;
3580 
3581 /*
3582 REM+=========================================================================+
3583 REM| PROCEDURE NAME                                                          |
3584 REM|    validate_formula                                                     |
3585 REM| DESCRIPTION                                                             |
3586 REM|                                                                         |
3587 REM|   Note that we are going to structure the formula retrieval query       |
3588 REM|   so that only the formulae used in Effectivities are fetched           |
3589 REM|   so trying to validate all at once does not cause any extra work       |
3590 REM|  Summary : Two validations need to be performed                         |
3591 REM|    1. ALL details can be converted to primary UOM                       |
3592 REM|    2. ALL details are present in gmp_item_aps with appropriate flags    |
3593 REM|                                                                         |
3594 REM| It is now determined that the check for gmp_item_aps and flags therein  |
3595 REM| should NOT be done here , so would be made immediately before inserting |
3596 REM| rows. The same may also be achieved by joining to gmp_item_aps table    |
3597 REM| while getting formula details                                           |
3598 REM|                                                                         |
3599 REM| HISTORY                                                                 |
3600 REM| 07/14/2002   Rajesh Patangya - Reorgnized the complete code B2314052    |
3601 REM+=========================================================================+
3602 */
3603 PROCEDURE validate_formula IS
3604 
3605 i                  INTEGER ;
3606 j                  INTEGER ;
3607 current_dtl_cnt    INTEGER ;
3608 start_pos_written  NUMBER ;
3609 detail_found       NUMBER ;
3610 uom_success        BOOLEAN ;
3611 
3612 BEGIN
3613 i                  := 1 ;
3614 j                  := 1 ;
3615 current_dtl_cnt    := 1 ;
3616 start_pos_written  := 0 ;
3617 detail_found       := 0 ;
3618 uom_success        := FALSE ;
3619    --  gmp_putline(' Begin validate_formula ','a');
3620    FOR i IN 1..formula_headers_size
3621    LOOP
3622      uom_success       := TRUE ;
3623      start_pos_written := 0 ;
3624      detail_found      := 0 ;
3625 
3626      FOR j IN current_dtl_cnt..formula_details_size
3627      LOOP
3628        IF formula_detail_tab(j).formula_id = formula_header_tab(i).formula_id
3629        THEN
3630            detail_found  := 1 ;
3631            IF formula_detail_tab(j).primary_qty < 0  THEN
3632 		uom_success := FALSE ;
3633            ELSE
3634 		uom_success := TRUE ;
3635            END IF;
3636 
3637            --  store the starting detail position
3638            IF start_pos_written = 0 THEN
3639               formula_header_tab(i).start_dtl_loc := j ;
3640               start_pos_written := 1 ;
3641            END IF;
3642 
3643            --  store the ending detail position, if it is the last row
3644            IF j = formula_details_size THEN
3645               formula_header_tab(i).end_dtl_loc := j ;
3646            END IF ;
3647 
3648        ELSIF formula_detail_tab(j).formula_id >
3649                           formula_header_tab(i).formula_id THEN
3650 
3651            --  store the ending detail position
3652            IF start_pos_written <> 1 THEN
3653               formula_header_tab(i).start_dtl_loc := -1 ;
3654               formula_header_tab(i).end_dtl_loc := -1 ;
3655            ELSE
3656               formula_header_tab(i).end_dtl_loc := j - 1 ;
3657            END IF ;
3658            current_dtl_cnt := j ;
3659            EXIT ;
3660 
3661        /* ELSE - no need to write else as it simply has to continue looping. */
3662        END IF ;
3663 
3664      END LOOP ;   /* formula_details_size  */
3665 
3666      IF (detail_found = 1) THEN
3667          IF (uom_success) THEN
3668            formula_header_tab(i).valid_flag := 1 ;
3669          ELSE
3670            formula_header_tab(i).valid_flag := -1 ;
3671            formula_header_tab(i).start_dtl_loc := -1 ;
3672            formula_header_tab(i).end_dtl_loc := -1 ;
3673    	   log_message(
3674                   'UOM Conversion falied for formula ' ||
3675    		  to_char(formula_header_tab(i).formula_id)
3676                   );
3677           END IF ;
3678      ELSE
3679            formula_header_tab(i).valid_flag := -1 ;
3680            formula_header_tab(i).start_dtl_loc := -1 ;
3681            formula_header_tab(i).end_dtl_loc := -1 ;
3682 	/* B4625724
3683    	   log_message(
3684                   'Formula detail not found for formula ' ||
3685    		  to_char(formula_header_tab(i).formula_id)
3686                   );
3687 	*/
3688      END IF ;
3689 
3690    END LOOP ;   /* Formula header loop */
3691 
3692    /* Now validate the formula for all the organizations */
3693    validate_formula_for_orgn ;
3694 
3695    --  gmp_putline(' End validate_formula ','a');
3696 END validate_formula ;
3697 
3698 /*
3699 REM+=========================================================================+
3700 REM| PROCEDURE NAME                                                          |
3701 REM|    validate_formula_for_orgn                                            |
3702 REM| DESCRIPTION                                                             |
3703 REM|    This procedure contains SQL query, but getting executed only once.   |
3704 REM| HISTORY                                                                 |
3705 REM| 07/14/2002   Rajesh Patangya - Reorgnized the complete code B2314052    |
3706 REM| 08/27/2002   Rajesh Patangya - Voltek Customer Fix B2362810             |
3707 REM+=========================================================================+
3708 */
3709 PROCEDURE validate_formula_for_orgn IS
3710 
3711     formula_orgn_count_cursor       VARCHAR2(32700) ;
3712     formula_dtl_count_cursor        VARCHAR2(32700) ;
3713     cur_formula_orgn_count          ref_cursor_typ;
3714     c_formula_dtl_count             ref_cursor_typ;
3715     fm_dtl_orgn_cnt                 INTEGER ;
3716     i                               INTEGER ;
3717 
3718 BEGIN
3719     formula_orgn_count_cursor       := NULL ;
3720     formula_dtl_count_cursor        := NULL ;
3721     fm_dtl_orgn_cnt                 := 1 ;
3722     i                               := 1 ;
3723       --  gmp_putline(' start of validate_formula_for_org ','a');
3724 
3725    formula_orgn_count_cursor :=
3726                      ' SELECT fmd.formula_id, gia.plant_code, '
3727                    ||'       gia.organization_id, count(*), 0 '
3728                    ||' FROM  fm_matl_dtl'||at_apps_link||' fmd, '
3729                    ||'       fm_form_mst'||at_apps_link||' ffm, '
3730                    ||'       gmp_item_aps'||at_apps_link||' gia, '
3731                    ||'       sy_orgn_mst'||at_apps_link||' som '
3732                    ||' WHERE ffm.formula_id = fmd.formula_id '
3733                    ||'   AND ffm.delete_mark = 0 '
3734                    ||'   AND fmd.qty <> 0 '  /* 2362810 Voltek Fix */
3735                    ||'   AND fmd.item_id = gia.item_id '
3736                    ||'   AND gia.plant_code = som.orgn_code ' ;
3737          IF l_in_str_org  IS NOT NULL THEN
3738             formula_orgn_count_cursor := formula_orgn_count_cursor
3739                    ||'   AND gia.whse_code = som.resource_whse_code ' ;
3740         END IF;
3741 
3742          formula_orgn_count_cursor := formula_orgn_count_cursor
3743                    ||'   AND ( '
3744                    ||'       ( fmd.line_type = -1 AND '
3745                    ||'         gia.consum_ind = 1 ) '
3746                    ||'     OR '
3747                    ||'       ( fmd.line_type IN (1,2) AND '
3748                    ||'         gia.replen_ind = 1 ) '
3749                    ||'       ) '
3750                    ||' GROUP BY fmd.formula_id, gia.plant_code, '
3751                    ||'          gia.organization_id, 0 '
3752                    ||' ORDER BY fmd.formula_id, gia.plant_code, '
3753                    ||'          gia.organization_id ' ;
3754 
3755        -- Get counts for the formulae
3756        formula_dtl_count_cursor :=
3757                      ' SELECT fmd.formula_id, count(*) '
3758                    ||' FROM  fm_matl_dtl'||at_apps_link||' fmd, '
3759                    ||'       fm_form_mst'||at_apps_link||' ffm '
3760                    ||' WHERE ffm.formula_id = fmd.formula_id '
3761                    ||'   AND ffm.delete_mark = 0 '
3762                    ||'   AND fmd.qty <> 0 '   /* 2362810 Voltek Fix */
3763                    ||' GROUP BY fmd.formula_id '
3764                    ||' ORDER BY fmd.formula_id ' ;
3765 
3766     OPEN cur_formula_orgn_count FOR formula_orgn_count_cursor;
3767     LOOP
3768     FETCH cur_formula_orgn_count INTO formula_orgn_count_tab(formula_orgn_size);
3769     EXIT WHEN cur_formula_orgn_count%NOTFOUND;
3770 
3771     formula_orgn_size := formula_orgn_size + 1 ;
3772     END LOOP;
3773     CLOSE cur_formula_orgn_count;
3774     formula_orgn_size := formula_orgn_size -1 ;
3775     time_stamp ;
3776     log_message('Formula Orgn size is = ' || to_char(formula_orgn_size)) ;
3777 
3778     OPEN c_formula_dtl_count FOR formula_dtl_count_cursor ;
3779     FETCH c_formula_dtl_count INTO formula_dtl_count_rec ;
3780      WHILE c_formula_dtl_count%FOUND
3781      LOOP
3782 
3783        FOR i IN fm_dtl_orgn_cnt..formula_orgn_size
3784        LOOP
3785         IF formula_dtl_count_rec.formula_id =
3786                       formula_orgn_count_tab(i).formula_id THEN
3787 
3788              IF formula_dtl_count_rec.formula_dtl_count =
3789                       formula_orgn_count_tab(i).orgn_count THEN
3790                  formula_orgn_count_tab(i).valid_flag := 1 ;
3791              ELSE
3792                  formula_orgn_count_tab(i).valid_flag := -1 ;
3793              END IF ;
3794 
3795         ELSIF formula_dtl_count_rec.formula_id <
3796                  formula_orgn_count_tab(i).formula_id THEN
3797                  fm_dtl_orgn_cnt := i ;
3798               EXIT ;
3799 
3800         /*  ELSE NULL ;  */
3801         END IF ;
3802        END LOOP ;
3803 
3804      /* Get the next record */
3805      FETCH c_formula_dtl_count INTO formula_dtl_count_rec ;
3806      END LOOP ;
3807      CLOSE c_formula_dtl_count ;
3808      --   gmp_putline(' End of validate_formula_for_org ','a');
3809 
3810 END validate_formula_for_orgn;
3811 
3812 /*
3813 REM+=========================================================================+
3814 REM| FUNCTION NAME                                                           |
3815 REM|    check_formula                                                        |
3816 REM| DESCRIPTION                                                             |
3817 REM|                                                                         |
3818 REM| HISTORY                                                                 |
3819 REM| 07/14/2002   Rajesh Patangya - Reorgnized the complete code B2314052    |
3820 REM+=========================================================================+
3821 */
3822 FUNCTION check_formula ( pplant_code IN VARCHAR2,
3823                          porganization_id IN NUMBER,
3824                          pformula_id IN NUMBER) return BOOLEAN IS
3825 
3826 i                 INTEGER ;
3827 p_plant_code      VARCHAR2(4) ;
3828 p_organization_id NUMBER ;
3829 p_formula_id      NUMBER ;
3830 
3831 BEGIN
3832 p_plant_code      := pplant_code;
3833 p_organization_id := porganization_id;
3834 p_formula_id      := pformula_id;
3835 
3836 FOR i in g_fm_hdr_loc..formula_headers_size
3837 LOOP
3838 	IF  formula_header_tab(i).formula_id = pformula_id THEN
3839 	    IF formula_header_tab(i).valid_flag = 1 THEN
3840 		-- Note down formula_header location to be used
3841 		-- while writing the bom
3842 		g_fm_dtl_start_loc := formula_header_tab(i).start_dtl_loc ;
3843 		g_fm_dtl_end_loc := formula_header_tab(i).end_dtl_loc ;
3844 	        IF check_formula_for_organization (p_plant_code ,
3845                                                    p_organization_id ,
3846                                                    p_formula_id) THEN
3847 		  g_fm_hdr_loc := i ;
3848                   return TRUE ;
3849                 ELSE
3850 		  g_fm_hdr_loc := i ;
3851                   return FALSE ;
3852                 END IF;
3853             ELSE
3854 		  g_fm_hdr_loc := i ;
3855 		  /* Bug 4625724-Relocated message here so we do not list
3856 			invalid formulas indep of organization*/
3857 		  log_message('Formula detail not found for formula id = ' ||
3858                  to_char(formula_header_tab(i).formula_id)||' in organization id = '||
3859               		to_char(p_organization_id));
3860                   return FALSE ;
3861 	    END IF ;  /* Header validation */
3862 	ELSIF formula_header_tab(i).formula_id > pformula_id THEN
3863 		g_fm_hdr_loc := i ;
3864 		return FALSE ;
3865         /* ELSE
3866              NULL ;   */
3867 	END IF ;
3868 END LOOP ;
3869 		return FALSE ;
3870 END check_formula ;
3871 
3872 /*
3873 REM+=========================================================================+
3874 REM| FUNCTION NAME                                                           |
3875 REM|    check_formula_for_organization                                       |
3876 REM| DESCRIPTION                                                             |
3877 REM|                                                                         |
3878 REM| HISTORY                                                                 |
3879 REM| 07/14/2002   Rajesh Patangya - Reorgnized the complete code B2314052    |
3880 REM+=========================================================================+
3881 */
3882 FUNCTION check_formula_for_organization (
3883                          pplant_code IN VARCHAR2,
3884                          porganization_id IN NUMBER,
3885                          pformula_id IN NUMBER) return BOOLEAN IS
3886 i            INTEGER ;
3887 BEGIN
3888 i            := 1  ;
3889 FOR i IN g_formula_orgn_count_tab..formula_orgn_count_tab.COUNT
3890 LOOP
3891   IF formula_orgn_count_tab(i).formula_id = pformula_id THEN
3892 
3893     IF formula_orgn_count_tab(i).plant_code = pplant_code THEN
3894         IF formula_orgn_count_tab(i).organization_id = porganization_id THEN
3895           IF formula_orgn_count_tab(i).valid_flag = 1 THEN
3896              g_formula_orgn_count_tab := i ;
3897              return TRUE ;
3898           ELSE
3899              g_formula_orgn_count_tab := i ;
3900              return FALSE ;
3901           END IF;
3902         ELSIF formula_orgn_count_tab(i).organization_id > porganization_id THEN
3903              g_formula_orgn_count_tab := i ;
3904              return FALSE ;
3905            /* ELSE
3906                  NULL ;  */
3907         END IF;  /* Organizatin ID */
3908     ELSIF formula_orgn_count_tab(i).plant_code >  pplant_code THEN
3909              g_formula_orgn_count_tab := i ;
3910              return FALSE ;
3911     /* ELSE
3912         NULL ;  */
3913     END IF ;   /* For Plant code  */
3914   ELSIF formula_orgn_count_tab(i).formula_id > pformula_id THEN
3915            g_formula_orgn_count_tab := i ;
3916            return FALSE ;
3917   /* ELSE
3918     NULL ;  */
3919   END IF;
3920 END LOOP ;
3921    return FALSE ;
3922 END check_formula_for_organization ;
3923 
3924 /*
3925 REM+=========================================================================+
3926 REM| FUNCTION NAME                                                           |
3927 REM|    bsearch_routing                                                      |
3928 REM| DESCRIPTION                                                             |
3929 REM|                                                                         |
3930 REM| HISTORY                                                                 |
3931 REM| 07/14/2002   Rajesh Patangya - Reorgnized the complete code B2314052    |
3932 REM+=========================================================================+
3933 */
3934 FUNCTION bsearch_routing (p_routing_id IN NUMBER ,
3935 			  p_plant_code IN VARCHAR2)
3936 			RETURN INTEGER IS
3937 
3938 top     INTEGER ;
3939 bottom  INTEGER ;
3940 mid     INTEGER ;
3941 
3942 BEGIN
3943      top    := 1;
3944      bottom := routing_headers_size ;
3945      mid    := -1 ;
3946    WHILE  (top <= bottom )
3947     LOOP
3948      mid := top + ( ( bottom - top ) / 2 );
3949 
3950      IF p_routing_id < rtg_org_hdr_tab(mid).routing_id OR
3951   	(p_routing_id = rtg_org_hdr_tab(mid).routing_id AND
3952 	 p_plant_code < rtg_org_hdr_tab(mid).plant_code ) THEN
3953 	bottom := mid -1 ;
3954      ELSIF
3955 	p_routing_id > rtg_org_hdr_tab(mid).routing_id OR
3956         (p_routing_id = rtg_org_hdr_tab(mid).routing_id AND
3957          p_plant_code > rtg_org_hdr_tab(mid).plant_code ) THEN
3958 	top := mid + 1 ;
3959      ELSE
3960 	-- We can do the checking for the validity etc here
3961 	-- OR just return the location to calling function and
3962 	-- let the calling function do rest of the work
3963 	RETURN mid ;
3964      END IF ;
3965     END LOOP;
3966     -- Not found
3967     Return -1 ;
3968 END bsearch_routing ;
3969 /*
3970 REM+=========================================================================+
3971 REM| FUNCTION NAME                                                           |
3972 REM|    bsearch_setupid  SGIDUGU                                             |
3973 REM| DESCRIPTION                                                             |
3974 REM|                                                                         |
3975 REM| HISTORY                                                                 |
3976 REM+=========================================================================+
3977 */
3978 FUNCTION bsearch_setupid (p_oprn_id       IN NUMBER ,
3979                           p_category_id   IN NUMBER
3980                          ) RETURN INTEGER IS
3981 --
3982 top     INTEGER ;
3983 bottom  INTEGER ;
3984 mid     INTEGER ;
3985 
3986 BEGIN
3987 --
3988      top    := 1;
3989      bottom := setup_size ;
3990      mid    := -1 ;
3991 --
3992    WHILE  (top <= bottom )
3993     LOOP
3994      mid := top + ( ( bottom - top ) / 2 );
3995 
3996      IF p_oprn_id < setupid_tab(mid).oprn_id OR
3997   	(p_oprn_id = setupid_tab(mid).oprn_id AND
3998 	 p_category_id < setupid_tab(mid).category_id ) THEN
3999 	bottom := mid -1 ;
4000      ELSIF
4001 	p_oprn_id > setupid_tab(mid).oprn_id OR
4002         (p_oprn_id = setupid_tab(mid).oprn_id AND
4003          p_category_id > setupid_tab(mid).category_id ) THEN
4004 	top := mid + 1 ;
4005      ELSE
4006 --	RETURN mid ;
4007 	RETURN setupid_tab(mid).seq_dep_id ;
4008      END IF ;
4009     END LOOP;
4010     -- Not found
4011     Return -1 ;
4012 END bsearch_setupid ;
4013 /*
4014 REM+=========================================================================+
4015 REM| PROCEDURE NAME                                                          |
4016 REM|    write_process_effectivities                                          |
4017 REM|                                                                         |
4018 REM| TYPE                                                                    |
4019 REM|    Private                                                              |
4020 REM|                                                                         |
4021 REM| USAGE                                                                   |
4022 REM|    This procedure creates the effectivty rows in gmp_form_eff and       |
4023 REM|    msc_process_effectivities                                            |
4024 REM|                                                                         |
4025 REM| DESCRIPTION                                                             |
4026 REM|                                                                         |
4027 REM|                                                                         |
4028 REM| INPUT PARAMETERS                                                        |
4029 REM|    None                                                                 |
4030 REM|                                                                         |
4031 REM| OUTPUT PARAMETERS                                                       |
4032 REM|    return_status    TRUE => OK                                          |
4033 REM|                                                                         |
4034 REM| INPUT/OUTPUT PARAMETERS                                                 |
4035 REM|    None                                                                 |
4036 REM|                                                                         |
4037 REM| HISTORY                                                                 |
4038 REM|  07/14/2002   Rajesh Patangya - Reorgnized the complete code B2314052   |
4039 REM|  06/02/2003   Sridhar Gidugu  Checked aps_fmeff_id before               |
4040 REM|                               inserts - B2989806                        |
4041 REM+=========================================================================+
4042 */
4043 PROCEDURE write_process_effectivity
4044 (
4045   p_x_aps_fmeff_id   IN NUMBER,
4046   p_aps_fmeff_id     IN NUMBER,
4047   return_status      OUT NOCOPY BOOLEAN
4048 )
4049 IS
4050   statement_form_eff     VARCHAR2(32700) ;
4051   loop_index       INTEGER;
4052   routing_id       NUMBER ;
4053 
4054 BEGIN
4055   statement_form_eff     := NULL ;
4056 
4057 /* B2989806  Added IF condition below */
4058 IF effectivity.aps_fmeff_id = -1 THEN
4059     statement_form_eff :=
4060 	          'INSERT INTO gmp_form_eff'||at_apps_link
4061 		   ||' ( '
4062 		   ||'  aps_fmeff_id,whse_code,plant_code,fmeff_id, '
4063                    ||'  formula_id, routing_id, '
4064 		   ||'  creation_date, created_by, last_update_date, '
4065                    ||'  last_updated_by '
4066 		   ||' ) '
4067 		   ||' VALUES '
4068 		   ||' ( :p1,:p2,:p3,:p4,:p5,:p6,:p7,:p8,:p9,:p10)';
4069 
4070              /* This aps_fmeff_id the next sequence ID, but not multiplied by
4071                 2 and added by 1 */
4072     EXECUTE IMMEDIATE statement_form_eff USING
4073 		   p_aps_fmeff_id,
4074 		   effectivity.whse_code,
4075 		   effectivity.plant_code,
4076 		   effectivity.fmeff_id,
4077 		   effectivity.formula_id,
4078 		   effectivity.routing_id,
4079 		   current_date_time,
4080 		   0,
4081 		   current_date_time,
4082 		   0;
4083 END IF ; /* New effectivity row to be created */
4084 
4085         /* Process Effectivity Bulk Insert assignment */
4086 
4087            pef_index := pef_index + 1 ;
4088            pef_process_sequence_id(pef_index) :=   p_x_aps_fmeff_id ;
4089            pef_item_id(pef_index) :=  effectivity.aps_item_id ;   /* aps_item_id */
4090            pef_organization_id(pef_index) :=  effectivity.organization_id ;
4091            pef_effectivity_date(pef_index) :=  effectivity.start_date ;
4092 
4093            IF effectivity.end_date IS NOT NULL THEN
4094                 pef_disable_date(pef_index) :=  effectivity.end_date ;
4095            ELSE
4096                 pef_disable_date(pef_index) := null_value ;
4097            END IF;
4098 
4099            pef_minimum_quantity(pef_index) :=  effectivity.inv_min_qty ;
4100            pef_maximum_quantity(pef_index) :=  effectivity.inv_max_qty ;
4101            pef_preference(pef_index)       :=  effectivity.preference ;
4102            pef_routing_sequence_id(pef_index) :=  p_x_aps_fmeff_id ;
4103            pef_bill_sequence_id(pef_index)    :=  p_x_aps_fmeff_id ;
4104            pef_sr_instance_id(pef_index) :=  b_instance_id ;
4105            -- pef_deleted_flag(pef_index)     := 2;
4106            pef_last_update_date(pef_index) := current_date_time ;
4107            -- bom_last_updated_by(pef_index)  := 0 ;
4108            pef_creation_date(pef_index)    := current_date_time ;
4109            -- pef_created_by(pef_index)       := 0;
4110 
4111   return_status := TRUE;
4112 
4113   EXCEPTION
4114     WHEN OTHERS THEN
4115        log_message('Write Process Effectivity Raised Exception: '||sqlerrm);
4116        log_message(to_char(effectivity.fmeff_id));
4117        return_status := FALSE;
4118 END write_process_effectivity;
4119 
4120 /*
4121 REM+=========================================================================+
4122 REM| PROCEDURE NAME                                                          |
4123 REM|    write_bom_components                                                 |
4124 REM|                                                                         |
4125 REM| TYPE                                                                    |
4126 REM|    Private                                                              |
4127 REM|                                                                         |
4128 REM| USAGE                                                                   |
4129 REM|    This procedure creates the bill of material components in msc_boms   |
4130 REM|                                                                         |
4131 REM| DESCRIPTION                                                             |
4132 REM|                                                                         |
4133 REM|                                                                         |
4134 REM| INPUT PARAMETERS                                                        |
4135 REM|    None                                                                 |
4136 REM|                                                                         |
4137 REM| OUTPUT PARAMETERS                                                       |
4138 REM|    return_status    TRUE => OK                                          |
4139 REM|                                                                         |
4140 REM| INPUT/OUTPUT PARAMETERS                                                 |
4141 REM|    None                                                                 |
4142 REM|                                                                         |
4143 REM| HISTORY                                                                 |
4144 REM|  07/14/2002   Rajesh Patangya - Reorgnized the complete code B2314052   |
4145 REM|  08/27/2002 - B2098058 Alternate_bomdesignator is being passed          |
4146 REM|               as the eff_id because 1. Alt_rtg_desgn is now required    |
4147 REM|               per explanation in the bug 2.alt_rtg_desgn should be same |
4148 REM|               alt_bom_desgn for the bom in the same eff 3.OPM has       |
4149 REM|               has no way to determine primary bom/rtg from alternate    |
4150 REM|                                                                         |
4151 REM+=========================================================================+
4152 */
4153 PROCEDURE write_bom_components
4154 (
4155   p_x_aps_fmeff_id   IN NUMBER,
4156   return_status      OUT NOCOPY BOOLEAN
4157 )
4158 IS
4159   temp_assembly_comment   VARCHAR2(240) ;
4160   primary_bom_written     NUMBER ;
4161   p_primary_qty           NUMBER ;
4162   loop_index              INTEGER;
4163   l_scale_type            INTEGER;
4164   l_offset_loc            NUMBER ;
4165   l_offset           	  NUMBER ;
4166   l_line_type 		  INTEGER;
4167   rtgstpno_loc            NUMBER;
4168 BEGIN
4169   temp_assembly_comment   := NULL ;
4170   p_primary_qty           := 0 ;
4171   l_offset_loc            := 0 ;
4172   l_offset           	  := 0 ;
4173   l_line_type 		  := 0 ;
4174 
4175 
4176   rtgstpno_loc := -1;
4177   primary_bom_written := 0 ;
4178 
4179   -- ABHAY write the code to get the offset percentages here.
4180   -- The code will loop through the formula_detail_tab  from
4181   -- g_fm_dtl_start_loc to g_fm_dtl_end_loc and update the field offset
4182   FOR loop_index IN g_fm_dtl_start_loc..g_fm_dtl_end_loc
4183   LOOP
4184 
4185      /* Do write a row for the primary produc */
4186 
4187    IF (effectivity.item_id = formula_detail_tab(loop_index).opm_item_id) AND
4188       (formula_detail_tab(loop_index).line_type = 1)  THEN
4189       IF primary_bom_written = 0 THEN
4190          /* WRITE_BOM : Do write a row for the primary product   */
4191         BEGIN
4192         /*B2870041 save the index of the product it will be used when writing
4193            the route and its details */
4194         effectivity.product_index := loop_index;
4195 
4196         temp_assembly_comment :=
4197 	 formula_detail_tab(loop_index).formula_no ||delimiter||
4198 	 to_char(formula_detail_tab(loop_index).formula_vers) ||delimiter||
4199 	 formula_detail_tab(loop_index).formula_desc1 ;
4200 
4201          /* BOM Bulk Insert assignments */
4202 
4203          bom_index := bom_index + 1 ;
4204          bom_bill_sequence_id(bom_index) := p_x_aps_fmeff_id ;
4205          bom_sr_instance_id(bom_index)   := b_instance_id ;
4206          bom_organization_id(bom_index)  := effectivity.organization_id ;
4207          bom_assembly_item_id(bom_index) := effectivity.aps_item_id ;
4208          -- bom_assembly_type(bom_index)    := 1 ;
4209          bom_alternate_bom_designator(bom_index)  := p_x_aps_fmeff_id ;
4210          bom_specific_assembly_comment(bom_index) :=  temp_assembly_comment ;
4211          bom_scaling_type(bom_index)    :=
4212                              formula_detail_tab(loop_index).bom_scale_type ;
4213          bom_assembly_quantity(bom_index)  :=
4214                             formula_detail_tab(loop_index).primary_qty ;
4215          bom_uom(bom_index)  := formula_detail_tab(loop_index).aps_um ;
4216 /* NAMIT_CR For Step Material Assoc */
4217 /* Used enhanced binary search to get the location for routing
4218     step number of product. */
4219 
4220             rtgstpno_loc :=
4221                enh_bsearch_stpno (effectivity.formula_id, effectivity.recipe_id,
4222                   effectivity.item_id);
4223 
4224 --
4225 
4226             IF(rtgstpno_loc > 0) THEN
4227                bom_op_seq_number(bom_index) := mat_assoc_tab(rtgstpno_loc).routingstep_no;
4228             ELSE
4229                 bom_op_seq_number(bom_index) := null_value ;
4230             END IF;
4231 
4232 --         bom_op_seq_number(bom_index) := formula_detail_tab(loop_index).routingstep_no;
4233 
4234          -- bom_deleted_flag(bom_index)     := 2;
4235          bom_last_update_date(bom_index) := current_date_time ;
4236          -- bom_last_updated_by(bom_index)  := 0 ;
4237          bom_creation_date(bom_index)    := current_date_time ;
4238          -- bom_created_by(bom_index)       := 0;
4239 
4240          EXCEPTION
4241               WHEN OTHERS THEN
4242               log_message('Error writing to msc_st_boms: '||sqlerrm);
4243               /* B3837959 MMK Issue, set return status to false */
4244               return_status := FALSE;
4245          END;
4246           primary_bom_written := 1 ;
4247 --          primary_bom_formulaline_id := formula_detail_tab(loop_index).x_formulaline_id; -- Bug # 4879588
4248       -- 01/17/2003 Rajesh Patangya B2740767
4249       ELSE      /* Primary BOM written */
4250            /* Primary product written and now co-prod is same as prod
4251               note that the co-products always contribute to yield and
4252               scale type can only be fixed or linear per restrictions in GMD
4253            */
4254 	-- Now get the offset percentage
4255 	-- -------------------------------
4256 	IF g_curr_rstep_loc > 0  AND
4257 	(formula_detail_tab(loop_index).release_type between  1 AND 3)
4258 	THEN
4259 	 l_offset_loc := get_offsets( effectivity.formula_id,
4260 				effectivity.plant_code,
4261 		formula_detail_tab(loop_index).x_formulaline_id ) ;
4262 	 IF l_offset_loc < 0 THEN
4263           IF formula_detail_tab(loop_index).line_type < 0 THEN
4264                 l_offset := 0 ;
4265           ELSE
4266                 l_offset := 100 ;
4267           END IF ;
4268 	 ELSE
4269           IF formula_detail_tab(loop_index).line_type < 0 THEN
4270                 l_offset := rstep_offsets(l_offset_loc).start_offset ;
4271           ELSE
4272                 l_offset := rstep_offsets(l_offset_loc).end_offset ;
4273           END IF ;
4274 
4275 	 END IF ;
4276 	ELSE
4277 	  IF formula_detail_tab(loop_index).line_type < 0 THEN
4278 		l_offset := 0 ;
4279 	  ELSE
4280 		l_offset := 100 ;
4281 	  END IF ;
4282 	END IF ;
4283 	-- -------------------------------
4284 
4285          BEGIN   /* co-product */
4286          /* BOM Component Bulk Insert assignments */
4287          bomc_index := bomc_index + 1 ;
4288          bomc_component_sequence_id(bomc_index) := formula_detail_tab(loop_index).x_formulaline_id ;
4289          bomc_sr_instance_id(bomc_index)   := b_instance_id ;
4290          bomc_organization_id(bomc_index)  := effectivity.organization_id ;
4291          bomc_Inventory_item_id(bomc_index) := formula_detail_tab(loop_index).aps_item_id ;
4292          bomc_using_assembly_id(bomc_index) := effectivity.aps_item_id ;
4293          bomc_bill_sequence_id(bomc_index) := p_x_aps_fmeff_id ;
4294          bomc_component_type(bomc_index) := 10 ;  /* for co-proudcts */
4295          bomc_scaling_type(bomc_index) := l_scale_type; /* Scailing type for APS */
4296            -- bomc_change_notice(i)  == null
4297            -- bomc_revision(i),  == null
4298          bomc_uom_code(bomc_index) := formula_detail_tab(loop_index).aps_um ;
4299          bomc_usage_quantity(bomc_index) :=  (-1 * formula_detail_tab(loop_index).primary_qty) ;
4300          bomc_effectivity_date(bomc_index) := current_date_time ;
4301          bomc_contribute_to_step_qty(bomc_index) := formula_detail_tab(loop_index).contribute_step_qty_ind;
4302          bomc_disable_date(bomc_index) := null_value ;
4303            -- bomc_from_unit_number := null_value,
4304            -- bomc_to_unit_number := null_value,
4305            -- bomc_use_up_code := null_value,
4306            -- bomc_suggested_effectivity_date := null_value,
4307            -- bomc_driving_item_id := null_value,
4308          IF l_offset IS NOT NULL THEN
4309            bomc_opr_offset_percent(bomc_index) := l_offset; /* offset percentage */
4310          ELSE
4311            bomc_opr_offset_percent(bomc_index) := null_value ;
4312          END IF;
4313 
4314          bomc_optional_component(bomc_index) := 2 ;
4315            -- bomc_old_effectivity_date := null_value,
4316          bomc_wip_supply_type(bomc_index) := formula_detail_tab(loop_index).phantom_type ;
4317            -- bomc_planning_factor := null_value,
4318            -- bomc_atp_flag := 1,
4319            -- bomc_component_yield_factor := 1,
4320            -- deleted_flag := 2,
4321          bomc_last_update_date(bomc_index) := current_date_time ;
4322            -- bomc_last_updated_by(bomc_index)  := 0 ;
4323          bomc_creation_date(bomc_index)    := current_date_time ;
4324            -- bomc_created_by(bomc_index)       := 0;
4325          IF  formula_detail_tab(loop_index).scale_multiple IS NOT NULL THEN
4326            bomc_scale_multiple(bomc_index) := formula_detail_tab(loop_index).scale_multiple ;
4327          ELSE
4328            bomc_scale_multiple(bomc_index) := null_value;
4329          END IF;
4330          IF formula_detail_tab(loop_index).scale_rounding_variance IS NOT NULL THEN
4331            bomc_scale_rounding_variance(bomc_index) :=
4332                      formula_detail_tab(loop_index).scale_rounding_variance ;
4333          ELSE
4334            bomc_scale_rounding_variance(bomc_index) := null_value;
4335          END IF;
4336          IF formula_detail_tab(loop_index).rounding_direction IS NOT NULL THEN
4337            bomc_rounding_direction(bomc_index) :=
4338                          formula_detail_tab(loop_index).rounding_direction ;
4339          ELSE
4340            bomc_rounding_direction(bomc_index) := null_value ;
4341          END IF;
4342 
4343          EXCEPTION
4344               WHEN OTHERS THEN
4345               log_message('Error co-products to msc_st_bom_comp: '||sqlerrm);
4346               /* B3837959 MMK Issue, set return status to false */
4347               return_status := FALSE;
4348          END ;   /* co-product */
4349 
4350       END IF ;  /* Primary BOM written */
4351 
4352    ELSE
4353 
4354      /* Do write all formula detail lines except primary product */
4355        IF formula_detail_tab(loop_index).line_type = -1 THEN
4356            p_primary_qty := formula_detail_tab(loop_index).primary_qty;
4357            /* B2559881, scrap_factor introduced */
4358            p_primary_qty := p_primary_qty *
4359             (1 + nvl(formula_detail_tab(loop_index).scrap_factor,0));
4360        ELSE
4361            p_primary_qty := (-1) * formula_detail_tab(loop_index).primary_qty;
4362            /* B2559881, scrap_factor introduced */
4363            p_primary_qty := p_primary_qty *
4364             (1 + nvl(formula_detail_tab(loop_index).scrap_factor,0));
4365        END IF;
4366 
4367        /* B3452524, If co-prodcut or by product is not same as product then
4368           component type should be 10 */
4369 
4370 	IF formula_detail_tab(loop_index).line_type = 1 THEN
4371 	  l_line_type := 10 ;
4372 	ELSE
4373 	  l_line_type := formula_detail_tab(loop_index).line_type ;
4374 	END IF ;
4375 
4376 
4377     /* B2657068 Scailing type decision Rajesh Patangya */
4378     /*  Scale type in material detail 0-Fixed, 1-proportional 2-Integer */
4379 
4380     IF formula_detail_tab(loop_index).contribute_yield_ind = 'Y' THEN
4381        IF formula_detail_tab(loop_index).scale_type = 0 THEN
4382           l_scale_type := 0 ;
4383        ELSIF formula_detail_tab(loop_index).scale_type = 1 THEN
4384           l_scale_type := 1 ;
4385        ELSIF  formula_detail_tab(loop_index).scale_type = 2 THEN
4386           l_scale_type := 4 ;
4387        ELSE
4388          /* scale type of other than 0,1,2 is not supported */
4389          l_scale_type := formula_detail_tab(loop_index).scale_type ;
4390        END IF ;
4391     ELSE
4392        IF formula_detail_tab(loop_index).scale_type = 0 THEN
4393           l_scale_type := 2 ;
4394        ELSIF formula_detail_tab(loop_index).scale_type = 1 THEN
4395           l_scale_type := 3 ;
4396        ELSIF  formula_detail_tab(loop_index).scale_type = 2 THEN
4397           l_scale_type := 5 ;
4398        ELSE
4399          /* scale type of other than 0,1,2 is not supported */
4400          l_scale_type := formula_detail_tab(loop_index).scale_type ;
4401        END IF ;
4402     END IF ;           /* IF contribute_yield_ind */
4403 	-- Now get the offsets
4404 	-- -------------------------------
4405 	IF g_curr_rstep_loc > 0  AND
4406 	(formula_detail_tab(loop_index).release_type between 1 AND 3)
4407 	THEN
4408 	 l_offset_loc := get_offsets( effectivity.formula_id,
4409 				effectivity.plant_code,
4410 		formula_detail_tab(loop_index).x_formulaline_id ) ;
4411 	 IF l_offset_loc < 0 THEN
4412           IF formula_detail_tab(loop_index).line_type < 0 THEN
4413                 l_offset := 0 ;
4414           ELSE
4415                 l_offset := 100 ;
4416           END IF ;
4417 	 ELSE
4418           IF formula_detail_tab(loop_index).line_type < 0 THEN
4419                 l_offset := rstep_offsets(l_offset_loc).start_offset ;
4420           ELSE
4421                 l_offset := rstep_offsets(l_offset_loc).end_offset ;
4422           END IF ;
4423 
4424 	 END IF ;
4425 	ELSE
4426 	  IF formula_detail_tab(loop_index).line_type < 0 THEN
4427 		l_offset := 0 ;
4428 	  ELSE
4429 		l_offset := 100 ;
4430 	  END IF ;
4431 	END IF ;
4432 	-- -----------------------------------
4433 
4434    /* B3267522, Rajesh Patangya Do not insert ingredients, if ingredient is same
4435       as product (single level circular reference) */
4436 
4437     IF (effectivity.aps_item_id = formula_detail_tab(loop_index).aps_item_id) AND
4438       (formula_detail_tab(loop_index).line_type = -1)  THEN
4439       NULL ;
4440     ELSE
4441          /* BOM Component Bulk Insert assignments */
4442          bomc_index := bomc_index + 1 ;
4443 
4444          /*Sowmya - Item substitution - start*/
4445          IF formula_detail_tab(loop_index).x_formulaline_id IS NOT NULL THEN
4446                 bomc_component_sequence_id(bomc_index) := formula_detail_tab(loop_index).x_formulaline_id ;
4447          ELSE
4448                 gmd_formline_cnt := gmd_formline_cnt + 1;
4449                 bomc_component_sequence_id(bomc_index) := (( v_gmd_formula_lineid + gmd_formline_cnt ) * 2) + 1;
4450                 /*For sustitutes the formula line id will be null. component sequence id in
4451                 msc_st_bom_components is a primary key. So the max value from gmd formula line sequence
4452                 is fetched and global counter value is added to it.Then odd value is passed on to APS. */
4453          END IF;
4454          /*Sowmya - Item substitution - End*/
4455 
4456          bomc_sr_instance_id(bomc_index)   := b_instance_id ;
4457          bomc_organization_id(bomc_index)  := effectivity.organization_id ;
4458          bomc_Inventory_item_id(bomc_index) := formula_detail_tab(loop_index).aps_item_id ;
4459          -- RDP B2445746, replace component aps_item_id to product aps_item_id
4460          bomc_using_assembly_id(bomc_index) := effectivity.aps_item_id ;
4461          bomc_bill_sequence_id(bomc_index) := p_x_aps_fmeff_id ;
4462          bomc_component_type(bomc_index) := l_line_type ;
4463          bomc_scaling_type(bomc_index) := l_scale_type; /* Scailing type for APS */
4464          bomc_uom_code(bomc_index) := formula_detail_tab(loop_index).aps_um ;
4465          bomc_usage_quantity(bomc_index) :=  p_primary_qty ;
4466          bomc_contribute_to_step_qty(bomc_index) := formula_detail_tab(loop_index).contribute_step_qty_ind;
4467 	-- Rounding off the start date  /* Bug: 5872693 Vpedarla Starts */
4468 	 IF formula_detail_tab(loop_index).start_date IS NULL  THEN
4469            bomc_effectivity_date(bomc_index) := trunc(current_date_time) ;
4470 	 ELSE
4471 	  bomc_effectivity_date(bomc_index) := trunc(formula_detail_tab(loop_index).start_date) ;
4472 	 END IF ;
4473 	 -- Rounding off the end date
4474 	 IF formula_detail_tab(loop_index).end_date IS NULL  THEN
4475            bomc_disable_date(bomc_index) := null_value ;
4476 	 ELSE
4477 	  bomc_disable_date(bomc_index) := trunc(formula_detail_tab(loop_index).end_date) ;
4478 	 END IF ;
4479           /* Bug: 5872693 Vpedarla Ends */
4480            -- bomc_from_unit_number := null_value,
4481            -- bomc_to_unit_number := null_value,
4482            -- bomc_use_up_code := null_value,
4483            -- bomc_suggested_effectivity_date := null_value,
4484            -- bomc_driving_item_id := null_value,
4485          IF l_offset IS NOT NULL THEN
4486            bomc_opr_offset_percent(bomc_index) := l_offset; /* offset percentage */
4487          ELSE
4488            bomc_opr_offset_percent(bomc_index) := null_value ;
4489          END IF;
4490 
4491          bomc_optional_component(bomc_index) := 2 ;
4492            -- bomc_old_effectivity_date := null_value,
4493          bomc_wip_supply_type(bomc_index) := formula_detail_tab(loop_index).phantom_type ;
4494          bomc_last_update_date(bomc_index) := current_date_time ;
4495          bomc_creation_date(bomc_index)    := current_date_time ;
4496          /* B2657068 Rajesh Patangya */
4497          IF  formula_detail_tab(loop_index).scale_multiple IS NOT NULL THEN
4498            bomc_scale_multiple(bomc_index) := formula_detail_tab(loop_index).scale_multiple ;
4499          ELSE
4500            bomc_scale_multiple(bomc_index) := null_value;
4501          END IF;
4502          IF formula_detail_tab(loop_index).scale_rounding_variance IS NOT NULL THEN
4503            bomc_scale_rounding_variance(bomc_index) :=
4504                      formula_detail_tab(loop_index).scale_rounding_variance ;
4505          ELSE
4506            bomc_scale_rounding_variance(bomc_index) := null_value;
4507          END IF;
4508          IF formula_detail_tab(loop_index).rounding_direction IS NOT NULL THEN
4509            bomc_rounding_direction(bomc_index) := formula_detail_tab(loop_index).rounding_direction ;
4510          ELSE
4511            bomc_rounding_direction(bomc_index) := null_value ;
4512          END IF;
4513 
4514     END IF;   /* Circular reference */
4515 
4516    END IF;
4517 
4518   END LOOP;
4519   return_status := TRUE;
4520 
4521   EXCEPTION
4522     WHEN OTHERS THEN
4523 	log_message('Error writing to msc_st_bom_components: '||sqlerrm);
4524 	return_status := FALSE;
4525 END write_bom_components;
4526 
4527 /*
4528 REM+=========================================================================+
4529 REM| PROCEDURE NAME                                                          |
4530 REM|    write_routing                                                        |
4531 REM|                                                                         |
4532 REM| TYPE                                                                    |
4533 REM|    Private                                                              |
4534 REM|                                                                         |
4535 REM| USAGE                                                                   |
4536 REM|    This procedure creates a routing in msc_routings                     |
4537 REM|                                                                         |
4538 REM| DESCRIPTION                                                             |
4539 REM|                                                                         |
4540 REM|                                                                         |
4541 REM| INPUT PARAMETERS                                                        |
4542 REM|    table_index      index into aps_effectivities structure for current  |
4543 REM|                     effectivity.                                        |
4544 REM|                                                                         |
4545 REM| OUTPUT PARAMETERS                                                       |
4546 REM|    return_status    TRUE => OK                                          |
4547 REM|                                                                         |
4548 REM| INPUT/OUTPUT PARAMETERS                                                 |
4549 REM|    None                                                                 |
4550 REM|                                                                         |
4551 REM| HISTORY                                                                 |
4552 REM|  07/14/2002   Rajesh Patangya - Reorgnized the complete code B2314052   |
4553 REM|  08/27/2002   B2098058 Alternate_routing_designator is being passed     |
4554 REM|               as the eff_id because 1. Alt_rtg_desgn is now required    |
4555 REM|               per explanation in the bug 2.alt_rtg_desgn should be same |
4556 REM|               alt_bom_desgn for the bom in the same eff 3.OPM has       |
4557 REM|               has no way to determine primary bom/rtg from alternate    |
4558 REM|                                                                         |
4559 REM+=========================================================================+
4560 */
4561 PROCEDURE write_routing
4562 (
4563   p_x_aps_fmeff_id   IN NUMBER,
4564   return_status      OUT NOCOPY BOOLEAN
4565 )
4566 IS
4567   p_routing_details  VARCHAR2(128) ;
4568   v_routing_qty      NUMBER ;
4569 BEGIN
4570   p_routing_details  := NULL;
4571   v_routing_qty      := 0;
4572   IF effectivity.rtg_hdr_location > 0 AND effectivity.product_index > 0 THEN
4573 
4574     p_routing_details := effectivity.routing_no ||delimiter||
4575                          to_char(effectivity.routing_vers) ||delimiter||
4576                          effectivity.routing_desc ;
4577 
4578     /*B2870041 The routing qty needs to be represented as the product of the
4579        effectivity so APS can scale the route correctly. If the product has
4580        fixed scaling then the route will need to use the full product qty
4581        as the route will not get scaled according to total output in APS.
4582        Otherwise the quantity will be the product qty scaled to match
4583        the total output if represented as the routing qty*/
4584     IF formula_detail_tab(effectivity.product_index).scale_type = 0 THEN
4585       v_routing_qty :=
4586         formula_detail_tab(effectivity.product_index).primary_qty;
4587     ELSE
4588       v_routing_qty := (effectivity.routing_qty /
4589         formula_header_tab(g_fm_hdr_loc).total_output) *
4590         formula_detail_tab(effectivity.product_index).primary_qty;
4591     END IF;
4592 
4593     /* B2870041 report the uom as the primary uom of the product in the discrete
4594       form. The quantity is the scaled version of the product to match the
4595       routing qty as explained previously */
4596 
4597           /* Routing Bulk insert assignments */
4598             rtg_index := rtg_index + 1 ;
4599             rtg_routing_sequence_id(rtg_index) := p_x_aps_fmeff_id ;
4600             rtg_sr_instance_id(rtg_index) := b_instance_id ;
4601               -- rtg_routing_type(rtg_index) := 1 ;
4602             rtg_routing_comment(rtg_index) := p_routing_details ;
4603             rtg_alt_routing_designator(rtg_index) := p_x_aps_fmeff_id ; /* B2098058 */
4604               -- project_id :=  null_value ;
4605               -- task_id :=  null_value ;
4606               -- line_id :=  null_value ;
4607             /*B2870041*/
4608             rtg_uom_code(rtg_index) := formula_detail_tab(effectivity.product_index).aps_um ;
4609               -- cfm_routing_flag := null_value ;
4610               -- ctp_flag := null_value ;
4611             /*B2870041*/
4612             rtg_routing_quantity(rtg_index) := v_routing_qty ;
4613             rtg_assembly_item_id(rtg_index) := effectivity.aps_item_id ;
4614             rtg_organization_id(rtg_index) := effectivity.organization_id ;
4615 /* NAMIT_CR Calculate Step Quantities */
4616             rtg_auto_step_qty_flag(rtg_index) := effectivity.calculate_step_quantity ;
4617 
4618               -- deleted_flag  = 2 ;
4619             rtg_last_update_date(rtg_index) := current_date_time ;
4620             rtg_creation_date(rtg_index) := current_date_time ;
4621 
4622     return_status := TRUE;
4623   ELSE
4624     return_status := FALSE;
4625   END IF ;
4626 
4627 /* NAMIT_CR Write Step Dependency Data. */
4628   write_step_dependency(p_x_aps_fmeff_id);
4629 
4630   EXCEPTION
4631     WHEN OTHERS THEN
4632 	log_message('Error writing to msc_st_routings: '||sqlerrm);
4633 	return_status := FALSE;
4634 END write_routing;
4635 
4636 /*
4637 REM+=========================================================================+
4638 REM| PROCEDURE NAME                                                          |
4639 REM|    write_routing_operations                                             |
4640 REM|                                                                         |
4641 REM| TYPE                                                                    |
4642 REM|    Private                                                              |
4643 REM|                                                                         |
4644 REM| DESCRIPTION                                                             |
4645 REM|    This procedure writes operation/resource/activity details to the MSC |
4646 REM|    tables and also caters for alternate resources.                      |
4647 REM|                                                                         |
4648 REM| INPUT PARAMETERS                                                        |
4649 REM|    table_index: index of APS effectivity in aps_effectivities           |
4650 REM|                                                                         |
4651 REM| OUTPUT PARAMETERS                                                       |
4652 REM|    return_status  TRUE=> OK                                             |
4653 REM|                                                                         |
4654 REM| INPUT/OUTPUT PARAMETERS                                                 |
4655 REM|    None                                                                 |
4656 REM|                                                                         |
4657 REM| HISTORY                                                                 |
4658 REM|  07/14/2002   Rajesh Patangya - Reorgnized the complete code B2314052   |
4659 REM|  12/12/2002   Abhay Satpute   - Resource Load Changes Bug# 2710139      |
4660 REM|  01/22/2003   Rajesh Patangya - Resource Unit = resource_count B2761278 |
4661 REM|  05/23/2003   Sridhar Gidugu  - Populating Activity Group Id using      |
4662 REM|                                 Resource Id bug#2975261                 |
4663 REM+=========================================================================+
4664 */
4665 PROCEDURE write_routing_operations
4666 (
4667   p_x_aps_fmeff_id   IN NUMBER,
4668   return_status      OUT NOCOPY BOOLEAN
4669 )
4670 IS
4671 
4672   start_index          INTEGER;
4673   end_index            INTEGER;
4674   loop_index           INTEGER;
4675   k                    INTEGER ;
4676   alt_cnt              INTEGER ;
4677   previous_id          NUMBER     ;
4678   previous_activity    NUMBER ;
4679   seq_no               INTEGER ;
4680   statement_no         INTEGER ;
4681   v_counter            INTEGER ;
4682   alternates_inserted  VARCHAR2(1);
4683   v_alternate          NUMBER ;
4684   t_scale_type         NUMBER ;
4685 
4686   f_step_qty             NUMBER ;
4687   f_resource_usage       NUMBER ;
4688   f_activity_factor      NUMBER ;
4689   f_process_qty          NUMBER ;
4690   f_min_capacity         NUMBER ;
4691   f_max_capacity         NUMBER ;
4692 
4693   calculated_resource_usage NUMBER ;
4694 
4695   prod_scale_factor      NUMBER ; /*B2870041 contains factor to scale usage */
4696   l_prod_scale_factor    NUMBER ;
4697   temp_min_xfer_qty      NUMBER ; /*B2870041*/
4698 
4699    l_seq_dep_class     VARCHAR2(8);
4700    orig_rs_seq_num     NUMBER ;
4701    u_setup_id          NUMBER ;
4702 
4703    oprn_found 		BOOLEAN ;
4704 BEGIN
4705   k                    := 0;
4706   alt_cnt              := 0;
4707   previous_id          := 0;
4708   previous_activity    := -1;
4709   seq_no               := 1;
4710   statement_no         := 0;
4711   v_counter            := 0;
4712   alternates_inserted   := 'N';
4713   v_alternate          := 0;
4714   t_scale_type         := -1;
4715   f_step_qty             := 0;
4716   f_resource_usage       := 0;
4717   f_activity_factor      := 0;
4718   f_process_qty          := 0;
4719   f_min_capacity         := 0;
4720   f_max_capacity         := 999999;
4721   calculated_resource_usage := 0;
4722   prod_scale_factor      := 1;
4723   l_prod_scale_factor    := 1;
4724   temp_min_xfer_qty      := 0;
4725    orig_rs_seq_num      := 0;
4726    oprn_found 		:= FALSE ;
4727 
4728 
4729   statement_no := 0 ;
4730 
4731   start_index := rtg_org_hdr_tab(effectivity.rtg_hdr_location).orgn_start_loc ;
4732   end_index :=  rtg_org_hdr_tab(effectivity.rtg_hdr_location).orgn_end_loc ;
4733 
4734 --
4735   /*B2870041 If the product has fixed scaling the route will need to be scaled
4736      to match the total output not the product. If the product is linear
4737      then the route can be scaled in APS. The routing qty in the route header
4738      was modified to match the original routing qty. The product qty
4739       was scaled to match that value, thus the factor will always be 1 */
4740 
4741   statement_no := 10 ;
4742   /* B3145206, No matter what scale type it is, factor needs to be calculated */
4743     l_prod_scale_factor := formula_header_tab(g_fm_hdr_loc).total_output/
4744         effectivity.routing_qty;
4745   IF formula_detail_tab(effectivity.product_index).scale_type = 0 THEN
4746  	prod_scale_factor := l_prod_scale_factor ;
4747   ELSE
4748     	prod_scale_factor := 1;
4749   END IF;
4750 
4751   IF (start_index > 0) AND (end_index > 0) THEN
4752 
4753   FOR loop_index IN start_index..end_index
4754   LOOP
4755   /* Write only non Do Not Plan rows and rows in which usage UOM
4756   and GMP UOM for Hours profile have Time as base UOM class. */
4757   IF (rtg_org_dtl_tab(loop_index).include_rtg_row = 1) THEN
4758     t_scale_type  := rtg_org_dtl_tab(loop_index).rtg_scale_type ;
4759 
4760     -- Routing Step insertion
4761     IF rtg_org_dtl_tab(loop_index).routingstep_id <> previous_id THEN
4762 
4763 -- Note that this code differs from R12 code -
4764      IF  rtg_org_dtl_tab(loop_index).step_qty = 0 THEN
4765        temp_min_xfer_qty := 0 ;
4766      ELSE
4767     -- in R12 the code
4768     -- temp_min_xfer_qty :=  rtg_org_dtl_tab(loop_index).minimum_transfer_qty ;
4769      temp_min_xfer_qty := (effectivity.routing_qty *
4770        formula_detail_tab(effectivity.product_index).primary_qty *
4771        rtg_org_dtl_tab(loop_index).minimum_transfer_qty) /
4772        (formula_header_tab(g_fm_hdr_loc).total_output *
4773         rtg_org_dtl_tab(loop_index).step_qty);
4774      END IF;
4775 
4776      /*B2870041 the mtq quantity needs to be represented as a value based on the
4777         product not the step qty. Since a formula can have multiple products
4778         in different effectivities the calculation will use the relationhip
4779         of the mtq based on the step qty as applied to the product */
4780 
4781 
4782   statement_no := 20 ;
4783     -- Routing Step Bulk insert assignments
4784        opr_index := opr_index + 1 ;
4785        opr_operation_sequence_id(opr_index) :=
4786                                       rtg_org_dtl_tab(loop_index).x_routingstep_id ;
4787        opr_routing_sequence_id(opr_index) := p_x_aps_fmeff_id ;
4788        opr_operation_seq_num(opr_index) := rtg_org_dtl_tab(loop_index).routingstep_no ;
4789        opr_sr_instance_id(opr_index) := b_instance_id ;
4790        opr_operation_description(opr_index) := rtg_org_dtl_tab(loop_index).oprn_desc ;
4791        opr_effectivity_date(opr_index) := current_date_time ;
4792          -- disable_date,from_unit_number, to_unit_number, := null ;
4793          -- option_dependent_flag := 1,
4794          -- operation_type := null_value ;
4795        opr_mtransfer_quantity(opr_index) := temp_min_xfer_qty;   /*B2870041*/
4796 
4797        /* NAMIT_ASQC
4798        l_prod_scale_factor is Scale factor based on fm total output qty and rtg qty.
4799        (l_prod_scale_factor = formula_header_tab.total_output/effectivity.routing_qty)
4800        Also added the Step Qty UOM. Discrete UOM is obtained from Sy_UOM_Mst */
4801 --       opr_step_qty(opr_index) := l_prod_scale_factor * rtg_org_dtl_tab(loop_index).step_qty;
4802 
4803       /* Step Qty calculated In correctly */
4804        opr_step_qty(opr_index) := prod_scale_factor * rtg_org_dtl_tab(loop_index).step_qty;
4805 
4806        opr_step_qty_uom(opr_index) := rtg_org_dtl_tab(loop_index).process_qty_um;
4807          -- yield := null_value ; /*  B2365684 rtg_org_dtl_tab(loop_index).step_qty, */
4808 
4809        opr_department_id(opr_index) := (effectivity.organization_id * 2) + 1 ;
4810        opr_organization_id(opr_index) := effectivity.organization_id  ;
4811        opr_department_code(opr_index) := effectivity.whse_code ;
4812          --  operation_lead_time_percent,cumulative_yield, := null ;
4813          -- reverse_cumulative_yield,net_planning_percent, := null;
4814          -- setup_duration,tear_down_duration, := null ;
4815        /*B2870041*/
4816        opr_uom_code(opr_index) := formula_detail_tab(effectivity.product_index).aps_um ;
4817          -- standard_operation_code := null_value,
4818        opr_last_update_date(opr_index) := current_date_time ;
4819        opr_creation_date(opr_index) := current_date_time ;
4820 
4821      previous_id := rtg_org_dtl_tab(loop_index).routingstep_id;
4822      previous_activity := -1;
4823      seq_no := 0;
4824     END IF;   /* routing Step Insertion */
4825 
4826     --  Activity Insertion
4827   statement_no := 30 ;
4828     IF rtg_org_dtl_tab(loop_index).oprn_line_id <> previous_activity THEN
4829 
4830        seq_no := seq_no + 1;
4831 
4832      /*B2870041 modified the population of schedule_flag. The value of this will
4833         come from the plsql table and not hardcoded to 1. The value was set
4834         in the proceesing for the routing details */
4835 
4836      /* B2975261 - Populating activity group id using resource id */
4837 
4838      /* Operation resource seqs Bulk Insert assignments */
4839        rs_index := rs_index + 1 ;
4840        rs_operation_sequence_id(rs_index) := rtg_org_dtl_tab(loop_index).x_routingstep_id ;
4841 --       rs_resource_seq_num(rs_index) := seq_no ;
4842        /* B3596028 */
4843        rs_resource_seq_num(rs_index) := rtg_org_dtl_tab(loop_index).seq_dep_ind ;
4844        rs_sr_instance_id(rs_index)   := b_instance_id ;
4845        rs_department_id(rs_index)    := (effectivity.organization_id * 2) + 1 ;
4846          -- rs_resource_offset_percent := null_value ;
4847        /*B2870041 */
4848        rs_schedule_flag(rs_index)    := rtg_org_dtl_tab(loop_index).schedule_flag ;
4849        rs_routing_sequence_id(rs_index) := p_x_aps_fmeff_id ;
4850        rs_organization_id(rs_index)    := effectivity.organization_id ;
4851          -- deleted_flag := 2 ;
4852        rs_last_update_date(rs_index) := current_date_time ;
4853        rs_creation_date(rs_index) := current_date_time ;
4854        rs_activity_group_id(rs_index) := rtg_org_dtl_tab(loop_index).x_resource_id ;
4855 
4856       previous_activity := rtg_org_dtl_tab(loop_index).oprn_line_id;
4857 
4858     END IF;  /* End if for Activity Change */
4859 
4860     /*
4861     New Changes for Alternate Resources Begin : Bug# 1319610
4862     The following code depends on the ordering of prim_rsrc_ind, right
4863     now the Secondary Resources are Not considered, and the
4864     Primary_rsrc_indicator will have
4865               1 for Primary Resource
4866               2 for a Auxilary Resource.
4867               0 for a Secondary Resource.
4868               The Logic in brief goes like this :
4869               The Resources are inserted as usual and then a check is made
4870               to find if the resource is a Primary resource and if it has
4871               any alternates,
4872               the Alternate Resources are inserted. Then the groups secondaries
4873               are inserted.
4874      Insert the Resources : Bug# 1319610
4875      mfc 12-01-99 changed scale type to 0>2 1>1
4876      */
4877 
4878       f_step_qty  := 0;
4879       f_activity_factor    := 0 ;
4880       f_process_qty        := 0 ;
4881       f_resource_usage     := 0 ;
4882 /* NAMIT_OC */
4883       f_min_capacity       := 0 ;
4884       f_max_capacity       := 999999;
4885 
4886       -- Get process_qty,activity_factor override
4887       statement_no := 80 ;
4888       IF (rtg_org_dtl_tab(loop_index).o_step_qty  > 0) THEN
4889      /* B3145206, Note that the overriden qty is with respect to the total o/p
4890         and not with respect to just the product, let's have an example
4891         rtg_qty = 40 , step_qty = 40 , but when used
4892         in a formula having prod = 40 and by-prod = 40 , the recipe step_qty
4893         field will show 80 , if the user overrides it to be 40, then this new
4894         overriden qty 40 is wrt to total o/p of 80  */
4895 
4896          f_step_qty := rtg_org_dtl_tab(loop_index).o_step_qty / l_prod_scale_factor  ;
4897       ELSE
4898          f_step_qty := rtg_org_dtl_tab(loop_index).step_qty ;
4899       END IF;
4900 
4901       IF rtg_org_dtl_tab(loop_index).o_resource_usage > 0 THEN
4902          f_resource_usage := rtg_org_dtl_tab(loop_index).o_resource_usage ;
4903       ELSE
4904          f_resource_usage := rtg_org_dtl_tab(loop_index).resource_usage ;
4905       END IF ;
4906 
4907       IF (rtg_org_dtl_tab(loop_index).o_activity_factor > 0) THEN
4908          f_activity_factor := rtg_org_dtl_tab(loop_index).o_activity_factor;
4909       ELSE
4910          f_activity_factor := rtg_org_dtl_tab(loop_index).activity_factor;
4911       END IF ;
4912 
4913       IF (rtg_org_dtl_tab(loop_index).o_process_qty > 0) THEN
4914          f_process_qty := rtg_org_dtl_tab(loop_index).o_process_qty;
4915       ELSE
4916          f_process_qty := rtg_org_dtl_tab(loop_index).process_qty;
4917       END IF ;
4918 
4919 /* NAMIT_OC */
4920 
4921       IF (rtg_org_dtl_tab(loop_index).o_min_capacity > 0) THEN
4922          f_min_capacity := rtg_org_dtl_tab(loop_index).o_min_capacity ;
4923       ELSE
4924          f_min_capacity := rtg_org_dtl_tab(loop_index).min_capacity ;
4925       END IF ;
4926 
4927       IF (rtg_org_dtl_tab(loop_index).o_max_capacity > 0) THEN
4928          f_max_capacity := rtg_org_dtl_tab(loop_index).o_max_capacity ;
4929       ELSE
4930          f_max_capacity := rtg_org_dtl_tab(loop_index).max_capacity ;
4931       END IF ;
4932 
4933          --  SPECIAL !!! process_qty ZERO than take final step_qty */
4934          IF f_process_qty = 0 THEN
4935             f_process_qty := f_step_qty;
4936          END IF ;
4937 
4938   statement_no := 90 ;
4939 
4940   /* NAMIT_OC If the resource is scaled as fixed or By Charge, the resource
4941   usage will be treated as if it were fixed. If the scale type of the resource
4942   is "By Charge" then  the usage defined is that of the charge and will not need
4943   to be scaled in any way, except of course by the number of charges. */
4944 
4945       IF ((rtg_org_dtl_tab(loop_index).scale_type = 0) OR
4946           (rtg_org_dtl_tab(loop_index).scale_type = 2)) THEN
4947          -- fixed scaling
4948          calculated_resource_usage := ((f_resource_usage * f_activity_factor));
4949       ELSE
4950          /*B2870041 the scale factor was added to ensure the usages match
4951             what is represented by the product in the routing qty */
4952 
4953          calculated_resource_usage := ((f_step_qty / f_process_qty) *
4954            (f_resource_usage * f_activity_factor) * prod_scale_factor ) ;
4955       END IF; /* fixed scaling */
4956 
4957   statement_no := 100 ;
4958      /* Bulk insert assignments for operation_resources */
4959 	/* OR insert # 1 */
4960       orig_rs_seq_num := orig_rs_seq_num + 1;
4961       or_index := or_index + 1 ;
4962 
4963       or_operation_sequence_id(or_index) :=
4964                        rtg_org_dtl_tab(loop_index).x_routingstep_id ;
4965 --      or_resource_seq_num(or_index) := seq_no ; /* B3596028 */
4966       or_resource_seq_num(or_index) := rtg_org_dtl_tab(loop_index).seq_dep_ind ;
4967       or_resource_id(or_index) := rtg_org_dtl_tab(loop_index).x_resource_id ;
4968       or_alternate_number(or_index) := 0 ;
4969       /* For Primary Rsrc Principal flag = 1, for Aux and Sec Rsrcs Principal Flag = 2*/
4970       IF (rtg_org_dtl_tab(loop_index).prim_rsrc_ind = 1) THEN
4971          or_principal_flag(or_index) := rtg_org_dtl_tab(loop_index).prim_rsrc_ind ;
4972       ELSE
4973          or_principal_flag(or_index) := 2 ;
4974       END IF;
4975       or_basis_type(or_index) := t_scale_type ;
4976       or_resource_usage(or_index) := ( calculated_resource_usage
4977                    * rtg_org_dtl_tab(loop_index).resource_count ) ;
4978       or_max_resource_units(or_index) := rtg_org_dtl_tab(loop_index).resource_count ;
4979       or_resource_units(or_index) := rtg_org_dtl_tab(loop_index).resource_count ;
4980       or_uom_code(or_index) := rtg_org_dtl_tab(loop_index).aps_usage_um ;
4981       or_sr_instance_id(or_index) := b_instance_id ;
4982       or_routing_sequence_id(or_index) := p_x_aps_fmeff_id ;
4983       or_organization_id(or_index) := effectivity.organization_id ;
4984       or_minimum_capacity(or_index) := nvl(f_min_capacity,0) ;
4985       or_maximum_capacity(or_index) := nvl(f_max_capacity,9999999) ;
4986       or_last_update_date(or_index) := current_date_time ;
4987       or_creation_date(or_index) := current_date_time ;
4988       or_orig_rs_seq_num(or_index) := orig_rs_seq_num;
4989       or_break_ind(or_index) := rtg_org_dtl_tab(loop_index).break_ind;
4990 --
4991    statement_no := 110 ;
4992 -- ---------------------------------------------
4993      u_setup_id   := NULL ;
4994      or_setup_id(or_index) := null_value ;
4995      IF (rtg_org_dtl_tab(loop_index).is_sds_rout >= 1) THEN
4996        IF (rtg_org_dtl_tab(loop_index).is_unique = 1) THEN
4997            or_setup_id(or_index) := rtg_org_dtl_tab(loop_index).setup_id ;
4998        ELSE
4999           IF (rtg_org_dtl_tab(loop_index).is_nonunique = 1) THEN
5000            -- If the resource is not unique then it should get the setup_id of
5001            -- unique resource present anywhere in a route
5002              bsearch_unique(rtg_org_dtl_tab(loop_index).resource_id,
5003                             effectivity.category_id,
5004                             u_setup_id);
5005             or_setup_id(or_index) := u_setup_id ;
5006             rtg_org_dtl_tab(loop_index).setup_id := u_setup_id;
5007           ELSE
5008             -- It is niether unique nor nonunique
5009             or_setup_id(or_index)  := null_value;
5010             rtg_org_dtl_tab(loop_index).setup_id := null_value;
5011           END IF;
5012 
5013        END IF; /* is_unique */
5014 
5015      END IF; /* Is sds route */
5016 
5017      IF rtg_org_dtl_tab(loop_index).prim_rsrc_ind = 1 THEN
5018        -- This assignment will ensure that , alternate will use this setup
5019        rtg_org_dtl_tab(loop_index).setup_id := or_setup_id(or_index) ;
5020      END IF;
5021 
5022 -- ---------------------------------------------
5023        /*
5024         Now the check if the above resource inserted is a Primary. If it is
5025         Primary then find its Alternates if existing, and then insert its rows
5026         into msc_st_operation_resources table. Also keep track of number of
5027         times alternates are inserted. 1319610
5028        */
5029 
5030   statement_no := 120 ;
5031         IF rtg_org_dtl_tab(loop_index).prim_rsrc_ind = 1 THEN
5032 
5033           --  Reset the Counters and the Flags
5034            v_counter := 0;
5035            alternates_inserted := 'N';
5036            v_alternate  := 0;
5037            k  := 0;
5038 
5039         --  Open the Alternate resource Cursor, for the above Primary Resource
5040  	/* we shall have to put a new BSEARCH function if this looping become
5041 		a performance problem */
5042         alt_cnt := 1 ;
5043         FOR alt_cnt IN 1..alt_rsrc_size
5044         LOOP
5045 -- 	    Prod Spec alternates
5046 --	    IF ( rtg_alt_rsrc_tab(alt_cnt).prim_resource_id =
5047 --                      rtg_org_dtl_tab(loop_index).resource_id ) THEN
5048 	    IF ( rtg_alt_rsrc_tab(alt_cnt).prim_resource_id =
5049                       rtg_org_dtl_tab(loop_index).resource_id
5050 		AND (rtg_alt_rsrc_tab(alt_cnt).item_id = -1 OR
5051 		     rtg_alt_rsrc_tab(alt_cnt).item_id = effectivity.item_id)) THEN
5052              orig_rs_seq_num := orig_rs_seq_num + 1;
5053             /* B2353759, alternate runtime_factor considered */
5054                v_alternate := v_alternate + 1;
5055 
5056             /* Bulk insert assignments for operation_resources, Alternate resources */
5057 		/* OR insert # 2 */
5058              or_index := or_index + 1 ;
5059              or_operation_sequence_id(or_index) :=
5060                         rtg_org_dtl_tab(loop_index).x_routingstep_id ;
5061 --             or_resource_seq_num(or_index) := seq_no ;
5062              /* B3596028 */
5063              or_resource_seq_num(or_index) := rtg_org_dtl_tab(loop_index).seq_dep_ind ;
5064              or_resource_id(or_index) :=
5065                   ((rtg_alt_rsrc_tab(alt_cnt).alt_resource_id * 2) + 1) ;
5066 
5067 --	Prod spec alternates
5068       /* B5688153 Rajesh Patangya
5069       We are removing the preference logic for primary resource and will continue
5070       to use the old logic of numbering the primary resources in sequence as per the
5071       order by clause used by alternate resource cursor.
5072       */
5073              or_alternate_number(or_index) := v_alternate ;
5074 
5075              or_principal_flag(or_index) := 1;  /* Taking Principal flag as 1 for Alternates */
5076              or_basis_type(or_index) := t_scale_type ;
5077              or_resource_usage(or_index) := ( calculated_resource_usage
5078                           * rtg_org_dtl_tab(loop_index).resource_count
5079                           * rtg_alt_rsrc_tab(alt_cnt).runtime_factor ) ;
5080              or_max_resource_units(or_index) := rtg_org_dtl_tab(loop_index).resource_count ;
5081              /* B2761278 */
5082              or_resource_units(or_index) := rtg_org_dtl_tab(loop_index).resource_count ;
5083              or_uom_code(or_index) := rtg_org_dtl_tab(loop_index).aps_usage_um ;
5084                -- or_deleted_flag(or_index) := 2 ;
5085              or_sr_instance_id(or_index) := b_instance_id ;
5086              or_routing_sequence_id(or_index) := p_x_aps_fmeff_id ;
5087              or_organization_id(or_index) := effectivity.organization_id ;
5088              /* SGIDUGU added min capacity and max capacity inserts */
5089              or_minimum_capacity(or_index) :=
5090                        nvl(rtg_alt_rsrc_tab(alt_cnt).min_capacity,0) ;
5091              or_maximum_capacity(or_index) :=
5092                        nvl(rtg_alt_rsrc_tab(alt_cnt).max_capacity,999999) ;
5093 
5094              or_orig_rs_seq_num(or_index) := orig_rs_seq_num;
5095              or_break_ind(or_index) := rtg_org_dtl_tab(loop_index).break_ind;
5096 -- ----------------------------------------------------
5097                statement_no := 125 ;
5098                IF  rtg_org_dtl_tab(loop_index).setup_id IS NOT NULL THEN
5099                  or_setup_id(or_index) := rtg_org_dtl_tab(loop_index).setup_id ;
5100                ELSE
5101                  or_setup_id(or_index) := null_value ;
5102                END IF;
5103 
5104 -- ----------------------------------------------------
5105              or_last_update_date(or_index) := current_date_time ;
5106                -- or_last_updated_by(or_index) := 0 ;
5107              or_creation_date(or_index) := current_date_time ;
5108                -- or_created_by(or_index) := 0 ;
5109 
5110                /* Increment counter to check the number of times the
5111                   alternates are inserted */
5112 
5113                alternates_inserted := 'Y'; /* Inserted alternates */
5114 
5115 	    ELSIF ( rtg_alt_rsrc_tab(alt_cnt).prim_resource_id >
5116                       rtg_org_dtl_tab(loop_index).resource_id ) THEN
5117                EXIT ;
5118             ELSE
5119                NULL ;
5120             END IF;  /* End if for alternate resource and orgn code match */
5121 	END LOOP;  /* Alternate loop */
5122 
5123         END IF;  /* End if for Check in Primary Resource Indicator */
5124 
5125       /*
5126       Now check if the resource is a Auxilary resource and if the
5127       alternates are inserted, if both the conditions are satisfied,
5128       then loop thru the number of times the alternate resources are inserted
5129       and insert the Auxilary resources.
5130       This will take care of the combinations that has to come with the
5131       alternate resources. 1319610
5132       08/10/00 - Bug# 1388757 Changed != to <> as per the Standards
5133       */
5134 
5135   statement_no := 130 ;
5136      IF ( rtg_org_dtl_tab(loop_index).prim_rsrc_ind <> 1) AND
5137         (alternates_inserted = 'Y')
5138      THEN
5139          for k in 1 ..v_alternate
5140          LOOP
5141 
5142             /* Bulk insert assignments operation_resources, Alternate resources */
5143 		/* OR insert # 3 */
5144              or_index := or_index + 1 ;
5145 
5146              or_operation_sequence_id(or_index) := rtg_org_dtl_tab(loop_index).x_routingstep_id ;
5147 --             or_resource_seq_num(or_index) := seq_no ;
5148             /* B3596028 */
5149              or_resource_seq_num(or_index) := rtg_org_dtl_tab(loop_index).seq_dep_ind ;
5150              or_resource_id(or_index) := rtg_org_dtl_tab(loop_index).x_resource_id ;
5151              or_alternate_number(or_index) := k ;
5152             /* K will determine the no. of times altenates are used */
5153              or_principal_flag(or_index) := 2 ;
5154             /* Principal flag as 2 for Secondary Resources */
5155              or_basis_type(or_index) := t_scale_type ;
5156              or_resource_usage(or_index) := ( calculated_resource_usage
5157                     * rtg_org_dtl_tab(loop_index).resource_count ) ;
5158 
5159              or_max_resource_units(or_index) := rtg_org_dtl_tab(loop_index).resource_count ;
5160              /* B2761278 */
5161              or_resource_units(or_index) := rtg_org_dtl_tab(loop_index).resource_count ;
5162              or_uom_code(or_index) := rtg_org_dtl_tab(loop_index).aps_usage_um ;
5163                -- or_deleted_flag(or_index) := 2 ;
5164              or_sr_instance_id(or_index) := b_instance_id ;
5165              or_routing_sequence_id(or_index) := p_x_aps_fmeff_id ;
5166              or_organization_id(or_index) := effectivity.organization_id ;
5167              /* SGIDUGU - Added min capacity and max capacity inserts */
5168              or_minimum_capacity(or_index) := nvl(f_min_capacity,0) ;
5169              or_maximum_capacity(or_index) := nvl(f_max_capacity,9999999) ;
5170              or_break_ind(or_index) := rtg_org_dtl_tab(loop_index).break_ind;
5171              or_setup_id(or_index) := null_value ;
5172              or_last_update_date(or_index) := current_date_time ;
5173                -- or_last_updated_by(or_index) := 0 ;
5174              or_creation_date(or_index) := current_date_time ;
5175                -- or_created_by(or_index) := 0 ;
5176              or_orig_rs_seq_num(or_index) := orig_rs_seq_num;
5177 
5178          END LOOP; /* End loop of the v_counter */
5179      END IF;  /* End if condition for the secondary resource flag */
5180 
5181   END IF; /* End if condition for include rtg row check */
5182          -- To nullify the override effect for next recipe to use
5183          rtg_org_dtl_tab(loop_index).o_step_qty := -1 ;
5184          rtg_org_dtl_tab(loop_index).o_process_qty := -1 ;
5185          rtg_org_dtl_tab(loop_index).o_activity_factor := -1 ;
5186          rtg_org_dtl_tab(loop_index).o_resource_usage := -1 ;
5187          rtg_org_dtl_tab(loop_index).o_max_capacity   := -1 ;
5188          rtg_org_dtl_tab(loop_index).o_min_capacity   := -1 ;
5189 /*
5190      log_message (
5191      rtg_org_hdr_tab(effectivity.rtg_hdr_location).valid_flag || ' ***' ||
5192      rtg_org_dtl_tab(loop_index).routing_id ||'*'||
5193      effectivity.recipe_id ||'*'||
5194      rtg_org_dtl_tab(loop_index).routingstep_id         ||' Us '||
5195      rtg_org_dtl_tab(loop_index).resource_usage      ||' *'||
5196      rtg_org_dtl_tab(loop_index).o_resource_usage      ||' AF '||
5197      rtg_org_dtl_tab(loop_index).activity_factor      ||' *'||
5198      rtg_org_dtl_tab(loop_index).o_activity_factor      ||' SQ '||
5199      rtg_org_dtl_tab(loop_index).step_qty      ||' *'||
5200      rtg_org_dtl_tab(loop_index).o_step_qty     ||' PQ '||
5201      rtg_org_dtl_tab(loop_index).process_qty      ||' *'||
5202      rtg_org_dtl_tab(loop_index).o_process_qty      ||' M '||
5203      rtg_org_dtl_tab(loop_index).min_capacity   ||' *'||
5204      rtg_org_dtl_tab(loop_index).o_min_capacity   ||' X '||
5205      rtg_org_dtl_tab(loop_index).max_capacity   ||' *'||
5206      rtg_org_dtl_tab(loop_index).o_max_capacity);
5207 */
5208   END LOOP;  /* End loop of the Main */
5209   END IF ;  /* Positive counter value check */
5210 
5211   statement_no := 140 ;
5212   return_status := TRUE;
5213 
5214   EXCEPTION
5215   WHEN OTHERS THEN
5216 	log_message('Write routing operations failed at statement '
5217                      ||to_char(statement_no)||': '||sqlerrm);
5218 	return_status := FALSE;
5219 
5220 END write_routing_operations;
5221 
5222 /*
5223 REM+=========================================================================+
5224 REM| PROCEDURE NAME                                                          |
5225 REM|    write_operation_componenets                                          |
5226 REM|                                                                         |
5227 REM| TYPE                                                                    |
5228 REM|    Private                                                              |
5229 REM|                                                                         |
5230 REM| DESCRIPTION                                                             |
5231 REM|     Writes routing/material associations to the MSC tables              |
5232 REM|                                                                         |
5233 REM| INPUT PARAMETERS                                                        |
5234 REM|    table_index: index of APS effectivity in aps_effectivities           |
5235 REM|                                                                         |
5236 REM| OUTPUT PARAMETERS                                                       |
5237 REM|    return_status  TRUE=> OK                                             |
5238 REM|                                                                         |
5239 REM| INPUT/OUTPUT PARAMETERS                                                 |
5240 REM|    None                                                                 |
5241 REM|                                                                         |
5242 REM| HISTORY                                                                 |
5243 REM|  07/14/2002   Rajesh Patangya - Reorgnized the complete code B2314052   |
5244 REM+=========================================================================+
5245 */
5246 PROCEDURE write_operation_components
5247 (
5248   p_x_aps_fmeff_id   IN  NUMBER,
5249   precipe_id         IN  NUMBER,
5250   return_status      OUT NOCOPY BOOLEAN
5251 )
5252 IS
5253 
5254   st_mst_operation_components VARCHAR2(4000) ;
5255   i    INTEGER ;
5256   record_written BOOLEAN ;    /* B3562488 */
5257   already_done INTEGER ;          /* 3562488  */
5258   found_product                 BOOLEAN ;
5259   write_row                     BOOLEAN ;
5260 
5261 BEGIN
5262   st_mst_operation_components := NULL ;
5263   i    				:= 1;
5264   record_written 		:= FALSE ;
5265   already_done 		:= 0 ;
5266   stmt_no 		:= 0;
5267 
5268    found_product        := FALSE;
5269    write_row            := TRUE;
5270 
5271   -- write routing/material associations to msc_operation_components
5272 --         log_message('Enter --- > ' || g_mat_assoc
5273 --          || ' Effec ' || effectivity.formula_id
5274 --          || ' Material ' || mat_assoc_tab(g_mat_assoc).formula_id || ' Recipe ' || precipe_id ) ;
5275 
5276 stmt_no := 0;
5277    FOR i in g_mat_assoc..material_assocs_size
5278    LOOP
5279 
5280      IF  effectivity.formula_id > mat_assoc_tab(i).formula_id THEN
5281 --         log_message(i || ' --- ' ||
5282 --          effectivity.formula_id || ' > ' || mat_assoc_tab(i).formula_id ) ;
5283           NULL ;   /* Keep on looping */
5284 
5285      ELSIF effectivity.formula_id < mat_assoc_tab(i).formula_id THEN
5286             /* B3562488 */
5287             IF record_written = TRUE THEN
5288                g_mat_assoc := already_done ;
5289             END IF ;
5290 
5291 --           log_message('Exit ' || g_mat_assoc || ' ***'
5292 --             || effectivity.formula_id || ' < ' || mat_assoc_tab(i).formula_id ) ;
5293 
5294            EXIT;
5295      ELSIF effectivity.formula_id = mat_assoc_tab(i).formula_id THEN
5296             /* B3562488 */
5297         IF record_written = FALSE THEN
5298            already_done := i ;
5299            record_written := TRUE ;
5300 --         log_message('Written ' || already_done);
5301         END IF ;
5302 
5303 stmt_no := 10;
5304         IF mat_assoc_tab(i).recipe_id = precipe_id  THEN
5305 --       AND primary_bom_formulaline_id <> mat_assoc_tab(i).x_formulaline_id  THEN
5306 -- /* Bug # 4879588*/
5307 -- Backed this out as the new code already has a check for product_id
5308 
5309            /*  Do Not write material association
5310                       for the product line */
5311 
5312            IF mat_assoc_tab(i).item_id = effectivity.item_id THEN
5313 	      IF NOT (found_product )THEN
5314 	         found_product := TRUE ;
5315 		 write_row := FALSE ;
5316 	      ELSE
5317                  write_row := TRUE ;
5318               END IF ;
5319            ELSE
5320               write_row := TRUE ;
5321            END IF ;
5322 
5323            /*  operation components bulk insert */
5324            IF (write_row ) THEN
5325               oc_index := oc_index + 1 ;
5326               oc_operation_sequence_id(oc_index) := mat_assoc_tab(i).x_routingstep_id ;
5327               oc_component_sequence_id(oc_index) := mat_assoc_tab(i).x_formulaline_id  ;
5328               oc_sr_instance_id(oc_index) := b_instance_id ;
5329               oc_bill_sequence_id(oc_index) := p_x_aps_fmeff_id  ;
5330               oc_routing_sequence_id(oc_index) := p_x_aps_fmeff_id ;
5331               oc_organization_id(oc_index) := effectivity.organization_id ;
5332               -- deleted_flag := 2,
5333               oc_last_update_date(oc_index) := current_date_time ;
5334               oc_creation_date(oc_index) := current_date_time ;
5335            END IF;
5336 
5337 stmt_no := 20;
5338 /* NAMIT_MTQ */
5339            IF ((mat_assoc_tab(i).min_trans_qty IS NOT NULL) OR
5340                    (mat_assoc_tab(i).min_delay IS NOT NULL)) THEN
5341 
5342               IF (mat_assoc_tab(i).min_trans_qty IS NULL) THEN
5343                  mat_assoc_tab(i).min_trans_qty := 0;
5344               END IF;
5345 
5346               mtq_index := mtq_index + 1;
5347 
5348    /* nsinghi B3970993 Start */
5349    /* If either the org, recipe, formula, rtg, step or item changes; re-initialize
5350    the globals. Write this MTQ row, and let the g_min_mtq be the mtq qty from this
5351    row. Also store the index of mtq row in global variable.
5352    The first MTQ row for a item belonging to a step is always written. If the same
5353    item is defined in the same step, then the row having minimum MTQ will be written. */
5354 
5355    /*
5356    1) If the MTQ is defined as null in one row, but min and/or max delay
5357    is defined for that row. Another row for the same item in same step, if MTQ is
5358    not null, but min and/or max delay are null, then which row to transfer. The code
5359    will transfer the row that has null MTQ.
5360    2) If MTQ is defined for same item multiple times in same step, and if all the
5361    MTQ values are equal, then the first row where MTQ is found will be sent. */
5362 
5363               IF g_old_recipe_id <> mat_assoc_tab(i).recipe_id OR
5364                  g_old_formula_id <> mat_assoc_tab(i).formula_id OR
5365                  g_old_rtg_id <> p_x_aps_fmeff_id OR
5366                  g_old_rtgstep_id <> mat_assoc_tab(i).x_routingstep_id OR
5367                  g_old_aps_item_id <> mat_assoc_tab(i).aps_item_id
5368               THEN
5369                  g_old_recipe_id := mat_assoc_tab(i).recipe_id;
5370                  g_old_formula_id := mat_assoc_tab(i).formula_id;
5371                  g_old_rtg_id := p_x_aps_fmeff_id;
5372                  g_old_rtgstep_id := mat_assoc_tab(i).x_routingstep_id;
5373                  g_old_aps_item_id := mat_assoc_tab(i).aps_item_id;
5374                  g_mtq_loc := mtq_index;
5375                  g_min_mtq := mat_assoc_tab(i).min_trans_qty;
5376 
5377                  itm_mtq_from_op_seq_id(mtq_index) :=  mat_assoc_tab(i).x_routingstep_id;
5378                  itm_mtq_routing_sequence_id(mtq_index) := p_x_aps_fmeff_id ;
5379                  itm_mtq_sr_instance_id(mtq_index) := b_instance_id ;
5380                  itm_mtq_from_item_id(mtq_index) := mat_assoc_tab(i).aps_item_id ;
5381                  itm_mtq_organization_id(mtq_index) := effectivity.organization_id ;
5382                  itm_mtq_min_tran_qty(mtq_index) := mat_assoc_tab(i).min_trans_qty * mat_assoc_tab(i).uom_conv_factor;
5383                  itm_mtq_min_time_offset(mtq_index) := mat_assoc_tab(i).min_delay;
5384                  itm_mtq_max_time_offset(mtq_index) := mat_assoc_tab(i).max_delay;
5385                  itm_mtq_frm_op_seq_num(mtq_index) := mat_assoc_tab(i).routingstep_no;
5386               END IF;
5387 
5388      /* If an item is yielded in the same step multiple times and if MTQ value is associated
5389       to that item multiple times, then write row that has min MTQ. */
5390 
5391               IF g_old_recipe_id = mat_assoc_tab(i).recipe_id AND
5392                  g_old_formula_id = mat_assoc_tab(i).formula_id AND
5393                  g_old_rtg_id = p_x_aps_fmeff_id AND
5394                  g_old_rtgstep_id = mat_assoc_tab(i).x_routingstep_id AND
5395                  g_old_aps_item_id = mat_assoc_tab(i).aps_item_id AND
5396                  g_mtq_loc <> mtq_index
5397               THEN
5398                  log_message('Item : '||mat_assoc_tab(i).item_id||' in recipe : '||mat_assoc_tab(i).recipe_id
5399                  ||' is associated multiple times in step '||mat_assoc_tab(i).routingstep_no
5400                  ||' with MTQ/Min/Max Delay defined. Row with Minimum/Null MTQ will be considered. ');
5401                  IF mat_assoc_tab(i).min_trans_qty < g_min_mtq THEN
5402                     itm_mtq_from_op_seq_id(g_mtq_loc) :=  mat_assoc_tab(i).x_routingstep_id;
5403                     itm_mtq_routing_sequence_id(g_mtq_loc) := p_x_aps_fmeff_id ;
5404                     itm_mtq_sr_instance_id(g_mtq_loc) := b_instance_id ;
5405                     itm_mtq_from_item_id(g_mtq_loc) := mat_assoc_tab(i).aps_item_id ;
5406                     itm_mtq_organization_id(g_mtq_loc) := effectivity.organization_id ;
5407                     itm_mtq_min_tran_qty(g_mtq_loc) := mat_assoc_tab(i).min_trans_qty * mat_assoc_tab(i).uom_conv_factor;
5408                     itm_mtq_min_time_offset(g_mtq_loc) := mat_assoc_tab(i).min_delay;
5409                     itm_mtq_max_time_offset(g_mtq_loc) := mat_assoc_tab(i).max_delay;
5410                     itm_mtq_frm_op_seq_num(g_mtq_loc) := mat_assoc_tab(i).routingstep_no;
5411                  END IF;
5412                  mtq_index := mtq_index - 1;
5413               END IF;
5414         /* nsinghi B3970993 End */
5415 
5416            END IF;
5417 stmt_no := 30;
5418 
5419 --       log_message(i || ' - RCP - ' || p_x_aps_fmeff_id || ' ** ' || mat_assoc_tab(i).recipe_id ) ;
5420 
5421         END IF ;   /* Recipe check */
5422 
5423      END IF ;   /* formula check */
5424    END LOOP ;
5425 
5426   return_status := TRUE;
5427 
5428   EXCEPTION
5429   WHEN OTHERS THEN
5430 	log_message('Error writing operation components: '||sqlerrm);
5431 	return_status := FALSE;
5432 END write_operation_components;
5433 
5434 /*
5435 REM+=========================================================================+
5436 REM| PROCEDURE NAME                                                          |
5437 REM|    export_effectivities                                                 |
5438 REM|                                                                         |
5439 REM| TYPE                                                                    |
5440 REM|    Private                                                              |
5441 REM|                                                                         |
5442 REM| DESCRIPTION                                                             |
5443 REM|    This procedure is called after all of the effectivities have been    |
5444 REM|    validated and extracted. It exports the data gathered to APS using   |
5445 REM|    the defined table mappings.                                          |
5446 REM|                                                                         |
5447 REM| INPUT PARAMETERS                                                        |
5448 REM|    None                                                                 |
5449 REM|                                                                         |
5450 REM| OUTPUT PARAMETERS                                                       |
5451 REM|    return_status    TRUE => OK                                          |
5452 REM|                                                                         |
5453 REM| INPUT/OUTPUT PARAMETERS                                                 |
5454 REM|    None                                                                 |
5455 REM|                                                                         |
5456 REM| HISTORY                                                                 |
5457 REM|  07/14/2002   Rajesh Patangya - Reorgnized the complete code B2314052   |
5458 REM|  06/02/2003   Sridhar Gidugu  - Added code to check aps fm eff          |
5459 REM|                                 B2989806                                |
5460 REM+=========================================================================+
5461 */
5462 PROCEDURE export_effectivities
5463 (
5464   return_status            OUT NOCOPY BOOLEAN
5465 )
5466 IS
5467   p_status       BOOLEAN;
5468   b_status       BOOLEAN;
5469   r_status       BOOLEAN;
5470   ro_status      BOOLEAN;
5471   oc_status      BOOLEAN;
5472 
5473 BEGIN
5474 
5475         /* Finally generate the effectivity_id */
5476 
5477         /* B2989806
5478            If aps_fmeff_id from gmp_form_eff was null,
5479            then create a new one.  Otherwise, use original.
5480         */
5481 
5482         /*
5483           g_aps_eff_id := g_aps_eff_id + 1 ;
5484           aps_fmeff_id := g_aps_eff_id ;
5485           x_aps_fmeff_id := (aps_fmeff_id * 2 ) + 1 ;
5486           B2989806
5487         */
5488 
5489         IF effectivity.aps_fmeff_id = -1 THEN
5490          g_aps_eff_id := g_aps_eff_id + 1 ;
5491          aps_fmeff_id := g_aps_eff_id ;
5492         ELSE
5493          aps_fmeff_id := effectivity.aps_fmeff_id ;
5494         END IF ;
5495 
5496         x_aps_fmeff_id := (aps_fmeff_id * 2 ) + 1 ;
5497 
5498 
5499     /* B3837959 MMK Issue, Handling of return status */
5500     write_process_effectivity(x_aps_fmeff_id, aps_fmeff_id, p_status);
5501     return_status := p_status ;
5502 
5503     IF return_status = TRUE THEN
5504       write_bom_components(x_aps_fmeff_id, b_status);
5505       return_status := b_status ;
5506 
5507       IF (effectivity.routing_id IS NOT NULL) AND (b_status = TRUE) THEN
5508         write_routing(x_aps_fmeff_id, r_status);
5509         return_status := r_status ;
5510 
5511         IF return_status = TRUE THEN
5512           write_routing_operations(x_aps_fmeff_id,ro_status);
5513           return_status := ro_status ;
5514 
5515           IF return_status = TRUE THEN
5516              write_operation_components(x_aps_fmeff_id,
5517                                         effectivity.recipe_id,
5518                                         oc_status);
5519              return_status := oc_status ;
5520              IF return_status = FALSE THEN
5521                log_message('write_operation_components Returned FALSE');
5522              END IF;
5523           ELSE
5524             log_message('write_routing_operations Returned FALSE');
5525             return_status := FALSE;
5526           END IF;
5527         ELSE
5528           log_message('write_routing Returned FALSE');
5529           return_status := FALSE;
5530         END IF;
5531       ELSE
5532           IF return_status = FALSE THEN
5533             log_message('write_bom_components Returned FALSE');
5534           END IF;
5535       END IF;
5536     ELSE
5537       log_message('write_process_effectivity Returned FALSE');
5538       return_status := FALSE;
5539     END IF;
5540 
5541   EXCEPTION
5542     WHEN OTHERS THEN
5543        log_message('Export Effectivities Raised Exception: '||sqlerrm);
5544        log_message(to_char(effectivity.fmeff_id));
5545        return_status := FALSE;
5546 END export_effectivities;
5547 
5548 /*
5549 REM+=========================================================================+
5550 REM+                                                                         +
5551 REM+                         PUBLIC PROCEDURES                               +
5552 REM+                                                                         +
5553 REM+=========================================================================+
5554 
5555 REM+=========================================================================+
5556 REM| PROCEDURE NAME                                                          |
5557 REM|    extract_effectivities                                                |
5558 REM|                                                                         |
5559 REM| TYPE                                                                    |
5560 REM|    Public                                                               |
5561 REM|                                                                         |
5562 REM| USAGE                                                                   |
5563 REM|    This is the 'main' procedure for extracting effectivities and then   |
5564 REM|    exploding the ones which are valid for export to APS                 |
5565 REM|                                                                         |
5566 REM| DESCRIPTION                                                             |
5567 REM|                                                                         |
5568 REM|                                                                         |
5569 REM| INPUT PARAMETERS                                                        |
5570 REM|    None                                                                 |
5571 REM|                                                                         |
5572 REM| OUTPUT PARAMETERS                                                       |
5573 REM|    return_status                                                        |
5574 REM|                                                                         |
5575 REM| INPUT/OUTPUT PARAMETERS                                                 |
5576 REM|    None                                                                 |
5577 REM|                                                                         |
5578 REM| HISTORY                                                                 |
5579 REM|  07/14/2002   Rajesh Patangya - Reorgnized the complete code B2314052   |
5580 REM| 04/21/2004   - Navin Sinha - B3577871 -ST:OSFME2: collections failing   |
5581 REM|                               in planning data pull.                    |
5582 REM|                               Added handling of NO_DATA_FOUND Exception.|
5583 REM|                               And return the return_status as TRUE.     |
5584 REM+=========================================================================+
5585 */
5586 PROCEDURE extract_effectivities
5587 (
5588   at_apps_link     IN VARCHAR2,
5589   delimiter_char   IN VARCHAR2,
5590   instance         IN INTEGER,
5591   run_date         IN DATE,
5592   return_status    IN OUT NOCOPY BOOLEAN
5593 )
5594 IS
5595   valid            BOOLEAN;
5596   setup_failure    EXCEPTION;
5597   extract_failure  EXCEPTION;
5598   export_failure   EXCEPTION;
5599 
5600   retrieval_cursor        VARCHAR2(32700) ;
5601 BEGIN
5602 g_aps_eff_id              := 0; /* Global Aps Effectivity ID */
5603 aps_fmeff_id              := 0 ;/* Generated effectivity Id */
5604 x_aps_fmeff_id            := 0 ;/* encoded effectivity Id */
5605 retrieval_cursor          := NULL ;
5606 
5607   IF return_status THEN
5608     v_cp_enabled := TRUE;
5609   ELSE
5610     v_cp_enabled := FALSE;
5611   END IF;
5612 
5613   /* B2104059 GMP-APS ENHANCEMENT FOR GMD FORMULA SECURITY FUNCTIONALITY  */
5614   /* Disable the security  */
5615 
5616     retrieval_cursor := ' begin gmd_p_fs_context.set_additional_attr'
5617                         || at_apps_link || ';end;'   ;
5618     EXECUTE IMMEDIATE retrieval_cursor ;
5619 
5620   /* Before we do anything we need to create/setup/size a few things */
5621 
5622   g_instance_id := instance ;
5623 
5624   setup(at_apps_link, delimiter_char, instance, run_date, valid);
5625 
5626   IF NOT valid THEN
5627     RAISE setup_failure;
5628   END IF;
5629 
5630   /* If all is OK, extract the effectivities to PL/SQL tables */
5631   retrieve_effectivities(valid);
5632 
5633   IF NOT valid THEN
5634     RAISE extract_failure;
5635   END IF;
5636 
5637   return_status := TRUE;
5638 
5639   EXCEPTION
5640 	WHEN setup_failure THEN
5641 	    /* Initial setup failed */
5642 		log_message('Effectivity extract setup failure');
5643 		return_status := FALSE;
5644 
5645 	WHEN extract_failure THEN
5646 	    /* Effectivity extraction failed */
5647 		log_message('Effectivity extraction failed');
5648 		return_status := FALSE;
5649 
5650 	WHEN export_failure THEN
5651 	    /* Effectivity export failed */
5652 		log_message('Effectivity export failed');
5653 		return_status := FALSE;
5654 
5655         WHEN NO_DATA_FOUND THEN  /* B3577871 */
5656                 log_message(' NO_DATA_FOUND exception raised in Procedure: MSC_CL_GMP_UTILITY.Extract_effectivities ' );
5657                 return_status := TRUE;
5658 	WHEN OTHERS THEN
5659 		log_message('Untrapped effectivity extraction error');
5660 		log_message(sqlerrm);
5661         return_status := FALSE;
5662 
5663 END extract_effectivities;
5664 
5665 /*
5666 REM+=========================================================================+
5667 REM| PROCEDURE NAME                                                          |
5668 REM|    Extract_Items                                                        |
5669 REM|                                                                         |
5670 REM| TYPE                                                                    |
5671 REM|    Public                                                               |
5672 REM|                                                                         |
5673 REM| USAGE                                                                   |
5674 REM|                                                                         |
5675 REM|                                                                         |
5676 REM| DESCRIPTION                                                             |
5677 REM|    This procedure refreshes the gmp_items_aps table with all items for  |
5678 REM|    which planning is required. An item is deemed to fall within the     |
5679 REM|    scope of planning if it occurs in the plant/warehouse effectivity    |
5680 REM|    (ps_whse_eff). If a row in ps_whse_eff has a blank item_id this      |
5681 REM|    indicates all items, and this means that we must generate rows in    |
5682 REM|    gmp_item_aps for all items using the plant/warehouse combination     |
5683 REM|    just read.                                                           |
5684 REM|                                                                         |
5685 REM|                                                                         |
5686 REM| INPUT PARAMETERS                                                        |
5687 REM|    opm_link   VARCHAR2 database link to opm_instance                    |
5688 REM|    aps_link   VARCHAR2 database link to aps_instance                    |
5689 REM|                                                                         |
5690 REM|    Either or both of these parameters may be NULL or they may both be   |
5691 REM|    be set up, depending on requirements and which server(s) are         |
5692 REM|    present.                                                             |
5693 REM|                                                                         |
5694 REM| OUTPUT PARAMETERS                                                       |
5695 REM|    return_status    BOOLEAN: TRUE=> OK                                  |
5696 REM|                                                                         |
5697 REM| INPUT/OUTPUT PARAMETERS                                                 |
5698 REM|    None                                                                 |
5699 REM|                                                                         |
5700 REM| HISTORY                                                                 |
5701 REM|    Created 8th July 1999 by P.J.Schofield (OPM Development Oracle UK)   |
5702 REM|                                                                         |
5703 REM|    15th July 1999 P.J.Schofield                                         |
5704 REM|    Include inventory_item_id from mtl_system_items and uom_code from    |
5705 REM|    mtl_units_of_measure                                                 |
5706 REM|    04/03/2000 - Using mtl_organization_id from ic_item_mst instead of   |
5707 REM|               - organization_id from sy_orgn_mst table. Bug# 1252322    |
5708 REM|    12/14/00   - B1540127 By Rajesh Patangya                             |
5709 REM|                 join change for unit_of_measure field in sy_uoms_mst    |
5710 REM| 04/21/2004   - Navin Sinha - B3577871 -ST:OSFME2: collections failing   |
5711 REM|                               in planning data pull.                    |
5712 REM|                               Added handling of NO_DATA_FOUND Exception.|
5713 REM|                               And return the return_status as TRUE.     |
5714 REM|                                                                         |
5715 REM+=========================================================================+
5716 */
5717 PROCEDURE extract_items
5718 (
5719   at_apps_link  IN VARCHAR2,
5720   instance      IN INTEGER,
5721   run_date      IN DATE,
5722   return_status IN OUT NOCOPY BOOLEAN
5723 )
5724 IS
5725   c_item_cursor           ref_cursor_typ;
5726 
5727   retrieval_cursor        VARCHAR2(32700);
5728   insert_statement        VARCHAR2(32700);
5729 
5730   TYPE gmp_item_aps_typ  IS RECORD (
5731     item_no               VARCHAR2(32),
5732     item_id               PLS_INTEGER,
5733     category_id           NUMBER,        /* SGIDUGU  Bug 5882984 */
5734     seq_dpnd_class        VARCHAR2(8),   /* SGIDUGU  Bug 5882984 */
5735     item_um               VARCHAR2(4),
5736     uom_code              VARCHAR2(3),
5737     lot_control           PLS_INTEGER,
5738     item_desc1            VARCHAR2(70),
5739     aps_item_id           PLS_INTEGER,
5740     organization_id       PLS_INTEGER,
5741     whse_code             VARCHAR2(4),
5742     replen_ind            PLS_INTEGER,
5743     consum_ind            PLS_INTEGER,
5744     plant_code            VARCHAR2(4),
5745     creation_date         DATE,
5746     created_by            PLS_INTEGER,
5747     last_update_date      DATE,
5748     last_updated_by       PLS_INTEGER,
5749     last_update_login     PLS_INTEGER,
5750     experimental_ind      PLS_INTEGER);   /* Bug # 5238790 */
5751 
5752   gmp_item_aps_rec        gmp_item_aps_typ;
5753 
5754   i                       INTEGER ;
5755   v_dummy                 NUMBER ;
5756 
5757 BEGIN
5758   i                       := 0;
5759   v_dummy                 := 0;
5760 
5761   IF return_status THEN
5762     v_cp_enabled := TRUE;
5763   ELSE
5764     v_cp_enabled := FALSE;
5765   END IF;
5766 
5767    /* populate the org_string */
5768      IF MSC_CL_GMP_UTILITY.org_string(instance) THEN
5769         NULL ;
5770      ELSE
5771         RAISE invalid_string_value  ;
5772      END IF;
5773 
5774      l_in_str_org := MSC_CL_GMP_UTILITY.g_in_str_org ;    /* 3491625 */
5775 
5776   retrieval_cursor := 'DELETE FROM gmp_item_aps'||at_apps_link;
5777   EXECUTE IMMEDIATE retrieval_cursor;
5778 
5779   COMMIT;
5780 
5781 /*   New Changes - Using mtl_organization_id from ic_whse_mst , instead of organization_id
5782                    from sy_orgn_mst , Bug# 1252322
5783 */
5784 
5785   /* SGIDUGU - code added for Seq Dep Bug 5882984 */
5786   retrieval_cursor :=
5787                 'SELECT iim.item_no, iim.item_id,nvl(iim.seq_category_id,-1), '
5788                 ||'  iim.seq_dpnd_class , '
5789                 ||'  iim.item_um, mum.uom_code,iim.lot_ctl, iim.item_desc1, '
5790                 ||'  msi.inventory_item_id, '
5791                 ||'  iwm.mtl_organization_id, '
5792 		||'  pwe.whse_code, decode(sum(pwe.replen_ind), 0, 0, 1), '
5793                 ||'  decode(sum(pwe.consum_ind), 0, 0, 1), '
5794 		||'  pwe.plant_code, iim.creation_date, iim.created_by, '
5795                 ||'  iim.last_update_date,iim.last_updated_by, NULL '
5796                  /* Bug # 5238790 */
5797                 ||'  ,NVL(iim.experimental_ind,0) '
5798                 ||'  FROM  ic_item_mst'||at_apps_link||' iim,'
5799 		||'        sy_uoms_mst'||at_apps_link||' sou,'   /* B1540127 */
5800 		||'        ps_whse_eff'||at_apps_link||' pwe,'
5801 		||'        ic_whse_mst'||at_apps_link||' iwm,'
5802 		||'        mtl_system_items'||at_apps_link||' msi,'
5803 		||'        mtl_units_of_measure'||at_apps_link||' mum, '
5804                 ||'        sy_orgn_mst'||at_apps_link||' som '
5805 		||'  WHERE iim.delete_mark = 0 '
5806 		||'    AND som.delete_mark = 0 '
5807 		||'    AND iim.inactive_ind = 0 '
5808 		||'    AND iim.item_no = msi.segment1 '
5809 		||'    AND iwm.mtl_organization_id = msi.organization_id '
5810                 ||'    AND pwe.plant_code = som.orgn_code '
5811 		||'    AND pwe.whse_code = iwm.whse_code '
5812 		||'    AND sou.unit_of_measure = mum.unit_of_measure '
5813                 ||'    AND sou.delete_mark = 0 ' ;
5814              IF l_in_str_org  IS NOT NULL THEN     /* B3491625 */
5815                 retrieval_cursor := retrieval_cursor
5816                 ||'    AND iwm.mtl_organization_id ' || l_in_str_org ;
5817              END IF;
5818                 retrieval_cursor := retrieval_cursor
5819 		||'    AND iim.item_um = sou.um_code '
5820 		/*||'    AND iim.experimental_ind = 0 '*//* Bug # 5238790 */
5821 		||'    AND ( '
5822 		||'          pwe.whse_item_id IS NULL OR '
5823 		||'          pwe.whse_item_id = iim.whse_item_id OR '
5824 		||'          ( '
5825 		||'            pwe.whse_item_id = iim.item_id AND '
5826 		||'            iim.item_id <> iim.whse_item_id '
5827 		||'          ) '
5828                 ||'        ) '
5829 		||' GROUP BY '
5830 		||'   iim.item_id, iim.item_no,iim.seq_category_id, '
5831                 ||'   iim.seq_dpnd_class, '
5832                 ||'   iim.item_desc1, iim.item_um, '
5833                 ||'   iim.lot_ctl, pwe.whse_code, '
5834 		||'   pwe.plant_code, mum.uom_code, msi.inventory_item_id, '
5835                 ||'   iwm.mtl_organization_id, '
5836 		||'   iim.creation_date, iim.created_by, iim.last_update_date, '
5837                 ||'   iim.last_updated_by '
5838                 ||'  ,iim.experimental_ind ' ;/* Bug # 5238790 */
5839 
5840   OPEN c_item_cursor FOR retrieval_cursor;
5841 
5842   /* SGIDUGU - added inserts for Category Id and Seq Dep Id Bug 5882984 */
5843   insert_statement :=
5844                 'INSERT INTO gmp_item_aps'||at_apps_link||' '
5845 		||' ( '
5846 		||'  item_no, item_id,category_id,seq_dpnd_class, '
5847                 ||'  item_um, uom_code, '
5848                 ||'  lot_control, item_desc1, '
5849 	        ||'  aps_item_id, organization_id, whse_code, replen_ind,'
5850 		||'  consum_ind,  plant_code, creation_date, created_by, '
5851 		||'  last_update_date, last_updated_by, last_update_login '
5852                 ||'  ,experimental_ind '  /* Bug # 5238790 */
5853 		||' ) '
5854 		||'  VALUES '
5855 		||' (:p1,:p2,:p3,:p4, '
5856                 ||'  :p5,:p6, '
5857                 ||'  :p7,:p8,:p9,:p10,'
5858                 ||'  :p11,:p12,:p13,:p14, '
5859                 ||'  :p15,:p16,:p17,:p18,:p19,:p20 )'; /* Bug # 5238790 */
5860 
5861   FETCH c_item_cursor
5862   INTO  gmp_item_aps_rec;
5863 
5864   WHILE c_item_cursor%FOUND
5865   LOOP
5866     EXECUTE IMMEDIATE insert_statement USING
5867                  gmp_item_aps_rec.item_no,
5868 		 gmp_item_aps_rec.item_id,
5869 		 gmp_item_aps_rec.category_id,     /* SGIDUGU Bug 5882984 */
5870 		 gmp_item_aps_rec.seq_dpnd_class,  /* SGIDUGU Bug 5882984 */
5871 		 gmp_item_aps_rec.item_um,
5872 		 gmp_item_aps_rec.uom_code,
5873 		 gmp_item_aps_rec.lot_control,
5874 		 gmp_item_aps_rec.item_desc1,
5875 		 gmp_item_aps_rec.aps_item_id,
5876 		 gmp_item_aps_rec.organization_id,
5877 		 gmp_item_aps_rec.whse_code,
5878 	         gmp_item_aps_rec.replen_ind,
5879 		 gmp_item_aps_rec.consum_ind,
5880 		 gmp_item_aps_rec.plant_code,
5881 		 run_date,
5882 		 gmp_item_aps_rec.created_by,
5883 	         run_date,
5884 		 gmp_item_aps_rec.last_updated_by,
5885 		 0
5886                  ,gmp_item_aps_rec.experimental_ind ;   /* Bug # 5238790 */
5887 
5888     i := i + 1;
5889 
5890     IF i = 500 then
5891       COMMIT;
5892       i := 0;
5893     END IF;
5894 
5895 
5896     FETCH c_item_cursor
5897     INTO gmp_item_aps_rec;
5898 
5899   END LOOP;
5900 
5901   COMMIT;
5902 
5903   CLOSE c_item_cursor;
5904 
5905           SELECT st.VALUE INTO v_dummy from V$MYSTAT st, V$STATNAME sn
5906           where st.STATISTIC# = sn.STATISTIC#
5907           and sn.NAME in ('session pga memory');
5908           log_message('After Item Cursor Session pga memory = ' || TO_CHAR(v_dummy) );
5909 
5910   return_status := TRUE;
5911 
5912   EXCEPTION
5913     WHEN invalid_string_value  THEN
5914       log_message('Organization string is Invalid ' );
5915       return_status := FALSE;
5916     WHEN NO_DATA_FOUND THEN /* B3577871 */
5917       log_message(' NO_DATA_FOUND exception raised in Procedure: MSC_CL_GMP_UTILITY.Extract_Items ' );
5918       return_status := TRUE;
5919     WHEN OTHERS THEN
5920       log_message('Item extraction failed with error '||sqlerrm);
5921       return_status := FALSE;
5922 
5923 END Extract_Items;
5924 
5925 /*
5926 REM+=========================================================================+
5927 REM| PROCEDURE NAME                                                          |
5928 REM|    extract_sub_inventory                                                |
5929 REM|                                                                         |
5930 REM| TYPE                                                                    |
5931 REM|    Public                                                               |
5932 REM|                                                                         |
5933 REM| USAGE                                                                   |
5934 REM|                                                                         |
5935 REM|                                                                         |
5936 REM| DESCRIPTION                                                             |
5937 REM|    This procedure creates sub-inventories for each eligible OPM         |
5938 REM|    warehouse and writes them to the msc_sub_inventories table.          |
5939 REM|                                                                         |
5940 REM| INPUT PARAMETERS                                                        |
5941 REM|    opm_link   VARCHAR2 database link to opm_instance                    |
5942 REM|    aps_link   VARCHAR2 database link to aps_instance                    |
5943 REM|                                                                         |
5944 REM|    Either or both of these parameters may be NULL or they may both be   |
5945 REM|    be set up, depending on requirements and which server(s) are         |
5946 REM|    present.                                                             |
5947 REM|                                                                         |
5948 REM| OUTPUT PARAMETERS                                                       |
5949 REM|    return_status    BOOLEAN: TRUE=> OK                                  |
5950 REM|                                                                         |
5951 REM| INPUT/OUTPUT PARAMETERS                                                 |
5952 REM|    None                                                                 |
5953 REM|                                                                         |
5954 REM| HISTORY                                                                 |
5955 REM|    Created 12th August 1999 by P.J.Schofield (OPM Development UK)       |
5956 REM|    10/13/99 - Added deleted_flag in the insert statement                |
5957 REM| 04/21/2004  - Navin Sinha - B3577871 -ST:OSFME2: collections failing    |
5958 REM|                               in planning data pull.                    |
5959 REM|                               Return return_status as TRUE in case      |
5960 REM|                               no_warehouses Exception is raised.        |
5961 REM|                                                                         |
5962 REM+=========================================================================+
5963 */
5964 PROCEDURE extract_sub_inventory
5965 (
5966   at_apps_link  IN VARCHAR2,
5967   instance      IN INTEGER,
5968   run_date      IN DATE,
5969   return_status IN OUT NOCOPY BOOLEAN
5970 )
5971 IS
5972   c_whse_cursor           ref_cursor_typ;
5973 
5974   retrieval_cursor        VARCHAR2(32700);
5975 
5976   whse_code           VARCHAR2(4);
5977   organization_id     NUMBER;
5978   valid               BOOLEAN;
5979 
5980   no_warehouses       EXCEPTION;
5981   setup_failure       EXCEPTION;
5982 BEGIN
5983 
5984   IF return_status THEN
5985     v_cp_enabled := TRUE;
5986   ELSE
5987     v_cp_enabled := FALSE;
5988   END IF;
5989 
5990    /* populate the org_string */
5991      IF MSC_CL_GMP_UTILITY.org_string(instance) THEN
5992         NULL ;
5993      ELSE
5994         RAISE invalid_string_value  ;
5995      END IF;
5996 
5997      l_in_str_org := MSC_CL_GMP_UTILITY.g_in_str_org ;    /* B3491625 */
5998 
5999   /* New Changes - Using mtl_organization_id from ic_whse_mst , instead of
6000      organization_id from sy_orgn_mst , Bug# 1252322 */
6001 
6002   retrieval_cursor :=
6003                      ' SELECT iwm.whse_code, iwm.mtl_organization_id '
6004 		   ||' FROM  ic_whse_mst'||at_apps_link||' iwm '
6005 	           ||' WHERE iwm.delete_mark = 0 AND '
6006 		   ||'       iwm.mtl_organization_id IS NOT NULL ';
6007 
6008         IF l_in_str_org  IS NOT NULL THEN     /* B3491625 */
6009            retrieval_cursor := retrieval_cursor
6010                 ||'    AND iwm.mtl_organization_id ' || l_in_str_org ;
6011         END IF;
6012 
6013   OPEN c_whse_cursor FOR retrieval_cursor;
6014 
6015   FETCH c_whse_cursor
6016   INTO  whse_code, organization_id;
6017 
6018   IF c_whse_cursor%NOTFOUND
6019   THEN
6020     raise no_warehouses;
6021   END IF;
6022 
6023   WHILE c_whse_cursor%FOUND
6024   LOOP
6025      INSERT INTO msc_st_sub_inventories
6026 	 (
6027 	   sub_inventory_code,
6028 	   organization_id,
6029 	   netting_type,
6030 	   sr_instance_id,
6031            deleted_flag,
6032 	   creation_date,
6033 	   created_by,
6034 	   last_update_date,
6035 	   last_updated_by
6036 	 )
6037 	 VALUES
6038 	 (
6039 	   whse_code,
6040 	   organization_id,
6041 	   1,
6042 	   instance,
6043            2,
6044 	   run_date,
6045 	   0,
6046 	   run_date,
6047 	   0
6048 	 );
6049 
6050      COMMIT;
6051 
6052      FETCH c_whse_cursor
6053 	 INTO  whse_code, organization_id;
6054 
6055   END LOOP;
6056   CLOSE c_whse_cursor;
6057 
6058   return_status := TRUE;
6059 
6060   EXCEPTION
6061     WHEN invalid_string_value  THEN
6062         log_message('Organization string is Invalid ' );
6063         return_status := FALSE;
6064 
6065     WHEN no_warehouses
6066 	THEN
6067 	  log_message('No warehouses found to export');
6068 	  return_status := TRUE;   /* B3577871 */
6069 
6070     WHEN setup_failure
6071 	THEN
6072 	  log_message('Sub-inventory export setup failure');
6073 	  return_status := FALSE;
6074 
6075     WHEN OTHERS
6076 	THEN
6077 	  log_message('Sub-Inventory Export failed:');
6078 	  log_message(sqlerrm);
6079 	  return_status := FALSE;
6080 END extract_sub_inventory;
6081 
6082 /*
6083 REM+=========================================================================+
6084 REM| PROCEDURE NAME                                                          |
6085 REM|    setup                                                                |
6086 REM|                                                                         |
6087 REM| TYPE                                                                    |
6088 REM|    Private                                                              |
6089 REM|                                                                         |
6090 REM| USAGE                                                                   |
6091 REM|    This procedure sets up and initilialises various program structures  |
6092 REM|    for the extraction of effectivities                                  |
6093 REM|                                                                         |
6094 REM| DESCRIPTION                                                             |
6095 REM|                                                                         |
6096 REM|                                                                         |
6097 REM| INPUT PARAMETERS                                                        |
6098 REM|    apps_link_name VARCHAR2 - database link to APPS database instance    |
6099 REM|    delimtiter_char VARCHAR2 - used to links strings together            |
6100 REM|    instance       INTEGER - the GMP instance ID                         |
6101 REM|    run_date       DATE    - the run date                                |
6102 REM|                                                                         |
6103 REM| OUTPUT PARAMETERS                                                       |
6104 REM|    return_status: TRUE => OK                                            |
6105 REM|                                                                         |
6106 REM| INPUT/OUTPUT PARAMETERS                                                 |
6107 REM|    None                                                                 |
6108 REM|                                                                         |
6109 REM| HISTORY                                                                 |
6110 REM|  07/14/2002   Rajesh Patangya - Reorgnized the complete code B2314052   |
6111 REM+=========================================================================+
6112 */
6113 PROCEDURE setup
6114 (
6115   apps_link_name IN VARCHAR2,
6116   delimiter_char IN VARCHAR2,
6117   instance       IN INTEGER,
6118   run_date       IN DATE,
6119   return_status  OUT NOCOPY BOOLEAN
6120 )
6121 IS
6122   stat           VARCHAR2(1024);
6123   statement_no   INTEGER;
6124 
6125 BEGIN
6126   /* Construct link names */
6127 
6128   IF apps_link_name IS NOT NULL
6129   THEN
6130     at_apps_link := apps_link_name;
6131   ELSE
6132     at_apps_link := ' ';
6133   END IF;
6134 
6135   /* select maximum aps_effectivity ID */
6136 
6137   stat := ' SELECT max(APS_FMEFF_ID) from gmp_form_eff'||at_apps_link ;
6138   EXECUTE IMMEDIATE stat INTO g_aps_eff_id ;
6139 
6140   IF NVL(g_aps_eff_id,0) = 0 THEN
6141      g_aps_eff_id := 1 ;
6142   END IF ;
6143 
6144   /* Everything starts with index # of 1 */
6145 
6146   alt_rsrc_size             := 1;
6147   formula_headers_size      := 1;
6148   formula_details_size	    := 1;
6149   formula_orgn_size         := 1;
6150   routing_headers_size      := 1;
6151   rtg_org_dtl_size          := 1;
6152   rtg_gen_dtl_size          := 1;
6153   material_assocs_size      := 1;
6154   recipe_orgn_over_size     := 1;
6155   recipe_override_size      := 1;
6156   g_mat_assoc      	    := 1;
6157   opr_stpdep_size           := 1;
6158   g_dep_index               := 1;
6159 
6160 /* These variables store the MTQ related values that is last inserted. */
6161   g_old_formula_id          := -1; /* B3970993 */
6162   g_old_recipe_id           := -1; /* B3970993 */
6163   g_old_rtg_id              := -1; /* B3970993 */
6164   g_old_rtgstep_id          := -1; /* B3970993 */
6165   g_old_aps_item_id         := -1; /* B3970993 */
6166   g_mtq_loc                 := -1; /* B3970993 */
6167   g_min_mtq                 := -1; /* B3970993 */
6168 
6169   current_date_time := run_date;
6170 
6171   b_instance_id := instance;
6172 
6173   delimiter := delimiter_char;
6174 
6175   /* Initialize the counter values for bulk inserts */
6176    bom_index   := 0 ;
6177    bomc_index  := 0 ;
6178    or_index    := 0 ;
6179    rtg_index   := 0 ;
6180    opr_index   := 0 ;
6181    rs_index    := 0 ;
6182    oc_index    := 0 ;
6183    mtq_index   := 0 ;
6184 
6185   return_status := TRUE;
6186 
6187    /* Get the directory specified in the 'utl_file_dir' in init.ora file */
6188    BEGIN
6189        SELECT substrb(translate(ltrim(value),',',' '), 1,
6190                      instr(translate(ltrim(value),',',' '),' ') - 1)
6191         INTO p_location
6192         FROM v$parameter
6193        WHERE name = 'utl_file_dir';
6194   EXCEPTION
6195     WHEN OTHERS THEN
6196 	return_status := FALSE;
6197 	log_message('directory select failed ');
6198 	log_message(sqlerrm);
6199     END ;
6200 
6201     IF p_location IS NOT NULL THEN
6202       -- gmp_putline ( 'file opened ' || p_location  || ' at '
6203       --    || TO_CHAR ( SYSDATE, 'DD-MON-YYYY HH24:MI:SS' ), 'w' );
6204       -- gmp_putline ('  ' , 'a' );
6205       null ;
6206     END IF ;
6207 
6208   EXCEPTION
6209     WHEN OTHERS THEN
6210 	return_status := FALSE;
6211 	log_message('Setup failed at statement ');
6212 	log_message(sqlerrm);
6213 
6214 END setup;
6215 /*
6216 REM+=========================================================================+
6217 REM| FUNCTION NAME                                                           |
6218 REM|    find_routing_offsets                                                  |
6219 REM| DESCRIPTION                                                             |
6220 REM|                                                                         |
6221 REM| HISTORY                                                                 |
6222 REM+=========================================================================+
6223 */
6224 FUNCTION find_routing_offsets (p_formula_id    	IN NUMBER,
6225                                p_plant_code 	IN VARCHAR2)
6226                                RETURN NUMBER IS
6227 
6228 i 	    NUMBER ;
6229 retvar 	    NUMBER ;
6230 
6231 BEGIN
6232 i 	    := 1 ;
6233 retvar 	    := -1 ;
6234 
6235 IF p_formula_id = g_prev_formula_id THEN
6236  retvar := g_prev_locn ;
6237  IF g_prev_locn > 0 THEN
6238    g_rstep_loc := g_prev_locn ;
6239  END IF ;
6240 ELSE
6241 g_prev_formula_id := p_formula_id ;
6242 FOR i in g_rstep_loc..rtg_offsets_size
6243 LOOP
6244   IF rstep_offsets(i).formula_id = p_formula_id THEN
6245     IF rstep_offsets(i).plant_code = p_plant_code THEN
6246       retvar := i ;
6247       g_rstep_loc := i ;
6248       EXIT ;
6249     ELSIF rstep_offsets(i).plant_code > p_plant_code THEN
6250       g_rstep_loc := i ;
6251       retvar := -1 ;
6252       EXIT ;
6253     ELSE  /* continue looping */
6254       NULL ;
6255     END IF ;
6256   ELSIF rstep_offsets(i).formula_id < p_formula_id THEN
6257     NULL ;  /* Continue looping */
6258   ELSE -- rstep_offsets(i).formula_id > p_formula_id THEN
6259    retvar := -1 ;
6260    g_rstep_loc := i ;
6261    EXIT ;
6262   END IF;
6263 END LOOP ;
6264 
6265 END IF ; /* different formula_id */
6266  g_prev_locn := retvar ;
6267  return retvar ;
6268 END find_routing_offsets;
6269 
6270 /*
6271 REM+=========================================================================+
6272 REM| FUNCTION NAME                                                           |
6273 REM|    get_offsets                                                          |
6274 REM| DESCRIPTION                                                             |
6275 REM|                                                                         |
6276 REM| HISTORY                                                                 |
6277 REM+=========================================================================+
6278 */
6279 FUNCTION get_offsets( p_formula_id		IN NUMBER,
6280 			p_plant_code 		IN VARCHAR2,
6281 			p_formulaline_id	IN NUMBER )
6282 			RETURN NUMBER IS
6283 
6284 i 	    NUMBER ;
6285 retvar 	    NUMBER ;
6286 
6287 BEGIN
6288 i 	    := 1 ;
6289 retvar 	    := -1 ;
6290 
6291 FOR i in g_rstep_loc..rtg_offsets_size
6292 LOOP
6293   IF rstep_offsets(i).formula_id = p_formula_id THEN
6294     IF rstep_offsets(i).plant_code = p_plant_code THEN
6295       IF rstep_offsets(i).formulaline_id = p_formulaline_id THEN
6296 	retvar := i ;
6297 	g_rstep_loc := i+1 ;
6298 	EXIT ;
6299       ELSIF
6300 	rstep_offsets(i).formulaline_id > p_formulaline_id THEN
6301 	retvar := -1 ;
6302 	g_rstep_loc := i ;
6303 	EXIT ;
6304       ELSE
6305 	NULL ; /* continue looping */
6306       END IF ;
6307     ELSIF rstep_offsets(i).plant_code > p_plant_code THEN
6308       g_rstep_loc := i ;
6309       retvar := -1 ;
6310       EXIT ;
6311     ELSE  /* continue looping */
6312       NULL ;
6313     END IF ;
6314   ELSIF rstep_offsets(i).formula_id < p_formula_id THEN
6315     NULL ;  /* Continue looping */
6316   ELSE -- rstep_offsets(i).formula_id > p_formula_id THEN
6317    retvar := -1 ;
6318    g_rstep_loc := i ;
6319    EXIT ;
6320   END IF;
6321 END LOOP ;
6322  return retvar ;
6323 END get_offsets;
6324 
6325 /*
6326 REM+=========================================================================+
6327 REM| PROCEDURE NAME                                                          |
6328 REM|    gmp_putline                                                          |
6329 REM| HISTORY                                                                 |
6330 REM|    Created by Rajesh Patangya (OPM Development Oracle US)               |
6331 REM+=========================================================================+
6332 */
6333    /* Define a function that open the log file, makes entry into the log file
6334       and close the log file */
6335    PROCEDURE gmp_putline (
6336        v_text                    IN       VARCHAR2,
6337        v_mode                    IN       VARCHAR2 )
6338    IS
6339       LOG   UTL_FILE.file_type;
6340   BEGIN
6341 
6342     IF p_location IS NOT NULL THEN
6343       LOG    :=
6344              UTL_FILE.fopen ( p_location, 'GMPBM11B.log', v_mode );
6345       UTL_FILE.put_line ( LOG, v_text );
6346       UTL_FILE.fflush ( LOG );
6347       UTL_FILE.fclose ( LOG );
6348     ELSE
6349       NULL ;
6350     END IF;
6351 END gmp_putline;
6352 
6353 /*
6354 REM+=========================================================================+
6355 REM| PROCEDURE NAME                                                          |
6356 REM|    time_stamp                                                           |
6357 REM| DESCRIPTION                                                             |
6358 REM|                                                                         |
6359 REM| HISTORY                                                                 |
6360 REM| 07/14/2002   Rajesh Patangya - Reorgnized the complete code B2314052    |
6361 REM+=========================================================================+
6362 */
6363 PROCEDURE time_stamp IS
6364 
6365   cur_time VARCHAR2(25) ;
6366 BEGIN
6367   cur_time := NULL ;
6368 
6369    SELECT to_char(sysdate,'DD-MON-RRRR HH24:MI:SS')
6370    INTO cur_time FROM sys.dual ;
6371 
6372    log_message(cur_time);
6373   EXCEPTION
6374     WHEN OTHERS THEN
6375         log_message('Failure occured in time_stamp');
6376         log_message(sqlerrm);
6377       RAISE;
6378 END time_stamp ;
6379 
6380 /*
6381 REM+=========================================================================+
6382 REM| PROCEDURE NAME                                                          |
6383 REM|    msc_inserts                                                          |
6384 REM| DESCRIPTION                                                             |
6385 REM|    All the Bulk insert to MSC tables for OPM data                       |
6386 REM|                                                                         |
6387 REM| HISTORY                                                                 |
6388 REM| 03/12/2004   Created Rajesh Patangya                                    |
6389 REM|                                                                         |
6390 REM+=========================================================================+
6391 */
6392 PROCEDURE msc_inserts
6393 (
6394   return_status  OUT NOCOPY BOOLEAN
6395 )
6396 IS
6397 
6398 i         integer ;
6399 
6400 BEGIN
6401 stmt_no   := 0 ;
6402 i         := 1;
6403 
6404 /* --------------------------- Process Effectivity Insert ------------------------- */
6405 
6406      stmt_no := 901 ;
6407      i := 1 ;
6408      IF pef_organization_id.FIRST > 0 THEN
6409      FORALL i IN pef_organization_id.FIRST..pef_organization_id.LAST
6410       INSERT INTO msc_st_process_effectivity (
6411              process_sequence_id,
6412              item_id,
6413              organization_id,
6414              effectivity_date,
6415              disable_date,
6416              minimum_quantity,
6417              maximum_quantity,
6418              preference,
6419              routing_sequence_id,
6420              bill_sequence_id,
6421              sr_instance_id,
6422              item_process_cost, line_id,
6423              total_product_cycle_time, primary_line_flag, production_line_rate,
6424              deleted_flag,
6425              last_update_date,
6426              last_updated_by,
6427              creation_date,
6428              created_by )
6429              VALUES
6430              (
6431              pef_process_sequence_id(i) ,
6432              pef_item_id(i) ,
6433              pef_organization_id(i) ,
6434              pef_effectivity_date(i) ,
6435              pef_disable_date(i) ,
6436              pef_minimum_quantity(i) ,
6437              pef_maximum_quantity(i) ,
6438              pef_preference(i) ,
6439              pef_routing_sequence_id(i) ,
6440              pef_bill_sequence_id(i) ,
6441              pef_sr_instance_id(i) ,
6442              null_value, null_value,
6443              null_value, null_value, null_value,
6444              2     ,                           /* Deleted Flag */
6445              pef_last_update_date(i) ,
6446              0  ,                              /* Last Updated By */
6447              pef_creation_date(i)    ,
6448              0                                /* Created By */
6449              ) ;
6450      END IF;
6451 /* -------------------------------  BOM Insert --------------------------- */
6452      stmt_no := 902 ;
6453      i := 1 ;              /* B3837959 MMK Issue */
6454      IF bom_organization_id.FIRST > 0 THEN
6455      FORALL i IN bom_organization_id.FIRST..bom_organization_id.LAST
6456        INSERT INTO msc_st_boms (
6457 	 bill_sequence_id,
6458          sr_instance_id,
6459          organization_id,
6460 	 assembly_item_id,
6461          assembly_type,
6462          alternate_bom_designator,
6463 	 specific_assembly_comment,
6464          scaling_type,
6465          assembly_quantity,
6466 	 uom,
6467 /* NAMIT_CR */
6468          operation_seq_num,
6469          deleted_flag,
6470          last_update_date,
6471          last_updated_by,
6472          creation_date,
6473          created_by )
6474 	 VALUES
6475          (
6476          bom_bill_sequence_id(i),
6477          bom_sr_instance_id(i)  ,
6478          bom_organization_id(i) ,
6479          bom_assembly_item_id(i),
6480          1   ,                             /* Assembly Type  */
6481          bom_alternate_bom_designator(i),
6482          bom_specific_assembly_comment(i),
6483          bom_scaling_type(i)     ,
6484          bom_assembly_quantity(i),
6485          bom_uom(i)              ,
6486 /* NAMIT_CR */
6487          bom_op_seq_number(i)    ,
6488 	 2     ,                           /* Deleted Flag */
6489          bom_last_update_date(i) ,
6490          0  ,                              /* Last Updated By */
6491          bom_creation_date(i)    ,
6492          0                                 /* Created By */
6493          ) ;
6494       END IF;
6495 
6496 
6497 /* --------------------------- BOM Components Insert Stars ------------------------- */
6498 
6499      stmt_no := 903 ;
6500      i := 1 ;
6501      IF bomc_organization_id.FIRST > 0 THEN
6502      FORALL i IN bomc_organization_id.FIRST..bomc_organization_id.LAST
6503         INSERT INTO msc_st_bom_components
6504        (
6505        component_sequence_id,
6506        sr_instance_id,
6507        organization_id,
6508        Inventory_item_id,
6509        using_assembly_id,
6510        bill_sequence_id,
6511        component_type,
6512        scaling_type,
6513        change_notice,
6514        revision,
6515        uom_code,
6516        usage_quantity,
6517        effectivity_date,
6518        contribute_to_step_qty,
6519        disable_date,
6520        from_unit_number,
6521        to_unit_number,
6522        use_up_code,
6523        suggested_effectivity_date,
6524        driving_item_id,
6525        operation_offset_percent,
6526        optional_component,
6527        old_effectivity_date,
6528        wip_supply_type,
6529        planning_factor,
6530        atp_flag,
6531        component_yield_factor,
6532        deleted_flag,
6533        last_update_date,
6534        last_updated_by,
6535        creation_date,
6536        created_by,
6537        scale_multiple,
6538        scale_rounding_variance,
6539        rounding_direction
6540        )
6541        VALUES
6542        (
6543        bomc_component_sequence_id(i),
6544        bomc_sr_instance_id(i),
6545        bomc_organization_id(i),
6546        bomc_Inventory_item_id(i),
6547        bomc_using_assembly_id(i),
6548        bomc_bill_sequence_id(i),
6549        bomc_component_type(i),
6550        bomc_scaling_type(i),
6551        null_value,
6552        null_value,
6553        bomc_uom_code(i),
6554        bomc_usage_quantity(i),
6555        bomc_effectivity_date(i),
6556         /* NAMIT_ASQC */
6557        bomc_contribute_to_step_qty(i),
6558        bomc_disable_date(i),
6559        null_value,
6560        null_value,
6561        null_value,
6562        null_value,
6563        null_value,
6564        bomc_opr_offset_percent(i),
6565        bomc_optional_component(i),
6566        null_value,
6567        bomc_wip_supply_type(i),
6568        null_value,
6569        1,                                /* atp flag */
6570        1,                                /* component_yield_factor */
6571        2     ,                           /* Deleted Flag */
6572        bomc_last_update_date(i) ,
6573        0  ,                              /* Last Updated By */
6574        bomc_creation_date(i)    ,
6575        0 ,                               /* Created By */
6576        bomc_scale_multiple(i),
6577        bomc_scale_rounding_variance(i),
6578        bomc_rounding_direction(i)
6579        );
6580       END IF;
6581 
6582 /* --------------------------- Routing Insert Stars ------------------------- */
6583      stmt_no := 904 ;
6584      i := 1 ;
6585      IF rtg_organization_id.FIRST > 0 THEN
6586      FORALL i IN rtg_organization_id.FIRST..rtg_organization_id.LAST
6587           INSERT INTO msc_st_routings (
6588            routing_sequence_id,
6589            sr_instance_id,
6590            routing_type,
6591            routing_comment,
6592            alternate_routing_designator,
6593            project_id,
6594            task_id,
6595            line_id,
6596            uom_code,
6597            cfm_routing_flag,
6598            ctp_flag,
6599            routing_quantity,
6600            assembly_item_id,
6601            organization_id,
6602            auto_step_qty_flag,
6603            deleted_flag,
6604            last_update_date,
6605            last_updated_by,
6606            creation_date,
6607            created_by )
6608            VALUES (
6609            rtg_routing_sequence_id(i),
6610            rtg_sr_instance_id(i),
6611            1 ,                                    /* routing_type */
6612            rtg_routing_comment(i),
6613            rtg_alt_routing_designator(i),
6614            null_value,
6615            null_value,
6616            null_value,
6617            rtg_uom_code(i),
6618            null_value,
6619            null_value,
6620            rtg_routing_quantity(i),
6621            rtg_assembly_item_id(i),
6622            rtg_organization_id(i),
6623            rtg_auto_step_qty_flag(i),
6624            2,                                   /* Deleted Flag */
6625            rtg_last_update_date(i),             /* Last Update Date */
6626            0,
6627            rtg_creation_date(i),                /* Creation Date */
6628            0 ) ;
6629       END IF;
6630 
6631 /* ----------------------- Operation Resource  Insert --------------------- */
6632      stmt_no := 905 ;
6633      i := 1 ;
6634 
6635   /*
6636      for i in or_operation_sequence_id.FIRST..or_operation_sequence_id.LAST
6637      loop
6638         log_message('========');
6639         log_message('Op seq id '||or_operation_sequence_id(i)) ;
6640         log_message('Res Seq Num '||or_resource_seq_num(i)) ;
6641         log_message('Resource id '||or_resource_id(i)) ;
6642         log_message(' Alternate Num ' ||or_alternate_number(i));
6643         log_message( 'principal flag '||or_principal_flag(i));
6644         log_message( 'Basis type '||or_basis_type(i));
6645         log_message( 'resource usage '||or_resource_usage(i));
6646         log_message( 'Max rsrc units '||or_max_resource_units(i)) ;
6647         log_message(' rsrc units '||or_resource_units(i)) ;
6648         log_message(' uom code '||or_uom_code(i)) ;
6649         log_message('Min capacity '||or_minimum_capacity(i)) ;
6650         log_message('Max capacity '||or_maximum_capacity(i)) ;
6651         log_message('Setup Id '||or_setup_id(i)) ;
6652         log_message('========');
6653      end loop;
6654     */
6655 
6656 --
6657      IF or_operation_sequence_id.FIRST > 0 THEN
6658      FORALL i IN or_operation_sequence_id.FIRST..or_operation_sequence_id.LAST
6659         INSERT INTO msc_st_operation_resources (
6660         operation_sequence_id,
6661         resource_seq_num,
6662         resource_id,
6663         alternate_number,
6664         principal_flag,
6665         basis_type,
6666         resource_usage,
6667         max_resource_units,
6668         resource_units,
6669         uom_code,
6670         deleted_flag,
6671         sr_instance_id,
6672         routing_sequence_id,
6673         organization_id,
6674         minimum_capacity,
6675         maximum_capacity,
6676         setup_id,
6677         orig_resource_seq_num,
6678         breakable_activity_flag,
6679         last_update_date,
6680         last_updated_by,
6681         creation_date,
6682         created_by )
6683         VALUES (
6684         or_operation_sequence_id(i) ,
6685         or_resource_seq_num(i) ,
6686         or_resource_id(i) ,
6687         or_alternate_number(i) ,
6688         or_principal_flag(i) ,
6689         or_basis_type(i) ,
6690         or_resource_usage(i) ,
6691         or_max_resource_units(i) ,
6692         or_resource_units(i) ,
6693         or_uom_code(i) ,
6694         2,
6695         or_sr_instance_id(i) ,
6696         or_routing_sequence_id(i) ,
6697         or_organization_id(i),
6698         or_minimum_capacity(i),
6699         or_maximum_capacity(i),
6700         or_setup_id(i),
6701         or_orig_rs_seq_num(i),
6702         or_break_ind(i),
6703         or_last_update_date(i) ,
6704         0,
6705         or_creation_date(i) ,
6706         0 );
6707       END IF;
6708 /* ----------------------- Operations Insert --------------------- */
6709      stmt_no := 906 ;
6710      i := 1 ;
6711      IF opr_operation_sequence_id.FIRST > 0 THEN
6712      FORALL i IN opr_operation_sequence_id.FIRST..opr_operation_sequence_id.LAST
6713        INSERT INTO msc_st_routing_operations (
6714        operation_sequence_id,
6715        routing_sequence_id,
6716        operation_seq_num,
6717        sr_instance_id,
6718        operation_description,
6719        effectivity_date,
6720        disable_date,
6721        from_unit_number,
6722        to_unit_number,
6723        option_dependent_flag,
6724        operation_type,
6725        minimum_transfer_quantity,
6726        yield,
6727 /* NAMIT_ASQC */
6728        step_quantity,
6729        step_quantity_uom,
6730        department_id,
6731        department_code,
6732        operation_lead_time_percent,
6733        cumulative_yield,
6734        reverse_cumulative_yield,
6735        net_planning_percent,
6736        setup_duration,
6737        tear_down_duration,
6738        uom_code,
6739        organization_id,
6740        standard_operation_code,
6741        deleted_flag,
6742        last_update_date,
6743        last_updated_by,
6744        creation_date,
6745        created_by )
6746        VALUES
6747        (
6748        opr_operation_sequence_id(i),
6749        opr_routing_sequence_id(i),
6750        opr_operation_seq_num(i),
6751        opr_sr_instance_id(i),
6752        opr_operation_description(i),
6753        opr_effectivity_date(i),
6754        null_value,
6755        null_value,
6756        null_value,
6757        1,
6758        null_value,
6759        opr_mtransfer_quantity(i),    /*B2870041*/
6760        null_value, /*  B2365684 rtg_org_dtl_tab(loop_index).step_qty, */
6761 /* NAMIT_ASQC */
6762        opr_step_qty(i),
6763        opr_step_qty_uom(i),
6764        opr_department_id(i),
6765        opr_department_code(i),
6766        null_value,
6767        null_value,
6768        null_value,
6769        null_value,
6770        null_value,
6771        null_value,
6772        opr_uom_code(i),
6773        opr_organization_id(i),
6774        null_value ,
6775        2,                    /* Deleted Flag */
6776        opr_last_update_date(i),
6777        0,
6778        opr_creation_date(i),
6779        0 ) ;
6780       END IF;
6781 
6782 /* ----------------------- Operation Sequence Insert --------------------- */
6783      stmt_no := 907 ;
6784      i := 1 ;
6785      IF rs_operation_sequence_id.FIRST > 0 THEN
6786      FORALL i IN rs_operation_sequence_id.FIRST..rs_operation_sequence_id.LAST
6787        INSERT INTO msc_st_operation_resource_seqs (
6788        operation_sequence_id,
6789        resource_seq_num,
6790        sr_instance_id,
6791        department_id,
6792        resource_offset_percent,
6793        schedule_flag,
6794        routing_sequence_id,
6795        organization_id,
6796        deleted_flag,
6797        last_update_date,
6798        last_updated_by,
6799        creation_date,
6800        created_by,
6801        activity_group_id )
6802        VALUES (
6803        rs_operation_sequence_id(i),
6804        rs_resource_seq_num(i),
6805        rs_sr_instance_id(i),
6806        rs_department_id(i),
6807        null_value,
6808        rs_schedule_flag(i),
6809        rs_routing_sequence_id(i),
6810        rs_organization_id(i),
6811        2,                         /* deleted flag */
6812        rs_last_update_date(i),
6813        0,
6814        rs_creation_date(i),
6815        0 ,
6816        rs_activity_group_id(i)
6817        ) ;
6818       END IF;
6819 
6820 /* ----------------------- Operation Component Insert --------------------- */
6821      stmt_no := 908 ;
6822      i := 1 ;
6823   /*
6824      for i in oc_operation_sequence_id.FIRST..oc_operation_sequence_id.LAST
6825      loop
6826         log_message('========');
6827         log_message('Op seq id '||oc_operation_sequence_id(i)) ;
6828         log_message('Comp seq id '||oc_component_sequence_id(i)) ;
6829         log_message('Instance '||oc_sr_instance_id(i)) ;
6830         log_message('Bill Seq '||oc_bill_sequence_id(i)) ;
6831         log_message('Routing Seq '||oc_routing_sequence_id(i)) ;
6832         log_message('Org Id '||oc_organization_id(i)) ;
6833      end loop;
6834   */
6835      IF oc_operation_sequence_id.FIRST > 0 THEN
6836      FORALL i IN oc_operation_sequence_id.FIRST..oc_operation_sequence_id.LAST
6837       INSERT INTO msc_st_operation_components (
6838       operation_sequence_id, component_sequence_id, sr_instance_id,
6839       bill_sequence_id, routing_sequence_id, organization_id,
6840       deleted_flag, last_update_date, last_updated_by,
6841       creation_date, created_by )
6842       VALUES (
6843       oc_operation_sequence_id(i),
6844       oc_component_sequence_id(i),
6845       oc_sr_instance_id(i),
6846       oc_bill_sequence_id(i),
6847       oc_routing_sequence_id(i),
6848       oc_organization_id(i),
6849       2,
6850       oc_last_update_date(i),
6851       0,
6852       oc_creation_date(i),
6853       0   ) ;
6854 
6855       END IF;
6856 
6857 /* ----------------------- MTQ Insert --------------------- */
6858 /*  NAMIT_MTQ */
6859 
6860      stmt_no := 909 ;
6861      i := 1 ;
6862      IF itm_mtq_from_op_seq_id.FIRST > 0 THEN
6863      FORALL i IN itm_mtq_from_op_seq_id.FIRST..itm_mtq_from_op_seq_id.LAST
6864        INSERT INTO msc_st_operation_networks(
6865        from_op_seq_id,
6866        routing_sequence_id,
6867        dependency_type,
6868        transition_type,
6869        plan_id,
6870        sr_instance_id,
6871        deleted_flag,
6872        from_item_id,
6873        organization_id,
6874        minimum_transfer_qty,
6875        minimum_time_offset,
6876        maximum_time_offset,
6877        last_update_date,
6878        last_updated_by,
6879        creation_date,
6880        created_by,
6881        from_op_seq_num
6882        ) VALUES
6883        (
6884         itm_mtq_from_op_seq_id(i),
6885         itm_mtq_routing_sequence_id(i),
6886         5, /* MTQ with Hardlink */
6887         1, /* Primary */
6888         -1,
6889         itm_mtq_sr_instance_id(i),
6890         2,
6891         itm_mtq_from_item_id(i),
6892         itm_mtq_organization_id(i),
6893         itm_mtq_min_tran_qty(i),
6894         itm_mtq_min_time_offset(i),
6895         itm_mtq_max_time_offset(i),
6896         opr_last_update_date(i),
6897         0,
6898         opr_creation_date(i),
6899         0,
6900         itm_mtq_frm_op_seq_num(i)
6901        );
6902 
6903       END IF;
6904 
6905 /* ----------------------- Step Dependency Insert --------------------- */
6906 /* NAMIT_CR */
6907 
6908      stmt_no := 910 ;
6909      i := 1 ;
6910      IF opr_stpdep_frm_seq_id.FIRST > 0 THEN
6911      FORALL i IN opr_stpdep_frm_seq_id.FIRST..opr_stpdep_frm_seq_id.LAST
6912        INSERT INTO msc_st_operation_networks(
6913        from_op_seq_id,
6914        to_op_seq_id,
6915        routing_sequence_id,
6916        dependency_type,
6917        transition_type,
6918        plan_id,
6919        sr_instance_id,
6920        deleted_flag,
6921        minimum_time_offset,
6922        maximum_time_offset,
6923        transfer_pct,
6924        last_update_date,
6925        last_updated_by,
6926        creation_date,
6927        created_by,
6928        from_op_seq_num,
6929        to_op_seq_num,
6930        apply_to_charges,
6931        organization_id
6932        ) VALUES
6933        (
6934         opr_stpdep_frm_seq_id(i),
6935         opr_stpdep_to_seq_id(i),
6936         opr_stpdep_routing_sequence_id(i),
6937         opr_stpdep_dependency_type(i),
6938         1, /* Transition Type, 1 = Primary*/
6939         -1, /* Plan Id */
6940         opr_stpdep_sr_instance_id(i),
6941         2, /* Deleted Flag */
6942         opr_stpdep_min_time_offset(i),
6943         opr_stpdep_max_time_offset(i),
6944         opr_stpdep_trans_pct(i),
6945         opr_last_update_date(i),
6946         0,
6947         opr_creation_date(i),
6948         0,
6949         opr_stpdep_frm_op_seq_num(i),
6950         opr_stpdep_to_op_seq_num(i),
6951         opr_stpdep_app_to_chrg(i),
6952         opr_stpdep_organization_id(i)
6953        );
6954 
6955       END IF;
6956               bom_organization_id.delete  ;
6957               bomc_organization_id.delete ;
6958               pef_organization_id.delete ;
6959               rtg_organization_id.delete ;
6960               oc_organization_id.delete ;
6961               opr_organization_id.delete   ;
6962               or_organization_id.delete ;
6963               rs_organization_id.delete ;
6964 
6965               bom_bill_sequence_id.delete ;
6966               bomc_bill_sequence_id.delete ;
6967               pef_bill_sequence_id.delete ;
6968               oc_bill_sequence_id.delete ;
6969 
6970               bom_last_update_date.delete ;
6971               bomc_last_update_date.delete ;
6972               pef_last_update_date.delete ;
6973               rtg_last_update_date.delete ;
6974               or_last_update_date.delete ;
6975               opr_last_update_date.delete ;
6976               rs_last_update_date.delete ;
6977               oc_last_update_date.delete ;
6978 
6979               bom_creation_date.delete ;
6980               bomc_creation_date.delete ;
6981               pef_creation_date.delete ;
6982               rtg_creation_date.delete ;
6983               or_creation_date.delete ;
6984               opr_creation_date.delete ;
6985               rs_creation_date.delete ;
6986               oc_creation_date.delete ;
6987 
6988               pef_effectivity_date.delete ;
6989               bomc_effectivity_date.delete ;
6990               opr_effectivity_date.delete ;
6991 
6992               rtg_routing_sequence_id.delete ;
6993               pef_routing_sequence_id.delete ;
6994               or_routing_sequence_id.delete ;
6995               opr_routing_sequence_id.delete ;
6996               rs_routing_sequence_id.delete ;
6997               oc_routing_sequence_id.delete ;
6998 
6999               bomc_uom_code.delete;
7000               rtg_uom_code.delete;
7001               or_uom_code.delete ;
7002               opr_uom_code.delete;
7003 
7004               bom_assembly_item_id.delete ;
7005               rtg_assembly_item_id.delete ;
7006 
7007               bomc_component_sequence_id.delete ;
7008               oc_component_sequence_id.delete ;
7009 
7010               or_operation_sequence_id.delete  ;
7011               opr_operation_sequence_id.delete ;
7012               rs_operation_sequence_id.delete ;
7013               oc_operation_sequence_id.delete ;
7014 
7015               or_resource_seq_num.delete ;
7016               rs_resource_seq_num.delete ;
7017 
7018             /* -- BOM Variable Initialization -- */
7019               bom_alternate_bom_designator.delete ;
7020               bom_specific_assembly_comment.delete ;
7021               bom_scaling_type.delete ;
7022               bom_assembly_quantity.delete ;
7023               bom_uom.delete ;
7024               bom_index := 0 ;
7025 
7026             /* -- BOMC Variable Initialization -- */
7027               bomc_Inventory_item_id.delete ;
7028               bomc_using_assembly_id.delete ;
7029               bomc_component_type.delete ;
7030               bomc_scaling_type.delete ;
7031               bomc_usage_quantity.delete ;
7032               bomc_opr_offset_percent.delete  ;
7033               bomc_optional_component.delete  ;
7034               bomc_wip_supply_type.delete ;
7035               bomc_scale_multiple.delete  ;
7036               bomc_scale_rounding_variance.delete ;
7037               bomc_rounding_direction.delete  ;
7038               bomc_index := 0 ;
7039 
7040             /* -- Pef Variable Initialization -- */
7041               pef_process_sequence_id.delete ;
7042               pef_item_id.delete ;
7043               pef_disable_date.delete ;
7044               pef_minimum_quantity.delete ;
7045               pef_maximum_quantity.delete ;
7046               pef_preference.delete ;
7047               pef_index := 0 ;
7048 
7049             /* -- Rtg Variable Initialization -- */
7050               rtg_routing_comment.delete ;
7051               rtg_alt_routing_designator.delete ;
7052               rtg_routing_quantity.delete ;
7053               rtg_index := 0 ;
7054 
7055             /* -- Or Variable Initialization -- */
7056               or_resource_id.delete ;
7057               or_alternate_number.delete ;
7058               or_principal_flag.delete ;
7059               or_basis_type.delete ;
7060               or_resource_usage.delete ;
7061               or_max_resource_units.delete ;
7062               or_resource_units.delete ;
7063               or_index := 0 ;
7064 
7065             /* -- Opr Variable Initialization -- */
7066               opr_operation_seq_num.delete ;
7067               opr_operation_description.delete ;
7068               opr_mtransfer_quantity.delete ;
7069               opr_department_id.delete ;
7070               rs_department_id.delete ;
7071               opr_department_code.delete ;
7072               rs_activity_group_id.delete ;
7073               rs_schedule_flag.delete ;
7074               opr_index := 0 ;
7075               rs_index := 0 ;
7076               oc_index := 0 ;
7077 
7078               dbms_session.free_unused_user_memory;/* akaruppa B5007729 */
7079 
7080 
7081         return_status := TRUE ;
7082   EXCEPTION
7083     WHEN OTHERS THEN
7084         log_message('Error in MSC Inserts : '||stmt_no || ':' || sqlerrm);
7085         return_status := FALSE;
7086 
7087 END msc_inserts ;
7088 --
7089 /*
7090 REM+=========================================================================+
7091 REM| PROCEDURE NAME                                                          |
7092 REM|    write_setups_and_transitions                                         |
7093 REM|                                                                         |
7094 REM| TYPE                                                                    |
7095 REM|    Private                                                              |
7096 REM|                                                                         |
7097 REM| USAGE                                                                   |
7098 REM|    This procedure inserts rows into msc_st_resource_setups and          |
7099 REM|    msc_st_setup_transitions                                             |
7100 REM|                                                                         |
7101 REM| DESCRIPTION                                                             |
7102 REM|                                                                         |
7103 REM|                                                                         |
7104 REM| INPUT PARAMETERS                                                        |
7105 REM|    None                                                                 |
7106 REM|                                                                         |
7107 REM| OUTPUT PARAMETERS                                                       |
7108 REM|    None                                                                 |
7109 REM|                                                                         |
7110 REM| INPUT/OUTPUT PARAMETERS                                                 |
7111 REM|    None                                                                 |
7112 REM|                                                                         |
7113 REM| HISTORY                                                                 |
7114 REM|  06/02/2004   Sridhar Gidugu  created                                   |
7115 REM|  0519/06 Rewrite for SDS                                                |
7116 REM|   MSC_RESOURCE_SETUPS unique key is ON                                  |
7117 REM|   Instance_id,resource_id,organization_id and setup_id                  |
7118 REM+=========================================================================+
7119 */
7120 PROCEDURE write_setups_and_transitions
7121 (
7122   return_status  OUT NOCOPY BOOLEAN
7123 )  IS
7124    l_profile            VARCHAR2(4);
7125    Zero_tran            VARCHAR2(25000);
7126    fact_tran            VARCHAR2(25000);
7127    rsrc_setup           VARCHAR2(25000);
7128    um_code_cursor       VARCHAR2(1000);
7129    um_code_ref          ref_cursor_typ;
7130 BEGIN
7131    stmt_no     := 0 ;
7132    Zero_tran   := NULL ;
7133    fact_tran   := NULL ;
7134    rsrc_setup  := NULL ;
7135    um_code_cursor   := ' select fnd_profile.VALUE' ||at_apps_link
7136                       ||' (''BOM:HOUR_UOM_CODE'') from dual ' ;
7137 
7138        OPEN um_code_ref FOR um_code_cursor ;
7139        FETCH um_code_ref INTO l_profile;
7140        CLOSE um_code_ref;
7141 
7142      -- ZERO Transitions  (Alternate Resources are considered)
7143      stmt_no := 910 ;
7144      Zero_tran := ' INSERT INTO msc_st_setup_transitions ( '
7145      ||'    resource_id,          '
7146      ||'    organization_id,     '
7147      ||'    from_setup_id,        '
7148      ||'    to_setup_id,         '
7149      ||'    transition_time,      '
7150      ||'    transition_penalty,   '
7151      ||'    transition_uom,       '
7152      ||'    sr_instance_id,     '
7153      ||'    deleted_flag )   '
7154      ||' SELECT  '
7155      ||'    ((a.resource_id * 2 ) +1 ), '
7156      ||'    a.mtl_organization_id, '
7157      ||'    a.seq_dep_id, '
7158      ||'    b.seq_dep_id, '
7159      ||'    0 setup_time, '
7160      ||'    0 penalty_factor, '
7161      ||'    :profile, '
7162      ||'    :instance1 , '
7163      ||'    2 '
7164      ||' FROM ( '
7165      ||' SELECT '
7166      ||' iwm.mtl_organization_id, '
7167      ||' s.category_id, '
7168      ||' s.seq_dep_id, '
7169      ||' o.oprn_id, '
7170      ||' rd.resource_id, '
7171      ||' count(o.oprn_id) OVER (PARTITION BY rd.orgn_code,s.category_id,rd.resource_id) CNT '
7172      ||' FROM '
7173      ||'     ic_whse_mst'||at_apps_link||' iwm, '
7174      ||'     sy_orgn_mst'||at_apps_link||' sy, '
7175      ||'     cr_rsrc_dtl'||at_apps_link||' rd, '
7176      ||'     gmp_sequence_types'||at_apps_link||' s, '
7177      ||'     gmd_operation_resources'||at_apps_link||' r, '
7178      ||'     gmd_operation_activities'||at_apps_link||' a, '
7179      ||'     gmd_operations'||at_apps_link||' o '
7180      ||' WHERE o.oprn_id = a.oprn_id '
7181      ||' AND a.oprn_line_id = r.oprn_line_id '
7182      ||' AND rd.orgn_code = sy.orgn_code '
7183      ||' AND sy.resource_whse_code = iwm.whse_code '
7184      ||' AND a.sequence_dependent_ind = 1 '
7185      ||' AND r.prim_rsrc_ind = 1 '
7186      ||' AND r.resources = rd.resources '
7187      ||' AND o.oprn_id = s.oprn_id ' ;
7188 --     ||' AND iwm.mtl_organization_id in (1381,1382,1383,11159) '
7189      IF l_in_str_org  IS NOT NULL THEN
7190       Zero_tran := Zero_tran
7191       ||'   AND iwm.mtl_organization_id ' || l_in_str_org  ;
7192      END IF;
7193      Zero_tran := Zero_tran
7194      ||' UNION ALL '
7195      ||' SELECT '
7196      ||' rd.mtl_organization_id, '
7197      ||' s.category_id, '
7198      ||' s.seq_dep_id, '
7199      ||' o.oprn_id, '
7200      ||' rd.alt_resource_id, '
7201      ||' count(o.oprn_id) OVER (PARTITION BY rd.mtl_organization_id,s.category_id,rd.alt_resource_id) CNT '
7202      ||' FROM '
7203      ||'     gmp_sequence_types'||at_apps_link||' s, '
7204      ||'     gmd_operation_resources'||at_apps_link||' r, '
7205      ||'     gmd_operation_activities'||at_apps_link||' a, '
7206      ||'     gmd_operations'||at_apps_link||' o, '
7207      ||' (SELECT pcrd.resource_id prim_resource_id, '
7208      ||'         pcrd.resources prim_resources,  '
7209      ||'         acrd.resource_id alt_resource_id,  '
7210      ||'         acrd.resources alt_resources, '
7211      ||'         iwm.mtl_organization_id  '
7212      ||'                     FROM  ic_whse_mst'||at_apps_link||' iwm,  '
7213      ||'                           sy_orgn_mst'||at_apps_link||' sy,  '
7214      ||'                           cr_rsrc_dtl'||at_apps_link||' acrd,  '
7215      ||'                           cr_rsrc_dtl'||at_apps_link||' pcrd,  '
7216      ||'                           cr_ares_mst'||at_apps_link||' cam  '
7217      ||'                     WHERE cam.alternate_resource = acrd.resources  '
7218      ||'                       AND cam.primary_resource = pcrd.resources  '
7219      ||'                       AND acrd.orgn_code = pcrd.orgn_code  '
7220      ||'                       AND acrd.orgn_code = sy.orgn_code'
7221      ||'                       AND sy.resource_whse_code = iwm.whse_code  ' ;
7222 --     ||'                       AND iwm.mtl_organization_id in (1381,1382,1383,11159) '
7223      IF l_in_str_org  IS NOT NULL THEN
7224         Zero_tran := Zero_tran
7225         ||'   AND iwm.mtl_organization_id ' || l_in_str_org  ;
7226      END IF;
7227      Zero_tran := Zero_tran
7228      ||'                       AND acrd.delete_mark = 0   '
7229      ||'                     ORDER BY pcrd.resource_id ) rd '
7230      ||' WHERE o.oprn_id = a.oprn_id '
7231      ||' AND a.oprn_line_id = r.oprn_line_id '
7232      ||' AND a.sequence_dependent_ind = 1 '
7233      ||' AND r.prim_rsrc_ind = 1 '
7234      ||' AND o.oprn_id = s.oprn_id '
7235      ||' AND r.resources = rd.prim_resources '
7236      ||' ) a, '
7237      ||' ( '
7238      ||' SELECT '
7239      ||' iwm.mtl_organization_id, '
7240      ||' s.category_id, '
7241      ||' s.seq_dep_id, '
7242      ||' o.oprn_id, '
7243      ||' rd.resource_id, '
7244      ||' count(o.oprn_id) OVER (PARTITION BY rd.orgn_code,s.category_id,rd.resource_id) CNT '
7245      ||' FROM '
7246      ||'     ic_whse_mst'||at_apps_link||' iwm, '
7247      ||'     sy_orgn_mst'||at_apps_link||' sy, '
7248      ||'     cr_rsrc_dtl'||at_apps_link||' rd, '
7249      ||'     gmp_sequence_types'||at_apps_link||' s, '
7250      ||'     gmd_operation_resources'||at_apps_link||' r, '
7251      ||'     gmd_operation_activities'||at_apps_link||' a, '
7252      ||'     gmd_operations'||at_apps_link||' o '
7253      ||' WHERE o.oprn_id = a.oprn_id '
7254      ||' AND a.oprn_line_id = r.oprn_line_id '
7255      ||' AND rd.orgn_code = sy.orgn_code '
7256      ||' AND sy.resource_whse_code = iwm.whse_code '
7257      ||' AND a.sequence_dependent_ind = 1 '
7258      ||' AND r.prim_rsrc_ind = 1 '
7259      ||' AND r.resources = rd.resources '
7260      ||' AND o.oprn_id = s.oprn_id ' ;
7261 --     ||' AND iwm.mtl_organization_id in (1381,1382,1383,11159) '
7262      IF l_in_str_org  IS NOT NULL THEN
7263         Zero_tran := Zero_tran
7264         ||'   AND iwm.mtl_organization_id ' || l_in_str_org  ;
7265      END IF;
7266      Zero_tran := Zero_tran
7267      ||' UNION ALL '
7268      ||' SELECT '
7269      ||' rd.mtl_organization_id, '
7270      ||' s.category_id, '
7271      ||' s.seq_dep_id, '
7272      ||' o.oprn_id, '
7273      ||' rd.alt_resource_id, '
7274      ||' count(o.oprn_id) OVER (PARTITION BY rd.mtl_organization_id,s.category_id,rd.alt_resource_id) CNT '
7275      ||' FROM '
7276      ||'     gmp_sequence_types'||at_apps_link||' s, '
7277      ||'     gmd_operation_resources'||at_apps_link||' r, '
7278      ||'     gmd_operation_activities'||at_apps_link||' a, '
7279      ||'     gmd_operations'||at_apps_link||' o, '
7280      ||' (SELECT pcrd.resource_id prim_resource_id, '
7281      ||'         pcrd.resources prim_resources,  '
7282      ||'         acrd.resource_id alt_resource_id,  '
7283      ||'         acrd.resources alt_resources, '
7284      ||'         iwm.mtl_organization_id  '
7285      ||'                     FROM  ic_whse_mst'||at_apps_link||' iwm,  '
7286      ||'                           sy_orgn_mst'||at_apps_link||' sy,  '
7287      ||'                           cr_rsrc_dtl'||at_apps_link||' acrd,  '
7288      ||'                           cr_rsrc_dtl'||at_apps_link||' pcrd,  '
7289      ||'                           cr_ares_mst'||at_apps_link||' cam  '
7290      ||'                     WHERE cam.alternate_resource = acrd.resources  '
7291      ||'                       AND cam.primary_resource = pcrd.resources  '
7292      ||'                       AND acrd.orgn_code = sy.orgn_code  '
7293      ||'                       AND sy.resource_whse_code = iwm.whse_code  '
7294      ||'                       AND acrd.orgn_code = pcrd.orgn_code  ' ;
7295 --     ||'                       AND iwm.mtl_organization_id in (1381,1382,1383,11159) '
7296      IF l_in_str_org  IS NOT NULL THEN
7297         Zero_tran := Zero_tran
7298         ||'   AND iwm.mtl_organization_id ' || l_in_str_org  ;
7299      END IF;
7300 
7301      Zero_tran := Zero_tran
7302      ||'                       AND acrd.delete_mark = 0   '
7303      ||'                     ORDER BY pcrd.resource_id ) rd '
7304      ||' WHERE o.oprn_id = a.oprn_id '
7305      ||' AND a.oprn_line_id = r.oprn_line_id '
7306      ||' AND a.sequence_dependent_ind = 1 '
7307      ||' AND r.prim_rsrc_ind = 1 '
7308      ||' AND o.oprn_id = s.oprn_id '
7309      ||' AND r.resources = rd.prim_resources '
7310      ||' ORDER BY 1,2,4,3 '
7311      ||' ) b '
7312      ||' WHERE a.mtl_organization_id = b.mtl_organization_id '
7313      ||'   AND a.category_id = b.category_id '
7314      ||'   AND a.resource_id = b.resource_id '
7315      ||'   AND a.cnt = b.cnt '
7316      ||'   AND a.seq_dep_id <> b.seq_dep_id '
7317      ||'   AND a.cnt > 1 ' ;
7318 
7319      IF l_in_str_org  IS NOT NULL THEN
7320         Zero_tran := Zero_tran
7321         ||' AND  a.mtl_organization_id ' || l_in_str_org  ;
7322      END IF;
7323 
7324      EXECUTE IMMEDIATE Zero_tran USING l_profile, b_instance_id ;
7325     -- Fact Transitions (Alternate Resources are considered)
7326      stmt_no := 920 ;
7327      Fact_tran := ' INSERT INTO msc_st_setup_transitions ( '
7328      ||'   resource_id, '
7329      ||'   organization_id, '
7330      ||'   from_setup_id, '
7331      ||'   to_setup_id, '
7332      ||'   transition_time, '
7333      ||'   transition_penalty, '
7334      ||'   transition_uom, '
7335      ||'   sr_instance_id, '
7336      ||'   deleted_flag ) '
7337      ||' SELECT unique  '
7338      ||'   b.resource_id, '
7339      ||'   b.organization_id, '
7340      ||'   a.from_seq_dep_id, '
7341      ||'   a.to_seq_dep_id, '
7342      ||'   a.setup_time, '
7343      ||'   a.penalty_factor, '
7344      ||'   b.uom_code, '
7345      ||'   b.sr_instance_id, '
7346      ||'   b.deleted_flag '
7347      ||' FROM gmp_sequence_dependencies'||at_apps_link||' a, '
7348      ||'     (select unique RESOURCE_ID, ORGANIZATION_ID,'
7349      ||'       setup_id , deleted_flag, sr_instance_id, uom_code '
7350      ||'   from msc_st_operation_resources '
7351      ||'      WHERE sr_instance_id = :instance1 '
7352      ||'   and setup_id is not null  ) b '
7353      ||' WHERE ( b.setup_id = a.from_seq_dep_id OR '
7354      ||'         b.setup_id = a.to_seq_dep_id ) '  ;
7355      IF l_in_str_org  IS NOT NULL THEN
7356         Fact_tran := Fact_tran
7357         ||'   AND b.organization_id ' || l_in_str_org  ;
7358      END IF;
7359 
7360      EXECUTE IMMEDIATE Fact_tran USING b_instance_id ;
7361 
7362    -- Resource Setups (Alternate Resources are considered)
7363    stmt_no := 930 ;
7364    rsrc_setup := ' INSERT INTO msc_st_resource_setups ( '
7365     ||'   resource_id,      '
7366     ||'   organization_id,  '
7367     ||'   sr_instance_id,   '
7368     ||'   setup_id,         '
7369     ||'   setup_code,       '
7370     ||'   setup_description,'
7371     ||'   deleted_flag   ) '
7372     ||'SELECT unique  '
7373     ||'   mst.resource_id, '
7374     ||'   mst.organization_id, '
7375     ||'   mst.sr_instance_id, '
7376     ||'   gst.SEQ_DEP_ID , '
7377     ||'   mc.CONCATENATED_SEGMENTS, '
7378     ||'   mc.CONCATENATED_SEGMENTS, '
7379     ||'   2 '
7380     ||' FROM gmp_sequence_types'||at_apps_link||' gst, '
7381     ||'     MTL_CATEGORIES_B_KFV'||at_apps_link||' mc, '
7382     ||'    ( SELECT unique mt.organization_id, mt.resource_id, '
7383     ||'      mt.transition_uom,mt.sr_instance_id, '
7384     ||'      mt.deleted_flag , mt.from_setup_id, mt.to_setup_id '
7385     ||'      FROM mtl_parameters'||at_apps_link|| ' mp, '
7386     ||'       msc_st_setup_transitions mt  '
7387     ||'      WHERE mp.organization_id = mt.organization_id AND '
7388     ||'       mp.process_enabled_flag = '|| ''''||'Y'||'''' ||' )  mst '
7389     ||' WHERE gst.oprn_id <> -1 '
7390     ||'  AND mc.category_id = gst.category_id  '
7391     ||'  AND mst.sr_instance_id = :instance1 '
7392     ||'  AND (gst.seq_dep_id = mst.from_setup_id OR '
7393     ||'       gst.seq_dep_id = mst.to_setup_id )  ' ;
7394 
7395     IF l_in_str_org  IS NOT NULL THEN
7396       rsrc_setup := rsrc_setup
7397       ||'     AND mst.organization_id ' || l_in_str_org  ;
7398     END IF;
7399 
7400        EXECUTE IMMEDIATE rsrc_setup USING b_instance_id ;
7401 
7402         return_status := TRUE ;
7403   EXCEPTION
7404     WHEN NO_DATA_FOUND THEN
7405       NULL ;
7406       return_status := TRUE ;
7407     WHEN OTHERS THEN
7408        log_message('Write setups and Transitions Exception: '||sqlerrm||'-'||stmt_no);
7409         return_status := FALSE ;
7410 
7411 END write_setups_and_transitions ;
7412 
7413 /*
7414 REM+=========================================================================+
7415 REM| PROCEDURE NAME                                                          |
7416 REM|    write_step_dependency                                                |
7417 REM|                                                                         |
7418 REM| TYPE                                                                    |
7419 REM|    Private                                                              |
7420 REM|                                                                         |
7421 REM| USAGE                                                                   |
7422 REM|    This procedure inserts rows for step dependency                      |
7423 REM|                                                                         |
7424 REM| DESCRIPTION                                                             |
7425 REM|                                                                         |
7426 REM|                                                                         |
7427 REM| INPUT PARAMETERS                                                        |
7428 REM|    None                                                                 |
7429 REM|                                                                         |
7430 REM| OUTPUT PARAMETERS                                                       |
7431 REM|    None                                                                 |
7432 REM|                                                                         |
7433 REM| INPUT/OUTPUT PARAMETERS                                                 |
7434 REM|    None                                                                 |
7435 REM|                                                                         |
7436 REM| HISTORY                                                                 |
7437 REM|  06/16/2004   Namit Singhi created                                      |
7438 REM+=========================================================================+
7439 */
7440 
7441 PROCEDURE write_step_dependency (
7442   p_x_aps_fmeff_id   IN NUMBER
7443 )
7444 IS
7445 
7446   stpdep_start_index   INTEGER;
7447   stpdep_end_index     INTEGER;
7448   dep_index            NUMBER ;
7449 
7450 BEGIN
7451 
7452    dep_index := g_dep_index ;
7453 
7454 /* Get index for Routing Step Dependency */
7455   stpdep_start_index :=
7456       rtg_org_hdr_tab(effectivity.rtg_hdr_location).stpdep_start_loc ;
7457   stpdep_end_index :=
7458       rtg_org_hdr_tab(effectivity.rtg_hdr_location).stpdep_end_loc ;
7459 
7460   IF ((stpdep_start_index > 0) AND (stpdep_end_index > 0) AND (stpdep_end_index >= stpdep_start_index)) THEN
7461       FOR stpdp_cnt IN stpdep_start_index..stpdep_end_index
7462       LOOP
7463           opr_stpdep_frm_seq_id(dep_index) :=  gmp_opr_stpdep_tbl(stpdp_cnt).x_dep_routingstep_id;
7464           opr_stpdep_to_seq_id(dep_index) :=  gmp_opr_stpdep_tbl(stpdp_cnt).x_routingstep_id;
7465           opr_stpdep_routing_sequence_id(dep_index) := p_x_aps_fmeff_id ;
7466           opr_stpdep_dependency_type(dep_index) := gmp_opr_stpdep_tbl(stpdp_cnt).dep_type;
7467           opr_stpdep_sr_instance_id(dep_index) := b_instance_id ;
7468           opr_stpdep_min_time_offset(dep_index) := gmp_opr_stpdep_tbl(stpdp_cnt).standard_delay;
7469           opr_stpdep_max_time_offset(dep_index) := gmp_opr_stpdep_tbl(stpdp_cnt).max_delay;
7470           opr_stpdep_trans_pct(dep_index) := gmp_opr_stpdep_tbl(stpdp_cnt).transfer_pct;
7471           opr_stpdep_frm_op_seq_num(dep_index) := gmp_opr_stpdep_tbl(stpdp_cnt).dep_routingstep_no;
7472           opr_stpdep_to_op_seq_num(dep_index) := gmp_opr_stpdep_tbl(stpdp_cnt).routingstep_no;
7473           opr_stpdep_app_to_chrg(dep_index) := gmp_opr_stpdep_tbl(stpdp_cnt).chargeable_ind;
7474           opr_stpdep_organization_id(dep_index) := effectivity.organization_id;
7475           dep_index := dep_index + 1;
7476       END LOOP;  /* Step Dependency loop */
7477   END IF;
7478     g_dep_index := dep_index ;
7479 
7480 END write_step_dependency ;
7481 
7482 /*
7483 REM+=========================================================================+
7484 REM| FUNCTION NAME                                                           |
7485 REM|    enh_bsearch_stpno                                                    |
7486 REM|                                                                         |
7487 REM| TYPE                                                                    |
7488 REM|    Private                                                              |
7489 REM|                                                                         |
7490 REM| USAGE                                                                   |
7491 REM|    This function returns the location in mat_assoc_tab                  |
7492 REM|    for given recipe, formula and formulaline_id                         |
7493 REM|                                                                         |
7494 REM| DESCRIPTION                                                             |
7495 REM|                                                                         |
7496 REM|                                                                         |
7497 REM| INPUT PARAMETERS                                                        |
7498 REM|    l_formula_id   IN NUMBER                                             |
7499 REM|    l_recipe_id IN NUMBER                                                |
7500 REM|    l_item_id IN NUMBER                                                  |
7501 REM|                                                                         |
7502 REM| OUTPUT PARAMETERS                                                       |
7503 REM|    INTEGER - Location in mat_assoc_tab                                  |
7504 REM|                                                                         |
7505 REM| INPUT/OUTPUT PARAMETERS                                                 |
7506 REM|    None                                                                 |
7507 REM|                                                                         |
7508 REM| HISTORY                                                                 |
7509 REM|  06/16/2004   Namit Singhi created                                      |
7510 REM+=========================================================================+
7511 */
7512 
7513 FUNCTION enh_bsearch_stpno ( l_formula_id   IN NUMBER,
7514                              l_recipe_id    IN NUMBER,
7515                              l_item_id      IN NUMBER)
7516 		RETURN INTEGER IS
7517 
7518 top     INTEGER ;
7519 bottom  INTEGER ;
7520 mid     INTEGER ;
7521 loop_direction NUMBER;
7522 ret_loc     INTEGER ;
7523 formula_start INTEGER ;
7524 
7525 BEGIN
7526      top    := 1;
7527      bottom := material_assocs_size ;
7528      mid    := -1 ;
7529      ret_loc   := -1 ;
7530      loop_direction := 0;
7531      formula_start := -1;
7532 
7533    WHILE  (top <= bottom )
7534     LOOP
7535      mid := top + ( ( bottom - top ) / 2 );
7536 --
7537      IF l_formula_id < mat_assoc_tab(mid).formula_id THEN
7538 	bottom := mid - 1 ;
7539      ELSIF l_formula_id > mat_assoc_tab(mid).formula_id THEN
7540 	top := mid + 1 ;
7541      ELSE
7542 	ret_loc := mid ;
7543         EXIT;
7544      END IF ;
7545     END LOOP;
7546 
7547     IF ret_loc > 0 THEN
7548         IF ret_loc = 1 THEN
7549             formula_start := 1 ;
7550         ELSE  /* ret_loc > 1*/
7551         LOOP
7552             ret_loc := ret_loc - 1;
7553             IF ret_loc = 1 THEN
7554                 formula_start := 1 ;
7555                 EXIT;
7556             ELSIF mat_assoc_tab(ret_loc).formula_id <> l_formula_id THEN
7557                 formula_start := ret_loc + 1;
7558                 EXIT;
7559             END IF;
7560         END LOOP;
7561         END IF;
7562     ELSE
7563         RETURN -1 ;
7564     END IF;
7565 
7566     ret_loc := formula_start;
7567 
7568     WHILE(ret_loc <= material_assocs_size) LOOP
7569     IF(mat_assoc_tab(ret_loc).formula_id > l_formula_id) THEN
7570         RETURN -1;
7571     ELSIF mat_assoc_tab(ret_loc).recipe_id = l_recipe_id AND
7572     mat_assoc_tab(ret_loc).item_id = l_item_id THEN
7573         RETURN ret_loc;
7574     ELSE
7575         ret_loc := ret_loc + 1;
7576     END IF;
7577     END LOOP;
7578 
7579     RETURN -1;
7580 
7581 EXCEPTION WHEN OTHERS THEN
7582    log_message(' Error in MSC_CL_GMP_UTILITY.enh_bsearch_stpno: '||SQLERRM);
7583    RETURN -1;
7584 END enh_bsearch_stpno ;
7585 
7586 /*
7587 REM+=========================================================================+
7588 REM| PROCEDURE NAME                                                          |
7589 REM|    bsearch_unique                                                       |
7590 REM|                                                                         |
7591 REM| DESCRIPTION                                                             |
7592 REM|    This procedure finds the unique setup id for the combination passed  |
7593 REM|                                                                         |
7594 REM| HISTORY                                                                 |
7595 REM|  02/10/2006 B4918786 Rajesh Patangya Rewrite for SDS Enhancement        |
7596 REM|                                                                         |
7597 REM+=========================================================================+
7598 */
7599 PROCEDURE bsearch_unique (p_resource_id   IN NUMBER ,
7600                           p_category_id   IN NUMBER ,
7601                           p_setup_id      OUT NOCOPY NUMBER
7602                          ) IS
7603 i  INTEGER;
7604 BEGIN
7605   i := 1 ;
7606    FOR i IN 1..SD_INDEX LOOP
7607      IF  (sds_tab(i).resource_id = p_resource_id) AND
7608          (sds_tab(i).category_id = p_category_id) THEN
7609              p_setup_id := sds_tab(i).setup_id ;
7610              EXIT ;
7611      ELSE
7612              p_setup_id := NULL ;
7613      END IF ;
7614    END LOOP;
7615 EXCEPTION
7616    WHEN OTHERS THEN
7617    log_message('Error in bsearch_unique ' || sqlerrm);
7618    p_setup_id := NULL ;
7619 END bsearch_unique ;
7620 
7621 -- for future use
7622 FUNCTION GMP_BOM_UTILITY1_R10
7623             (
7624                           p_dblink      IN VARCHAR2,
7625                           p_delimiter   IN VARCHAR2,
7626                           p_instance    IN INTEGER,
7627                           p_run_date    IN DATE,
7628                           p_num1        IN NUMBER,
7629                           p_num2        IN NUMBER,
7630                           p_num3        IN NUMBER,
7631                           p_num4        IN NUMBER,
7632                           p_varchar1    IN VARCHAR2,
7633                           p_varchar2    IN VARCHAR2,
7634                           p_varchar3    IN VARCHAR2,
7635                           p_varchar4    IN VARCHAR2
7636             ) RETURN INTEGER IS
7637 BEGIN
7638     return 0;
7639 END GMP_BOM_UTILITY1_R10;
7640 
7641 FUNCTION GMP_BOM_UTILITY2_R10
7642             (
7643                           p_dblink      IN VARCHAR2,
7644                           p_delimiter   IN VARCHAR2,
7645                           p_instance    IN INTEGER,
7646                           p_run_date    IN DATE,
7647                           p_num1        IN NUMBER,
7648                           p_num2        IN NUMBER,
7649                           p_num3        IN NUMBER,
7650                           p_num4        IN NUMBER,
7651                           p_varchar1    IN VARCHAR2,
7652                           p_varchar2    IN VARCHAR2,
7653                           p_varchar3    IN VARCHAR2,
7654                           p_varchar4    IN VARCHAR2
7655             ) RETURN INTEGER IS
7656 BEGIN
7657     return 0;
7658 END GMP_BOM_UTILITY2_R10;
7659 
7660 PROCEDURE GMP_BOM_PROC1_R10
7661             (
7662                           p_dblink      IN VARCHAR2,
7663                           p_delimiter   IN VARCHAR2,
7664                           p_instance    IN INTEGER,
7665                           p_run_date    IN DATE,
7666                           p_num1        IN NUMBER,
7667                           p_num2        IN NUMBER,
7668                           p_num3        IN NUMBER,
7669                           p_num4        IN NUMBER,
7670                           p_varchar1    IN VARCHAR2,
7671                           p_varchar2    IN VARCHAR2,
7672                           p_varchar3    IN VARCHAR2,
7673                           p_varchar4    IN VARCHAR2,
7674                           return_status  OUT NOCOPY BOOLEAN
7675             ) IS
7676 BEGIN
7677     return_status := TRUE;
7678 END GMP_BOM_PROC1_R10;
7679 
7680 PROCEDURE GMP_BOM_PROC2_R10
7681             (
7682                           p_dblink      IN VARCHAR2,
7683                           p_delimiter   IN VARCHAR2,
7684                           p_instance    IN INTEGER,
7685                           p_run_date    IN DATE,
7686                           p_num1        IN NUMBER,
7687                           p_num2        IN NUMBER,
7688                           p_num3        IN NUMBER,
7689                           p_num4        IN NUMBER,
7690                           p_varchar1    IN VARCHAR2,
7691                           p_varchar2    IN VARCHAR2,
7692                           p_varchar3    IN VARCHAR2,
7693                           p_varchar4    IN VARCHAR2,
7694                           return_status  OUT NOCOPY BOOLEAN
7695               ) IS
7696 BEGIN
7697     return_status := TRUE;
7698 END GMP_BOM_PROC2_R10;
7699 
7700 /*======================OPM BOM Package End ===================================*/
7701 
7702 /***********************************************************************
7703 *
7704 *   NAME
7705 *	bsearch_rsrc_chg
7706 *
7707 *   DESCRIPTION
7708 *	This function will search through the resource charges PL/SQL table
7709 *       using Binary Search.
7710 *
7711 *       IF  p_batch_id Found IN  stp_chg_tbl THEN
7712 *         Return the last record location for p_batch_id in stp_chg_tbl.
7713 *       ELSE if p_batch_id NOT Found IN the stp_chg_tbl THEN
7714 *          Return -1
7715 *       END IF;
7716 *
7717 *   HISTORY
7718 *	Navin Sinha
7719 ************************************************************************/
7720 FUNCTION bsearch_rsrc_chg ( p_batch_id IN NUMBER)
7721 	 RETURN INTEGER IS
7722 
7723 top         INTEGER ;
7724 bottom      INTEGER ;
7725 mid         INTEGER ;
7726 ret_loc     INTEGER ;
7727 BEGIN
7728      top    := 1;
7729      bottom := stp_chg_tbl.count;
7730      mid    := -1 ;
7731      ret_loc   := -1 ;
7732 
7733    WHILE  (top <= bottom )
7734     LOOP
7735      mid := top + ( ( bottom - top ) / 2 );
7736 
7737      IF p_batch_id < stp_chg_tbl(mid).wip_entity_id THEN
7738 	bottom := mid -1 ;
7739      ELSIF p_batch_id > stp_chg_tbl(mid).wip_entity_id THEN
7740 	top := mid + 1 ;
7741      ELSE
7742 	ret_loc := mid ;
7743               EXIT;
7744      END IF ;
7745     END LOOP; /* (top <= bottom ) */
7746 
7747     -- Identify the location of the last record for the currently processed p_batch_id in stp_chg_tbl.
7748     IF ret_loc > 0 AND ret_loc <= stp_chg_tbl.count THEN
7749       LOOP
7750        IF ret_loc = stp_chg_tbl.count THEN
7751           -- Pointer is at last record of the array.
7752           Return ret_loc;
7753        END IF ;
7754 
7755        ret_loc :=  ret_loc + 1;
7756        IF p_batch_id <> stp_chg_tbl(ret_loc).wip_entity_id THEN
7757           -- Missmatch occurred hence return the previous location.
7758           Return (ret_loc - 1);
7759        END IF ;
7760       END LOOP;
7761     ELSE
7762        -- Not found
7763        Return -1 ;
7764     END IF ;
7765 
7766 END bsearch_rsrc_chg ;
7767 
7768 /* **********************************************************************
7769 *   NAME
7770 *	inst_stp_chg_tbl
7771 *
7772 *   DESCRIPTION
7773 *       Inserts Data into step charge staging table.
7774 *   HISTORY
7775 *       B4761946, 20-DEC-2005 Rajesh Patangya Changed the while loop logic
7776 ************************************************************************/
7777 
7778 PROCEDURE inst_stp_chg_tbl(pinstance_id IN NUMBER, p_batch_loc IN NUMBER)
7779 IS
7780 
7781 rsrc_chg_loc NUMBER;
7782 
7783 BEGIN
7784   -- Locate the batch in Resource Charge PL/SQL table, i.e stp_chg_tbl
7785   -- rsrc_chg_loc will be -1 if NOT found OR it will point to last record
7786   -- location for x_batch_id in stp_chg_tbl.
7787   rsrc_chg_loc := bsearch_rsrc_chg(rsrc_tab(p_batch_loc).x_batch_id);
7788 
7789   -- IF resource charges found then process....
7790   IF rsrc_chg_loc > 0 THEN
7791      IF prod_tab(p).firmed_ind = 1 AND
7792          stp_chg_tbl(rsrc_chg_loc).charge_start_dt_time IS NULL AND
7793          stp_chg_tbl(rsrc_chg_loc).charge_end_dt_time IS NULL THEN
7794             -- APS decoded value as per
7795             -- DECODE(rsrc_tab(p_batch_loc).scale_type,0,2,1,1,2,3);
7796             rsrc_tab(p_batch_loc).scale_type := 1;
7797      ELSE
7798       -- Insert all the resource charge records untill the batch_id,
7799       -- batchstep_id and resource_id
7800       -- are same as currently processed resource record.
7801      /* B4761946, Rajesh Patangya Changed the while loop logic */
7802       LOOP
7803   /*
7804       log_message(rsrc_tab(p_batch_loc).x_batch_id || ' -- ' ||
7805                   rsrc_tab(p_batch_loc).batchstep_id || ' -- ' ||
7806                   rsrc_tab(p_batch_loc).x_resource_id || ' -- ' ||
7807              rsrc_chg_loc || ' -- ' ||
7808              stp_chg_tbl(rsrc_chg_loc).wip_entity_id   || ' -- ' ||
7809       ((stp_chg_tbl(rsrc_chg_loc).operation_seq_id -1)/2) || ' --'||
7810              stp_chg_tbl(rsrc_chg_loc).resource_id );
7811 */
7812        IF (rsrc_tab(p_batch_loc).x_batch_id =
7813              stp_chg_tbl(rsrc_chg_loc).wip_entity_id) AND
7814           (rsrc_tab(p_batch_loc).batchstep_id =
7815              ((stp_chg_tbl(rsrc_chg_loc).operation_seq_id -1)/2)) AND
7816           (rsrc_tab(p_batch_loc).x_resource_id =
7817              stp_chg_tbl(rsrc_chg_loc).resource_id) THEN
7818 
7819 	chg_res_index := chg_res_index + 1 ;
7820         stp_chg_resource_id(chg_res_index) := stp_chg_tbl(rsrc_chg_loc).resource_id ;
7821         stp_chg_organization_id(chg_res_index) := stp_chg_tbl(rsrc_chg_loc).organization_id ;
7822         stp_chg_department_id(chg_res_index) := ((v_orgn_id * 2) + 1) ;
7823         stp_chg_wip_entity_id(chg_res_index) := stp_chg_tbl(rsrc_chg_loc).wip_entity_id ;
7824         stp_chg_operation_seq_id(chg_res_index) := stp_chg_tbl(rsrc_chg_loc).operation_seq_id ;
7825         stp_chg_operation_seq_no(chg_res_index) := stp_chg_tbl(rsrc_chg_loc).operation_seq_no ;
7826         stp_chg_resource_seq_num(chg_res_index) := stp_chg_tbl(rsrc_chg_loc).resource_seq_num ;
7827         stp_chg_charge_num(chg_res_index) := stp_chg_tbl(rsrc_chg_loc).charge_num ;
7828         stp_chg_charge_quanitity(chg_res_index) := stp_chg_tbl(rsrc_chg_loc).charge_quantity ;
7829         stp_chg_charge_start_dt_time(chg_res_index) := stp_chg_tbl(rsrc_chg_loc).charge_start_dt_time ;
7830         stp_chg_charge_end_dt_time(chg_res_index) := stp_chg_tbl(rsrc_chg_loc).charge_end_dt_time ;
7831         stp_instance_id (chg_res_index) := pinstance_id ;
7832        END IF;
7833 
7834        rsrc_chg_loc := rsrc_chg_loc - 1 ;
7835 
7836        IF ((rsrc_chg_loc = 0) OR (rsrc_tab(p_batch_loc).x_batch_id <>
7837                 stp_chg_tbl(rsrc_chg_loc).wip_entity_id)) THEN
7838                 -- No more records to process in Step Charge PL/SQL table.
7839            EXIT;
7840        END IF;
7841       END LOOP;
7842      END IF;
7843   END IF;  /*  rsrc_chg_loc > 0 */
7844 END inst_stp_chg_tbl;
7845 
7846 /***********************************************************************
7847 *
7848 *   NAME
7849 *	Enh_bsearch_alternate_rsrc
7850 *
7851 *
7852 *       IF  pprim_resource_id Found IN  prod_alt_rsrc_tab THEN
7853 *         Return the first record location for pprim_resource_id in prod_alt_rsrc_tab.
7854 *       ELSE IF pprim_resource_id NOT Found IN  prod_alt_rsrc_tab THEN
7855 *          Return -1
7856 *       END IF;
7857 *
7858 *   DESCRIPTION
7859 *	This function will search throught the alternate resource PL/SQL table
7860 *       using Binary Search. It is a modified Binary Search, as after finding a hit
7861 *       it loops back to find the first row that gave the hit.
7862 *   HISTORY
7863 *	Navin Sinha
7864 ************************************************************************/
7865 
7866 FUNCTION Enh_bsearch_alternate_rsrc ( pprim_resource_id   IN NUMBER)
7867 		RETURN INTEGER IS
7868 
7869 top     INTEGER ;
7870 bottom  INTEGER ;
7871 mid     INTEGER ;
7872 
7873 ret_loc     INTEGER ;
7874 BEGIN
7875      top    := 1;
7876      bottom := alt_prod_size ;
7877      mid    := -1 ;
7878      ret_loc   := -1 ;
7879 
7880    WHILE  (top <= bottom )
7881     LOOP
7882      mid := top + ( ( bottom - top ) / 2 );
7883 
7884      IF pprim_resource_id < prod_alt_rsrc_tab(mid).prim_resource_id THEN
7885 	bottom := mid -1 ;
7886      ELSIF pprim_resource_id > prod_alt_rsrc_tab(mid).prim_resource_id THEN
7887 	top := mid + 1 ;
7888      ELSE
7889 	ret_loc := mid ;
7890               EXIT;
7891      END IF ;
7892     END LOOP; /* (top <= bottom ) */
7893 
7894     -- Bring back the pointer to the first location from where the Primary resource data starts.
7895     IF ret_loc >= 1 THEN
7896       LOOP
7897        IF ret_loc = 1 THEN
7898           -- Pointer is at first location of the array.
7899           Return ret_loc;
7900        END IF ;
7901 
7902        ret_loc :=  ret_loc - 1;
7903        IF pprim_resource_id <> prod_alt_rsrc_tab(ret_loc).prim_resource_id THEN
7904           -- Missmatch occurred hence return the previous location.
7905           Return (ret_loc +1);
7906        END IF ;
7907       END LOOP;
7908     ELSE
7909       -- Not found
7910       Return -1 ;
7911     END IF ;  /* ret_loc >= 1 */
7912 
7913 END Enh_bsearch_alternate_rsrc ;
7914 
7915 /***********************************************************************
7916 *
7917 *   NAME
7918 *     production_orders
7919 *
7920 *   DESCRIPTION
7921 *     This procedure will take the production orders, batches and FPOs,
7922 *     that have valid item/warehouse definitions as defined in the
7923 *     the plant/whse eff and write them to the table msc_std_demands and \
7924 *     msc_st_supplies. The products and byproducts will be written as
7925 *     supplies and ingredients as demands
7926 *   HISTORY
7927 *     M Craig
7928 *   04/03/2000 - Using mtl_organization_id instead of organization_id from
7929 *              - sy_orgn_mst , Bug# 1252322
7930 *   Sridhar 31-DEC-01 B2159482 - Added Alcoa Cursor Changes to the
7931 *                                latest version of the package
7932 *   Sridhar 15-JAN-02 B1992371   Modified the Cursor with GME Changes
7933 *   Sridhar 27-FEB-2002 B2239948 Added correction for poc_ind comparisons
7934 *   Sridhar 15-MAY-2002 B2363117 Added nvl Statement for If statements with
7935 *                                Actual_cmplt_date and Start Date
7936 *   Sridhar 10-JUL-2002 B2383692 Added code to take care of the last record
7937 *   Sridhar 10-JUL-2002 B1522576 Added code to differentiate FPO Batches
7938 *   Sridhar 19-MAR-2003 B2858929 Added Code to take resolve the Bug
7939 *                                Resource Seq is incremented only if the
7940 *                                activity is Changed
7941 *   Sridhar 31-MAR-2003 B2882286 Ensuring the Order so that if the last batch
7942 *                                resource requirements are written
7943 *   Sridhar 30-APR-2003 B2919303 Added Operation Seq Number in msc_st_supplies
7944 *                                and in msc_st_demands table
7945 *   Sridhar 09-MAY-2003 B2919303 Added line_no and included in order by clause
7946 *   Sridhar 12-MAY-2003 B2953953 Populated BY_PRODUCT_USING_ASSY_ID with
7947 *                                product_line which is the assembly_item_id
7948 *   Navin   21-APR-2003 B3577871 ST:OSFME2: collections failing in planning data pull.
7949 *                                Added handling of NO_DATA_FOUND Exception.
7950 *                                And return the return_status as TRUE.
7951 *   Sulipta 25-JAN-2006 B4612203 Populating supply_type as 1 in
7952 *                                MSC_ST_RESOURCE_REQUIREMENTS table
7953 ************************************************************************/
7954 
7955 PROCEDURE production_orders(
7956   pdblink        IN  VARCHAR2,
7957   pinstance_id   IN  NUMBER,
7958   prun_date      IN  DATE,
7959   pdelimiter     IN  VARCHAR2,
7960   return_status  IN OUT NOCOPY BOOLEAN)
7961 
7962 IS
7963 
7964 /* Defining the dynamic cursors to be used to retrieve data later. Production
7965    details, resource details, resource warehouse, and warehouse organization */
7966 
7967   TYPE gmp_cursor_typ IS REF CURSOR;
7968   c_prod_dtl           gmp_cursor_typ;
7969   rsrc_dtl             gmp_cursor_typ;
7970   rsrc_whse            gmp_cursor_typ;
7971   cur_alt_rsrc         gmp_cursor_typ; /* NAVIN :- Alternate Resource */
7972   cur_rs_intance       gmp_cursor_typ; /* NAVIN :- Resource Intance */
7973   c_chg_cursor         gmp_cursor_typ; /* NAVIN :- Resource Charges */
7974   rsrc_uoms_cur        gmp_cursor_typ; /* Sowmya - As per latest FDD Changes */
7975   uom_code_ref         gmp_cursor_typ; /* NAMIT - UOM Class */
7976   um_code_ref          gmp_cursor_typ; /* NAMIT - UOM Class */
7977   ic_code_ref          gmp_cursor_typ;
7978   bs_code_ref          gmp_cursor_typ;
7979 
7980   v_prod_cursor        VARCHAR2(32000) ;
7981   v_rsrc_cursor        VARCHAR2(32000) ;
7982   sql_stmt	       VARCHAR2(32000) ;
7983   uom_code_cursor      VARCHAR2(32000);
7984   um_code_cursor       VARCHAR2(32000);
7985 
7986   l_charges_remaining  NUMBER;
7987   res_whse             BOOLEAN ;
7988   res_whse_id          NUMBER ;
7989   supply_type          NUMBER ;
7990   old_batch_id         NUMBER;
7991   product_line         NUMBER ;
7992   opm_product_line     NUMBER ;
7993   prod_line_id         NUMBER ;
7994   prod_plant           VARCHAR2(4) ;
7995   order_no             VARCHAR2(37) ;
7996   v_inflate_wip        NUMBER ;
7997   found_mtl            NUMBER ;
7998   i                    NUMBER ;
7999   old_step_no          NUMBER ;
8000   prod_count           NUMBER ;
8001   resource_count       NUMBER ;
8002   stp_chg_count        NUMBER ;
8003   /* B1224660 added locals to develop resource sequence numbers */
8004   v_resource_usage     NUMBER ;
8005   v_res_seq            NUMBER ;
8006   v_schedule_flag      NUMBER ;
8007   v_parent_seq_num     NUMBER ;
8008   v_seq_dep_usage      NUMBER ; /* NAVIN :- Sequence Dependency */
8009   found_chrg_rsrc      NUMBER ; /* NAVIN :- Chargeable Resource */
8010   chrg_activity        NUMBER ; /* NAVIN :- Chargeable Activity */
8011   v_rsrc_cnt           NUMBER ;
8012   v_start_date         DATE ;
8013   v_end_date           DATE ;
8014   old_activity         NUMBER ;
8015   v_alternate          NUMBER ; /* NAVIN :- added for alternate resource */
8016   alternate_rsrc_loc   NUMBER ; /* NAVIN :- added for alternate resource */
8017   alt_cnt              NUMBER ; /* NAVIN :- added for alternate resource */
8018   row_count            NUMBER ;
8019   start_loc            NUMBER ;
8020   l_gmp_um_code        VARCHAR2(25);
8021   l_gmp_uom_class      VARCHAR2(10); /* UOM Class */
8022   v_max_rsrcs          NUMBER; --for collecting the max resources
8023   v_activity_group_id  NUMBER ;   /* B3995361 rpatangy */
8024   mk_alt_grp           NUMBER ;   /* B3995361 rpatangy */
8025 
8026 BEGIN
8027   /* Initialize the values */
8028   v_activity_group_id  := 0;     /* B3995361 rpatangy */
8029   mk_alt_grp           := 0 ;    /* B3995361 rpatangy */
8030   v_prod_cursor        := NULL;
8031   v_rsrc_cursor        := NULL;
8032 
8033   res_whse             := FALSE;
8034   res_whse_id          := 0;
8035   supply_type          := 0;
8036   product_line         := 0;
8037   opm_product_line     := 0;
8038   prod_line_id         := 0;
8039   prod_plant           := NULL;
8040   order_no             := NULL;
8041   v_inflate_wip        := 0;
8042   found_mtl            := 0;
8043   i                    := 0;
8044   p                    := 0;
8045   r                    := 0;
8046   old_step_no          := 0;
8047   prod_count           := 1;
8048   resource_count       := 1;
8049   stp_chg_count        := 1;
8050 
8051   /* B1224660 added locals to develop resource sequence numbers */
8052   v_resource_usage     := 0;
8053   v_res_seq            := 0;
8054   v_schedule_flag      := 0;
8055   v_parent_seq_num     := 0;
8056   v_seq_dep_usage      := 0; /* NAVIN :- Sequence Dependency */
8057   found_chrg_rsrc      := 0; /* NAVIN :- Chargeable Resource */
8058   chrg_activity        := -1; /* NAVIN :- Chargeable Activity */
8059   chg_res_index        := 0; /* NAVIN :- Resource Charges */
8060   v_rsrc_cnt           := 0;
8061   v_start_date         := NULL;
8062   v_end_date           := NULL;
8063   old_activity         := 0;
8064   v_alternate          := 0; /* NAVIN :- added for alternate resource */
8065   alternate_rsrc_loc   := 0; /* NAVIN :- added for alternate resource */
8066   alt_cnt              := 0; /* NAVIN :- added for alternate resource */
8067 
8068   d_index              := 0 ;
8069   s_index              := 0 ;
8070   rr_index             := 0 ;
8071   arr_index            := 0 ;
8072   jo_index             := 0;
8073   gprod_size           := 0 ;
8074   grsrc_size           := 0;
8075   g_rsrc_cnt           := 1;
8076   si_index             := 1;
8077   inst_indx            := 0;
8078   row_count            := 1; /* NAVIN :- Maintains the row count. From set of repetitive rows, only one row is inserted. */
8079   start_loc            := 1;
8080   l_res_inst_process   := 0;
8081   v_max_rsrcs          := 0;
8082 
8083   IF return_status THEN
8084     v_cp_enabled := TRUE;
8085   ELSE
8086     v_cp_enabled := FALSE;
8087   END IF;
8088 
8089     /* populate the org_string */
8090    IF MSC_CL_GMP_UTILITY.org_string(pinstance_id) THEN
8091         NULL ;
8092      ELSE
8093         RAISE invalid_string_value  ;
8094      END IF;
8095 
8096     /* Disable Formula Security Functionality */
8097 
8098   v_sql_stmt := 'BEGIN '
8099     || ' gmd_p_fs_context.set_additional_attr' || pdblink
8100     || ';END;'   ;
8101   EXECUTE IMMEDIATE v_sql_stmt ;
8102 
8103 
8104   /* Get the profile value for inflating usage by the utilization and
8105      efficiency */
8106   IF NVL(fnd_profile.value('MSC_INFLATE_WIP') ,'N')= 'N' THEN
8107     v_inflate_wip := 0 ;
8108   ELSE
8109     v_inflate_wip := 1 ;
8110   END IF;
8111 
8112 /* NAMIT UOM Change, This should come from source */
8113     um_code_cursor   := ' select fnd_profile.VALUE' ||pdblink
8114                       ||' (''SY$UOM_HOURS'') from dual ' ; /* OPM UOM */
8115 
8116        OPEN um_code_ref FOR um_code_cursor ;
8117        FETCH um_code_ref INTO l_gmp_um_code;
8118        CLOSE um_code_ref;
8119 
8120   IF l_gmp_um_code IS NOT NULL THEN
8121 /* Get the UOM code and UOM Class corresponding to "GMP: UOM for Hour" Profile */
8122      uom_code_cursor :=
8123                       ' select um_type '
8124                       ||' from sy_uoms_mst'||pdblink
8125                       ||' where um_code = :gmp_um_code ';
8126 
8127      OPEN uom_code_ref FOR uom_code_cursor USING l_gmp_um_code;
8128      FETCH uom_code_ref INTO l_gmp_uom_class;
8129      CLOSE uom_code_ref;
8130   ELSE
8131      RAISE invalid_gmp_uom_profile  ;
8132   END IF;
8133   IF (l_gmp_uom_class IS NULL) THEN
8134      RAISE invalid_gmp_uom_profile  ;
8135   END IF;
8136 
8137 
8138   /* B2919303 - The following cursor has been modified to include
8139      batchstep_no for material txns which has release type as 3 ( auto by step )
8140      , if the rows are not release type as 3 then batchstep is taken as 0
8141   */
8142   /* B2953953 Added two temporary columns so that we can get the correct
8143      Order , Note that the Line_type is decoded so that Line_type - prod
8144      becomes 3 and is ordered first and product row is made into line_no 0
8145   */
8146   /* B2964633 - Added t.trans_date also in the Order by Clause to make sure
8147      Product comes in the first row, because product is always in the last
8148      step and therefore ordering by trans_date in the descending order */
8149   /* B3054460 - OPM/APS TO CATER FOR CHANGE TO TIME PHASED PLANNING
8150      OF MANUAL CONSUMPTION TYPE, - Considered release_type 1 also
8151   */
8152 
8153   /* Bug 4774975 -- FRUTAROM INDUSTRIES LTD, org string check should be
8154      removed so that all the supplies and demand belongs to other warehouse
8155      should be sent to APS in resource warehouse */
8156 
8157   v_prod_cursor := 'SELECT'
8158       || '   h.batch_no,'
8159       || '   h.plant_code,'
8160       || '   h.batch_id,'
8161       || '   ((h.batch_id * 2) + 1), '
8162       || '   h.wip_whse_code,'
8163       || '   iwm.mtl_organization_id, '
8164       || '   h.routing_id,'
8165       || '   h.plan_start_date, '
8166       || '   h.plan_cmplt_date end_date,'
8167       || '   DECODE(d.line_type,-1,MIN(t.trans_date),MAX(t.trans_date)),'
8168       || '   h.batch_status,'
8169       || '   h.batch_type,'
8170       || '   i.organization_id,'
8171       || '   t.whse_code,'
8172       || '   i.aps_item_id,'
8173       || '   d.material_detail_id,'
8174       || '   d.line_no  ,'     /* B2919303 */
8175       || ' DECODE(d.item_id ,v.item_id,0,d.line_no) t_line_no,' /* B2953953 */
8176       || '   d.line_type,'
8177       || ' DECODE(d.line_type,1,3,d.line_type) t_line_type,' /* B2953953 */
8178       || '   SUM(t.trans_qty),'
8179       || '   d.item_id  matl_item_id,'
8180       || '   v.item_id  recipe_item_id, '
8181       || '   h.poc_ind,   '
8182       || '   DECODE(h.firmed_ind,1,1,2), '
8183       || '   decode(d.release_type,0, -1, nvl(gbs.batchstep_no,-1)) batchstep_no,'
8184       || '   d.plan_qty, '
8185       || '   DECODE(d.item_um, i.item_um, 1, '
8186       || '     GMICUOM.uom_conversion'||pdblink
8187       || '       (d.item_id, 0, 1, d.item_um, i.item_um, 0)), ' /* NAVIN: Get UOM
8188                                         conversion factor for unit qty */
8189       || '   h.due_date,'
8190       || '   h.order_priority,'
8191       ||'   ((gbsi.batchstep_id*2)+1) from_op_seq_id, '     /* B5461922 */
8192       || '   DECODE(d.line_type,1,gbsi.minimum_transfer_qty, NULL) t_minimum_transfer_qty,'
8193       || '   DECODE(d.line_type,1,gbsi.minimum_delay, NULL) t_minimum_delay, '
8194       || '   DECODE(d.line_type,1,gbsi.maximum_delay, NULL) t_maximum_delay,'
8195       || '   gbs.batchstep_no'
8196       || ' FROM'
8197       || '   gme_batch_header'||pdblink||' h,'
8198       || '   gme_material_details'||pdblink||' d,'
8199       || '   gme_batch_step_items'||pdblink||' gbsi,'  /* 2919303 */
8200       || '   gme_batch_steps'||pdblink||' gbs,'       /* 2919303 */
8201       || '   gmd_recipe_validity_rules'||pdblink||' v,'
8202       || '   ic_whse_mst'||pdblink||' iwm,'
8203       || '   ic_tran_pnd'||pdblink||' t,'
8204       || '   gmp_item_aps'||pdblink||' i'
8205       || ' WHERE'
8206       || '     h.batch_id = d.batch_id'
8207       || '   AND h.recipe_validity_rule_id = v.recipe_validity_rule_id'
8208       || '   AND EXISTS (SELECT '
8209       || '                 1  '
8210       || '               FROM '
8211       || '                 gme_material_details'||pdblink||' gmd '
8212       || '               WHERE '
8213       || '                     gmd.batch_id = h.batch_id '
8214       || '                 AND gmd.item_id = v.item_id) '
8215       || '   AND h.wip_whse_code = iwm.whse_code'
8216       || '   AND h.batch_id = t.doc_id'
8217       || '   AND ((h.batch_type = 0 and t.doc_type = :p1) OR'
8218       || '        (h.batch_type = 10 and t.doc_type = :p2))'
8219       || '   AND d.material_detail_id = gbsi.material_detail_id (+)' /* 2919303 */
8220       || '   AND d.batch_id = gbsi.batch_id (+)  '      /* 2919303 */
8221       || '   AND gbsi.batch_id = gbs.batch_id (+) '       /* 2919303 */
8222       || '   AND gbsi.batchstep_id  = gbs.batchstep_id (+)'    /* 2919303 */
8223       || '   AND d.material_detail_id = t.line_id'
8224       || '   AND t.item_id = i.item_id'
8225       || '   AND t.whse_code = i.whse_code'
8226       || '   AND t.orgn_code = i.plant_code'
8227       || '   AND h.batch_status in (1, 2)'
8228       || '   AND t.completed_ind = 0'
8229       || '   AND t.delete_mark = 0'
8230   -- B3721336 Rajesh Patangya If product is 100% Yeiled, But steps are pending
8231   --  || '   AND t.trans_qty <> 0'
8232       || ' GROUP BY'
8233       || '   h.batch_no,'
8234       || '   h.plant_code,'
8235       || '   h.batch_id,'
8236       || '   h.wip_whse_code,'
8237       || '   iwm.mtl_organization_id, '
8238       || '   h.routing_id,'
8239       || '   h.plan_start_date,'
8240       || '   h.plan_cmplt_date,'
8241       || '   v.item_id,'
8242       || '   h.poc_ind,'
8243       || '   h.firmed_ind,'
8244       || '   decode(d.release_type, 0, -1, nvl(gbs.batchstep_no,-1)),' /*2919303*/
8245       || '   d.item_id,'
8246       || '   h.batch_status,'
8247       || '   h.batch_type,'
8248       || '   i.organization_id,'
8249       || '   t.whse_code,'
8250       || '   i.aps_item_id,'
8251       || '   d.material_detail_id,'
8252       || '   d.line_no,'
8253       || '   d.line_type,'
8254       /* NAVIN:  Added following columns in group by as these are newly added in the select clouse.*/
8255       || '   d.plan_qty, '
8256       || '   DECODE(d.item_um, i.item_um, 1, GMICUOM.uom_conversion' || pdblink
8257       || '       (d.item_id, 0, 1, d.item_um, i.item_um, 0)), '
8258       || '   h.due_date,'
8259       || '   h.order_priority,'
8260       || '   gbsi.batchstep_id,'
8261       || '   DECODE(d.line_type,1,gbsi.minimum_transfer_qty, NULL) ,'
8262       || '   DECODE(d.line_type,1,gbsi.minimum_delay, NULL), '
8263       || '   DECODE(d.line_type,1,gbsi.maximum_delay, NULL),'
8264       || '   gbs.batchstep_no'
8265       || ' ORDER BY h.batch_id ,t_line_type DESC ,t_line_no , '
8266       || '   DECODE(d.line_type,-1,MIN(t.trans_date),MAX(t.trans_date)) DESC ';
8267 
8268     OPEN c_prod_dtl FOR v_prod_cursor USING v_doc_prod, v_doc_fpo;
8269     LOOP
8270       FETCH  c_prod_dtl INTO prod_tab(prod_count);
8271       EXIT WHEN  c_prod_dtl%NOTFOUND ;
8272       prod_count := prod_count + 1;
8273     END LOOP;
8274     CLOSE c_prod_dtl ;
8275     gprod_size := prod_count - 1;
8276     log_message('Batches size is = '|| to_char(gprod_size) );
8277     time_stamp ;
8278 
8279     v_rsrc_cursor := 'SELECT'
8280       || ' h.batch_id,'
8281       || ' ((r.batch_id * 2) + 1), '
8282       || ' r.batchstep_no,'
8283       || ' NVL(o.sequence_dependent_ind, -1),'	/* NAVIN: Moved this column up for order by clause and changed from NVL(o.sequence_dependent_ind,0) */
8284       || ' DECODE(gs.prim_rsrc_ind, 1,1,2,2,0,3),' /* This will ensure that ordering will always have primary first */
8285       || ' gs.resources,'
8286       || ' ((gri.instance_id * 2) + 1) , '  /* SOWMYA - Resources Instances */
8287       || ' NVL(t.sequence_dependent_ind,0), '
8288       || ' gs.plan_start_date,'
8289       || ' h.plant_code,'
8290       -- || ' o.activity,'			/* NAVIN: Remove this column. */
8291       || ' gs.prim_rsrc_ind,'
8292       || ' c.resource_id,'
8293       || ' ((c.resource_id * 2) + 1),'
8294       || ' gs.plan_rsrc_count,'
8295       || ' gs.actual_rsrc_count,'
8296       || ' gs.actual_start_date,'
8297       || ' gs.plan_cmplt_date,'
8298       || ' gs.actual_cmplt_date,'
8299 --      || ' DECODE(r.step_status,2,1,NULL), '
8300       || ' r.step_status, '  /* B3995361 */
8301       || ' SUM(t.resource_usage) OVER (PARTITION BY t.doc_id, t.resources, t.line_id) resource_usage, '  -- summarized usage for the step resource
8302       || ' 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
8303       || ' nvl(gri.eqp_serial_number,to_char(gri.instance_number)), '  /* SOWMYA - As Per latest FDD changes - Resources Instances */
8304       || ' DECODE(gs.scale_type,0,2,1,1,2,3), '
8305       || ' c.capacity_constraint , '
8306       || ' r.plan_step_qty, '
8307       || ' NVL(r.minimum_transfer_qty,-1), '
8308       || ' NVL(o.material_ind,0), '
8309       || ' 1 schedule_flag, '
8310        --  || ' o.offset_interval, '	/* NAVIN: Remove this column. */
8311       || ' o.plan_start_date, '
8312       || ' (DECODE(c.utilization,0,100,NVL(c.utilization,100))/100) * '
8313       || '   (DECODE(c.efficiency,0,100,NVL(c.efficiency,100))/100), '
8314       || ' o.batchstep_activity_id, '
8315       || ' gs.group_sequence_id,'
8316       || ' gs.group_sequence_number,'
8317       || ' nvl(gs.firm_type,0),'	/*Sowmya - If null then pass 0*/
8318       || ' gs.sequence_dependent_id  setup_id,'
8319   -- In the situation that value of calculate_charges at Step Resource has been
8320   -- set to 0 or NULL the values will need to be adjusted for min and max capacity
8321   -- at the resource level. min capacity will be set to 0 and the max capacity
8322   -- will be set to 99999999999999999
8323       || ' DECODE(NVL(gs.calculate_charges,0), 0, 0, gs.min_capacity) t_min_capacity,'
8324       || ' DECODE(NVL(gs.calculate_charges,0), 0, 99999999999999999, gs.max_capacity) t_max_capacity,'
8325       || ' gs.sequence_dependent_usage, '
8326       || ' gs.batchstep_resource_id,'
8327       /* NAVIN: for calculating WIP Charges */
8328       || ' r.step_status, '
8329       || ' r.plan_charges,'
8330       || ' gs.plan_rsrc_usage,'
8331       || ' gs.actual_rsrc_usage,'
8332       || ' r.batchstep_id,'    /* Navin 6/23/2004 Added for resource charges*/
8333       || '  SUM(NVL(o.material_ind,0))  OVER (PARTITION BY '
8334       || '  o.batch_id, r.batchstep_id) mat_found, '
8335    -- OPM break_ind values 0 and NULL maps to value 2 of MSC breakable_activity_flag
8336    -- and 1 maps with 1.
8337       || ' DECODE(NVL(o.break_ind,0), 1, 1, 2) breakable_activity_flag , '
8338       || ' uom.uom_code ,'
8339       || ' uom2.uom_code ,'
8340       || ' gri.equipment_item_id ,' /* SOWMYA - As Per latest FDD changes */
8341       || ' gs.plan_rsrc_count gmd_rsrc_count,' /*passed on msc_st_resource_requirements*/
8342       || ' r.plan_start_date, ' /* populate msc_st_job_operations.reco_start_date */
8343       || ' r.plan_cmplt_date, ' /* populate msc_st_job_operations.reco_completion_date */
8344       || ' NVL(c.efficiency,100) ' /*B4320561 - If null then resource is 100%efficient */
8345       || ' FROM'
8346       || ' mtl_units_of_measure'||pdblink||' uom, '
8347       || ' mtl_units_of_measure'||pdblink||' uom2, '
8348       || ' gme_batch_header'||pdblink||' h,'
8349       || ' gme_batch_steps'||pdblink||' r,'
8350       || ' gme_batch_step_activities'||pdblink||' o,'
8351       || ' gme_batch_step_resources'||pdblink||' gs,'
8352       || ' gme_resource_txns'||pdblink||' t , '
8353       || ' gmp_resource_instances'||pdblink||' gri, '
8354       || ' cr_rsrc_dtl'||pdblink||' c'
8355       || ' WHERE'
8356       || '     h.batch_id = r.batch_id '
8357       || ' AND r.batch_id = o.batch_id'
8358       || ' AND r.batchstep_id = o.batchstep_id'
8359       || ' AND o.batchstep_activity_id = gs.batchstep_activity_id'
8360       || ' AND o.batch_id = t.doc_id'
8361       || ' AND gs.batchstep_resource_id = t.line_id'
8362       || ' AND t.completed_ind = 0 '
8363       || ' AND NVL(t.sequence_dependent_ind,0) = 0 ' /* B4900503, Rajesh Patangya */
8364       || ' AND t.delete_mark = 0 '
8365       || ' AND t.instance_id = gri.instance_id (+) '
8366       || ' AND nvl(gri.inactive_ind,0) = 0 '
8367       || ' AND c.orgn_code = h.plant_code '
8368       || ' AND c.resources = gs.resources'
8369 /*B4313202 COLLECTING DATA FOR COMPLETED OPERATIONS:Included a chk for step status = 3*/
8370       || ' AND r.step_status in (1, 2, 3)'
8371       || ' AND c.Schedule_Ind <> 3 ' /* NAVIN:  gs.prim_rsrc_ind in (1,2) */
8372       || ' AND uom.uom_class = :gmp_uom_class '
8373       || ' AND uom.unit_of_measure = gs.usage_uom '
8374       || ' AND uom2.unit_of_measure = r.step_qty_uom '
8375       || ' AND c.delete_mark = 0 '
8376       || ' AND nvl(c.inactive_ind,0) = 0 ' ;
8377 
8378       IF MSC_CL_GMP_UTILITY.g_in_str_org  IS NOT NULL THEN
8379          v_rsrc_cursor := v_rsrc_cursor
8380            ||' AND EXISTS ( SELECT 1 FROM sy_orgn_mst'||pdblink||' som '
8381            ||' WHERE h.wip_whse_code = som.resource_whse_code )' ;
8382       END IF;
8383 
8384       v_rsrc_cursor := v_rsrc_cursor
8385         || ' ORDER BY '
8386         ||'         1,2,3,4,5,6,7,8 DESC,9';	/* NAVIN: converted to position notation in Order By*/
8387 
8388 --      || ' ORDER BY '
8389 --      || '   h.batch_id,'
8390 --      || '   ((r.batch_id * 2) + 1), '
8391 --      || '   r.batchstep_no, '
8392 --      || '   NVL(o.sequence_dependent_ind,0) DESC,'
8393 --      || '   o.offset_interval, '
8394 --      || '   o.activity,  '
8395 --      || '   o.batchstep_activity_id, '
8396 --      || '   gs.prim_rsrc_ind,'
8397 --      || '   gs.resources,'
8398 --      || '   NVL(t.sequence_dependent_ind,0) DESC, '
8399 --      || '   gs.plan_start_date';
8400 
8401       /* RAJESH PATANGYA open and fetch all the batch details  */
8402       OPEN rsrc_dtl FOR v_rsrc_cursor USING l_gmp_uom_class;
8403       LOOP
8404             FETCH rsrc_dtl INTO rsrc_tab(resource_count);
8405             EXIT WHEN rsrc_dtl%NOTFOUND;
8406             resource_count := resource_count + 1;
8407       END LOOP;
8408       CLOSE rsrc_dtl ;
8409       grsrc_size := resource_count - 1;
8410       log_message('Batches Resource size is = '|| to_char(grsrc_size) );
8411       time_stamp ;
8412 
8413       -- Get all the Operation Charges for the batch step
8414       -- NAVIN: START Operation Charges Data needs to be transferred to APS in to Msc_st_resource_charges
8415       stp_chg_cursor:=
8416         ' SELECT '
8417       ||' ((gbsc.batch_id*2)+1) x_batch_id,'
8418       ||' ((gbsc.batchstep_id*2)+1),'       /* B5461922 */
8419       || ' ((crd.resource_id * 2) + 1),'
8420       ||' gbsc.charge_number,'
8421       ||' iwm.mtl_organization_id,'
8422       ||' gbs.batchstep_no,'
8423       ||' gbsc.activity_sequence_number,'
8424       ||' gbsc.charge_quantity, '
8425       ||' gbsc.plan_start_date, '
8426       ||' gbsc.plan_cmplt_date'
8427       ||' FROM'
8428       ||' gme_batch_step_charges'||pdblink||' gbsc,'
8429       ||' cr_rsrc_dtl'||pdblink||' crd,'
8430       ||' ic_whse_mst'||pdblink||' iwm,'
8431       ||' gmd_recipe_validity_rules'||pdblink||' v,'
8432       ||' gme_batch_steps'||pdblink||' gbs,'
8433       ||' gme_batch_header'||pdblink||' h'
8434       ||' WHERE       '
8435       ||' h.batch_id = gbs.batch_id '
8436       ||' AND gbsc.batch_id = gbs.batch_id '
8437       ||' AND gbsc.batchstep_id = gbs.batchstep_id '
8438       ||' AND h.recipe_validity_rule_id = v.recipe_validity_rule_id'
8439       ||' AND EXISTS (SELECT '
8440       ||'               1  '
8441       ||'             FROM '
8442       ||'               gme_material_details'||pdblink||' gmd '
8443       ||'             WHERE '
8444       ||'                   gmd.batch_id = h.batch_id '
8445       ||'               AND gmd.item_id = v.item_id) '
8446       ||' AND crd.resources = gbsc.resources '
8447       ||' AND h.wip_whse_code = iwm.whse_code'
8448       ||' AND gbs.step_status in (1, 2) ';
8449 
8450       IF MSC_CL_GMP_UTILITY.g_in_str_org  IS NOT NULL THEN
8451 	   stp_chg_cursor := stp_chg_cursor
8452           ||'   AND EXISTS ( SELECT 1 FROM sy_orgn_mst'||pdblink||' som '
8453           ||'   WHERE  h.wip_whse_code = som.resource_whse_code )' ;
8454       END IF;
8455 
8456       stp_chg_cursor := stp_chg_cursor
8457             ||' ORDER BY 1, 2, 3, 4 ' ;
8458 
8459       OPEN c_chg_cursor FOR stp_chg_cursor ;
8460       LOOP
8461             FETCH c_chg_cursor INTO stp_chg_tbl(stp_chg_count);
8462             EXIT WHEN c_chg_cursor%NOTFOUND;
8463             stp_chg_count := stp_chg_count + 1;
8464       END LOOP;
8465       CLOSE c_chg_cursor ;
8466       stp_chg_count := stp_chg_count - 1;
8467       log_message('Batch Step charge size is = '|| to_char(stp_chg_count) );
8468       time_stamp ;
8469 
8470       -- NAVIN: END Operation Charges Data needs to be transferred to APS in to Msc_st_resource_charges
8471 
8472      /* NAVIN :- alternate resource */
8473      /* NAVIN: In Procedure production_orders just before starting the looping for prod_dtl cursor
8474      try to get all the alternate Resources.*/
8475 
8476      /* Alternate Resource selection   */
8477      /* B5688153, Rajesh Patangya prod spec alt*/
8478      /* B5879844  Uday Phadtare replaced at_apps_link with pdblink for prod */
8479         statement_alt_resource :=
8480                      ' SELECT pcrd.resource_id, acrd.resource_id, '
8481                    ||' cam.runtime_factor, '
8482 /*prod spec alt*/  ||' nvl(cam.preference,-1), nvl(prod.item_id,-1)   '
8483                    ||' FROM  cr_rsrc_dtl'||pdblink||' acrd, '
8484                    ||'       cr_rsrc_dtl'||pdblink||' pcrd, '
8485                    ||'       cr_ares_mst'||pdblink||' cam, '
8486                    ||'       gmp_altresource_products'||pdblink||' prod'
8487                    ||' WHERE cam.alternate_resource = acrd.resources '
8488                    ||'   AND cam.primary_resource = pcrd.resources '
8489                    ||'   AND acrd.orgn_code = pcrd.orgn_code '
8490                    ||'   AND cam.primary_resource = prod.primary_resource(+) '
8491                    ||'   AND cam.alternate_resource = prod.alternate_resource(+) '
8492                    ||'   AND acrd.delete_mark = 0  '
8493                    ||' ORDER BY pcrd.resource_id, '
8494                    ||' DECODE(cam.preference,NULL,cam.runtime_factor,cam.preference),'
8495                    ||'   prod.item_id ' ;
8496 
8497      -- Retrive the Details of all the Alternate Resources.
8498      alt_prod_size := 1;
8499      OPEN cur_alt_rsrc FOR statement_alt_resource ;
8500      LOOP
8501          FETCH cur_alt_rsrc INTO prod_alt_rsrc_tab(alt_prod_size);
8502          EXIT WHEN cur_alt_rsrc%NOTFOUND;
8503          alt_prod_size := alt_prod_size + 1;
8504      END LOOP;
8505      CLOSE cur_alt_rsrc;
8506      alt_prod_size := alt_prod_size -1 ;
8507      log_message('Production alternate resource size is = '|| to_char(alt_prod_size) );
8508 
8509     old_batch_id := -1;
8510     p := 1 ;
8511     FOR p IN 1..gprod_size LOOP  /* Batch loop starts */
8512 
8513     /* Multiply plan_qty with UOM conv factor. Factor will be 1 when the
8514     plan_qty and primary UOM is same. */
8515 
8516     prod_tab(p).matl_qty := prod_tab(p).matl_qty * prod_tab(p).uom_conv_factor;
8517     prod_tab(p).Minimum_Transfer_Qty := prod_tab(p).Minimum_Transfer_Qty * prod_tab(p).uom_conv_factor;
8518     /*Sowmya - As per the latest FDD changes - Modified as per Matt's review commet.
8519     The minimum tranfer qty should be passed in the primary uom*/
8520 
8521     IF old_batch_id <> prod_tab(p).batch_id THEN
8522 
8523       old_batch_id := prod_tab(p).batch_id;
8524       product_line := -1;
8525       opm_product_line := -1;
8526       prod_line_id := -1;
8527 
8528       /* create a logical number by combining the plant and batch number */
8529       order_no := prod_tab(p).plant_code || pdelimiter ||
8530                   prod_tab(p).batch_no;
8531 
8532       IF prod_tab(p).batch_type = 10 THEN
8533         order_no := 'F/'||order_no ;
8534       END IF;
8535 
8536       IF prod_tab(p).plant_code = prod_plant THEN
8537          IF (res_whse) THEN
8538            v_orgn_id := res_whse_id;
8539          ELSE
8540            v_orgn_id := prod_tab(p).mtl_org_id;
8541          END IF;
8542       ELSE
8543         prod_plant := prod_tab(p).plant_code;
8544 
8545      /* Bug 4774975 --  Rajesh Patangya starts */
8546         v_sql_stmt :=
8547              'SELECT '
8548           || ' iwm.mtl_organization_id '
8549           || 'FROM '
8550           || '  sy_orgn_mst' ||pdblink|| ' sy, '
8551           || '  ic_whse_mst' ||pdblink|| ' iwm '
8552           || 'WHERE '
8553           || '  sy.orgn_code = :p1'
8554           || '  AND sy.resource_whse_code = iwm.whse_code';
8555 
8556      /* Bug 4774975 --  Rajesh Patangya End */
8557 
8558         OPEN rsrc_whse FOR v_sql_stmt USING prod_tab(p).plant_code;
8559         FETCH rsrc_whse INTO res_whse_id;
8560           IF rsrc_whse%NOTFOUND THEN
8561             v_orgn_id := prod_tab(p).mtl_org_id;
8562             res_whse := FALSE;
8563           ELSE
8564             v_orgn_id := res_whse_id;
8565             res_whse := TRUE;
8566           END IF;
8567         CLOSE rsrc_whse;
8568 
8569       END IF;  /* for Plant code */
8570     END IF;   /* Batch Changes */
8571 
8572     IF ( prod_tab(p).matl_item_id = prod_tab(p).recipe_item_id) AND (product_line = -1) THEN
8573 
8574       product_line := prod_tab(p).item_id;  /* APS Item Identifier for Product */
8575       opm_product_line := prod_tab(p).recipe_item_id;  /* OPM Item Identifier for Product */
8576       prod_line_id := prod_tab(p).line_id;
8577       old_step_no := -1;
8578       i := 1;
8579 
8580       IF prod_tab(p).routing_id IS NOT NULL AND NVL(prod_tab(p).poc_ind, 'N') = 'Y'  AND
8581          (res_whse) THEN
8582 
8583         -- log_message( ' Entry --  ' || g_rsrc_cnt );
8584         r := 1 ;
8585         resource_usage_flag := 0 ;
8586         resource_instance_usage_flag := 0 ;
8587         old_rsrc_batch_id :=  -999;
8588         old_rsrc_resources :=  -999;
8589         old_rsrc_original_seq_num := -999;
8590         old_instance_number :=  -999;
8591         old_rsrc_inst_batch_id := -999;
8592         old_rsrc_inst_resources := -999;
8593         old_rsrc_inst_original_seq_num := -999;
8594 
8595         FOR r IN g_rsrc_cnt..grsrc_size LOOP   /* Resource Cursor */
8596 
8597            /* ------------- Navin: START Process Resource Requirements ------------- */
8598            IF old_rsrc_batch_id <> rsrc_tab(r).batch_id
8599               OR old_rsrc_resources <> rsrc_tab(r).resources
8600               OR old_rsrc_original_seq_num <> rsrc_tab(r).original_seq_num THEN
8601                 -- Reset the flags.
8602                 resource_usage_flag := 0 ;
8603            END IF;
8604 
8605            IF rsrc_tab(r).resource_usage > 0 AND resource_usage_flag = 0 THEN
8606              -- Process and insert the very first resource record
8607              resource_usage_flag := 1 ;
8608              -- Populate flags
8609              old_rsrc_batch_id := rsrc_tab(r).batch_id ;
8610              old_rsrc_resources := rsrc_tab(r).resources ;
8611              old_rsrc_original_seq_num := rsrc_tab(r).original_seq_num ;
8612 
8613             /*Sowmya - As per the latest FDD changes - process this resource only
8614             if the class type of this is same as the one defined in profile*/
8615             l_res_inst_process := 1;
8616 
8617              IF  prod_tab(p).batch_id > rsrc_tab(r).batch_id THEN --- MAIN IF
8618                NULL ;
8619              ELSIF  prod_tab(p).batch_id < rsrc_tab(r).batch_id THEN
8620                g_rsrc_cnt := r ;
8621                /* Initialize for the change of batch */
8622                v_resource_usage := 0;
8623                v_res_seq        := 0;
8624                v_schedule_flag  := 0;
8625                v_parent_seq_num := 0;
8626                v_rsrc_cnt       := 0;
8627                v_start_date     := NULL;
8628                v_end_date       := NULL;
8629                old_activity     := 0;
8630                /* NAVIN :- */
8631                V_ACTIVITY_GROUP_ID  := 0;  /* B3995361 rpatangy */
8632                v_seq_dep_usage  := 0;
8633                found_chrg_rsrc := 0;
8634                chrg_activity   := -1;
8635 
8636                EXIT;
8637              ELSIF  prod_tab(p).batch_id =  rsrc_tab(r).batch_id THEN
8638                IF old_step_no <> rsrc_tab(r).batchstep_no THEN /* Step change */
8639                  v_res_seq        := 0;
8640                  old_activity     := -1;
8641                  v_resource_usage := 0;
8642                  v_res_seq        := 0;
8643                  v_schedule_flag  := 0;
8644                  v_parent_seq_num := 0;
8645                  v_rsrc_cnt       := 0;
8646                  v_start_date     := NULL;
8647                  v_end_date       := NULL;
8648                  /* NAVIN :- */
8649                  V_ACTIVITY_GROUP_ID  := 0;  /* B3995361 rpatangy */
8650                  v_seq_dep_usage  := 0;
8651                  found_chrg_rsrc := 0;
8652                  chrg_activity   := -1;
8653                /* nsinghi APSK - Insert Step related information in msc_st_job_operations
8654                   every time step changes. */
8655 
8656                  jo_index := jo_index + 1;
8657                  jo_wip_entity_id(jo_index) := rsrc_tab(r).x_batch_id;
8658                  jo_instance_id(jo_index) := pinstance_id;
8659                  jo_operation_seq_num(jo_index) := rsrc_tab(r).batchstep_no;
8660                  jo_recommended(jo_index) := 'Y';
8661                  jo_network_start_end(jo_index) := null_value;
8662                  jo_reco_start_date(jo_index) := rsrc_tab(r).step_start_date;
8663                  jo_reco_completion_date(jo_index) := rsrc_tab(r).step_end_date;
8664                  jo_operation_sequence_id(jo_index) := rsrc_tab(r).batchstep_id;
8665                  jo_organization_id(jo_index) := v_orgn_id;
8666                  jo_department_id(jo_index) := ((v_orgn_id*2) + 1);
8667                  jo_minimum_transfer_quantity(jo_index) := prod_tab(p).minimum_transfer_qty;
8668 
8669                END IF;   /* Step change */
8670 
8671                IF rsrc_tab(r).seq_dep_ind <> -1 THEN /* NAVIN :- Process Rows only if
8672                                            Sequence Dependent is not -1 */
8673 
8674                  IF (old_activity <> rsrc_tab(r).bs_activity_id) OR (old_activity = -1) THEN
8675                    v_res_seq := v_res_seq + 1;
8676                    old_activity := rsrc_tab(r).bs_activity_id;
8677 
8678                    /* B3421856, If materail indicator activity then previous = 3, Next = 4 */
8679                    IF rsrc_tab(r).mat_found > 0 THEN
8680 
8681                      IF rsrc_tab(r).material_ind = 1 THEN
8682                          v_schedule_flag := 4;
8683                      ELSE
8684                        IF v_schedule_flag < 4 THEN
8685                           v_schedule_flag := 3 ;
8686                        END IF ;
8687                      END IF;   /* Material Indicator */
8688                    END IF;  /* Mat_found */
8689                  END IF;   /* old_activity */
8690 
8691                  IF (rsrc_tab(r).material_ind = 0) AND  (rsrc_tab(r).mat_found > 0) THEN
8692                    rsrc_tab(r).schedule_flag := v_schedule_flag;
8693                  END IF;
8694 
8695                  IF NVL(rsrc_tab(r).actual_cmplt_date,v_null_date) = v_null_date THEN
8696                    /* when the actual start is null the resource has not started
8697                       and the plan start will be used.  */
8698                    IF rsrc_tab(r).tran_seq_dep = 1 THEN
8699                      v_parent_seq_num := v_res_seq;
8700                      v_resource_usage := rsrc_tab(r).resource_usage;
8701                      v_start_date := rsrc_tab(r).act_start_date;
8702                      v_end_date := rsrc_tab(r).plan_start_date;
8703                      /* NAVIN :- added Sequence Dependency */
8704                      v_seq_dep_usage := rsrc_tab(r).sequence_dependent_usage;
8705                    ELSE
8706                      v_seq_dep_usage  := 0;
8707                      v_parent_seq_num := TO_NUMBER(NULL);
8708                      v_start_date := rsrc_tab(r).plan_start_date;
8709                      v_end_date := rsrc_tab(r).plan_cmplt_date;
8710                      IF v_inflate_wip = 1 THEN
8711                        v_resource_usage := rsrc_tab(r).resource_usage / rsrc_tab(r).utl_eff;
8712                      ELSE
8713                        v_resource_usage := rsrc_tab(r).resource_usage;
8714                      END IF;
8715                    END IF;   /* tran_seq_ind */
8716 
8717                    /*Sowmya - As per the latest FDD changes - Start*/
8718                    /*For a Pending batch if the original resoucre count is less than the plan
8719                    resource count then pass pln resource count otherwise the original resource
8720                    count is passed*/
8721                    IF rsrc_tab(r).org_step_status = 1 THEN
8722         /* B4349002 Resource Count is same as Plan resource count */
8723                                 v_max_rsrcs := rsrc_tab(r).gmd_rsrc_count;
8724                    ELSIF rsrc_tab(r).org_step_status = 2 THEN
8725                         IF rsrc_tab(r).actual_rsrc_count IS NULL THEN
8726                                 v_max_rsrcs := rsrc_tab(r).plan_rsrc_count;
8727                         ELSE
8728                                 v_max_rsrcs := rsrc_tab(r).actual_rsrc_count;
8729                         END IF;
8730                    END IF;
8731                    /*Sowmya - As per the latest FDD changes - End*/
8732 
8733                    /* If no actual resource exists then the resource has not
8734                       started and the planned value will be used */
8735                    IF rsrc_tab(r).actual_rsrc_count IS NULL THEN
8736                      v_rsrc_cnt := rsrc_tab(r).plan_rsrc_count;
8737                    ELSE
8738                      v_rsrc_cnt := rsrc_tab(r).actual_rsrc_count;
8739                    END IF;
8740 
8741                   /* write the current resource detail row asscoiating it with the
8742                     batch through the product line */
8743 
8744                   /* NAVIN :- If there are more than 1 activities in a step having
8745                    chargeable resources and scale_type = 3 and scheduled, then
8746                    change scale_type for all activities after the 1st is changed
8747                    to linear  */
8748 
8749                    IF rsrc_tab(r).mat_found = 0 OR rsrc_tab(r).material_ind = 1 THEN
8750                      IF rsrc_tab(r).scale_type = 3 -- APS decoded value as per DECODE(rsrc_tab(r).scale_type,0,2,1,1,2,3);
8751                      AND rsrc_tab(r).capacity_constraint = 1
8752                      AND found_chrg_rsrc = 0 THEN
8753                            found_chrg_rsrc := 1;
8754                            chrg_activity := rsrc_tab(r).bs_activity_id;
8755                            /* if the rtg_scale_type is 3 but another activity was found
8756                            with 2 then this row will be assigned scale_type = 1. */
8757                      ELSIF rsrc_tab(r).scale_type = 3
8758                      AND rsrc_tab(r).capacity_constraint = 1
8759                      AND found_chrg_rsrc = 1
8760                      AND chrg_activity <> rsrc_tab(r).bs_activity_id THEN
8761                            rsrc_tab(r).scale_type := 1;
8762                      END IF;
8763                    END IF;
8764 
8765                    IF rsrc_tab(r).scale_type = 3 AND found_chrg_rsrc = 1 THEN
8766 -- APS decoded value as per DECODE(rsrc_tab(r).scale_type,0,2,1,1,2,3);
8767                    /* NAVIN: END Operation Charges Data needs to be transferred
8768                       to APS  in to Msc_st_resource_charges */
8769                       IF rsrc_tab(r).org_step_status = 2 THEN
8770                          l_charges_remaining := CEIL(((rsrc_tab(r).plan_rsrc_usage -
8771                              rsrc_tab(r).actual_rsrc_usage) * rsrc_tab(r).plan_charges) /
8772                              rsrc_tab(r).plan_rsrc_usage);
8773 -- HW B4761811- Calculate the remaining charged
8774                       ELSE
8775                         l_charges_remaining := rsrc_tab(r).plan_charges ;
8776 
8777                       END IF;
8778 
8779                       IF rsrc_tab(r).org_step_status = 1 OR (l_charges_remaining > 0 AND rsrc_tab(r).org_step_status = 2) THEN
8780                       /* Batch step status is pending OR there are some remaining charges for a WIP batch */
8781                          inst_stp_chg_tbl(pinstance_id, r);
8782                       END IF;
8783                    END IF ;
8784 
8785                    /* B3995361 rpatangy start */
8786                    IF rsrc_tab(r).prim_rsrc_ind = 1 THEN
8787                     v_activity_group_id := rsrc_tab(r).x_resource_id ;
8788                    END IF;
8789                    /* B3995361 rpatangy end */
8790 
8791                    IF v_resource_usage > 0 THEN
8792                      /* Bulk Insert for insert_resource_requirements */
8793                        rr_index := rr_index + 1 ;
8794                        rr_organization_id(rr_index) := v_orgn_id ;
8795                        rr_sr_instance_id(rr_index) := pinstance_id ;
8796                        rr_supply_id(rr_index) :=  rsrc_tab(r).x_batch_id ; /* B1177070 encoded key */
8797                        rr_resource_seq_num(rr_index) := rsrc_tab(r).seq_dep_ind ;
8798                        rr_resource_id(rr_index) := rsrc_tab(r).x_resource_id ; /* B1177070 encoded key */
8799                        rr_start_date(rr_index) := v_start_date ;
8800                        rr_end_date(rr_index)  :=  v_end_date ;
8801                        rr_opr_hours_required(rr_index) :=  v_resource_usage ;
8802        /* Bug 4431718 populate usage_rate column starts */
8803                     IF rsrc_tab(r).scale_type = 1 THEN /*linearly scaled */
8804                         IF rsrc_tab(r).plan_step_qty > 0 THEN
8805                         rr_usage_rate(rr_index) :=
8806                         v_resource_usage / rsrc_tab(r).plan_step_qty ;
8807                         ELSE
8808                         rr_usage_rate(rr_index) :=  v_resource_usage ;
8809                         END IF ;
8810                     ELSIF rsrc_tab(r).scale_type = 2 THEN /*fix scaled*/
8811                         rr_usage_rate(rr_index) := v_resource_usage ;
8812                     ELSIF rsrc_tab(r).scale_type = 3 THEN /* Charge Scaled */
8813                         IF l_charges_remaining > 0 THEN
8814                         rr_usage_rate(rr_index) :=
8815                                 v_resource_usage /l_charges_remaining ;
8816                         ELSE
8817                         rr_usage_rate(rr_index) := v_resource_usage ;
8818                         END IF ;
8819                     END IF ;
8820        /* Bug 4431718 populate usage_rate column Ends */
8821 
8822                        rr_assigned_units(rr_index) := v_rsrc_cnt ;
8823                        rr_department_id(rr_index) := ((v_orgn_id * 2) + 1) ;  /* B1177070 encoded key */
8824                        rr_wip_entity_id(rr_index) :=  rsrc_tab(r).x_batch_id ; /* B1177070 encoded key */
8825                        /* B1224660 write the step number for oper seq num */
8826                        rr_operation_seq_num(rr_index)  :=   rsrc_tab(r).batchstep_no ;
8827                       /* B3995361 */
8828                        IF rsrc_tab(r).step_status = 2 THEN
8829                           rr_firm_flag(rr_index) :=   7 ;
8830                        ELSE
8831                           rr_firm_flag(rr_index) :=    rsrc_tab(r).firm_type ;
8832                        END IF;
8833 --                       rr_firm_flag(rr_index) :=    rsrc_tab(r).firm_type ;
8834                        rr_minimum_transfer_quantity(rr_index) := 0 ;
8835                        rr_parent_seq_num(rr_index) := TO_NUMBER(NULL) ;
8836                        rr_schedule_flag(rr_index) := rsrc_tab(r).schedule_flag ;
8837                    -- HW B4902328 - Added inventory_item_id
8838                        rr_inventory_item_id(rr_index) := product_line;
8839                        /* NAVIN :- start */
8840                        rr_sequence_id(rr_index) := rsrc_tab(r).group_sequence_id ;
8841                        rr_sequence_number(rr_index) := rsrc_tab(r).group_sequence_number ;
8842                        rr_firm_type(rr_index) := rsrc_tab(r).firm_type ;
8843                        rr_setup_id(rr_index) := rsrc_tab(r).setup_id ;
8844                        rr_original_seq_num (rr_index) := rsrc_tab(r).original_seq_num;
8845                        rr_min_capacity(rr_index) := rsrc_tab(r).minimum_capacity;
8846                        rr_max_capacity(rr_index)  := rsrc_tab(r).maximum_capacity;
8847                        rr_alternate_number(rr_index) := 0 ;
8848                        rr_basis_type(rr_index) := rsrc_tab(r).scale_type;
8849                        rr_hours_expended(rr_index) := rsrc_tab(r).actual_rsrc_usage;
8850                        rr_breakable_activity_flag(rr_index) := rsrc_tab(r).breakable_activity_flag;
8851                        /* Sowmya - As per the latest FDD changes - Start */
8852                        rr_plan_step_qty(rr_index) := rsrc_tab(r).plan_step_qty ;
8853                        rr_step_qty_uom(rr_index) := rsrc_tab(r).step_qty_uom ;
8854                        rr_gmd_rsrc_cnt(rr_index) := v_max_rsrcs;
8855                        /* Sowmya - As per the latest FDD changes - End */
8856 
8857                        /* B3995361 rpatangy */
8858                        rr_activity_group_id(rr_index) := v_activity_group_id ;
8859                        rr_operation_sequence_id(rr_index) := rsrc_tab(r).batchstep_id ; /* B5461922 rpatangy */
8860                        /*B4320561 - sowsubra - start*/
8861                        rr_unadjusted_resource_hrs(rr_index) := rsrc_tab(r).resource_usage ;
8862                        rr_touch_time(rr_index) := rr_unadjusted_resource_hrs(rr_index)/ rsrc_tab(r).efficiency ;
8863                        /*B4320561 - sowsubra - end*/
8864 
8865                        /* NAVIN :- START - Logic To Handle Alternate Resources */
8866                        /*
8867                            Now check if the above resource inserted is a Primary. If it is
8868                            Primary then find its Alternates if existing, and then insert its rows
8869                            into msc_st_operation_resources table. Also keep track of number of
8870                            times alternates are inserted.
8871                        */
8872 
8873                        IF rsrc_tab(r).prim_rsrc_ind = 1 THEN
8874                          ---------------------------------------------------------------------
8875                          -- Use Bsearch technique to identify if any Alternate exists for the primary.
8876                          -- Enh_bsearch_alternate_rsrc is a new procedure to locate the Alternate Resource
8877                          -- for a given Primary resource in the PL/SQl table.
8878                          ---------------------------------------------------------------------
8879                          alternate_rsrc_loc := Enh_bsearch_alternate_rsrc (rsrc_tab(r).resource_id);
8880                          v_alternate  := 0;
8881 
8882                          IF alternate_rsrc_loc > 0 THEN  /* Alternate resource location */
8883                          /*Sowmya - As per latest FDD changes - Included chks that determine
8884                          when the alternate resources will be passed */
8885                             IF prod_tab(p).firmed_ind <> 1 THEN /* Batch firm chk */
8886                             /*If batch not firmed then pass on the alternate resource data*/
8887                                 IF rsrc_tab(r).org_step_status <> 2 THEN /* Batch Step not in WIP */
8888                                 /*Pass on the alternate resource data when the batch step is not in WIP status*/
8889                                 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
8890                                  /* Batch resources not firmed */
8891                                  /*0 - UnFrim ,         1 - Firm Start Date ,
8892                                    2 - Firm End Date ,  3 - Firm Resource  ,
8893                                    4 - Firm Start Date and End Date ,
8894                                    5 - Firm Start Date and Resource ,
8895                                    6 - Firm End Date and Resource ,
8896                                    7 - Firm All*/
8897                                    alt_cnt := 1 ;
8898                                    --  Loop through the Alternate resources for the Primary Resource
8899                                    /*Sowmya - As per the latest FDD changes - Start */
8900                                    FOR alt_cnt IN alternate_rsrc_loc..alt_prod_size
8901                                    LOOP
8902      /* B5688153, Rajesh Patangya prod spec alt*/
8903                                        IF ( prod_alt_rsrc_tab(alt_cnt).prim_resource_id =
8904                                             rsrc_tab(r).resource_id
8905                                        AND (prod_alt_rsrc_tab(alt_cnt).item_id = -1 OR
8906                                             prod_alt_rsrc_tab(alt_cnt).item_id = opm_product_line )) THEN
8907                            --          IF ( prod_alt_rsrc_tab(alt_cnt).prim_resource_id = rsrc_tab(r).resource_id ) THEN
8908                                          v_alternate := v_alternate + 1;
8909                                          /* Bulk Insert for Alternate_resource_requirements */
8910                                          arr_index := arr_index + 1 ;
8911                                          arr_organization_id(arr_index) := v_orgn_id ;
8912                                          arr_sr_instance_id(arr_index) := pinstance_id;
8913                                          arr_res_seq_num(arr_index) := rsrc_tab(r).original_seq_num ;
8914                                          arr_assigned_units(arr_index) := v_rsrc_cnt ;
8915                                          arr_department_id(arr_index) :=
8916                                                              ((v_orgn_id * 2) + 1) ;
8917                                          arr_wip_entity_id(arr_index) :=
8918                                                              rsrc_tab(r).x_batch_id ;
8919                                          /* B1224660 write the step number for oper seq num */
8920                                          arr_operation_seq_num(arr_index) :=
8921                                                         rsrc_tab(r).batchstep_no ;
8922                                          arr_setup_id(arr_index) :=
8923                                                         rsrc_tab(r).setup_id ;
8924                                          arr_schedule_seq_num(arr_index) :=
8925                                                         rsrc_tab(r).seq_dep_ind;
8926                                          arr_maximum_assigned_units(arr_index) :=
8927                                                         v_max_rsrcs;
8928                                          arr_activity_group_id(arr_index) :=
8929                                 ((prod_alt_rsrc_tab(alt_cnt).alt_resource_id * 2) + 1);
8930                                          arr_basis_type(arr_index):=
8931                                                         rsrc_tab(r).scale_type;
8932                                          arr_resource_id(arr_index) :=
8933                                 ((prod_alt_rsrc_tab(alt_cnt).alt_resource_id * 2) + 1) ;
8934                                          arr_usage_rate(arr_index) := v_resource_usage
8935                                             * prod_alt_rsrc_tab(alt_cnt).runtime_factor;
8936                                          arr_alternate_num(arr_index) := v_alternate ;
8937                                          arr_uom_code(arr_index) :=
8938                                                         rsrc_tab(r).usage_uom;
8939                 --                       arr_gmd_rsrc_cnt(rr_index) := v_max_rsrcs;
8940                                        ELSIF ( prod_alt_rsrc_tab(alt_cnt).prim_resource_id > rsrc_tab(r).resource_id ) THEN
8941                                            EXIT ;
8942                                        END IF;  /* End if for alternate resource and orgn code match */
8943                                    END LOOP;  /* Alternate loop */
8944                                 END IF; /* Batch resources not firmed */
8945                                 END IF;/* Batch Step not in WIP */
8946                            END IF; /* Batch firm chk */
8947                          END IF ; /* Alternate resource location */
8948                        END IF;  /* rsrc_tab(r).prim_rsrc_ind = 1 */
8949 
8950                        /* NAVIN:
8951                        Below logic is to create the resource group pattern with different
8952                        values of Alternate_Number. Variable v_alternate holds the count of
8953                        alternate resources that has been inserted for the Primary resource
8954                        of the group. Now insert all the resource records other than primary
8955                        with a value of Alternate_Number from 1 to v_alternate, to complete
8956                        the pattern of resource group.
8957                        NAVIN: */
8958 
8959                        IF rsrc_tab(r).prim_rsrc_ind <> 1 AND v_alternate > 0 THEN
8960                        /* B3995361 rpatangy  start */
8961                          mk_alt_grp := 0 ;
8962                          FOR alt_cnt IN alternate_rsrc_loc..alt_prod_size
8963                           LOOP
8964                           IF prod_alt_rsrc_tab(alt_cnt).prim_resource_id =
8965                               ((v_activity_group_id - 1)/2) THEN
8966                            arr_index := arr_index + 1 ;
8967                            mk_alt_grp := mk_alt_grp + 1 ;
8968                            arr_organization_id(arr_index) := v_orgn_id ;
8969                            arr_sr_instance_id(arr_index) := pinstance_id ;
8970                            arr_res_seq_num(arr_index) := rsrc_tab(r).original_seq_num ;
8971                            arr_resource_id(arr_index) := rsrc_tab(r).x_resource_id ;
8972                            arr_assigned_units(arr_index) := v_rsrc_cnt ;
8973                            arr_department_id(arr_index) := ((v_orgn_id * 2) + 1) ;
8974                            arr_wip_entity_id(arr_index) :=  rsrc_tab(r).x_batch_id ;
8975                            arr_operation_seq_num(arr_index)  := rsrc_tab(r).batchstep_no ;
8976                            arr_setup_id(arr_index) := rsrc_tab(r).setup_id ;
8977                            arr_schedule_seq_num(arr_index) := rsrc_tab(r).seq_dep_ind;
8978                            arr_maximum_assigned_units(arr_index) := v_max_rsrcs;
8979                            arr_activity_group_id(arr_index) :=
8980                                    ((prod_alt_rsrc_tab(alt_cnt).alt_resource_id * 2) + 1);
8981                            arr_basis_type(arr_index):= rsrc_tab(r).scale_type;
8982                            arr_usage_rate(arr_index) := v_resource_usage ;
8983                            arr_alternate_num(arr_index) := mk_alt_grp ;
8984                            arr_uom_code(arr_index) := rsrc_tab(r).usage_uom;
8985                           ELSIF prod_alt_rsrc_tab(alt_cnt).prim_resource_id >
8986                                 ((v_activity_group_id - 1)/2) THEN
8987                              EXIT ;
8988                           END IF;  /* End if for alternate resource and orgn code match */
8989                          /* B3995361 rpatangy  End */
8990                          END LOOP;  /* mk_alt_grp loop */
8991                        END IF;  /* End if for Check in Primary Resource Indicator and  v_alternate > 0*/
8992                        /* NAVIN :- END - Logic To Handle Alternate Resources */
8993 
8994                        /* NAVIN :- Logic to Handle Additional row For Sequence Dependency Start */
8995                        IF v_seq_dep_usage > 0 THEN
8996                          rr_index := rr_index + 1 ;
8997                          rr_organization_id(rr_index) := v_orgn_id ;
8998                          rr_sr_instance_id(rr_index) := pinstance_id ;
8999                          rr_supply_id(rr_index) :=  rsrc_tab(r).x_batch_id ; /* B1177070 encoded key */
9000                          /* B1224660 new value to write resource seq num */
9001                          rr_resource_seq_num(rr_index) := rsrc_tab(r).seq_dep_ind ;
9002                          rr_resource_id(rr_index) := rsrc_tab(r).x_resource_id ; /* B1177070 encoded key */
9003                          rr_start_date(rr_index) := v_start_date ;
9004                          rr_end_date(rr_index)  :=  v_end_date ;
9005                          rr_opr_hours_required(rr_index) :=  rsrc_tab(r).sequence_dependent_usage; -- * converted_usage;
9006     /* B4637398, We will treat This extra usage row as fixed and provide
9007           the same reosurce usage in usage_rate column */
9008                          rr_usage_rate(rr_index) := v_resource_usage ;
9009 
9010                          /* Sowmya - As per the latest FDD changes - multiply the usage with the conveted factor */
9011                          rr_assigned_units(rr_index) := v_rsrc_cnt ;
9012                          rr_department_id(rr_index) := ((v_orgn_id * 2) + 1) ;  /* B1177070 encoded key */
9013                          rr_wip_entity_id(rr_index) :=  rsrc_tab(r).x_batch_id ; /* B1177070 encoded key */
9014                          /* B1224660 write the step number for oper seq num */
9015                          rr_operation_seq_num(rr_index)  :=   rsrc_tab(r).batchstep_no ;
9016                          rr_operation_sequence_id(rr_index) := rsrc_tab(r).batchstep_id ; /* B5461922 rpatangy */
9017                          rr_firm_flag(rr_index) :=    rsrc_tab(r).firm_type ;
9018                          rr_minimum_transfer_quantity(rr_index) := 0 ;
9019                          rr_parent_seq_num(rr_index) := rsrc_tab(r).original_seq_num;
9020                          rr_schedule_flag(rr_index) := rsrc_tab(r).schedule_flag ;
9021                    -- HW B4902328 - Added inventory_item_id
9022                          rr_inventory_item_id(rr_index) := product_line;
9023                          rr_sequence_id(rr_index) := rsrc_tab(r).group_sequence_id ;
9024                          rr_sequence_number(rr_index) := rsrc_tab(r).group_sequence_number ;
9025                          rr_firm_type(rr_index) := rsrc_tab(r).firm_type ;
9026                          rr_setup_id(rr_index) := rsrc_tab(r).setup_id ;
9027                          rr_original_seq_num (rr_index) := TO_NUMBER(NULL) ;
9028                          rr_min_capacity(rr_index) := rsrc_tab(r).minimum_capacity;
9029                          rr_max_capacity(rr_index)  := rsrc_tab(r).maximum_capacity;
9030                          rr_alternate_number(rr_index) := 0 ;
9031                          rr_basis_type(rr_index) := rsrc_tab(r).scale_type;           -- Added 7/14/2004
9032                          rr_hours_expended(rr_index) := rsrc_tab(r).actual_rsrc_usage;
9033                          rr_breakable_activity_flag(rr_index) := rsrc_tab(r).breakable_activity_flag;
9034                          /* Sowmya - As per the latest FDD changes - Start */
9035                          rr_plan_step_qty(rr_index) := rsrc_tab(r).plan_step_qty ;
9036                          rr_step_qty_uom(rr_index) := rsrc_tab(r).step_qty_uom ;
9037                          rr_gmd_rsrc_cnt(rr_index) := v_max_rsrcs;
9038                          /* Sowmya - As per the latest FDD changes - End */
9039 
9040                          /* B3995361 rpatangy */
9041                        rr_activity_group_id(rr_index) := v_activity_group_id ;
9042                        /*B4320561 - sowsubra - start*/
9043                        rr_unadjusted_resource_hrs(rr_index) := rsrc_tab(r).resource_usage ;
9044                        rr_touch_time(rr_index) := rr_unadjusted_resource_hrs(rr_index)/ rsrc_tab(r).efficiency ;
9045                        /*B4320561 - sowsubra - end*/
9046 
9047                        END IF;
9048                    END IF;   /* resource usage */  -- v_resource_usage > 0
9049                  END IF;   /* actual completion date */ -- NVL(rsrc_tab(r).actual_cmplt_date,v_null_date) = v_null_date
9050                END IF; /* NAVIN :- End If condition for seq_dep_ind <> -1 */ -- rsrc_tab(r).seq_dep_ind <> -1
9051 
9052                old_step_no := rsrc_tab(r).batchstep_no;
9053              END IF ;   /* entry/Exit Logic */  --- MAIN IF
9054 
9055            END IF; /* rsrc_tab(r).resource_usage > 0 AND resource_usage_flag = 0 */
9056 
9057            /* ------------- Navin: END Process Resource Requirements ------------- */
9058 
9059            /* ------------- Navin: START Process Resource Instances Requirements ------------- */
9060            IF rsrc_tab(r).instance_number <> -1 THEN
9061              IF old_rsrc_inst_batch_id <> rsrc_tab(r).batch_id
9062                 OR old_rsrc_inst_resources <> rsrc_tab(r).resources
9063                 OR old_rsrc_inst_original_seq_num <> rsrc_tab(r).original_seq_num
9064                 OR old_instance_number <> rsrc_tab(r).instance_number THEN
9065                   -- Reset the flags.
9066                   resource_instance_usage_flag := 0 ;
9067              END IF;
9068 
9069              IF rsrc_tab(r).resource_instance_usage > 0 AND resource_instance_usage_flag = 0  AND l_res_inst_process = 1 THEN
9070                   -- Process and insert the very first resource_instance_usage record
9071                   resource_instance_usage_flag := 1 ;
9072 
9073                   /* Sowmya - As per the latest FDD changes - Reinitialise the variable*/
9074                   l_res_inst_process := 0 ;
9075 
9076                   -- Populate flags
9077                   old_rsrc_inst_batch_id := rsrc_tab(r).batch_id ;
9078                   old_rsrc_inst_resources := rsrc_tab(r).resources ;
9079                   old_rsrc_inst_original_seq_num := rsrc_tab(r).original_seq_num ;
9080                   old_instance_number := rsrc_tab(r).instance_number;
9081 
9082                   -- Insert the very first resource_instance_usage record
9083                   inst_indx := inst_indx + 1 ;
9084 
9085                   rec_inst_supply_id(inst_indx) := rsrc_tab(r).x_batch_id ;
9086                   rec_inst_organization_id(inst_indx) := v_orgn_id ;
9087                   rec_inst_sr_instance_id(inst_indx) := pinstance_id ;
9088                   rec_inst_rec_resource_seq_num(inst_indx) := rsrc_tab(r).seq_dep_ind ;
9089                   rec_inst_resource_id(inst_indx) := rsrc_tab(r).x_resource_id ;
9090                   rec_inst_instance_id(inst_indx) := rsrc_tab(r).instance_number ;
9091                   rec_inst_start_date(inst_indx) := v_start_date ;
9092                   rec_inst_end_date(inst_indx)  :=  v_end_date ;
9093                   rec_inst_rsrc_instance_hours(inst_indx) := rsrc_tab(r).resource_instance_usage;-- * converted_usage;
9094                   /* Sowmya - As per the latest FDD changes - multiply the usage with the conveted factor */
9095                   rec_inst_operation_seq_num(inst_indx) := rsrc_tab(r).batchstep_no ;
9096                   rec_inst_department_id(inst_indx) := ((v_orgn_id * 2) + 1) ;
9097                   rec_inst_wip_entity_id(inst_indx) :=  rsrc_tab(r).x_batch_id ;
9098                   rec_inst_serial_number(inst_indx)  :=   rsrc_tab(r).eqp_serial_number ;
9099                   rec_inst_original_seq_num(inst_indx)  :=   rsrc_tab(r).original_seq_num ;
9100                   rec_inst_parent_seq_num(inst_indx) := TO_NUMBER(NULL) ;
9101                   rec_inst_equp_item_id(inst_indx) := rsrc_tab(r).equp_item_id;
9102                   /*Sowmya - As per the latest FDD changes - Resource Instances */
9103 
9104                   IF v_seq_dep_usage > 0 THEN
9105                     /* Bulk Insert for insert_resource_requirements */
9106                     inst_indx := inst_indx + 1 ;
9107 
9108                     rec_inst_supply_id(inst_indx) := rsrc_tab(r).x_batch_id ;
9109                     rec_inst_organization_id(inst_indx) := v_orgn_id ;
9110                     rec_inst_sr_instance_id(inst_indx) := pinstance_id ;
9111                     rec_inst_rec_resource_seq_num(inst_indx) := rsrc_tab(r).seq_dep_ind ;
9112                     rec_inst_resource_id(inst_indx) := rsrc_tab(r).x_resource_id ;
9113                     rec_inst_instance_id(inst_indx) := rsrc_tab(r).instance_number ;
9114                     rec_inst_start_date(inst_indx) := v_start_date ;
9115                     rec_inst_end_date(inst_indx)  :=  v_end_date ;
9116                     /* NAVIN: Divide the seq dep usage equally amongst the instances. */
9117                     rec_inst_rsrc_instance_hours(inst_indx) := rsrc_tab(r).sequence_dependent_usage;-- * converted_usage;
9118                     /* Sowmya - As per the latest FDD changes - multiply the usage with the conveted factor */
9119                     rec_inst_operation_seq_num(inst_indx) := rsrc_tab(r).batchstep_no ;
9120                     rec_inst_department_id(inst_indx) := ((v_orgn_id * 2) + 1) ;
9121                     rec_inst_wip_entity_id(inst_indx) :=  rsrc_tab(r).x_batch_id ;
9122                     rec_inst_serial_number(inst_indx)  :=   rsrc_tab(r).eqp_serial_number ;
9123                     rec_inst_original_seq_num(inst_indx)  :=  TO_NUMBER(NULL) ;
9124                     rec_inst_parent_seq_num(inst_indx) := rsrc_tab(r).original_seq_num;
9125                     rec_inst_equp_item_id(inst_indx) := rsrc_tab(r).equp_item_id;
9126                     /*Sowmya - As per the latest FDD changes - Resource Instances */
9127 
9128                   END IF; /* Sequence Dependency Row */
9129              END IF; /* rsrc_tab(r).resource_instance_usage > 0 AND resource_instance_usage_flag = 0 */
9130            END IF; /* rsrc_tab(r).instance_number <> -1 */
9131            /* ------------- Navin: END Process Resource Instances Requirements ------------- */
9132 
9133        END LOOP;   /* Resource Cursor */
9134 
9135 
9136       END IF;   /* Routing_id is not null */
9137    END IF;  /* item should be product */
9138 
9139         IF prod_tab(p).line_id = prod_line_id THEN
9140           supply_type := 3;    /* Product */
9141         ELSE
9142           supply_type := 14;   /* Co Product or a by-Product */
9143         END IF;
9144 
9145         /* ingredient get written to the demands. the quantity needs to be
9146            positive so we reverse it */
9147         IF prod_tab(p).line_type = -1 THEN
9148           IF prod_tab(p).batchstep_no = -1   /* 2919303 */
9149           THEN
9150               prod_tab(p).batchstep_no := TO_NUMBER(NULL);
9151           END IF;
9152     -- ----------------
9153     /*  B3267522, Rajesh Patangya Do not insert demands, if ingradient is same as product
9154         (single level circular reference) */
9155 
9156         IF prod_tab(p).item_id <> product_line THEN
9157 
9158              /* Demands Bulk inserts */
9159                 d_index := d_index + 1 ;
9160                 d_organization_id(d_index) := v_orgn_id ;
9161                 d_inventory_item_id(d_index) :=  prod_tab(p).item_id ;
9162                 d_sr_instance_id(d_index) :=  pinstance_id ;
9163                 d_assembly_item_id(d_index) := product_line ;
9164                 d_demand_date(d_index) := prod_tab(p).trans_date ;
9165                 /* Reverse sign to make positive */
9166                 d_requirement_quantity(d_index) := (prod_tab(p).qty * -1);
9167                 d_demand_type(d_index) := 1 ;
9168                 d_origination_type(d_index) := 3 ;
9169                  /* B1177070 encoded key */
9170                 d_wip_entity_id(d_index) := prod_tab(p).x_batch_id ;
9171                 d_demand_schedule(d_index) := null_value ;
9172                 d_order_number(d_index)  := order_no ;
9173                 d_wip_entity_name(d_index) := null_value ;
9174                 d_operation_seq_num(d_index) := prod_tab(p).batchstep_no; /* B2919303 Batchstep */
9175                 d_selling_price(d_index) := null_value ;
9176 
9177                 /*B5100481 - sowsubra - WIP STATUS OF BATCHES NOT SHOWN*/
9178                 IF prod_tab(p).batch_status = 1 THEN
9179                    d_wip_status_code(d_index) := 16 ; /* batch status -> pending */
9180                 ELSE
9181                    d_wip_status_code(d_index) := 3 ; /* batch status -> WIP */
9182                 END IF;
9183 
9184          END IF;    /* Circular reference   */
9185     -- ----------------
9186 
9187     /* If the line is a product or byproduct write to the supplies */
9188         ELSE
9189           IF prod_tab(p).batchstep_no = -1   /* 2919303 */
9190           THEN
9191               prod_tab(p).batchstep_no := TO_NUMBER(NULL);
9192           END IF;
9193 
9194            /* Supply Bulk Insert Assignments */
9195                 s_index := s_index + 1 ;
9196                 s_inventory_item_id(s_index) := prod_tab(p).item_id ;
9197                 s_organization_id(s_index)   := v_orgn_id ;
9198                 s_sr_instance_id(s_index)    := pinstance_id;
9199                 s_new_schedule_date(s_index) :=  prod_tab(p).trans_date ;
9200                 s_old_schedule_date(s_index)       := prod_tab(p).trans_date ;
9201                 s_new_wip_start_date(s_index) := prod_tab(p).start_date ;
9202                 s_old_wip_start_date(s_index) := prod_tab(p).start_date ;
9203                 s_lunit_completion_date(s_index) := prod_tab(p).end_date ;
9204                 /* B1177070 encoded key */
9205                 s_disposition_id(s_index)    :=  prod_tab(p).x_batch_id ;
9206 
9207                 /*B5100481 - sowsubra - WIP STATUS OF BATCHES NOT SHOWN*/
9208                 IF prod_tab(p).batch_status = 1 THEN
9209                    s_wip_status_code(s_index) := 16 ; /* batch status -> pending */
9210                 ELSE
9211                    s_wip_status_code(s_index) := 3 ; /* batch status -> WIP */
9212                 END IF;
9213 
9214              IF supply_type IS NOT NULL THEN
9215                 s_order_type(s_index)        := supply_type ;
9216              ELSE
9217                 s_order_type(s_index)        := null_value ;
9218              END IF ;
9219 
9220              IF order_no IS NOT NULL THEN
9221                 s_order_number(s_index)            := order_no ;
9222              ELSE
9223                 s_order_number(s_index)        := null_value ;
9224              END IF ;
9225                 s_new_order_quantity(s_index) := prod_tab(p).qty ;
9226                 s_old_order_quantity(s_index) := prod_tab(p).qty ;
9227                 s_firm_planned_type(s_index)  := prod_tab(p).firmed_ind; /* 2821248 Firmed Indicator */
9228                 s_firm_quantity(s_index)  := prod_tab(p).qty ; /* B2821248 Firmed Batches Qty  - */
9229                 s_firm_date(s_index) := prod_tab(p).trans_date; /* B2821248 Firmed Batches Date - */
9230 
9231                 s_requested_completion_date(s_index) := prod_tab(p).requested_completion_date; /* Navin : APS K Enh */
9232                 s_schedule_priority(s_index) := prod_tab(p).schedule_priority; /* Navin : APS K Enh */
9233 
9234              IF order_no IS NOT NULL THEN
9235                 s_wip_entity_name(s_index)        := order_no ;
9236              ELSE
9237                 s_wip_entity_name(s_index)        := null_value ;
9238              END IF ;
9239                 -- lot_number         := null_value ;
9240                 -- expiration_date    := null_value ;
9241             s_operation_seq_num(s_index) := prod_tab(p).batchstep_no;  /* B2919303 Batchstep  */
9242 
9243             IF supply_type = 3 THEN
9244               s_by_product_using_assy_id(s_index) := to_number(NULL) ;
9245             ELSE
9246               s_by_product_using_assy_id(s_index) := product_line ;
9247             END IF;
9248 
9249             /* Section 11.1.1.2 MTQ with Hardlinks */
9250             IF (prod_tab(p).Minimum_Time_Offset IS NOT NULL) THEN
9251                   stp_var_itm_instance_id(si_index) := pinstance_id;
9252                   stp_var_itm_from_op_seq_id(si_index) := prod_tab(p).from_op_seq_id ;
9253                   stp_var_itm_wip_entity_id (si_index) := prod_tab(p).x_batch_id;
9254 	          stp_var_itm_FROM_item_ID(si_index) := prod_tab(p).item_id;
9255 	          stp_var_min_tran_qty(si_index) := prod_tab(p).Minimum_Transfer_Qty;
9256         	  stp_var_itm_min_tm_off(si_index) := prod_tab(p).Minimum_Time_Offset;
9257 	          stp_var_itm_max_tm_off(si_index) := prod_tab(p).Maximum_Time_Offset;
9258                   stp_var_itm_from_op_seq_num(si_index) := prod_tab(p).from_op_seq_num;
9259                   stp_var_itm_organization_id(si_index)   := v_orgn_id ;
9260 	          si_index := si_index+1;
9261             END IF;
9262     END IF;
9263   END LOOP;   /* all the details are retrieved so close the cursor */
9264   --close prod_dtl;
9265 
9266      i := 1 ;
9267      log_message(rr_organization_id.FIRST || ' *rr*' || rr_organization_id.LAST );
9268      IF rr_organization_id.FIRST > 0 THEN
9269      FORALL i IN rr_organization_id.FIRST..rr_organization_id.LAST
9270         INSERT INTO msc_st_resource_requirements (
9271 		organization_id,
9272 		sr_instance_id,
9273 		supply_id,
9274                 supply_type, /* sultripa B4612203 Need to populate supply_type field */
9275 		resource_seq_num,
9276 		resource_id,
9277 		start_date,
9278 		end_date,
9279 		operation_hours_required,
9280                 usage_rate, /* B4637398 Rajesh Patangya */
9281 		assigned_units,
9282 		department_id,
9283 		wip_entity_id,
9284 		operation_seq_num,
9285 		deleted_flag,
9286 		firm_flag,
9287 		minimum_transfer_quantity,
9288 		parent_seq_num,
9289 		schedule_flag,
9290             -- HW B4902328 - Added inventory_item_id
9291                 inventory_item_id,
9292 		basis_type,
9293 		setup_id,
9294 		group_sequence_id,
9295 		group_sequence_number,
9296 		minimum_capacity,
9297 		maximum_capacity,
9298 		orig_resource_seq_num,
9299 		alternate_number,
9300                 hours_expended,
9301                 breakable_activity_flag,
9302                 step_quantity,    /* Sowmya - As per latest FDD changes*/
9303                 step_quantity_uom , /* Sowmya - As per latest FDD changes*/
9304                 maximum_assigned_units, /* Sowmya - As per latest FDD changes*/
9305                 unadjusted_resource_hours, /*B4320561 - Same as in wip (without eff and util) */
9306                 touch_time, /* B4320561 - Unadjusted res. hrs / efficiency.*/
9307                 activity_group_id, /* B3995361 rpatangy */
9308                 operation_sequence_id /* B5461922 rpatangy */
9309 	)
9310         VALUES (
9311 		rr_organization_id(i),
9312 		rr_sr_instance_id(i),
9313 		rr_supply_id(i),
9314                 1, /* sultripa B4612203 supply_type = 1 for OPM batches*/
9315 		rr_resource_seq_num(i),
9316 		rr_resource_id(i),
9317 		rr_start_date(i),
9318 		rr_end_date(i),
9319 		rr_opr_hours_required(i),
9320                 nvl(rr_usage_rate(i),0), /* B4637398 Rajesh Patangya */
9321 		rr_assigned_units(i),
9322 		rr_department_id(i),
9323 		rr_wip_entity_id(i),
9324 		rr_operation_seq_num(i),
9325 		2,
9326 		rr_firm_flag(i),
9327 		rr_minimum_transfer_quantity(i),
9328 		rr_parent_seq_num(i),
9329 		rr_schedule_flag(i),
9330             -- HW B4902328 - Added inventory_item_id
9331                 rr_inventory_item_id(i),
9332 		rr_basis_type(i),
9333 		rr_setup_id(i),
9334 		rr_sequence_id(i),     -- group_sequence_id
9335 		rr_sequence_number(i), -- group_sequence_number
9336 		rr_min_capacity(i),
9337 		rr_max_capacity(i),
9338 		rr_original_seq_num(i),
9339 		rr_alternate_number(i),
9340                 rr_hours_expended(i),
9341                 rr_breakable_activity_flag(i),
9342                 rr_plan_step_qty(i),  /* Sowmya - As per the latest FDD changes*/
9343                 rr_step_qty_uom(i) , /* Sowmya - As per the latest FDD changes*/
9344                 rr_gmd_rsrc_cnt(i),
9345                 rr_unadjusted_resource_hrs(i), /*B4320561 - sowsubra*/
9346                 rr_touch_time(i), /*B4320561 - sowsubra*/
9347                 rr_activity_group_id(i),  /* B3995361 rpatangy */
9348                 rr_operation_sequence_id(i) /* B5461922 rpatangy */
9349         )   ;
9350 
9351      END IF;
9352 
9353 /* akaruppa B5007729 */
9354         rr_organization_id   := empty_num_table ;
9355         rr_inventory_item_id := empty_num_table ;
9356         rr_sr_instance_id    := empty_num_table ;
9357         rr_supply_id         := empty_num_table ;
9358         rr_resource_seq_num  := empty_num_table ;
9359         rr_resource_id       := empty_num_table ;
9360         rr_start_date        := empty_dat_table ;
9361         rr_end_date          := empty_dat_table ;
9362         rr_opr_hours_required := empty_num_table ;
9363         rr_usage_rate        := empty_num_table ;
9364         rr_assigned_units    := empty_num_table ;
9365         rr_department_id     := empty_num_table ;
9366         rr_wip_entity_id     := empty_num_table ;
9367         rr_operation_seq_num := empty_num_table ;
9368         rr_firm_flag         := empty_num_table ;
9369         rr_minimum_transfer_quantity   := empty_num_table ;
9370         rr_parent_seq_num    := empty_num_table ;
9371         rr_schedule_flag     := empty_num_table ;
9372         rr_basis_type        := empty_num_table ;
9373         rr_setup_id          := empty_num_table ;
9374         rr_sequence_id       := empty_num_table ;
9375         rr_sequence_number   := empty_num_table ;
9376         rr_min_capacity      := empty_num_table ;
9377         rr_max_capacity      := empty_num_table ;
9378         rr_original_seq_num  := empty_num_table ;
9379         rr_alternate_number  := empty_num_table ;
9380         rr_hours_expended    := empty_num_table ;
9381         rr_breakable_activity_flag := empty_num_table ;
9382         rr_plan_step_qty     := empty_num_table ;
9383         rr_step_qty_uom      := rr_step_qty_uom ;
9384         rr_gmd_rsrc_cnt      := empty_num_table ;
9385         rr_unadjusted_resource_hrs  := empty_num_table;
9386         rr_touch_time           := empty_num_table  ;
9387         rr_activity_group_id    := empty_num_table ;
9388         rr_operation_sequence_id := empty_num_table ; /* B5461922 rpatangy */
9389 /* ----------------------- Supply Insert --------------------- */
9390       i := 1 ;
9391       log_message(s_organization_id.FIRST || ' *s*' || s_organization_id.LAST );
9392       IF s_organization_id.FIRST > 0 THEN
9393       FORALL i IN s_organization_id.FIRST..s_organization_id.LAST
9394         INSERT INTO msc_st_supplies (
9395         plan_id,
9396         inventory_item_id,
9397         organization_id,
9398         sr_instance_id,
9399         new_schedule_date,
9400         old_schedule_date,
9401         new_wip_start_date,
9402         old_wip_start_date,
9403         last_unit_completion_date,
9404         disposition_id,
9405         order_type,
9406         order_number,
9407         new_order_quantity,
9408         old_order_quantity,
9409         firm_planned_type,
9410         firm_quantity,
9411         firm_date,
9412         wip_entity_name,
9413         lot_number,
9414         expiration_date,
9415         operation_seq_num,
9416         by_product_using_assy_id,
9417         deleted_flag,
9418         requested_completion_date,
9419         wip_status_code, /*B5100481*/
9420         schedule_priority
9421         )
9422         VALUES (
9423         -1,
9424         s_inventory_item_id(i),
9425         s_organization_id(i),
9426         s_sr_instance_id(i),
9427         s_new_schedule_date(i),
9428         s_old_schedule_date(i),
9429         s_new_wip_start_date(i),
9430         s_old_wip_start_date(i),
9431         s_lunit_completion_date(i),
9432         s_disposition_id(i),
9433         s_order_type(i),
9434         s_order_number(i),
9435         s_new_order_quantity(i),
9436         s_old_order_quantity(i),
9437         s_firm_planned_type(i),  /* 2 */
9438         s_firm_quantity(i),
9439         s_firm_date(i),
9440         s_wip_entity_name(i),   /* Order Number */
9441         null_value,
9442         null_value,
9443         s_operation_seq_num(i),
9444         s_by_product_using_assy_id(i),
9445         2,                      /* Deleted Flag */
9446         s_requested_completion_date(i),
9447         s_wip_status_code(i), /*B5100481 - 16 for pending, 3 for wip */
9448         s_schedule_priority(i)
9449         ) ;
9450       END IF;
9451 
9452         s_inventory_item_id  := empty_num_table ;
9453         s_organization_id    := empty_num_table ;
9454         s_sr_instance_id     := empty_num_table ;
9455         s_new_schedule_date  := empty_dat_table ;
9456         s_old_schedule_date  := empty_dat_table ;
9457         s_new_wip_start_date := empty_dat_table ;
9458         s_old_wip_start_date := empty_dat_table ;
9459         s_lunit_completion_date  := empty_dat_table ;
9460         s_disposition_id      := empty_num_table ;
9461         s_order_type          := empty_num_table ;
9462         s_order_number        := se_order_number ;
9463         s_new_order_quantity  := empty_num_table ;
9464         s_old_order_quantity  := empty_num_table ;
9465         s_firm_planned_type   := empty_num_table ;
9466         s_firm_quantity       := empty_num_table ;
9467         s_firm_date           := empty_dat_table ;
9468         s_wip_entity_name     := se_wip_entity_name ;
9469         s_operation_seq_num   := empty_num_table ;
9470         s_by_product_using_assy_id  := empty_num_table ;
9471         s_lot_number          := e_lot_number;
9472         s_wip_status_code     := empty_num_table;
9473         s_requested_completion_date := empty_dat_table ;
9474 
9475 /* ----------------------- Demands Insert --------------------- */
9476       i := 1 ;
9477       log_message(d_organization_id.FIRST || '*' || d_index || '*' || d_organization_id.LAST );
9478       IF d_organization_id.FIRST > 0 THEN
9479       FORALL i IN d_organization_id.FIRST..d_organization_id.LAST
9480         INSERT INTO msc_st_demands (
9481         organization_id,
9482         inventory_item_id,
9483         sr_instance_id,
9484         using_assembly_item_id,
9485         using_assembly_demand_date,
9486         using_requirement_quantity,
9487         demand_type,
9488         origination_type,
9489         wip_entity_id,
9490         demand_schedule_name,
9491         order_number,
9492         wip_entity_name,
9493         selling_price,
9494         operation_seq_num,
9495         wip_status_code, /*B5100481*/
9496         deleted_flag )
9497         VALUES (
9498         d_organization_id(i),
9499         d_inventory_item_id(i),
9500         d_sr_instance_id(i),
9501         d_assembly_item_id(i),
9502         d_demand_date(i),
9503         d_requirement_quantity(i),
9504         d_demand_type(i),
9505         d_origination_type(i),
9506         d_wip_entity_id(i),
9507         d_demand_schedule(i),
9508         d_order_number(i),
9509         d_wip_entity_name(i),
9510         d_selling_price(i),
9511         d_operation_seq_num(i),
9512         d_wip_status_code(i), /*B5100481*/
9513         2 ) ;
9514       END IF;
9515 
9516 /* akaruppa B5007729 starts*/
9517         d_organization_id    := empty_num_table ;
9518         d_inventory_item_id  := empty_num_table ;
9519         d_sr_instance_id     := empty_num_table ;
9520         d_assembly_item_id   := empty_num_table ;
9521         d_demand_date        := empty_dat_table ;
9522         d_requirement_quantity  := empty_num_table ;
9523         d_demand_type      := empty_num_table ;
9524         d_origination_type := empty_num_table ;
9525         d_wip_entity_id    := empty_num_table ;
9526         d_demand_schedule  := e_demand_schedule ;
9527         d_order_number     := e_order_number ;
9528         d_wip_entity_name  := e_wip_entity_name ;
9529         d_selling_price    := empty_num_table ;
9530         d_wip_status_code  := empty_num_table;
9531         d_operation_seq_num := empty_num_table ;
9532 /* akaruppa B5007729 End*/
9533 
9534 
9535       s_index := 0 ;
9536       d_index := 0 ;
9537       rr_index := 0 ;
9538 
9539 /* NAVIN: -- START: Complex Route -- Collect Batch Step Dependencies in one insert-select --*/
9540         sql_stmt :=
9541          ' INSERT INTO msc_st_job_operation_networks '
9542          || ' ( '
9543                 || '    from_op_seq_id, '
9544                 || '    to_op_seq_id, '
9545                 || '    wip_entity_id, '
9546                 || '    dependency_type, '
9547                 || '    transition_type, '
9548                 || '    sr_instance_id, '
9549                 || '    deleted_flag, '
9550                 || '    minimum_time_offset, '
9551                 || '    maximum_time_offset, '
9552                 || '    transfer_pct, '
9553                 || '    from_op_seq_num, '
9554                 || '    to_op_seq_num, '
9555                 || '    apply_to_charges, '
9556                 || '    organization_id, '
9557                 || '    recommended '
9558          || ' ) '
9559          || ' SELECT '
9560                 ||'         ((gbsd.dep_step_id*2)+1), '     /* B5461922 */
9561                 ||'         ((gbsd.batchstep_id*2)+1),'     /* B5461922 */
9562                 ||'          ((gbsd.batch_id * 2) + 1) x_batch_id, '
9563                 ||'          decode(gbsd.dep_type,0,1,2) dependency_type, '
9564                 ||'          1, '
9565                 ||'          :1, '
9566                 ||'          2, '
9567                 ||'          gbsd.standard_delay, '
9568                 ||'          gbsd.max_delay, '
9569                 ||'          gbsd.transfer_percent, '
9570                 ||'          gbs1.batchstep_no, '
9571                 ||'          gbs2.batchstep_no, '
9572                 ||'          DECODE(NVL(gbsd.chargeable_ind,0),1,1,2), '   /* convert a Null or 0 to a 2, a 1 remains a 1 */
9573                 ||'          iwm.mtl_organization_id, '
9574                 ||           '''Y'''
9575                 ||'      FROM '
9576                 ||'          gme_batch_step_dependencies'||pdblink||' gbsd, '
9577                 ||'          gme_batch_header'||pdblink||' h,'
9578                 ||'          gme_batch_steps'||pdblink||' gbs1, '
9579                 ||'          gme_batch_steps'||pdblink||' gbs2, '
9580                 ||'          ic_whse_mst'||pdblink||' iwm, '
9581                 ||'          sy_orgn_mst'||pdblink||' som '
9582                 ||'      WHERE '
9583                 ||'               h.batch_id = gbsd.batch_id '
9584                 ||'          AND gbs1.batch_id = gbsd.batch_id '
9585                 ||'          AND gbs1.batchstep_id = gbsd.dep_step_id '
9586                 ||'          AND gbs2.batch_id = gbsd.batch_id '
9587                 ||'          AND gbs2.batchstep_id = gbsd.batchstep_id '
9588                 ||'          AND h.batch_status in (1, 2) '
9589                 ||'          AND h.plant_code = som.orgn_code '
9590                 ||'          AND som.delete_mark = 0 '
9591                 ||'          AND som.resource_whse_code = iwm.whse_code ' ;
9592 
9593 
9594 	        IF MSC_CL_GMP_UTILITY.g_in_str_org  IS NOT NULL THEN
9595 	         sql_stmt := sql_stmt
9596 	                   ||'   AND iwm.mtl_organization_id ' || MSC_CL_GMP_UTILITY.g_in_str_org ;
9597 	        END IF;
9598 
9599 	         EXECUTE IMMEDIATE  sql_stmt USING pinstance_id;
9600         /* NAVIN: ------------ END: Complex Route -- Collect Batch Step Dependencies in one insert-select ------------*/
9601 
9602 /* NAVIN: ----------------------- MTQ with Hardlinks --------------------- */
9603 i := 1;
9604 log_message(stp_var_itm_from_op_seq_id.FIRST || ' *OPERNETTWORK*' ||
9605 stp_var_itm_from_op_seq_id.LAST );
9606 IF stp_var_itm_from_op_seq_id.FIRST > 0 THEN
9607 FORALL i IN stp_var_itm_from_op_seq_id.FIRST..stp_var_itm_from_op_seq_id.LAST
9608  INSERT INTO msc_st_job_operation_networks(
9609 	from_op_seq_id,
9610 	wip_entity_id,
9611 	dependency_type,
9612 	transition_type,
9613 	sr_instance_id,
9614 	deleted_flag,
9615 	from_item_id,
9616 	organization_id,
9617 	minimum_time_offset,
9618 	maximum_time_offset,
9619 	from_op_seq_num,
9620         minimum_transfer_qty,
9621         recommended
9622   )
9623  VALUES
9624   (
9625 	stp_var_itm_from_op_seq_id(i),
9626 	stp_var_itm_wip_entity_id(i),
9627 	5,	-- dependency_type for mtq with hardlink
9628 	1,	-- transition_type: primary
9629 	stp_var_itm_instance_id(i),
9630 	2,
9631 	stp_var_itm_FROM_item_ID(i),
9632 	stp_var_itm_organization_id(i),
9633 	stp_var_itm_min_tm_off(i),
9634 	stp_var_itm_max_tm_off(i),
9635 	stp_var_itm_from_op_seq_num(i),
9636         stp_var_min_tran_qty(i),
9637         'Y'
9638   );
9639 
9640 END IF ;
9641 
9642         stp_var_itm_from_op_seq_id  := empty_num_table ;
9643         stp_var_itm_wip_entity_id   := empty_num_table ;
9644         stp_var_itm_instance_id     := empty_num_table ;
9645         stp_var_itm_FROM_item_ID    := empty_num_table ;
9646         stp_var_itm_organization_id := empty_num_table ;
9647         stp_var_itm_min_tm_off      := empty_num_table ;
9648         stp_var_itm_max_tm_off      := empty_num_table ;
9649         stp_var_itm_from_op_seq_num := empty_num_table ;
9650         stp_var_min_tran_qty        := empty_num_table ;
9651 /* ----------------------- MTQ with Hardlinks --------------------- */
9652 
9653 
9654 /* ----------------------- Operation Charges --------------------- */
9655 /* NAVIN: Operation Charges */
9656 i := 1 ;
9657 log_message(stp_chg_organization_id.FIRST || ' *STEPCHARGE*' ||
9658 stp_chg_organization_id.LAST );
9659 IF stp_chg_organization_id.FIRST > 0 THEN
9660  FORALL i IN stp_chg_organization_id.FIRST..stp_chg_organization_id.LAST
9661   INSERT INTO msc_st_resource_charges
9662   (
9663       sr_instance_id          ,
9664       resource_id             ,
9665       organization_id         ,
9666       department_id         ,
9667       wip_entity_id           ,
9668       operation_sequence_id   ,
9669       operation_seq_num       ,
9670       resource_seq_num        ,
9671       charge_number              ,
9672       charge_quantity         ,
9673       deleted_flag            ,
9674       charge_start_datetime   ,
9675       charge_end_datetime
9676   )
9677 
9678    VALUES
9679 
9680   (
9681       stp_instance_id(i)      ,
9682       stp_chg_resource_id(i)  ,
9683       stp_chg_organization_id(i),
9684       stp_chg_department_id(i),
9685       stp_chg_wip_entity_id(i),
9686       stp_chg_operation_seq_id(i),
9687       stp_chg_operation_seq_no(i),
9688       stp_chg_resource_seq_num(i),
9689       stp_chg_charge_num(i),
9690       stp_chg_charge_quanitity(i),
9691       2,
9692       stp_chg_charge_start_dt_time(i) ,
9693       stp_chg_charge_end_dt_time(i)
9694   );
9695 END IF ;
9696 
9697         stp_instance_id           := empty_num_table ;
9698         stp_chg_resource_id       := empty_num_table ;
9699         stp_chg_organization_id   := empty_num_table ;
9700         stp_chg_department_id     := empty_num_table ;
9701         stp_chg_wip_entity_id     := empty_num_table ;
9702         stp_chg_operation_seq_id  := empty_num_table ;
9703         stp_chg_operation_seq_no  := empty_num_table ;
9704         stp_chg_resource_seq_num  := empty_num_table ;
9705         stp_chg_charge_num        := empty_num_table ;
9706         stp_chg_charge_quanitity  := empty_num_table ;
9707         stp_chg_charge_start_dt_time := stpe_chg_charge_start_dt_time ;
9708         stp_chg_charge_end_dt_time   := stpe_chg_charge_end_dt_time ;
9709 
9710 /* ----------------------- Operation Charges  --------------------- */
9711 
9712 /* ----------------------- Resource Instances  --------------------- */
9713 
9714      i := 1 ;
9715      log_message(rec_inst_organization_id.FIRST || ' *rir*' || rec_inst_organization_id.LAST );
9716      IF rec_inst_organization_id.FIRST > 0 THEN
9717      FORALL i IN rec_inst_organization_id.FIRST..rec_inst_organization_id.LAST
9718        INSERT INTO msc_st_resource_instance_reqs (
9719         supply_id,
9720         organization_id,
9721         sr_instance_id,
9722         resource_seq_num,
9723         resource_id,
9724         res_instance_id,
9725         start_date,
9726         end_date,
9727         resource_instance_hours,
9728 /* NAVIN :- CHECK Should This be Included. It is
9729 mentioned in FDD, but not included in APS script file. */
9730 --        schedule_flag,
9731         operation_seq_num,
9732         department_id,
9733         wip_entity_id,
9734         serial_number,
9735         deleted_flag,
9736         parent_seq_num, /* Sowmya -  as the column was changed from parent_seq_number to parent_seq_num */
9737         orig_resource_seq_num,
9738         equipment_item_id /*Sowmya - As per the latest FDD changes - End*/
9739         )
9740         VALUES (
9741         rec_inst_supply_id(i) ,
9742         rec_inst_organization_id(i) ,
9743         rec_inst_sr_instance_id(i) ,
9744         rec_inst_rec_resource_seq_num(i) ,
9745         rec_inst_resource_id(i) ,
9746         rec_inst_instance_id(i) ,
9747         rec_inst_start_date(i) ,
9748         rec_inst_end_date(i) ,
9749         rec_inst_rsrc_instance_hours(i) ,
9750 --        1 , /* Schedule Flag 1 = Scheduled */
9751         rec_inst_operation_seq_num(i) ,
9752         rec_inst_department_id(i) ,
9753         rec_inst_wip_entity_id(i) ,
9754         rec_inst_serial_number(i) ,
9755         2 , /* Delete Flag */
9756         rec_inst_parent_seq_num(i) ,
9757         rec_inst_original_seq_num(i),
9758         rec_inst_equp_item_id(i) /*Sowmya - As per the latest FDD changes - End*/
9759         )   ;
9760      END IF;
9761 
9762         rec_inst_supply_id             := empty_num_table ;
9763         rec_inst_organization_id       := empty_num_table ;
9764         rec_inst_sr_instance_id        := empty_num_table ;
9765         rec_inst_rec_resource_seq_num  := empty_num_table ;
9766         rec_inst_resource_id           := empty_num_table ;
9767         rec_inst_instance_id           := empty_num_table ;
9768         rec_inst_start_date            := empty_dat_table ;
9769         rec_inst_end_date              := empty_dat_table ;
9770         rec_inst_rsrc_instance_hours   := empty_num_table ;
9771         rec_inst_operation_seq_num     := empty_num_table ;
9772         rec_inst_department_id         := empty_num_table ;
9773         rec_inst_wip_entity_id         := empty_num_table ;
9774         rec_inst_serial_number         := empty_inst_serial_number ;   -- Bug 5713355
9775         rec_inst_parent_seq_num        := empty_num_table ;
9776         rec_inst_original_seq_num      := empty_num_table ;
9777         rec_inst_equp_item_id          := empty_num_table ;
9778 
9779 /* ----------------------- Resource Instances  --------------------- */
9780 
9781 /* ----------------------- Alternate Resources --------------------- */
9782 /*Sowmya - As per the latest FDD changes - Start*/
9783      i := 1 ;
9784      log_message(arr_organization_id.FIRST || ' *rir*' || arr_organization_id.LAST );
9785      IF arr_organization_id.FIRST > 0 THEN
9786      FORALL i IN arr_organization_id.FIRST..arr_organization_id.LAST
9787 
9788         INSERT INTO msc_st_job_op_resources
9789         (
9790          wip_entity_id,
9791          organization_id,
9792          sr_instance_id ,
9793          operation_seq_num ,
9794          resource_seq_num ,
9795          resource_id ,
9796          alternate_num ,
9797          reco_start_date ,
9798          reco_completion_date ,
9799          usage_rate_or_amount  ,
9800          assigned_units ,
9801          schedule_flag ,
9802          parent_seq_num ,
9803          recommended ,
9804          department_id ,
9805          uom_code ,
9806          activity_group_id ,
9807          basis_type ,
9808          firm_flag ,
9809          setup_id ,
9810          schedule_seq_num  ,
9811          group_sequence_id ,
9812          group_sequence_number ,
9813 --         resource_batch_id ,
9814          maximum_assigned_units ,
9815          deleted_flag ,
9816          batch_number
9817         )
9818         VALUES
9819         (
9820         arr_wip_entity_id(i),
9821         arr_organization_id(i),
9822         arr_sr_instance_id(i),
9823         arr_operation_seq_num(i),
9824         arr_res_seq_num(i),
9825         arr_resource_id(i),
9826         arr_alternate_num(i),
9827         null_value,
9828         null_value,
9829         arr_usage_rate(i),
9830         arr_assigned_units(i),
9831         1,
9832         null_value,
9833         1,
9834         arr_department_id(i),
9835         arr_uom_code(i),
9836         arr_activity_group_id(i),
9837         arr_basis_type(i),
9838         null_value,
9839         arr_setup_id(i),
9840         arr_schedule_seq_num(i),
9841         null_value,
9842         null_value,
9843 --        null_value,
9844         arr_maximum_assigned_units(i),
9845         2,
9846         null_value
9847         );
9848 
9849      END IF;
9850 
9851         arr_wip_entity_id              := empty_num_table ;
9852         arr_organization_id            := empty_num_table ;
9853         arr_sr_instance_id             := empty_num_table ;
9854         arr_operation_seq_num          := empty_num_table ;
9855         arr_res_seq_num                := empty_num_table ;
9856         arr_resource_id                := empty_num_table ;
9857         arr_alternate_num              := empty_num_table ;
9858         arr_usage_rate                 := empty_num_table ;
9859         arr_assigned_units             := empty_num_table ;
9860         arr_department_id              := empty_num_table ;
9861         arr_uom_code                   := arre_uom_code   ;
9862         arr_activity_group_id          := empty_num_table ;
9863         arr_basis_type                 := empty_num_table ;
9864         arr_setup_id                   := empty_num_table ;
9865         arr_schedule_seq_num           := empty_num_table ;
9866         arr_maximum_assigned_units     := empty_num_table ;
9867 
9868 /*Sowmya - As per the latest FDD changes - End*/
9869 /* ----------------------- Alternate Resources --------------------- */
9870 
9871 /* nsinghi : Populate Msc_Job_Operations Table. */
9872 /* ----------------------- Job Operations --------------------- */
9873      i := 1 ;
9874      log_message(jo_wip_entity_id.FIRST || ' *jo*' || jo_wip_entity_id.LAST );
9875      IF jo_wip_entity_id.FIRST > 0 THEN
9876      FORALL i IN jo_wip_entity_id.FIRST..jo_wip_entity_id.LAST
9877         INSERT INTO msc_st_job_operations
9878         (
9879            wip_entity_id,
9880            sr_instance_id,
9881            operation_seq_num,
9882            recommended,
9883            network_start_end,
9884            reco_start_date,
9885            reco_completion_date,
9886            operation_sequence_id,
9887            organization_id,
9888            department_id,
9889            minimum_transfer_quantity,
9890            effectivity_date,
9891            deleted_flag
9892         )
9893         VALUES
9894         (
9895            jo_wip_entity_id(i),
9896            jo_instance_id(i),
9897            jo_operation_seq_num(i),
9898            jo_recommended(i),
9899            jo_network_start_end(i),
9900            jo_reco_start_date(i),
9901            jo_reco_completion_date(i),
9902            jo_operation_sequence_id(i),
9903            jo_organization_id(i),
9904            jo_department_id(i),
9905            jo_minimum_transfer_quantity(i),
9906            (SYSDATE-100),
9907            2
9908         );
9909 
9910      END IF;
9911 
9912         jo_wip_entity_id         := empty_num_table ;
9913         jo_instance_id           := empty_num_table ;
9914         jo_operation_seq_num     := empty_num_table ;
9915         jo_recommended           := joe_recommended ;
9916         jo_network_start_end     := joe_network_start_end;
9917         jo_reco_start_date       := empty_dat_table ;
9918         jo_reco_completion_date  := empty_dat_table ;
9919         jo_operation_sequence_id := empty_num_table ;
9920         jo_organization_id       := empty_num_table ;
9921         jo_department_id         := empty_num_table ;
9922         jo_minimum_transfer_quantity := empty_num_table ;
9923 
9924       dbms_session.free_unused_user_memory;/* akaruppa B5007729 */
9925 
9926 /* ----------------------- Job Operations --------------------- */
9927 
9928   return_status := TRUE;
9929 
9930   EXCEPTION
9931     WHEN invalid_string_value  THEN
9932         log_message('Organization string is Invalid ' );
9933         return_status := FALSE;
9934 
9935     WHEN invalid_gmp_uom_profile THEN
9936         log_message('Profile "GMP: UOM for Hour" is Invalid ' );
9937         return_status := FALSE;
9938 
9939     WHEN NO_DATA_FOUND THEN /* B3577871 */
9940       log_message(' NO_DATA_FOUND exception raised in Procedure: MSC_CL_GMP_UTILITY.Production_orders ' );
9941       return_status := TRUE;
9942 
9943     WHEN OTHERS THEN
9944 	return_status := FALSE;
9945 	log_message('Failure occured during Production Orders extract' || sqlerrm);
9946 	log_message(sqlerrm);
9947 
9948 END production_orders;
9949 
9950 /***********************************************************************
9951 *
9952 *   NAME
9953 *	insert_supplies
9954 *
9955 *   DESCRIPTION
9956 *	This procedure will take the parameter values and insert a row into
9957 *	the table msc_st_supplies
9958 *   HISTORY
9959 *	M Craig
9960 *  2/10/2000 - Populating Order number column with Wip Entity Name  ( porder_no )
9961 *  2/24/2003 - populating Firmed batches Indicator, Qty and Date
9962 ************************************************************************/
9963 PROCEDURE insert_supplies(
9964   pitem_id          NUMBER,
9965   porganization_id  NUMBER,
9966   pinstance_id      NUMBER,
9967   pdate             DATE,
9968   pstart_date       DATE,
9969   pend_date         DATE,
9970   pbatch_id         NUMBER,
9971   pqty              NUMBER,
9972   pfirmed_ind       NUMBER,
9973   pbatchstep_no     NUMBER,   /* Added pbatchstep_no - B2919303 */
9974   porder_no         VARCHAR2,
9975   plot_number       VARCHAR2,
9976   pexpire_date      DATE,
9977   psupply_type      NUMBER,
9978   pproduct_item_id  NUMBER)     /* B2953953 - CoProduct */
9979 
9980 AS
9981   st_supplies  VARCHAR2(32000) ;
9982   vproduct_item_id NUMBER ;  /* B2953953 - CoProduct */
9983 BEGIN
9984 
9985   st_supplies :=
9986     ' INSERT INTO msc_st_supplies ( '
9987   ||' plan_id, inventory_item_id, organization_id, sr_instance_id, '
9988   ||' new_schedule_date, old_schedule_date, new_wip_start_date, '
9989   ||' old_wip_start_date, last_unit_completion_date, disposition_id, '
9990   ||' order_type, order_number, new_order_quantity, old_order_quantity, '
9991   ||' firm_planned_type,firm_quantity,firm_date, wip_entity_name, '
9992   ||' lot_number, expiration_date,operation_seq_num, by_product_using_assy_id, '
9993   ||' deleted_flag ) '
9994   ||' VALUES '
9995   ||' (:p1, :p2, :p3, :p4, '
9996   ||'  :p5, :p6, :p7,      '
9997   ||'  :p8, :p9, :p10,     '
9998   ||'  :p11,:p12,:p13,:p14,'
9999   ||'  :p15,:p16,:p17,:p18,'
10000   ||'  :p19,:p20,:p21,'
10001   ||'  :p22,:p23 ) ' ;
10002 
10003   /* B2953953 The by_product_assy_id should not be written for Products ,
10004      but should be written for co-products and by-products */
10005 
10006   IF psupply_type = 3 THEN
10007      vproduct_item_id := to_number(NULL) ;
10008   ELSE
10009     vproduct_item_id := pproduct_item_id ;
10010   END IF;
10011 
10012     EXECUTE IMMEDIATE st_supplies USING
10013     -1,
10014     pitem_id,
10015     porganization_id,
10016     pinstance_id,
10017     pdate,
10018     pdate,
10019     pstart_date,
10020     pstart_date,
10021     pend_date,
10022     pbatch_id,
10023     psupply_type,
10024     porder_no,     /* Populating Order no column - bug#1152778 */
10025     pqty,
10026     pqty,
10027     /* 2, */
10028     pfirmed_ind,  /* B2821248 Firmed Batches Indicator - */
10029     pqty,         /* B2821248 Firmed Batches Qty  - */
10030     pdate,        /* B2821248 Firmed Batches Date - */
10031     porder_no,
10032     plot_number,
10033     pexpire_date,
10034     pbatchstep_no,  /* B2919303 */
10035     vproduct_item_id,  /* B2953953 - Co-Product      - */
10036     2 ;
10037 
10038   EXCEPTION
10039     WHEN OTHERS THEN
10040 	log_message('Failure occured during the insert into msc_st_supplies');
10041 	log_message(sqlerrm);
10042         RAISE;
10043 
10044 END insert_supplies;
10045 
10046 /***********************************************************************
10047 *
10048 *   NAME
10049 *	 insert_resource_requirements
10050 *
10051 *   DESCRIPTION
10052 *	This procedure wil insert a row into the table
10053 *	msc_st_resource_requirements using the parameters passed in
10054 *   HISTORY
10055 * 	M Craig
10056 * 	10/13/99 - Added deleted_flag in the insert statement
10057 *       13-SEP-2002 - firm_flag = 1 for WIP steps B2266934
10058 ************************************************************************/
10059 PROCEDURE insert_resource_requirements(
10060   porganization_id  IN NUMBER,
10061   pinstance_id      IN NUMBER,
10062   pseq_num          IN NUMBER,
10063   presource_id      IN NUMBER,
10064   pstart_date       IN DATE,
10065   pend_date         IN DATE,
10066   presource_usage   IN NUMBER,
10067   prsrc_cnt         IN NUMBER,
10068   pbatchstep_no     IN NUMBER,  /* B1224660 new parm to write step number */
10069   pbatch_id         IN NUMBER,
10070   pstep_status      IN NUMBER,
10071   pschedule_flag    IN NUMBER,
10072   pparent_seq_num   IN NUMBER,
10073   pmin_xfer_qty     IN NUMBER)
10074 
10075 AS
10076   st_resource_requirements  VARCHAR2(32000) ;
10077 
10078 BEGIN
10079   st_resource_requirements :=
10080        ' INSERT INTO msc_st_resource_requirements ( '
10081        ||' organization_id, sr_instance_id, supply_id, resource_seq_num,'
10082        ||' resource_id, start_date, end_date, operation_hours_required,'
10083        ||' assigned_units, department_id, wip_entity_id, operation_seq_num, '
10084        ||' deleted_flag, firm_flag, minimum_transfer_quantity, '
10085        ||' parent_seq_num, schedule_flag ) '
10086        ||' VALUES '
10087        ||' ( :p1, :p2, :p3, :p4, '
10088        ||'   :p5, :p6, :p7, :p8, '
10089        ||'   :p9, :p10,:p11,:p12, '
10090        ||'   :p13,:p14, :p15, '
10091        ||'   :p16, :p17 ) ';
10092 
10093   EXECUTE IMMEDIATE st_resource_requirements USING
10094     porganization_id,
10095     pinstance_id,
10096     pbatch_id,
10097     pseq_num,
10098     presource_id,
10099     pstart_date,
10100     pend_date,
10101     presource_usage,
10102     prsrc_cnt,
10103     ((porganization_id * 2) + 1),  /* B1177070 encoded key */
10104     pbatch_id,
10105     pbatchstep_no,  /* B1224660 write the step number for oper seq num */
10106     2,
10107     pstep_status,
10108     pmin_xfer_qty,
10109     pparent_seq_num,
10110     pschedule_flag ;
10111 
10112   EXCEPTION
10113     WHEN OTHERS THEN
10114 	log_message('Failure occured during the insert into msc_st_resource_requirements');
10115 	log_message(sqlerrm);
10116         RAISE;
10117 
10118 END insert_resource_requirements;
10119 
10120 /***********************************************************************
10121 *
10122 *   NAME
10123 *	insert_demands
10124 *
10125 *   DESCRIPTION
10126 *	This procedure will take the parameter values and insert a row into
10127 *	the table msc_st_demands
10128 *   HISTORY
10129 *	M Craig
10130 *	10/13/99 - Added deleted_flag in the insert statement
10131 *     P Dong
10132 *     09/14/01 - added api_mode and pschedule_id parameters
10133 ************************************************************************/
10134 PROCEDURE insert_demands(
10135   pitem_id          NUMBER,
10136   porganization_id  NUMBER,
10137   pinstance_id      NUMBER,
10138   pbatch_id         NUMBER,
10139   pproduct_item_id  NUMBER,
10140   pdate             DATE,
10141   pqty              NUMBER,
10142   pbatchstep_no     NUMBER,   /* B2919303 - BatchStep */
10143   porder_no         VARCHAR2,
10144   pdesignator       VARCHAR2,
10145   pnet_price        NUMBER,  /* B1200400 added net price */
10146   porigination_type NUMBER,
10147   api_mode          BOOLEAN,
10148   pschedule_id      NUMBER )
10149 
10150 AS
10151 
10152   statement_demands_api  VARCHAR2(32000) ;
10153   statement_demands      VARCHAR2(32000) ;
10154   t_order_number         VARCHAR2(70)   ;
10155   t_wip_entity_name      VARCHAR2(70)   ;
10156 
10157 BEGIN
10158   t_order_number         := NULL ;
10159   t_wip_entity_name      := NULL ;
10160 
10161 /* mfc 11-30-99 changed to write batch_id to wip_entity_id */
10162 
10163 IF api_mode
10164 THEN
10165   BEGIN
10166     statement_demands_api  :=
10167       ' INSERT INTO gmp_demands_api ( '
10168     ||'  organization_id, schedule_id, inventory_item_id, demand_date, '
10169     ||'  demand_quantity, origination_type, doc_id, selling_price ) '
10170     ||' VALUES '
10171     ||' ( :p1, :p2, :p3, :p4, '
10172     ||'   :p5, :p6, :p7, :p8 ) ';
10173 
10174     EXECUTE IMMEDIATE statement_demands_api USING
10175       porganization_id,
10176       pschedule_id,
10177       pitem_id,
10178       pdate,
10179       pqty,
10180       porigination_type,
10181       pbatch_id,
10182       pnet_price;
10183 
10184   EXCEPTION
10185     WHEN OTHERS THEN
10186 	log_message('Failure occured during the insert into gmp_demands_api');
10187 	log_message(sqlerrm);
10188       RAISE;
10189   END;
10190 ELSE
10191   BEGIN
10192 
10193      SELECT DECODE(porigination_type,1,NULL,porder_no) ,
10194             DECODE(porigination_type,1,porder_no,NULL)
10195      INTO t_order_number, t_wip_entity_name
10196      FROM dual ;
10197 
10198     statement_demands  :=
10199       ' INSERT INTO msc_st_demands ( '
10200     ||' organization_id, inventory_item_id, sr_instance_id, '
10201     ||' using_assembly_item_id, using_assembly_demand_date, '
10202     ||' using_requirement_quantity, demand_type, origination_type, '
10203     ||' wip_entity_id, demand_schedule_name, order_number, '
10204     ||' wip_entity_name, selling_price,operation_seq_num,deleted_flag ) '
10205     ||' VALUES '
10206     ||' ( :p1, :p2, :p3,  '
10207     ||'   :p4, :p5,       '
10208     ||'   :p6, :p7, :p8 , '
10209     ||'   :p9, :p10,:p11, '
10210     ||'   :p12,:p13,:p14,:p15 )' ;
10211 
10212     EXECUTE IMMEDIATE statement_demands USING
10213       porganization_id,
10214       pitem_id,
10215       pinstance_id,
10216       pproduct_item_id,
10217       pdate,
10218       pqty,
10219       1,
10220       porigination_type,
10221       pbatch_id,
10222       pdesignator,
10223       t_order_number,
10224       t_wip_entity_name,
10225       pnet_price,    /* B1200400 added for net price */
10226       pbatchstep_no,  /* B2919303 */
10227       2 ;
10228   EXCEPTION
10229     WHEN OTHERS THEN
10230 	log_message('Failure occured during the insert into msc_st_demands');
10231 	log_message(sqlerrm);
10232       RAISE;
10233   END;
10234 
10235 END IF;
10236 
10237 END insert_demands;
10238 
10239 /***********************************************************************
10240 *
10241 *   NAME
10242 *	 onhand_inventory
10243 *
10244 *   DESCRIPTION
10245 *	This procedure will insert records into the table msc_st_supplies
10246 *	for the onhand balances in inventory. The insert is split into 3 parts
10247 *	one for non-lot controlled, lot controlled, and lot and status
10248 *	controlled item. Each inserted will need touse a distnct list from
10249 *	the table gmp_item_aps. The table may contain multiple values for
10250 *	the item/whse combination
10251 *   HISTORY
10252 * 	M Craig
10253 *  M Craig B1332662 changed to call two new procs to collect onhand and
10254 *          Inventory transfers
10255 *   Navin   21-APR-2003 B3577871 ST:OSFME2: collections failing in planning data pull.
10256 *                                Added handling of NO_DATA_FOUND Exception.
10257 *                                And return the return_status as TRUE.
10258 ************************************************************************/
10259 PROCEDURE onhand_inventory(
10260   pdblink        IN  VARCHAR2,
10261   pinstance_id   IN  NUMBER,
10262   prun_date      IN  DATE,
10263   pdelimiter     IN  VARCHAR2,
10264   return_status  IN OUT NOCOPY BOOLEAN)
10265 AS
10266 
10267   local_ret_status1       BOOLEAN ;
10268   local_ret_status2       BOOLEAN ;
10269   onhand_balances_failure EXCEPTION ;
10270   inv_transfer_failure    EXCEPTION ;
10271 
10272 BEGIN
10273   local_ret_status1  := TRUE;
10274   local_ret_status2  := TRUE;
10275 
10276   IF return_status THEN
10277     v_cp_enabled := TRUE;
10278   ELSE
10279     v_cp_enabled := FALSE;
10280   END IF;
10281 
10282   extract_onhand_balances( pdblink, pinstance_id, prun_date, pdelimiter,
10283     local_ret_status1);
10284 
10285   IF local_ret_status1 = TRUE THEN
10286     return_status := TRUE;
10287   ELSE
10288     return_status := FALSE;
10289     RAISE  onhand_balances_failure ;
10290   END IF;
10291 
10292    /* B 2756431 Changed the call to new proceudre */
10293   extract_inv_transfer_supplies(pdblink, pinstance_id, prun_date,
10294      pdelimiter, local_ret_status2);
10295 
10296   IF local_ret_status2 = TRUE  THEN
10297     return_status := TRUE ;
10298   ELSE
10299     return_status := FALSE;
10300     RAISE  inv_transfer_failure ;
10301   END IF;
10302 
10303   EXCEPTION
10304     WHEN onhand_balances_failure THEN
10305       log_message(' extract_onhand_balances_failure raised in Procedure: MSC_CL_GMP_UTILITY.Onhand_inventory ' );
10306       return_status := FALSE;
10307     WHEN inv_transfer_failure THEN
10308       log_message(' extract_inv_transfer_supplies_failure raised in Procedure: MSC_CL_GMP_UTILITY.Onhand_inventory ' );
10309       return_status := FALSE;
10310     WHEN NO_DATA_FOUND THEN /* B3577871 */
10311       log_message(' NO_DATA_FOUND exception raised in Procedure: MSC_CL_GMP_UTILITY.Onhand_inventory ' );
10312       return_status := TRUE;
10313 
10314 END onhand_inventory;  /* end onhand_inventory */
10315 
10316 /***********************************************************************
10317 *
10318 *   NAME
10319 *	extract_onhand_balances
10320 *
10321 *   DESCRIPTION
10322 *	This procedure will insert records into the table msc_st_supplies
10323 *	for the onhand balances in inventory. The insert is split into 3 parts
10324 *	one for non-lot controlled, lot controlled, and lot and status
10325 *	controlled item. Each inserted will need touse a distnct list from
10326 *	the table gmp_item_aps. The table may contain multiple values for
10327 *	the item/whse combination
10328 *   HISTORY
10329 * 	M Craig
10330 * 	10/13/99 - Added deleted_flag in the insert statement
10331 *	2/10/2000 - Populating sub inventory code with whse code - bug# 1172875
10332 *  M Craig B1332662 created a new function to just collect onhand inventory
10333 *  Sgidugu  B2251375 - Changed Substr Function to substrb Function
10334 *  AKARUPPA B4287033 - Changed direct insert selects to BULK INSERT as direct insert
10335 *		       select over dblink causes performance issues.
10336 *  AKARUPPA B4278082 - Changed query to select status controlled items to
10337 *		       fetch items with status control as No Inventory (status_ctl = 2)
10338 ************************************************************************/
10339 PROCEDURE extract_onhand_balances(
10340   pdblink        IN  VARCHAR2,
10341   pinstance_id   IN  NUMBER,
10342   prun_date      IN  DATE,
10343   pdelimiter     IN  VARCHAR2,
10344   return_status  IN OUT NOCOPY BOOLEAN)
10345 AS
10346 
10347 /* akaruppa B4287033 07-APR-2005 Adding new variable definitions for doing BULK INSERT in place of direct INSERT SELECT */
10348   TYPE onhand_balance_nolot_typ IS RECORD(
10349 	  plan_id		NUMBER,
10350 	  inventory_item_id	NUMBER,
10351 	  organization_id	NUMBER,
10352 	  sr_instance_id	NUMBER,
10353 	  new_schedule_date	DATE,
10354 	  order_type		NUMBER,
10355 	  firm_planned_type	NUMBER,
10356 	  deleted_flag		NUMBER,
10357 	  subinventory_code	VARCHAR2(10),
10358 	  new_order_quantity	NUMBER );
10359 
10360   TYPE onhand_balance_nolot_tbl IS TABLE OF onhand_balance_nolot_typ INDEX by BINARY_INTEGER;
10361   onhand_balance_nolot_tab   onhand_balance_nolot_tbl;
10362 
10363   TYPE onhand_balance_lot_typ IS RECORD(
10364 	  plan_id		NUMBER,
10365 	  inventory_item_id	NUMBER,
10366 	  organization_id	NUMBER,
10367 	  sr_instance_id	NUMBER,
10368 	  new_schedule_date	DATE,
10369 	  order_type		NUMBER,
10370 	  lot_number		VARCHAR2(30),
10371 	  expiration_date	DATE,
10372 	  firm_planned_type	NUMBER,
10373 	  deleted_flag		NUMBER,
10374 	  subinventory_code	VARCHAR2(10),
10375 	  new_order_quantity	NUMBER );
10376 
10377   TYPE onhand_balance_lot_tbl IS TABLE OF onhand_balance_lot_typ INDEX by BINARY_INTEGER;
10378   onhand_balance_lot_tab   onhand_balance_lot_tbl;
10379 
10380   TYPE onhand_balance_status_typ IS RECORD(
10381 	  plan_id		NUMBER,
10382 	  inventory_item_id	NUMBER,
10383 	  organization_id	NUMBER,
10384 	  sr_instance_id	NUMBER,
10385 	  new_schedule_date	DATE,
10386 	  new_dock_date		DATE,
10387 	  order_type		NUMBER,
10388 	  lot_number		VARCHAR2(30),
10389 	  expiration_date	DATE,
10390 	  firm_planned_type	NUMBER,
10391 	  deleted_flag		NUMBER,
10392 	  subinventory_code	VARCHAR2(10),
10393 	  new_order_quantity	NUMBER,
10394 	  non_nettable_qty 	NUMBER );
10395 
10396   TYPE onhand_balance_status_tbl IS TABLE OF onhand_balance_status_typ INDEX by BINARY_INTEGER;
10397   onhand_balance_status_tab   onhand_balance_status_tbl;
10398 
10399   TYPE gmp_cursor_typ IS REF CURSOR;
10400   c_onhand_balance_nolot  gmp_cursor_typ;
10401   c_onhand_balance_lot	  gmp_cursor_typ;
10402   c_onhand_balance_status gmp_cursor_typ;
10403   ex_code_ref             gmp_cursor_typ;
10404   mx_code_ref             gmp_cursor_typ;
10405 
10406   v_onhand_cursor   VARCHAR2(32000) ;
10407   onhand_count      NUMBER;
10408   insert_count      NUMBER;
10409 
10410   /* End of definitions for B4287033 */
10411 
10412  l_profile NUMBER ; /* Bug # 5238790 */
10413  sy_max_date DATE ; /* B5501754 Rajesh Patangya */
10414  ex_code_cursor       VARCHAR2(32000);
10415  mx_code_cursor       VARCHAR2(32000);
10416 
10417 BEGIN
10418 
10419    log_message('Entering Extract_OnHand_Balances. ');
10420    time_stamp ;
10421 
10422    /* Bug # 5238790 */
10423    l_profile := 0 ;
10424    ex_code_cursor   := ' select NVL(fnd_profile.VALUE' ||pdblink
10425                       ||' (''GMP_COLLECT_EXPR_ONHAND''),0) from dual ' ;
10426 
10427        OPEN ex_code_ref FOR ex_code_cursor ;
10428        FETCH ex_code_ref INTO l_profile;
10429        CLOSE ex_code_ref;
10430 
10431    /* B5501754 */
10432    mx_code_cursor   := ' select to_date(fnd_profile.VALUE' ||pdblink
10433                       ||' (''SY$MAX_DATE''),''YYYY/MM/DD'') from dual ' ;
10434 
10435        OPEN mx_code_ref FOR mx_code_cursor ;
10436        FETCH mx_code_ref INTO sy_max_date;
10437        CLOSE mx_code_ref;
10438 
10439   onhand_count     := 1;
10440   v_onhand_cursor  := NULL;
10441   insert_count     := 1;
10442 
10443   /* Query to select the production order details where the batch/fpo is pending
10444   the balances from ic_summ for the item/whse that are not lot controlled
10445   are inserted */
10446   v_onhand_cursor :=   ' SELECT '
10447 	 || ' -1,'
10448 	 || ' i.aps_item_id,'
10449 	 || ' i.organization_id,'
10450 	 || ' :pinstance_id, '
10451 	 || ' :prun_date, '
10452 	 || ' 18,'                        /* onhand inventory value */
10453 	 || ' 2,'
10454 	 || ' 2,'
10455 	 || ' s.whse_code,' /* Populate subinventory with Whse code B1172875 */
10456 	 || ' s.onhand_qty'
10457 	 || ' FROM '
10458 	 || ' ic_summ_inv_onhand_v' ||pdblink|| ' s,'
10459 	 || ' (select distinct aps_item_id,item_id,whse_code,organization_id, '
10460 	 || '  lot_control,experimental_ind from gmp_item_aps'||pdblink||') i'
10461 	 || ' WHERE '
10462 	 || ' s.item_id = i.item_id '
10463 	 || ' and s.whse_code = i.whse_code '
10464 	 || ' and i.lot_control = 0'
10465 	 || ' and s.onhand_qty <> 0';
10466 
10467         /* Bug # 5238790 */
10468         IF l_profile = 0 THEN
10469            v_onhand_cursor := v_onhand_cursor
10470          || ' and i.experimental_ind = 0 ' ;
10471         END IF;
10472 
10473     OPEN c_onhand_balance_nolot FOR v_onhand_cursor USING pinstance_id, prun_date;
10474     LOOP
10475       FETCH  c_onhand_balance_nolot INTO onhand_balance_nolot_tab(onhand_count);
10476       EXIT WHEN  c_onhand_balance_nolot%NOTFOUND ;
10477       onhand_count := onhand_count + 1;
10478     END LOOP;
10479     CLOSE c_onhand_balance_nolot ;
10480     gonhand_balance_size := onhand_count - 1;
10481 
10482    log_message('No lot on hand fetches : '|| to_char(gonhand_balance_size) );
10483    time_stamp ;
10484 
10485    IF onhand_count > 1 THEN
10486    FOR i in onhand_balance_nolot_tab.FIRST..onhand_balance_nolot_tab.LAST
10487    LOOP
10488     o_plan_id(insert_count)            :=  onhand_balance_nolot_tab(i).plan_id;
10489     o_inventory_item_id(insert_count)  :=  onhand_balance_nolot_tab(i).inventory_item_id;
10490     o_organization_id(insert_count)    :=  onhand_balance_nolot_tab(i).organization_id;
10491     o_sr_instance_id(insert_count)     :=  onhand_balance_nolot_tab(i).sr_instance_id;
10492     o_new_schedule_date(insert_count)  :=  onhand_balance_nolot_tab(i).new_schedule_date;
10493     o_new_dock_date(insert_count)      :=  NULL;
10494     o_order_type(insert_count)         :=  onhand_balance_nolot_tab(i).order_type;
10495     o_lot_number(insert_count)	       :=  NULL;
10496     o_expiration_date(insert_count)    :=  NULL;
10497     o_firm_planned_type(insert_count)  :=  onhand_balance_nolot_tab(i).firm_planned_type;
10498     o_deleted_flag(insert_count)       :=  onhand_balance_nolot_tab(i).deleted_flag;
10499     o_subinventory_code(insert_count)  :=  onhand_balance_nolot_tab(i).subinventory_code;
10500     o_new_order_quantity(insert_count) :=  onhand_balance_nolot_tab(i).new_order_quantity;
10501     o_non_nettable_qty(insert_count)   :=  NULL;
10502     insert_count := insert_count + 1;
10503    END LOOP;
10504    END IF;
10505 
10506     onhand_count := 1;
10507 
10508     v_onhand_cursor := NULL;
10509 
10510   /* Get onhand balances from the location inventory table for lot controlled
10511      items. The lot can not be status controlled, that will be in the next
10512      insert the lot number is the combo of lot and sublot
10513   */
10514   v_onhand_cursor :=   ' SELECT'
10515 	    || ' -1,'
10516 	    || ' i.aps_item_id,'
10517 	    || ' i.organization_id,'
10518 	    || ' :pinstance_id,'
10519 	    || ' :prun_date,'
10520 	    || ' 18,'                        /* onhand inventory value */
10521 	    || ' substrb(l.lot_no||DECODE(l.sublot_no, NULL,NULL ,:pdelimiter || '
10522 	    || ' l.sublot_no),1,30),'
10523 	    || ' l.expire_date,'
10524 	    || ' 2,'
10525 	    || ' 2,'
10526 	    || ' s.whse_code,' /* Populate subinventory with whse code B1172875 */
10527 	    || ' s.loct_onhand'
10528 	    || ' FROM'
10529 	    || ' ic_loct_inv'||pdblink||' s,'
10530 	    || ' ic_lots_mst'||pdblink||' l,'
10531 	    || ' ic_item_mst_b'||pdblink||' m,'
10532 	    || ' (select distinct aps_item_id,item_id,whse_code,organization_id, '
10533 	    || ' lot_control,experimental_ind from gmp_item_aps'||pdblink||') i'
10534 	    || ' WHERE'
10535 	    || '     s.item_id = i.item_id'
10536 	    || ' and s.item_id = m.item_id'
10537 	    || ' and s.whse_code = i.whse_code'
10538 	    || ' and i.lot_control = 1'
10539 	    || ' and m.status_ctl = 0'
10540 	    || ' and s.lot_id = l.lot_id'
10541 	    || ' and s.item_id = l.item_id'
10542 	    || ' and s.lot_id > 0'
10543 	    || ' and l.delete_mark = 0'
10544 	    || ' and s.loct_onhand <> 0';
10545     /* Bug # 5238790 */
10546     IF l_profile = 0 THEN
10547        v_onhand_cursor := v_onhand_cursor
10548     || ' and i.experimental_ind = 0 ' ;
10549     END IF;
10550 
10551 
10552     OPEN c_onhand_balance_lot FOR v_onhand_cursor USING pinstance_id, prun_date, pdelimiter;
10553     LOOP
10554       FETCH  c_onhand_balance_lot INTO onhand_balance_lot_tab(onhand_count);
10555       EXIT WHEN  c_onhand_balance_lot%NOTFOUND ;
10556       onhand_count := onhand_count + 1;
10557     END LOOP;
10558     CLOSE c_onhand_balance_lot ;
10559     gonhand_balance_size := gonhand_balance_size + onhand_count - 1;
10560 
10561    log_message('Lot on hand fetches : '|| to_char(gonhand_balance_size) );
10562    time_stamp ;
10563 
10564    IF onhand_count > 1 THEN
10565    FOR i in onhand_balance_lot_tab.FIRST..onhand_balance_lot_tab.LAST
10566    LOOP
10567      o_plan_id(insert_count)            :=  onhand_balance_lot_tab(i).plan_id;
10568      o_inventory_item_id(insert_count)  :=  onhand_balance_lot_tab(i).inventory_item_id;
10569      o_organization_id(insert_count)	:=  onhand_balance_lot_tab(i).organization_id;
10570      o_sr_instance_id(insert_count)	:=  onhand_balance_lot_tab(i).sr_instance_id;
10571      o_new_schedule_date(insert_count)  :=  onhand_balance_lot_tab(i).new_schedule_date;
10572      o_new_dock_date(insert_count)	:=  NULL;
10573      o_order_type(insert_count)  	:=  onhand_balance_lot_tab(i).order_type;
10574      o_lot_number(insert_count)	        :=  onhand_balance_lot_tab(i).lot_number;
10575 
10576      /* B5501754 */
10577      IF (onhand_balance_lot_tab(i).expiration_date >= sy_max_date) THEN
10578      o_expiration_date(insert_count)    :=  NULL;
10579      ELSE
10580      o_expiration_date(insert_count)    := onhand_balance_lot_tab(i).expiration_date;
10581      END IF;
10582 
10583      o_firm_planned_type(insert_count)  :=  onhand_balance_lot_tab(i).firm_planned_type;
10584      o_deleted_flag(insert_count)	:=  onhand_balance_lot_tab(i).deleted_flag;
10585      o_subinventory_code(insert_count)  :=  onhand_balance_lot_tab(i).subinventory_code;
10586      o_new_order_quantity(insert_count) :=  onhand_balance_lot_tab(i).new_order_quantity;
10587      o_non_nettable_qty(insert_count)   :=  NULL;
10588      insert_count := insert_count + 1;
10589    END LOOP;
10590    END IF;
10591 
10592     onhand_count := 1;
10593 
10594     v_onhand_cursor := NULL;
10595 
10596   /* Get the onhand balances for items that are lot and status controlled. The
10597      balances come from the location inventory table but the status must be
10598      nettable on the lots.
10599      B3177516 Rajesh D. Patangya  05-Oct-2003
10600      PPLT Logical change:
10601 	     If Hold release date is null then
10602 	          new schedule date = prun_date;
10603 	          new_dock_date=prun_date;
10604 	          order type = 18;
10605 	     Else
10606 	          new schedule date = hold release date ;
10607 	          new_dock_date=prun_date;
10608 	          order type = 8
10609 	     End if;
10610   */
10611 
10612   /* B2623374 -- Rajesh Patangya  PORT BUG FOR 2446925 (OM ATP CHECK TO
10613      RECOGNIZE THE ORDER PROCESSING FLAG) */
10614 
10615   v_onhand_cursor :=  ' SELECT'
10616 	  || ' -1,'
10617 	  || ' i.aps_item_id,'
10618 	  || ' i.organization_id,'
10619 	  || ' :pinstance_id,'
10620 	  || ' DECODE(c.ic_hold_date,NULL,:prun_date,c.ic_hold_date),'
10621 	  || ' :prun_date,'
10622 	  || ' DECODE(c.ic_hold_date,NULL,18,8),'   /* onhand inventory value */
10623 	  || ' substrb(l.lot_no||DECODE(l.sublot_no, NULL,NULL ,:pdelimiter || '
10624 	  || ' l.sublot_no),1,30),'
10625 	  || ' l.expire_date,'
10626 	  || ' 2,'
10627 	  || ' 2,'
10628 	  || ' s.whse_code,'  /* Populating subinventory code with whse code B1172875 */
10629 	  || ' s.loct_onhand, '
10630 	  || ' decode(t.order_proc_ind,0,s.loct_onhand,0)'
10631 	  || ' FROM'
10632 	  || ' ic_loct_inv'||pdblink||' s,'
10633 	  || ' ic_lots_mst'||pdblink||' l,'
10634 	  || ' ic_item_mst_b'||pdblink||' m,'
10635 	  || ' (select distinct aps_item_id, item_id, whse_code, organization_id, '
10636 	  || ' lot_control,experimental_ind from gmp_item_aps'||pdblink||') i,'
10637 	  || ' ic_lots_sts'||pdblink||' t,'
10638 	  || ' ic_lots_cpg'||pdblink||' c'
10639 	  || ' WHERE'
10640 	  || '     s.item_id = i.item_id'
10641 	  || ' and s.item_id = m.item_id'
10642 	  || ' and s.whse_code = i.whse_code'
10643 	  || ' and i.lot_control = 1'
10644 	  || ' and s.lot_id = l.lot_id'
10645 	  || ' and s.item_id = l.item_id'
10646 	  || ' and s.lot_id > 0'
10647 	  || ' and l.delete_mark = 0'
10648 	  || ' 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
10649 	  || ' and s.lot_status = t.lot_status'
10650 	  || ' and t.rejected_ind = 0'
10651 	  || ' and t.nettable_ind = 1'
10652 	  || ' and s.loct_onhand <> 0'
10653 	  || ' and c.item_id (+) = l.item_id'
10654 	  || ' and c.lot_id (+) = l.lot_id'
10655 	  || ' and c.ic_hold_date (+) > :run_date' ;
10656     /* Bug # 5238790 */
10657     IF l_profile = 0 THEN
10658        v_onhand_cursor := v_onhand_cursor
10659     || ' and i.experimental_ind = 0 ' ;
10660     END IF;
10661 
10662     OPEN c_onhand_balance_status FOR v_onhand_cursor USING pinstance_id, prun_date, prun_date, pdelimiter, prun_date;
10663     LOOP
10664       FETCH  c_onhand_balance_status INTO onhand_balance_status_tab(onhand_count);
10665       EXIT WHEN  c_onhand_balance_status%NOTFOUND ;
10666       onhand_count := onhand_count + 1;
10667     END LOOP;
10668     CLOSE c_onhand_balance_status ;
10669     gonhand_balance_size := gonhand_balance_size + onhand_count - 1;
10670 
10671    log_message('Lot and status on hand fetches : '|| to_char(gonhand_balance_size) );
10672    time_stamp ;
10673 
10674     IF onhand_count > 1 THEN
10675     FOR i in onhand_balance_status_tab.FIRST..onhand_balance_status_tab.LAST
10676     LOOP
10677      o_plan_id(insert_count)           := onhand_balance_status_tab(i).plan_id;
10678      o_inventory_item_id(insert_count) := onhand_balance_status_tab(i).inventory_item_id;
10679      o_organization_id(insert_count)   := onhand_balance_status_tab(i).organization_id;
10680      o_sr_instance_id(insert_count)    := onhand_balance_status_tab(i).sr_instance_id;
10681      o_new_schedule_date(insert_count) := onhand_balance_status_tab(i).new_schedule_date;
10682      o_new_dock_date(insert_count)     := onhand_balance_status_tab(i).new_dock_date;
10683      o_order_type(insert_count)        := onhand_balance_status_tab(i).order_type;
10684      o_lot_number(insert_count)        := onhand_balance_status_tab(i).lot_number;
10685      /* B5501754 */
10686      IF (onhand_balance_status_tab(i).expiration_date >= sy_max_date) THEN
10687      o_expiration_date(insert_count)    :=  NULL;
10688      ELSE
10689      o_expiration_date(insert_count)   := onhand_balance_status_tab(i).expiration_date;
10690      END IF;
10691      o_firm_planned_type(insert_count) := onhand_balance_status_tab(i).firm_planned_type;
10692      o_deleted_flag(insert_count)      := onhand_balance_status_tab(i).deleted_flag;
10693      o_subinventory_code(insert_count) := onhand_balance_status_tab(i).subinventory_code;
10694   o_new_order_quantity(insert_count) := onhand_balance_status_tab(i).new_order_quantity;
10695      o_non_nettable_qty(insert_count)  := onhand_balance_status_tab(i).non_nettable_qty;
10696      insert_count := insert_count + 1;
10697     END LOOP;
10698     END IF;
10699 
10700     insert_count := insert_count - 1;
10701 
10702     FORALL i IN 1..insert_count
10703     INSERT INTO msc_st_supplies
10704                 (plan_id,
10705 		inventory_item_id,
10706 		organization_id,
10707 		sr_instance_id,
10708 		new_schedule_date,
10709 		new_dock_date,
10710 		order_type,
10711 		lot_number,
10712 		expiration_date,
10713 		firm_planned_type,
10714 		deleted_flag,
10715 		subinventory_code,
10716 		new_order_quantity,
10717 		non_nettable_qty
10718 		)
10719          VALUES(o_plan_id(i),
10720 		o_inventory_item_id(i),
10721 		o_organization_id(i),
10722 		o_sr_instance_id(i),
10723 		o_new_schedule_date(i),
10724 		o_new_dock_date(i),
10725 		o_order_type(i),
10726 		o_lot_number(i),
10727 		o_expiration_date(i),
10728 		o_firm_planned_type(i),
10729 		o_deleted_flag(i),
10730 		o_subinventory_code(i),
10731 		o_new_order_quantity(i),
10732 		o_non_nettable_qty(i)
10733 		);
10734 
10735    log_message('On Hand Balances size is = '|| to_char(gonhand_balance_size) );
10736    time_stamp ;
10737 
10738 /* akaruppa B5007729 */
10739 	o_organization_id  := empty_num_table ;
10740 	o_sr_instance_id   := empty_num_table ;
10741 	o_plan_id          := empty_num_table ;
10742 	o_inventory_item_id := empty_num_table ;
10743 	o_new_schedule_date := empty_dat_table ;
10744         o_order_type        := empty_num_table ;
10745 	o_new_order_quantity := empty_num_table ;
10746 	o_firm_planned_type  := empty_num_table ;
10747 	o_lot_number         := e_lot_number;
10748 	o_expiration_date    := empty_dat_table ;
10749 	o_new_dock_date      := empty_dat_table ;
10750 	o_deleted_flag       := empty_num_table ;
10751 	o_subinventory_code  := e_subinventory_code;
10752         o_non_nettable_qty   := empty_num_table ;
10753 
10754         dbms_session.free_unused_user_memory;
10755 
10756 /* akaruppa B5007729 End*/
10757 
10758   return_status := TRUE;
10759 
10760   EXCEPTION
10761     WHEN OTHERS THEN
10762 	log_message('Failure occured during the Onhand Balances extract');
10763 	log_message(sqlerrm);
10764         return_status := FALSE;
10765 
10766 END extract_onhand_balances; /* end extract_onhand_balances */
10767 
10768 /***********************************************************************
10769 *
10770 *   NAME
10771 *	extract_inv_transfer_demands
10772 *
10773 *   DESCRIPTION
10774 *	This procedure will insert records into the table msc_st_demands
10775 *       According to APS team (Sam Tupe < prganesh Shah etc.
10776 *        The inventory transfer demand is similar to Internal Sales Order
10777 *        demand hence should be added to each of the demand schedule
10778 *        The specifics are
10779 *        demand_type = 6
10780 *        origination_type = 6
10781 *        disposition_id = same transfer_id This should match with the
10782 *                        corresponding transaction_id of the supply created
10783 *                        by the same transfer
10784 *       demand_schedule_name =  OPM specific demand_schedule name - The
10785 *              MDS names used in forecast/SO extraction
10786 *   HISTORY
10787 * 	25-Jan-2003 B2756431
10788 *         Note : Old procedure extract_inv_transfers is now removed
10789 *                and replaced with these two new procedures
10790 ************************************************************************/
10791 PROCEDURE extract_inv_transfer_demands(
10792   pdblink        IN  VARCHAR2,
10793   pinstance_id   IN  NUMBER,
10794   prun_date      IN  DATE,
10795   pdelimiter     IN  VARCHAR2,
10796   pwhse_code     IN  VARCHAR2,
10797   pdesignator    IN  VARCHAR2,
10798   return_status  IN OUT NOCOPY BOOLEAN)
10799 AS
10800 
10801   pdoc_type      VARCHAR2(4) ;
10802   l_profile      NUMBER      ; /* Bug # 5238790 */
10803   TYPE onh_cursor_typ IS REF CURSOR;
10804   ex_code_ref          onh_cursor_typ;
10805   ex_code_cursor       VARCHAR2(32000);
10806 
10807 BEGIN
10808    log_message('Entering extract_inv_transfer_demands. ');
10809    time_stamp ;
10810   pdoc_type      := 'XFER';
10811   /* Bug # 5238790 */
10812    l_profile := 0 ;
10813    ex_code_cursor   := ' select NVL(fnd_profile.VALUE' ||pdblink
10814                       ||' (''GMP_COLLECT_EXPR_ONHAND''),0) from dual ' ;
10815 
10816        OPEN ex_code_ref FOR ex_code_cursor ;
10817        FETCH ex_code_ref INTO l_profile;
10818        CLOSE ex_code_ref;
10819 
10820   return_status := TRUE ;
10821 
10822   v_sql_stmt := 'INSERT into msc_st_demands ('
10823     || '   organization_id,'
10824     || '   inventory_item_id,'
10825     || '   sr_instance_id,'
10826     || '   using_assembly_item_id,'
10827     || '   using_assembly_demand_date,'
10828     || '   using_requirement_quantity,'
10829     || '   demand_type,'
10830     || '   origination_type,'
10831     || '   order_number,'
10832     || '   demand_schedule_name,'
10833     || '   disposition_id,' /* B2756431 */
10834     || '   demand_source_type,' /* B2756431 */
10835     || '   original_system_reference,' /* B2756431  */
10836     || '   original_system_line_reference,' /* being added for B2756431 */
10837     || '   deleted_flag)'
10838     || ' SELECT '
10839     || '   i.organization_id,'
10840     || '   i.aps_item_id,'
10841     || '   :pinstance_id, '
10842     || '   i.aps_item_id,'
10843     || '   s.scheduled_release_date,'
10844     || '   s.release_quantity1,'
10845     || '   1,'  /* Discrete , other demands types are interpreted as continuous */
10846     || '   6,'   /* Orig_type should br 6 per Sam Tupe so change from 11 */
10847     || '   :pdoc_type || :pdelimiter || s.orgn_code ||'
10848     || '     :pdelimiter2 || s.transfer_no, '
10849     || '   :pdesignator,'
10850     || '   s.transfer_id,'
10851     || '   8,'             /* B2756431 Demand_source_type    */
10852     || '   s.transfer_id,' /* B2756431 original_system_reference */
10853     || '   s.transfer_id,' /* B2756431 original_system_line_reference */
10854     || '   2'
10855     || ' FROM '
10856     || '   ic_xfer_mst' ||pdblink|| ' s,'
10857     || '   (select distinct aps_item_id, item_id, whse_code, organization_id '
10858     || '    ,experimental_ind from gmp_item_aps'||pdblink||') i'
10859     || ' WHERE '
10860     || '   s.item_id = i.item_id '
10861     || '   and s.from_warehouse = i.whse_code '
10862     || '   and s.transfer_status IN (1) '
10863     || '   and s.from_warehouse = :pwhse_code '
10864     || '   and s.release_quantity1 <> 0';
10865     /* Bug # 5238790 */
10866     IF l_profile = 0 THEN
10867        v_sql_stmt := v_sql_stmt
10868     || ' and i.experimental_ind = 0 ' ;
10869     END IF;
10870 
10871   EXECUTE IMMEDIATE v_sql_stmt USING pinstance_id, pdoc_type, pdelimiter, pdelimiter , pdesignator, pwhse_code ;
10872 
10873   EXCEPTION
10874     WHEN OTHERS THEN
10875 	log_message('Failure occured during the Inventory Transfer extract');
10876 	log_message(sqlerrm);
10877         return_status := FALSE;
10878 
10879 END extract_inv_transfer_demands;/* end extract_inv_transfer_dem */
10880 
10881 /***********************************************************************
10882 *
10883 *   NAME
10884 *	Extract_inventory_transfer_supplies
10885 *
10886 *   DESCRIPTION
10887 *	This procedure will insert records into the table msc_st_supplies
10888 *	and msc_st_demands for pending inventory transfers.
10889 *   HISTORY
10890 * 	25-Jan-2003 B1332662  Created New procedure to insert supplies
10891 *         Per discussions with APS team the specifics are
10892 *          Order_type = 2
10893 *          Transaction_id = transafer_id of the transfer in OPM
10894 ************************************************************************/
10895 PROCEDURE extract_inv_transfer_supplies(
10896   pdblink        IN  VARCHAR2,
10897   pinstance_id   IN  NUMBER,
10898   prun_date      IN  DATE,
10899   pdelimiter     IN  VARCHAR2,
10900   return_status  IN OUT NOCOPY BOOLEAN)
10901 AS
10902 
10903   pdoc_type      VARCHAR2(4) ;
10904   l_profile      NUMBER      ;/* Bug # 5238790 */
10905   TYPE onh_cursor_typ IS REF CURSOR;
10906   ex_code_ref          onh_cursor_typ;
10907   ex_code_cursor       VARCHAR2(32000);
10908 
10909 BEGIN
10910    log_message('Entering extract_inv_transfer_supplies. ');
10911    time_stamp ;
10912   pdoc_type      := 'XFER';
10913 
10914    /* Bug # 5238790 */
10915    l_profile := 0 ;
10916    ex_code_cursor   := ' select NVL(fnd_profile.VALUE' ||pdblink
10917                       ||' (''GMP_COLLECT_EXPR_ONHAND''),0) from dual ' ;
10918 
10919        OPEN ex_code_ref FOR ex_code_cursor ;
10920        FETCH ex_code_ref INTO l_profile;
10921        CLOSE ex_code_ref;
10922 
10923   return_status := TRUE ;
10924 
10925   v_sql_stmt := 'INSERT into msc_st_supplies ('
10926     || ' plan_id,'
10927     || ' inventory_item_id,'
10928     || ' organization_id,'
10929     || ' sr_instance_id,'
10930     || ' source_sr_instance_id,'
10931     || ' new_schedule_date,'
10932     || ' order_type,'
10933     || ' order_number,'
10934     || ' lot_number,'
10935     || ' firm_planned_type,'
10936     || ' deleted_flag,'
10937     || ' subinventory_code,'
10938     || ' transaction_id,'          /* being added for B2756431 */
10939     || ' disposition_id,'          /* being added for B2756431 */
10940     || ' po_line_id,'              /* being added for B2756431 */
10941     || ' source_organization_id,'   /* being added for B2756431 */
10942     || ' new_order_quantity)'
10943     || ' SELECT '
10944     || ' -1,'
10945     || ' i.aps_item_id,'
10946     || ' i.organization_id,'
10947     || ' :pinstance_id, '
10948     || ' :pinstance_id, '
10949     || ' s.scheduled_receive_date, '
10950     || ' 2,'                        /* po requisition value */
10951     || ' :pdoc_type || :pdelimiter || s.orgn_code ||'
10952     || '   :pdelimiter2 || s.transfer_no, '
10953     || ' DECODE(s.lot_id, 0, NULL, '
10954     || '   substrb(l.lot_no||DECODE(l.sublot_no, NULL,NULL ,:pdelimiter3 || '
10955     || '   l.sublot_no),1,30)),'
10956     || ' 2,'
10957     || ' 2,'
10958     || ' s.to_warehouse,'
10959     || ' s.transfer_id,' /* B2756431 transaction_id */
10960     || ' s.transfer_id,' /* B2756431 disposition_id */
10961     || ' s.transfer_id,' /* B2756431 po_line_id     */
10962     || ' w.mtl_organization_id,' /* B2756431 source_organization_id */
10963     || ' s.release_quantity1'
10964     || ' FROM '
10965     || ' ic_xfer_mst' ||pdblink|| ' s,'
10966     || ' ic_whse_mst' ||pdblink|| ' w,'
10967     || ' ic_lots_mst'||pdblink||' l,'
10968     || ' (select distinct aps_item_id, item_id, whse_code, organization_id '
10969     || '  ,experimental_ind from gmp_item_aps'||pdblink||') i'
10970     || ' WHERE '
10971     || ' s.item_id = i.item_id '
10972     || ' and s.to_warehouse = i.whse_code '
10973     || ' and s.from_warehouse = w.whse_code '
10974     || ' and s.transfer_status IN (1,2) '
10975     || ' and s.lot_id = l.lot_id'
10976     || ' and s.item_id = l.item_id'
10977     || ' and s.release_quantity1 <> 0';
10978    /* Bug # 5238790 */
10979     IF l_profile = 0 THEN
10980        v_sql_stmt := v_sql_stmt
10981     || ' and i.experimental_ind = 0 ' ;
10982     END IF;
10983 
10984   EXECUTE IMMEDIATE v_sql_stmt USING pinstance_id,pinstance_id, pdoc_type, pdelimiter,
10985     pdelimiter, pdelimiter;
10986 
10987   EXCEPTION
10988     WHEN OTHERS THEN
10989 	log_message('Failure occured during the Inventory Transfer supplies ');
10990 	log_message(sqlerrm);
10991         return_status := FALSE;
10992 
10993 END extract_inv_transfer_supplies;/* end extract_inv_transfer_sup */
10994 
10995 
10996 /***********************************************************************
10997 *
10998 *   NAME
10999 *	 build_designator
11000 *
11001 *   DESCRIPTION
11002 *       This procedure will create a new row in the pl/sql table if one does
11003 *	for the current schedule/whse. The rows will be inserted into the
11004 *	database in the procedure sales_forecast which calls this procedure.
11005 *	A unique designator must be created for each schedule/whse otherwise a
11006 *	number is added to make it unique. If the row exists already the value
11007 *	is returned otherwise the table is added to and the new value is returned
11008 *       in the out parameter
11009 *   HISTORY
11010 * 	M Craig
11011 ************************************************************************/
11012 PROCEDURE build_designator(
11013   poccur       IN  NUMBER,
11014   pdelimiter   IN  VARCHAR2,
11015   pdesignator  OUT NOCOPY VARCHAR2)
11016 AS
11017 
11018   temp_designator VARCHAR2(10);
11019   i               NUMBER;
11020   j               NUMBER;
11021   k               NUMBER;
11022   found           NUMBER ;
11023   j_char          VARCHAR2(5);
11024 
11025 BEGIN
11026   found := 0 ;
11027   /*  The default name generation is the first 5 chars of the schedule and the
11028       four chars of the warehouse
11029   */
11030   temp_designator := substrb(sched_dtl_tab(poccur).schedule,1,5) || pdelimiter
11031                      || sched_dtl_tab(poccur).whse_code;
11032 
11033   pdesignator := NULL;
11034   found := 0;
11035 
11036   /* if there are existing rows search them for the key values */
11037   IF desig_count > 0 THEN
11038   /* {
11039         loop through the existing designator rows */
11040     FOR i IN 1..desig_count LOOP
11041     /* {
11042 
11043       if a row has alreday been inserted for the schedule and warehouse
11044       use the value from that row and stop the loop
11045      */
11046       IF desig_tab(i).schedule = sched_dtl_tab(poccur).schedule and
11047          desig_tab(i).whse_code = sched_dtl_tab(poccur).whse_code THEN
11048 
11049         pdesignator := desig_tab(i).designator;
11050         found := 1;
11051         EXIT;
11052 
11053       END IF;
11054 
11055     /* } */
11056     END LOOP;
11057 
11058     /* when the schedule and warehouse are not represented we need to find
11059        a unique name for the designator
11060     */
11061     IF found = 0 THEN
11062     /* { */
11063 
11064       k := 5;
11065       j := 0;
11066       j_char := NULL;
11067 
11068       /* the loop will try the default value then change it if necessary and
11069         until we have exhasted all of the values of 0-99999 (5 chars of numbers)
11070       */
11071       LOOP
11072       /* { */
11073         temp_designator := j_char || SUBSTR(sched_dtl_tab(poccur).schedule,1,k) ||
11074                            pdelimiter || sched_dtl_tab(poccur).whse_code;
11075         /* this loop goes through the current list to see if there is a duplicate
11076            if found we stop and generate a new value then try again
11077         */
11078         FOR i IN 1..desig_count LOOP
11079         /* { */
11080           IF desig_tab(i).designator = temp_designator THEN
11081             EXIT;
11082           END IF;
11083           IF i =  desig_count THEN
11084             found := 1;
11085             pdesignator := temp_designator;
11086           END IF;
11087         /* } */
11088         END LOOP;
11089 
11090         /* if we found a value or reached the max we stop */
11091         IF found = 1 or j = 99999 THEN
11092           EXIT;
11093         END IF;
11094 
11095         /* to get a unique value we keep taking one char at a time from the
11096            the schedule leaving the warehouse intact.
11097         */
11098         j := j + 1;
11099         IF j < 10 THEN
11100           k := 4;
11101         ELSIF j < 100 THEN
11102           k := 3;
11103         ELSIF j < 1000 THEN
11104           k := 2;
11105         ELSIF j < 10000 THEN
11106           k := 1;
11107         ELSE
11108           k := 0;
11109         END IF;
11110 
11111         j_char := TO_CHAR(j);
11112 
11113       /* } */
11114       END LOOP;
11115 
11116 
11117       /* put a new row in for the value that was found */
11118       IF found = 1 and pdesignator = temp_designator THEN
11119 
11120         desig_count := desig_count + 1;
11121         desig_tab(desig_count).designator := temp_designator;
11122         desig_tab(desig_count).schedule := sched_dtl_tab(poccur).schedule;
11123         desig_tab(desig_count).orgn_code := sched_dtl_tab(poccur).orgn_code;
11124         desig_tab(desig_count).whse_code := sched_dtl_tab(poccur).whse_code;
11125         desig_tab(desig_count).organization_id :=
11126           sched_dtl_tab(poccur).organization_id;
11127 
11128       END IF;
11129 
11130     /* } */
11131     END IF;
11132 
11133   /* if no rows are in the table yet just put a new one in */
11134   ELSE
11135 
11136     desig_tab(1).designator := temp_designator;
11137     desig_tab(1).schedule := sched_dtl_tab(poccur).schedule;
11138     desig_tab(1).orgn_code := sched_dtl_tab(poccur).orgn_code;
11139     desig_tab(1).whse_code := sched_dtl_tab(poccur).whse_code;
11140     desig_tab(1).organization_id := sched_dtl_tab(poccur).organization_id;
11141     pdesignator := temp_designator;
11142     desig_count := 1;
11143 
11144   /* } */
11145   END IF;
11146 
11147 END build_designator;
11148 
11149 /***********************************************************************
11150 *
11151 *   NAME
11152 *	 sales_forecast_api
11153 *
11154 *   DESCRIPTION
11155 *     This procedure is a wrapper for the preexisting sales_forecast procedure.
11156 *     This version is set up with the proper parameters to be called as from the
11157 *     concurrent manager.  In addition, the main difference is the table into
11158 *     which demands are inserted.  The standard procedure inserts into
11159 *     msc_st_demands.
11160 *     This new procedure inserts into gmp_demands_api. The difference between
11161 *     the two tables is the addition of a schedule_id column in
11162 *     gmp_demands_api.  Also, this version of sales_forecast begins by
11163 *     truncating gmp_demands_api and leaves it populated after
11164 *     it completes. By contrast, msc_st_demands (which is an APS staging table)
11165 *     is immediately truncated after APS reads its data. This difference allows
11166 *     gmp_demands_api to be a general purpose version of msc_st_demands.
11167 *
11168 *   HISTORY
11169 * 	P. Dong
11170 * 	09/14/01 - Created
11171 *       12/21/01 - Replaced TRUNCATE with DELETE
11172 ************************************************************************/
11173 PROCEDURE sales_forecast_api(
11174   errbuf         OUT NOCOPY VARCHAR2,
11175   retcode        OUT NOCOPY VARCHAR2,
11176   p_cp_enabled   IN BOOLEAN ,
11177   p_run_date     IN DATE )
11178 AS
11179   lv_cp_enabled  BOOLEAN;
11180 BEGIN
11181 
11182   lv_cp_enabled := p_cp_enabled;
11183 
11184   MSC_CL_GMP_UTILITY.extract_items(
11185     at_apps_link => NULL,
11186     instance => NULL,
11187     run_date => p_run_date,
11188     return_status => lv_cp_enabled  );
11189 
11190   DELETE FROM gmp_demands_api;
11191 
11192   lv_cp_enabled := p_cp_enabled;
11193 
11194   sales_forecast(
11195     pdblink => NULL,
11196     pinstance_id => NULL,
11197     prun_date => p_run_date,
11198     pdelimiter => '/',
11199     return_status => lv_cp_enabled,
11200     api_mode => TRUE);
11201 
11202  errbuf := NULL;
11203  retcode := NULL;
11204 
11205  EXCEPTION
11206      WHEN OTHERS THEN
11207              errbuf := SUBSTRB(SQLERRM,1,100);
11208              retcode := SQLCODE;
11209 
11210 END sales_forecast_api;
11211 
11212 /***********************************************************************
11213 *
11214 *   NAME
11215 *	 sales_forecast
11216 *
11217 *   DESCRIPTION
11218 *       This procedure will retrieve all of the sales order lines and forecast
11219 *	details for their respective schedules. The forecast will be consumed
11220 *       and the all of the rows will be written to msc_st_demands. Each demand
11221 *	is applied to an MDS aka designator.
11222 *   HISTORY
11223 * 	M Craig
11224 * 	10/13/99 - Sridhar Added Designator Type column in the insert statement
11225 * 	12/17/99 - Changes made to the insert statement for designators,
11226 *                  changed desig_tab(1).schedule and desig_tab(1).whse_code to
11227 *                  desig_tab(i).schedule and desig_tab(i).whse_code
11228 * 	04/01/00 - Code Fix for Bug# 1137597.
11229 * 	07/01/00 - Code Fix for Error in Designators Insert
11230 *
11231 *       02-MAY-2002 Re-engineered By : Abhay Satpute, Rajesh Patangya
11232 *              Brief Logic of the new code
11233 *                  Fetch the following data into PL/SQL tables
11234 *                       a. Distinct schd/item/whse combinations
11235 *                       b. Sales order details
11236 *                       c. Forecast details
11237 *                       d. Schedule forecast associations
11238 *               For each item combination loop through and
11239 *                  For each change of schedule change mark reuqired
11240 *                  forecast rows as well note down the stock and ord ind.
11241 *                  For each item insert sales orders, unconsumed forecast
11242 *                  or the forecast , based on the indicators
11243 *     P Dong
11244 *     09/14/01 - Added api_mode to pass to insert_demands
11245 *
11246 *   Navin   21-APR-2003 B3577871 ST:OSFME2: collections failing in planning data pull.
11247 *                                Added handling of NO_DATA_FOUND Exception.
11248 *                                And return the return_status as TRUE.
11249 ****************************************************************************/
11250 
11251 PROCEDURE sales_forecast( pdblink        IN  VARCHAR2,
11252 			  pinstance_id   IN  NUMBER,
11253 			  prun_date      IN  DATE,
11254 			  pdelimiter     IN  VARCHAR2,
11255 			  return_status  IN  OUT NOCOPY BOOLEAN,
11256 			  api_mode       IN  BOOLEAN)
11257 
11258 AS
11259 
11260     TYPE gmp_cursor_typ IS REF CURSOR;
11261     cur_gmp_schd_items  gmp_cursor_typ;
11262     cur_fcst_dtl        gmp_cursor_typ;
11263     cur_sales_dtl       gmp_cursor_typ;
11264     cur_schd_fcst       gmp_cursor_typ;
11265     ex_code_ref         gmp_cursor_typ;
11266 
11267     so_ind		BOOLEAN ;
11268     fcst_ind		BOOLEAN ;
11269     log_mesg            VARCHAR2(1000) ;
11270     i			NUMBER ;
11271     j			NUMBER ;
11272     old_schedule_id	NUMBER ;
11273     item_count		NUMBER ;
11274     fcst_count		NUMBER ;
11275     so_count		NUMBER ;
11276     schd_fcst_cnt	NUMBER ;
11277     local_ret_status    BOOLEAN;
11278     l_profile           NUMBER ; /* Bug # 5238790 */
11279     ex_code_cursor      VARCHAR2(32000);
11280 
11281 BEGIN
11282     g_delimiter         := '/';
11283     so_ind		:= FALSE ;
11284     fcst_ind		:= FALSE ;
11285     log_mesg            := NULL;
11286     i			:= 0;
11287     j			:= 0;
11288     old_schedule_id	:= 0 ;
11289     item_count		:= 1;
11290     fcst_count		:= 1;
11291     so_count		:= 1;
11292     schd_fcst_cnt	:= 1;
11293 
11294   gitem_size		:= 0;
11295   gfcst_size		:= 0;
11296   gso_size		:= 0;
11297   gschd_fcst_size	:= 0;
11298 
11299   gfcst_cnt		:= 0;
11300   gso_cnt		:= 0;
11301   gschd_fcst_cnt	:= 0;
11302   g_item_tbl_position	:= 0;
11303   local_ret_status      := return_status ;
11304 
11305   log_message('Start MSC_CL_GMP_UTILITY.sales forecast');
11306   time_stamp;
11307 
11308   IF return_status THEN
11309     v_cp_enabled := TRUE;
11310   ELSE
11311     v_cp_enabled := FALSE;
11312   END IF;
11313    g_delimiter		:= pdelimiter ;
11314    g_instance_id	:= pinstance_id ;
11315 
11316    /* Bug # 5238790 */
11317    l_profile := 0 ;
11318    ex_code_cursor   := ' select NVL(fnd_profile.VALUE' ||pdblink
11319                       ||' (''GMP_COLLECT_EXPR_ONHAND''),0) from dual ' ;
11320 
11321        OPEN ex_code_ref FOR ex_code_cursor ;
11322        FETCH ex_code_ref INTO l_profile;
11323        CLOSE ex_code_ref;
11324 
11325 IF api_mode THEN
11326   /* If forecast and sales order select queries have joins with gmp_item_aps
11327      we need to select only schedules and warehouses here
11328      ORDERED By Schedule , Aps_Item, Organization_id(Warehouse) */
11329 
11330         /* Extract Schedule Details */
11331         v_item_sql_stmt := 'SELECT DISTINCT'
11332          || ' h.schedule,'
11333          || ' h.schedule_id,'
11334          || ' h.order_ind,'
11335          || ' h.stock_ind,'
11336          || ' a.whse_code,'
11337          || ' d.orgn_code,'
11338          || ' a.organization_id, '
11339          || ' a.aps_item_id inventory_item_id'
11340          || ' FROM'
11341          || '    ps_schd_hdr'||pdblink||' h,'
11342          || '    ps_schd_dtl'||pdblink||' d,'
11343          || '    gmp_item_aps'||pdblink||' a'
11344          || ' WHERE'
11345          || ' h.schedule_id = d.schedule_id'
11346          || ' and d.orgn_code = a.plant_code'
11347          || ' and h.active_ind = 1'
11348          || ' and a.replen_ind = 1'
11349          || ' and (h.order_ind = 1 or h.stock_ind = 1)'
11350          || ' and h.delete_mark = 0'
11351          || ' and a.item_id > 0 ' ;
11352          /* Bug # 5238790 */
11353          IF l_profile = 0 THEN
11354         v_item_sql_stmt := v_item_sql_stmt
11355          || ' and a.experimental_ind = 0 ' ;
11356          END IF;
11357 
11358         v_item_sql_stmt := v_item_sql_stmt
11359          || ' ORDER BY'
11360          || ' h.schedule_id ASC,'
11361          || ' a.aps_item_id, '
11362          || ' a.organization_id ' ;
11363 
11364    -- B2596464, Order changed for inv_item and organization_id
11365    -- B2973249, undershipped or overshipped sales orders have shipped_qty
11366    -- populated by OM and as per APS this lines can not be selected, as OM
11367    -- split original line and keep the open line without any shipped qty.
11368         /* Extract Sales Order */
11369         v_sales_sql_stmt := 'SELECT '
11370           || ' msi.inventory_item_id, '
11371           || ' msi.organization_id, '
11372           || ' h.orgn_code, '
11373           || ' h.order_no, '
11374           || ' d.line_id,  '
11375           || ' d.net_price, '
11376           || ' d.sched_shipdate, '
11377           || ' d.requested_shipdate, '      /* B2971996 */
11378           || ' (sum(t.trans_qty) * -1) trans_qty '
11379           || ' FROM '
11380           || ' mtl_system_items'||pdblink||' msi, '
11381           || ' ic_item_mst'||pdblink||' iim,'
11382           || ' ic_whse_mst'||pdblink||' wm, '
11383           || ' op_ordr_hdr'||pdblink||' h, '
11384           || ' op_ordr_dtl'||pdblink||' d, '
11385           || ' ic_tran_pnd'||pdblink||' t '
11386           || ' WHERE '
11387           || '     msi.organization_id = wm.mtl_organization_id '
11388           || ' AND msi.segment1 = iim.item_no '
11389           || ' and wm.delete_mark = 0 '
11390           || ' and h.order_id = d.order_id '
11391           || ' and h.order_status = 0 '
11392           || ' and h.delete_mark = 0 '
11393           || ' and h.order_id = t.doc_id '
11394           || ' and d.line_status >= 0 '
11395           || ' and d.line_status < 20 '
11396           || ' and h.from_whse = wm.whse_code '
11397           || ' and t.line_id = d.line_id '
11398           || ' and t.item_id = d.item_id  '
11399           || ' and iim.item_id = t.item_id  '
11400           || ' and iim.delete_mark = 0 '
11401           || ' AND iim.inactive_ind = 0 '
11402           || ' and t.trans_qty <> 0 '
11403           || ' and t.completed_ind = 0 '
11404           || ' and t.delete_mark = 0 '
11405           || ' and t.doc_type = :popso '
11406           || ' GROUP BY  '
11407           || ' msi.inventory_item_id, '
11408           || ' msi.organization_id, '
11409           || ' h.orgn_code, '
11410           || ' h.order_no, '
11411           || ' d.line_id,  '
11412           || ' d.net_price, '
11413           || ' d.sched_shipdate, '
11414           || ' d.requested_shipdate '    /* B2971996 */
11415           || ' UNION ALL '
11416           || ' SELECT '
11417           || ' items.inventory_item_id, '
11418           || ' items.organization_id, '
11419           || ' org.organization_code, '
11420           || ' TO_CHAR(hdr.order_number), '
11421           || ' TO_NUMBER(NULL), '
11422           || ' TO_NUMBER(NULL), '
11423           || ' mtl.requirement_date, '
11424           || ' dtl.request_date, '      /* B2971996 */
11425           || ' mtl.primary_uom_quantity '
11426           || ' FROM '
11427           || '     mtl_demand_omoe'||pdblink||' mtl, '
11428           || '     mtl_system_items'||pdblink||' items, '
11429           || '     oe_order_headers_all'||pdblink||' hdr, '
11430           || '     oe_order_lines_all'||pdblink||' dtl, '
11431           || '     mtl_parameters'||pdblink||' org '
11432           || ' WHERE '
11433           || '     items.organization_id   = mtl.organization_id  '
11434           || ' and items.inventory_item_id = mtl.inventory_item_id '
11435           || ' and NVL(mtl.completed_quantity,0) = 0 '
11436           || ' and mtl.open_flag = ' || '''Y'''
11437           || ' and mtl.available_to_mrp = 1 '
11438           || ' and mtl.parent_demand_id is NULL '
11439           || ' and mtl.demand_source_type IN (2,8) '
11440           || ' and mtl.demand_id = dtl.line_id '
11441           || ' and dtl.header_id = hdr.header_id '
11442         -- B2743626, Changed the join to take process sales order (OMSO)
11443           || ' and dtl.ship_from_org_id = org.organization_id  '
11444           || ' and org.process_enabled_flag = ' || '''Y'''
11445           || ' and NOT EXISTS  '
11446           || '     (SELECT 1 '
11447           || '        FROM so_lines_all'||pdblink||' sl,'
11448           || '          so_lines_all'||pdblink||' slp,'
11449           || '          mtl_demand_omoe'||pdblink||' dem'
11450           || '      WHERE '
11451           || '           slp.line_id(+) = nvl(sl.parent_line_id,sl.line_id) '
11452           || '        and to_number(dem.demand_source_line) = sl.line_id(+) '
11453           || '        and dem.demand_source_type in (2,8) '
11454           || '        and sl.end_item_unit_number IS NULL '
11455           || '        and slp.end_item_unit_number IS NULL '
11456           || '        and dem.demand_id = mtl.demand_id '
11457           || '        and items.effectivity_control = 2) '
11458           || ' ORDER BY 1,2,7 DESC ' ;
11459 
11460        /* Extract Forecast details */
11461         v_forecast_sql_stmt := 'SELECT '
11462           || ' msi.inventory_item_id, '
11463           || ' msi.organization_id, '
11464           || ' h.forecast_id, '
11465           || ' h.forecast, '
11466           || ' d.orgn_code, '
11467           || ' d.trans_date, '
11468           || ' (sum(d.trans_qty * -1) ) trans_qty, '
11469           || ' (sum(d.trans_qty * -1) ) consumed_qty ,'
11470           || ' 0 use_fcst_flag '
11471           || ' FROM '
11472           || ' mtl_system_items'||pdblink||' msi, '
11473           || ' ic_item_mst'||pdblink||' iim, '
11474           || ' ic_whse_mst'||pdblink||' wm, '
11475           || ' fc_fcst_hdr'||pdblink||' h, '
11476           || ' fc_fcst_dtl'||pdblink||' d '
11477           || ' WHERE '
11478           || '     msi.organization_id = wm.mtl_organization_id ' ;
11479           /* Bug # 5238790 */
11480          IF l_profile = 0 THEN
11481                   v_forecast_sql_stmt := v_forecast_sql_stmt
11482          || ' and iim.experimental_ind = 0 ' ;
11483          END IF;
11484 
11485           v_forecast_sql_stmt := v_forecast_sql_stmt
11486           || ' and msi.segment1 = iim.item_no '
11487           || ' and wm.delete_mark = 0 '
11488           || ' and h.forecast_id = d.forecast_id '
11489           || ' and d.forecast_id > 0  '
11490           || ' and d.item_id = iim.item_id '
11491           || ' and d.whse_code = wm.whse_code '
11492           || ' and d.orgn_code = wm.orgn_code '
11493           || ' and h.delete_mark = 0 '
11494           || ' and d.delete_mark = 0 '
11495           || ' and d.trans_qty <> 0 '
11496           || ' and d.trans_date >=  sysdate '
11497           || ' and EXISTS (SELECT 1 FROM '
11498           || '                      ps_schd_for'||pdblink||' sf, '
11499           || '                      ps_schd_hdr'||pdblink||' sh  '
11500           || '             WHERE sh.schedule_id = sf.schedule_id '
11501           || '               and sh.delete_mark = 0 '
11502           || '               and sh.active_ind = 1 '
11503           || '               and sf.forecast_id = h.forecast_id) '
11504           || ' GROUP BY '
11505           || ' msi.inventory_item_id, '
11506           || ' msi.organization_id, '
11507           || ' h.forecast, '
11508           || ' h.forecast_id, '
11509           || ' d.orgn_code, '
11510           || ' d.trans_date '
11511           || ' ORDER BY msi.inventory_item_id,msi.organization_id, '
11512           || ' d.trans_date DESC ' ;
11513 
11514        /* Extract Schedule Forecast Association SQL selection */
11515         v_association_sql_stmt := 'SELECT '
11516           || ' schedule_id, forecast_id '
11517           || ' from ps_schd_for'||pdblink
11518           || ' ORDER BY 1,2 ' ;
11519 
11520     /* Start Fetching the schedule, forecast, sales order and association
11521        data for above queries */
11522 
11523     OPEN cur_gmp_schd_items FOR v_item_sql_stmt;
11524     LOOP
11525       FETCH cur_gmp_schd_items INTO sched_dtl_tab(item_count);
11526       EXIT WHEN cur_gmp_schd_items%NOTFOUND;
11527       item_count := item_count + 1;
11528     END LOOP;
11529     CLOSE cur_gmp_schd_items;
11530     gitem_size := item_count -1 ;
11531     time_stamp ;
11532     log_message('Schedule Items size is = ' || to_char(gitem_size)) ;
11533 
11534     OPEN cur_fcst_dtl FOR v_forecast_sql_stmt;
11535     LOOP
11536       FETCH cur_fcst_dtl INTO fcst_dtl_tab(fcst_count);
11537       EXIT WHEN cur_fcst_dtl%NOTFOUND;
11538       fcst_count := fcst_count + 1;
11539     END LOOP;
11540     CLOSE cur_fcst_dtl ;
11541     gfcst_size := fcst_count  -1 ;
11542     time_stamp ;
11543     log_message('Fcst size is = '|| to_char(gfcst_size) );
11544 
11545     OPEN cur_sales_dtl FOR v_sales_sql_stmt USING v_doc_opso;
11546     LOOP
11547       FETCH cur_sales_dtl INTO sales_dtl_tab(so_count);
11548       EXIT WHEN cur_sales_dtl%NOTFOUND;
11549       so_count := so_count + 1;
11550     END LOOP;
11551     CLOSE cur_sales_dtl ;
11552     gso_size := so_count  -1 ;
11553     time_stamp ;
11554     log_message ('SO size is = '||to_char(gso_size));
11555 
11556     OPEN cur_schd_fcst FOR v_association_sql_stmt;
11557     LOOP
11558       FETCH cur_schd_fcst INTO SCHD_FCST_DTL_TAB(schd_fcst_cnt);
11559       EXIT WHEN cur_schd_fcst%NOTFOUND;
11560       schd_fcst_cnt := schd_fcst_cnt + 1;
11561     END LOOP;
11562     CLOSE cur_schd_fcst ;
11563     gschd_fcst_size := schd_fcst_cnt -1 ;
11564     time_stamp ;
11565     log_message('Schedule Forecast Assoc size is ='||to_char(gschd_fcst_size));
11566 
11567      gschd_fcst_cnt := 1;
11568      so_ind 	:= FALSE ;
11569      fcst_ind	:= FALSE ;
11570 
11571     FOR i IN 1..gitem_size LOOP
11572     g_item_tbl_position := i ;
11573     IF old_schedule_id <> sched_dtl_tab(i).schedule_id THEN
11574 	-- Keep commiting the data to avoid Rollback segment growing problem
11575         COMMIT ;
11576 	time_stamp ;
11577 	  gfcst_cnt      := 1 ;
11578 	  gso_cnt        := 1 ;
11579      	  so_ind 	:= FALSE ;
11580      	  fcst_ind	:= FALSE ;
11581 
11582 	  IF sched_dtl_tab(i).order_ind = 1 THEN
11583 		so_ind := TRUE ;
11584 	  END IF;
11585 	  IF sched_dtl_tab(i).stock_ind = 1 THEN
11586 		fcst_ind := TRUE ;
11587 	  END IF;
11588 
11589         /* If there is no forecast associated to current schedule
11590            then set FCST_IND = FALSE */
11591 	IF sched_dtl_tab(i).stock_ind = 1 AND
11592           NOT (associate_forecasts(gschd_fcst_cnt,sched_dtl_tab(i).schedule_id))
11593         THEN
11594 		fcst_ind := FALSE;
11595 	/* Note that we are not Dis-associating the forecasts detail
11596 	  rows when stock_ind is turned OFF. Make sure that the
11597 	  forecast table is not used at all in such cases */
11598 	END IF ;   /* Stock Indicator  */
11599 
11600        old_schedule_id := sched_dtl_tab(i).schedule_id ;
11601     END IF;  /* Schedule ID match */
11602 
11603       -- If both stock_ind and order_ind are 0 , we should simply continue to
11604       -- the next record , the easiest method may be <<goto>>
11605 
11606        IF (fcst_ind) THEN
11607           IF (so_ind) THEN
11608               consume_forecast(sched_dtl_tab(i).inventory_item_id,
11609                                sched_dtl_tab(i).organization_id,api_mode) ;
11610            ELSE
11611     	       write_forecast(gfcst_cnt,sched_dtl_tab(i).inventory_item_id,
11612                               sched_dtl_tab(i).organization_id,api_mode ) ;
11613 	   END IF;
11614        ELSE
11615           IF (so_ind)  THEN
11616     		write_so(gso_cnt,sched_dtl_tab(i).inventory_item_id,
11617                           sched_dtl_tab(i).organization_id,api_mode ) ;
11618  	   END IF;
11619        END IF;
11620 
11621     END LOOP ;   /* Main Loop for Schedule, item, Warehouse */
11622 
11623     /* Bug 2756431 Moved the call to this function here per thisbug */
11624     /* the transfer demands and supplies need to be put under EACH of the
11625       demand schedules - Note that the supplies should NOT be replicated */
11626     FOR i IN 1..desig_tab.COUNT LOOP
11627       extract_inv_transfer_demands(pdblink, pinstance_id, prun_date,
11628       pdelimiter, desig_tab(i).whse_code,desig_tab(i).designator,
11629       local_ret_status);
11630     END LOOP ;
11631 
11632     return_status := local_ret_status ;
11633 
11634     Insert_Designator;
11635 
11636     log_message('End of MSC_CL_GMP_UTILITY.sales forecast') ;
11637     time_stamp ;
11638     return_status := TRUE;
11639 ELSE
11640   extract_forecasts( pdblink       ,
11641                           pinstance_id   ,
11642                           prun_date      ,
11643                           pdelimiter    ,
11644                           return_status  );
11645 
11646 END IF ; -- if NOT api_mode
11647   EXCEPTION
11648     WHEN NO_DATA_FOUND THEN /* B3577871 */
11649       log_message(' NO_DATA_FOUND exception raised in Procedure: MSC_CL_GMP_UTILITY.Sales_forecast ' );
11650       return_status := TRUE;
11651 
11652     WHEN OTHERS THEN
11653 	log_message('Failure occured during the Sales_Forecast extract');
11654 	log_message(sqlerrm);
11655         return_status := FALSE;
11656 END sales_forecast;
11657 
11658 /************************************************************************
11659 *   NAME
11660 *	sales_order_allocation
11661 *
11662 *   DESCRIPTION
11663 *  This procedure will have a new procedure to collect the additional data
11664 *  element for ASCP. OPM does not have sales order reservation
11665 *  functionality. Hence OM Reservation does not impact ic_tran_pnd. Only
11666 *  Allocation, which can be be done just after Order creation or after
11667 *  order is booked but before Shipping will create a  record in ic_tran_pnd
11668 *  table. Sales order Reservation Quantity is summation of allocated -
11669 *  quantity + remaining Quantity. We can Reserve/Allocate more than On hand
11670 *   committed quantity. These sales order item allocation record will be
11671 *  send to ASCP.
11672 *   For non-controlled items, no allocation/reservations are allowed
11673 *   and hence this enhancement will not send any information.
11674 *   The following enhancement will also support org specific
11675 *   collection for reservation entity. The net change
11676 *   functionality will not be supported by process code collection.
11677 *
11678 *   HISTORY
11679 *       Created By : B5501754 Rajesh Patangya
11680 ************************************************************************/
11681 PROCEDURE sales_order_allocation (
11682                           pdblink        IN  VARCHAR2,
11683                           pinstance_id   IN  NUMBER,
11684                           pentity        IN  NUMBER,
11685                           return_status  IN  OUT NOCOPY BOOLEAN)
11686 IS
11687 
11688 
11689    TYPE pld_cursor_typ IS REF CURSOR;
11690    ic_code_ref          pld_cursor_typ;
11691    bs_code_ref          pld_cursor_typ;
11692 
11693    ic_code_cursor       VARCHAR2(32000);
11694    bs_code_cursor       VARCHAR2(32000);
11695    l_profile            VARCHAR2(40) ;
11696    b_profile            VARCHAR2(70) ;
11697    pdoc_type            VARCHAR2(4) ;
11698    v_instance_id        NUMBER;
11699    v_entity             NUMBER;
11700    v_sql_stmt           VARCHAR2(32000);
11701 BEGIN
11702    v_instance_id := pinstance_id ;
11703    v_entity := pentity ;
11704    return_status := TRUE ;
11705    pdoc_type     := 'OMSO' ;
11706    l_profile := NULL ;
11707 
11708    /* This profile value holds the Defualt Location */
11709     ic_code_cursor   := ' select fnd_profile.VALUE' ||pdblink
11710                       ||' (''IC$DEFAULT_LOCT'') from dual ' ;
11711 
11712        OPEN ic_code_ref FOR ic_code_cursor ;
11713        FETCH ic_code_ref INTO l_profile;
11714        CLOSE ic_code_ref;
11715 
11716     bs_code_cursor   := ' select fnd_profile.VALUE' ||pdblink
11717                       ||' (''BIS_PRIMARY_RATE_TYPE'') from dual ' ;
11718 
11719        OPEN bs_code_ref FOR bs_code_cursor ;
11720        FETCH bs_code_ref INTO b_profile;
11721        CLOSE bs_code_ref;
11722 
11723     /* populate the org_string */
11724      IF MSC_CL_GMP_UTILITY.org_string(pinstance_id) THEN
11725         NULL ;
11726      ELSE
11727         RAISE invalid_string_value  ;
11728      END IF;
11729 
11730     IF v_entity = 1 THEN
11731 /* to consider ATP,
11732 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).
11733 2. Reservation record should be inserted in msc_sales_order table
11734 */
11735 
11736     v_sql_stmt := 'INSERT INTO MSC_ST_SALES_ORDERS ( '
11737    ||'    INVENTORY_ITEM_ID,'
11738    ||'    SOURCE_INVENTORY_ITEM_ID,'
11739    ||'    ORGANIZATION_ID,'
11740    ||'    PRIMARY_UOM_QUANTITY,'
11741    ||'    RESERVATION_TYPE, '
11742    ||'    RESERVATION_QUANTITY,'
11743    ||'    DEMAND_SOURCE_TYPE, '
11744    ||'    DEMAND_SOURCE_HEADER_ID,   '
11745    ||'    COMPLETED_QUANTITY,'
11746    ||'    SUBINVENTORY,'
11747    ||'    DEMAND_CLASS, '
11748    ||'    REQUIREMENT_DATE,'
11749    ||'    DEMAND_SOURCE_LINE, '
11750    ||'    SOURCE_DEMAND_SOURCE_LINE, '
11751    ||'    DEMAND_SOURCE_DELIVERY,'
11752    ||'    DEMAND_SOURCE_NAME,'
11753    ||'    PARENT_DEMAND_ID,'
11754    ||'    DEMAND_ID,'
11755    ||'    SOURCE_DEMAND_ID,'
11756    ||'    SALES_ORDER_NUMBER,'
11757    ||'    FORECAST_VISIBLE, '
11758    ||'    DEMAND_VISIBLE,'
11759    ||'    SALESREP_CONTACT,'
11760    ||'    SALESREP_ID,'
11761    ||'    CUSTOMER_ID,'
11762    ||'    SHIP_TO_SITE_USE_ID,'
11763    ||'    BILL_TO_SITE_USE_ID, '
11764    ||'    REQUEST_DATE, '
11765    ||'    PROJECT_ID, '
11766    ||'    TASK_ID, '
11767    ||'    PLANNING_GROUP,'
11768    ||'    SELLING_PRICE, '
11769    ||'    END_ITEM_UNIT_NUMBER, '
11770    ||'    ORDERED_ITEM_ID, '
11771    ||'    ORIGINAL_ITEM_ID,'
11772    ||'    LINK_TO_LINE_ID ,'
11773    ||'    CUST_PO_NUMBER, '
11774    ||'    CUSTOMER_LINE_NUMBER,'
11775    ||'    MFG_LEAD_TIME, '
11776    ||'    ORG_FIRM_FLAG,'
11777    ||'    SHIP_SET_ID, '
11778    ||'    ARRIVAL_SET_ID,'
11779    ||'    SHIP_SET_NAME, '
11780    ||'    ARRIVAL_SET_NAME,'
11781    ||'    ATP_REFRESH_NUMBER, '
11782    ||'    DELETED_FLAG, '
11783    ||'    ORIGINAL_SYSTEM_LINE_REFERENCE, '
11784    ||'    ORIGINAL_SYSTEM_REFERENCE, '
11785    ||'    CTO_FLAG, '
11786    ||'    AVAILABLE_TO_MRP,'
11787    ||'    DEMAND_PRIORITY,'
11788    ||'    PROMISE_DATE, '
11789    ||'    REFRESH_ID,'
11790    ||'    SR_INSTANCE_ID, '
11791    ||'    SCHEDULE_ARRIVAL_DATE, '
11792    ||'    LATEST_ACCEPTABLE_DATE,'
11793    ||'    SHIPPING_METHOD_CODE, '
11794    ||'    ATO_LINE_ID,'
11795    ||'    ORDER_DATE_TYPE_CODE,'
11796    ||'    INTRANSIT_LEAD_TIME '
11797    ||'   )  '
11798    ||'    SELECT '
11799    ||'    OOL.INVENTORY_ITEM_ID, '
11800    ||'    OOL.INVENTORY_ITEM_ID SOURCE_INVENTORY_ITEM_ID, '
11801    ||'    OOL.ORGANIZATION_ID, '
11802    ||'    (t.trans_qty * -1) PRIMARY_UOM_QUANTITY, '
11803    ||'    2 RESERVATION_TYPE, '
11804    ||'    TO_NUMBER(NULL) RESERVATION_QUANTITY, '
11805    ||'    decode(ool.SOURCE_DOCUMENT_TYPE_ID,10,8,2) DEMAND_SOURCE_TYPE, '
11806    ||'    so.SALES_ORDER_ID    DEMAND_SOURCE_HEADER_ID, '
11807    ||'    0 COMPLETED_QUANTITY, '
11808    ||'    TO_CHAR(NULL) SUBINVENTORY, '
11809    ||'    OOL.DEMAND_CLASS, '
11810    ||'    OOL.SCHEDULE_SHIP_DATE REQUIREMENT_DATE, '
11811    ||'    TO_CHAR(OOL.LINE_ID) DEMAND_SOURCE_LINE, '
11812    ||'    TO_CHAR(OOL.LINE_ID) SOURCE_DEMAND_SOURCE_LINE, '
11813    ||'    TO_CHAR(NULL) DEMAND_SOURCE_DELIVERY, '
11814    ||'    TO_CHAR(NULL) DEMAND_SOURCE_NAME, '
11815    ||'    TO_NUMBER(NULL) PARENT_DEMAND_ID, '
11816    ||'    MTL_DEMAND_S.nextval DEMAND_ID, '
11817    ||'    MTL_DEMAND_S.currval SOURCE_DEMAND_ID, '
11818    ||'    so.Concatenated_Segments, '
11819    ||'    ''Y'' , '
11820    ||'    ''Y'' , '
11821    ||'    TO_CHAR(NULL) Salesrep_Contact, '
11822    ||'    ool.salesrep_id, '
11823    ||'    ool.CUSTOMER_ID, '
11824    ||'    ool.SHIP_TO_SITE_ID, '
11825    ||'    ool.BILL_TO_SITE_ID, '
11826    ||'    ool.REQUEST_DATE, '
11827    ||'    ool.project_id, '
11828    ||'    ool.task_id, '
11829    ||'    TO_CHAR(NULL) PLANNING_GROUP, '
11830    ||'    ool.LIST_PRICE * decode(   GL_CURRENCY_API.get_rate_sql( '
11831    ||'				 h.transactional_curr_code, '
11832    ||'				 gsb.currency_code, '
11833    ||'				 h.booked_date, '
11834    ||'				 nvl(h.conversion_type_code, :b_prof1 )), '
11835    ||'				 -2,1,-1,1, '
11836    ||'				 GL_CURRENCY_API.get_rate_sql( '
11837    ||'				 h.transactional_curr_code, '
11838    ||'				 gsb.currency_code, '
11839    ||'				 h.booked_date, '
11840    ||'				 nvl(h.conversion_type_code, :b_prof2 )) '
11841    ||'				 ) LIST_PRICE, '
11842    ||'    ool.end_item_unit_number, '
11843    ||'    DECODE(DECODE(ool.ITEM_TYPE_CODE, '
11844    ||'          ''CLASS'',2, '
11845    ||'          ''CONFIG'',4, '
11846    ||'          ''MODEL'',1, '
11847    ||'          ''OPTION'' ,3, '
11848    ||'          ''STANDARD'',6, -1), 1, ool.inventory_item_id, NULL) ORDERED_ITEM_ID, '
11849    ||'    decode(ool.ORIGINAL_INVENTORY_ITEM_ID,-1,to_number(null), '
11850    ||'		  decode(ool.ITEM_RELATIONSHIP_TYPE,-1,to_number(null), '
11851    ||'						    2, ool.ORIGINAL_INVENTORY_ITEM_ID,  '
11852    ||'						    null,ool.ORIGINAL_INVENTORY_ITEM_ID,  '
11853    ||'						    to_number(null)) '
11854    ||'						    ) ORIGINAL_ITEM_ID, '
11855    ||'    TO_NUMBER(NULL) LINK_TO_LINE_ID, '
11856    ||'    nvl(ool.CUST_PO_NUMBER,''-1'') CUST_PO_NUMBER, '
11857    ||'    nvl(ool.CUSTOMER_LINE_NUMBER,''-1'') CUSTOMER_LINE_NUMBER, '
11858    ||'    ool.mfg_lead_time, '
11859    ||'    decode(ool.firm_demand_flag,NULL,to_number(null),''Y'',1,2) FIRM_DEMAND_FLAG, '
11860    ||'    ool.SHIP_SET_ID, '
11861    ||'    ool.ARRIVAL_SET_ID, '
11862    ||'    mrp_cl_function.get_ship_set_name(ool.SHIP_SET_ID) SHIP_SET_NAME, '
11863    ||'    mrp_cl_function.get_arrival_set_name(ool.ARRIVAL_SET_ID) ARRIVAL_SET_NAME, '
11864    ||'    TO_NUMBER(NULL) ATP_REFRESH_NUMBER, '
11865    ||'    2 DELETED_FLAG, '
11866    ||'    ool.original_system_reference, '
11867    ||'    ool.original_system_line_reference, '
11868    ||'    2 CTO_FLAG, '
11869    ||'    TO_NUMBER(NULL) available_to_mrp, '
11870    ||'    ool.DEMAND_PRIORITY, '
11871    ||'    ool.PROMISE_DATE, '
11872    ||'    TO_NUMBER(NULL) refresh_id, '
11873    ||'    :instance_id, '
11874    ||'    ool.SCHEDULE_ARRIVAL_DATE, '
11875    ||'    ool.LATEST_ACCEPTABLE_DATE, '
11876    ||'    ool.SHIPPING_METHOD_CODE, '
11877    ||'    ool.ATO_LINE_ID, '
11878    ||'    decode(h.ORDER_DATE_TYPE_CODE,''ARRIVAL'',2,1) ORDER_DATE_TYPE_CODE, '
11879    ||'    OOL.DELIVERY_LEAD_TIME  '
11880    ||'    FROM  '
11881    ||'        MRP_SN_SYS_ITEMS msik, '
11882    ||'        MTL_SALES_ORDERS_KFV so, '
11883    ||'        OE_ORDER_HEADERS_ALL h,       '
11884    ||'        GL_SETS_OF_BOOKS gsb, '
11885    ||'        AR_SYSTEM_PARAMETERS_ALL aspa   , '
11886    ||'        IC_TRAN_PND  t , '
11887    ||'        GMP_ITEM_APS i , '
11888    ||'        MRP_SN_ODR_LINES ool '
11889    ||'    WHERE  '
11890    ||'      t.item_id = i.item_id  '
11891    ||'      AND t.doc_type = :p_doc_type '
11892    ||'      AND ool.line_id = t.line_id '
11893    ||'      AND ( t.lot_id <> 0 OR t.location <> :p_prof ) '
11894    ||'      AND t.whse_code = i.whse_code  '
11895    ||'      AND t.orgn_code = i.plant_code  '
11896    ||'      AND t.completed_ind = 0  '
11897    ||'      AND t.trans_qty <> 0  '
11898    ||'      AND t.delete_mark = 0 '
11899    ||'      AND msik.inventory_item_id = i.aps_item_id '
11900    ||'      AND msik.organization_id = i.organization_id '
11901    ||'      AND so.Sales_Order_ID = t.doc_id  '
11902    ||'      AND ool.header_id = h.header_id(+) '
11903    ||'      AND h.org_id = aspa.org_id(+) '
11904    ||'      AND aspa.set_of_books_id = gsb.set_of_books_id(+) '
11905    ||'      AND h.org_id is not null ' ;
11906 
11907      IF MSC_CL_GMP_UTILITY.g_in_str_org  IS NOT NULL THEN
11908      v_sql_stmt := v_sql_stmt
11909      || '  AND i.organization_id ' || MSC_CL_GMP_UTILITY.g_in_str_org ;
11910      END IF;
11911 
11912     EXECUTE IMMEDIATE v_sql_stmt USING
11913       b_profile, b_profile, v_instance_id, pdoc_type, l_profile  ;
11914 
11915     v_sql_stmt := 'INSERT INTO MSC_ST_SALES_ORDERS ( '
11916    ||'    INVENTORY_ITEM_ID,'
11917    ||'    SOURCE_INVENTORY_ITEM_ID,'
11918    ||'    ORGANIZATION_ID,'
11919    ||'    PRIMARY_UOM_QUANTITY,'
11920    ||'    RESERVATION_TYPE, '
11921    ||'    RESERVATION_QUANTITY,'
11922    ||'    DEMAND_SOURCE_TYPE, '
11923    ||'    DEMAND_SOURCE_HEADER_ID,   '
11924    ||'    COMPLETED_QUANTITY,'
11925    ||'    SUBINVENTORY,'
11926    ||'    DEMAND_CLASS, '
11927    ||'    REQUIREMENT_DATE,'
11928    ||'    DEMAND_SOURCE_LINE, '
11929    ||'    SOURCE_DEMAND_SOURCE_LINE, '
11930    ||'    DEMAND_SOURCE_DELIVERY,'
11931    ||'    DEMAND_SOURCE_NAME,'
11932    ||'    PARENT_DEMAND_ID,'
11933    ||'    DEMAND_ID,'
11934    ||'    SOURCE_DEMAND_ID,'
11935    ||'    SALES_ORDER_NUMBER,'
11936    ||'    FORECAST_VISIBLE, '
11937    ||'    DEMAND_VISIBLE,'
11938    ||'    SALESREP_CONTACT,'
11939    ||'    SALESREP_ID,'
11940    ||'    CUSTOMER_ID,'
11941    ||'    SHIP_TO_SITE_USE_ID,'
11942    ||'    BILL_TO_SITE_USE_ID, '
11943    ||'    REQUEST_DATE, '
11944    ||'    PROJECT_ID, '
11945    ||'    TASK_ID, '
11946    ||'    PLANNING_GROUP,'
11947    ||'    SELLING_PRICE, '
11948    ||'    END_ITEM_UNIT_NUMBER, '
11949    ||'    ORDERED_ITEM_ID, '
11950    ||'    ORIGINAL_ITEM_ID,'
11951    ||'    LINK_TO_LINE_ID ,'
11952    ||'    CUST_PO_NUMBER, '
11953    ||'    CUSTOMER_LINE_NUMBER,'
11954    ||'    MFG_LEAD_TIME, '
11955    ||'    ORG_FIRM_FLAG,'
11956    ||'    SHIP_SET_ID, '
11957    ||'    ARRIVAL_SET_ID,'
11958    ||'    SHIP_SET_NAME, '
11959    ||'    ARRIVAL_SET_NAME,'
11960    ||'    ATP_REFRESH_NUMBER, '
11961    ||'    DELETED_FLAG, '
11962    ||'    ORIGINAL_SYSTEM_LINE_REFERENCE, '
11963    ||'    ORIGINAL_SYSTEM_REFERENCE, '
11964    ||'    CTO_FLAG, '
11965    ||'    AVAILABLE_TO_MRP,'
11966    ||'    DEMAND_PRIORITY,'
11967    ||'    PROMISE_DATE, '
11968    ||'    REFRESH_ID,'
11969    ||'    SR_INSTANCE_ID, '
11970    ||'    SCHEDULE_ARRIVAL_DATE, '
11971    ||'    LATEST_ACCEPTABLE_DATE,'
11972    ||'    SHIPPING_METHOD_CODE, '
11973    ||'    ATO_LINE_ID,'
11974    ||'    ORDER_DATE_TYPE_CODE,'
11975    ||'    INTRANSIT_LEAD_TIME '
11976    ||'   )  '
11977    ||'    SELECT '
11978    ||'    OOL.INVENTORY_ITEM_ID, '
11979    ||'    OOL.INVENTORY_ITEM_ID SOURCE_INVENTORY_ITEM_ID, '
11980    ||'    OOL.ORGANIZATION_ID, '
11981    ||'    (t.trans_qty * -1 ) PRIMARY_UOM_QUANTITY, '
11982    ||'    2 RESERVATION_TYPE, '
11983    ||'    TO_NUMBER(NULL) RESERVATION_QUANTITY, '
11984    ||'    decode(ool.SOURCE_DOCUMENT_TYPE_ID,10,8,2) DEMAND_SOURCE_TYPE, '
11985    ||'    so.SALES_ORDER_ID    DEMAND_SOURCE_HEADER_ID, '
11986    ||'    0 COMPLETED_QUANTITY, '
11987    ||'    TO_CHAR(NULL) SUBINVENTORY, '
11988    ||'    OOL.DEMAND_CLASS, '
11989    ||'    OOL.SCHEDULE_SHIP_DATE REQUIREMENT_DATE, '
11990    ||'    TO_CHAR(OOL.LINE_ID) DEMAND_SOURCE_LINE, '
11991    ||'    TO_CHAR(OOL.LINE_ID) SOURCE_DEMAND_SOURCE_LINE, '
11992    ||'    TO_CHAR(NULL) DEMAND_SOURCE_DELIVERY, '
11993    ||'    TO_CHAR(NULL) DEMAND_SOURCE_NAME, '
11994    ||'    TO_NUMBER(NULL) PARENT_DEMAND_ID, '
11995    ||'    MTL_DEMAND_S.nextval DEMAND_ID, '
11996    ||'    MTL_DEMAND_S.currval SOURCE_DEMAND_ID, '
11997    ||'    so.Concatenated_Segments, '
11998    ||'    ''Y'' , '
11999    ||'    ''Y'' , '
12000    ||'    TO_CHAR(NULL) Salesrep_Contact, '
12001    ||'    ool.salesrep_id, '
12002    ||'    ool.CUSTOMER_ID, '
12003    ||'    ool.SHIP_TO_SITE_ID, '
12004    ||'    ool.BILL_TO_SITE_ID, '
12005    ||'    ool.REQUEST_DATE, '
12006    ||'    ool.project_id, '
12007    ||'    ool.task_id, '
12008    ||'    TO_CHAR(NULL) PLANNING_GROUP, '
12009    ||'    ool.LIST_PRICE * decode(   GL_CURRENCY_API.get_rate_sql( '
12010    ||'				 h.transactional_curr_code, '
12011    ||'				 gsb.currency_code, '
12012    ||'				 h.booked_date, '
12013    ||'				 nvl(h.conversion_type_code, :b_prof1 )), '
12014    ||'				 -2,1,-1,1, '
12015    ||'				 GL_CURRENCY_API.get_rate_sql( '
12016    ||'				 h.transactional_curr_code, '
12017    ||'				 gsb.currency_code, '
12018    ||'				 h.booked_date, '
12019    ||'				 nvl(h.conversion_type_code, :b_prof2 )) '
12020    ||'				 ) LIST_PRICE, '
12021    ||'    ool.end_item_unit_number, '
12022    ||'    DECODE(DECODE(ool.ITEM_TYPE_CODE, '
12023    ||'          ''CLASS'',2, '
12024    ||'          ''CONFIG'',4, '
12025    ||'          ''MODEL'',1, '
12026    ||'          ''OPTION'' ,3, '
12027    ||'          ''STANDARD'',6, -1), 1, ool.inventory_item_id, NULL) ORDERED_ITEM_ID, '
12028    ||'    decode(ool.ORIGINAL_INVENTORY_ITEM_ID,-1,to_number(null), '
12029    ||'		  decode(ool.ITEM_RELATIONSHIP_TYPE,-1,to_number(null), '
12030    ||'						    2, ool.ORIGINAL_INVENTORY_ITEM_ID,  '
12031    ||'						    null,ool.ORIGINAL_INVENTORY_ITEM_ID,  '
12032    ||'						    to_number(null)) '
12033    ||'						    ) ORIGINAL_ITEM_ID, '
12034    ||'    TO_NUMBER(NULL) LINK_TO_LINE_ID, '
12035    ||'    nvl(ool.CUST_PO_NUMBER,''-1'') CUST_PO_NUMBER, '
12036    ||'    nvl(ool.CUSTOMER_LINE_NUMBER,''-1'') CUSTOMER_LINE_NUMBER, '
12037    ||'    ool.mfg_lead_time, '
12038    ||'    decode(ool.firm_demand_flag,NULL,to_number(null),''Y'',1,2) FIRM_DEMAND_FLAG, '
12039    ||'    ool.SHIP_SET_ID, '
12040    ||'    ool.ARRIVAL_SET_ID, '
12041    ||'    mrp_cl_function.get_ship_set_name(ool.SHIP_SET_ID) SHIP_SET_NAME, '
12042    ||'    mrp_cl_function.get_arrival_set_name(ool.ARRIVAL_SET_ID) ARRIVAL_SET_NAME, '
12043    ||'    TO_NUMBER(NULL) ATP_REFRESH_NUMBER, '
12044    ||'    2 DELETED_FLAG, '
12045    ||'    ool.original_system_reference, '
12046    ||'    ool.original_system_line_reference, '
12047    ||'    2 CTO_FLAG, '
12048    ||'    TO_NUMBER(NULL) available_to_mrp, '
12049    ||'    ool.DEMAND_PRIORITY, '
12050    ||'    ool.PROMISE_DATE, '
12051    ||'    TO_NUMBER(NULL) refresh_id, '
12052    ||'    :instance_id, '
12053    ||'    ool.SCHEDULE_ARRIVAL_DATE, '
12054    ||'    ool.LATEST_ACCEPTABLE_DATE, '
12055    ||'    ool.SHIPPING_METHOD_CODE, '
12056    ||'    ool.ATO_LINE_ID, '
12057    ||'    decode(h.ORDER_DATE_TYPE_CODE,''ARRIVAL'',2,1) ORDER_DATE_TYPE_CODE, '
12058    ||'    OOL.DELIVERY_LEAD_TIME  '
12059    ||'    FROM  '
12060    ||'        MRP_SN_SYS_ITEMS msik, '
12061    ||'        MTL_SALES_ORDERS_KFV so, '
12062    ||'        OE_ORDER_HEADERS_ALL h,       '
12063    ||'        GL_SETS_OF_BOOKS gsb, '
12064    ||'        AR_SYSTEM_PARAMETERS_ALL aspa   , '
12065    ||'        IC_TRAN_PND  t , '
12066    ||'        GMP_ITEM_APS i , '
12067    ||'        MRP_SN_ODR_LINES ool '
12068    ||'    WHERE  '
12069    ||'      t.item_id = i.item_id  '
12070    ||'      AND t.doc_type = :p_doc_type '
12071    ||'      AND ool.line_id = t.line_id '
12072    ||'      AND ( t.lot_id <> 0 OR t.location <> :p_prof ) '
12073    ||'      AND t.whse_code = i.whse_code  '
12074    ||'      AND t.orgn_code = i.plant_code  '
12075    ||'      AND t.completed_ind = 0  '
12076    ||'      AND t.trans_qty <> 0  '
12077    ||'      AND t.delete_mark = 0 '
12078    ||'      AND msik.inventory_item_id = i.aps_item_id '
12079    ||'      AND msik.organization_id = i.organization_id '
12080    ||'      AND so.Sales_Order_ID = t.doc_id  '
12081    ||'      AND ool.header_id = h.header_id(+) '
12082    ||'      AND  nvl(h.org_id,-99) = nvl(aspa.org_id,-99) '
12083    ||'      AND aspa.set_of_books_id = gsb.set_of_books_id(+) '
12084    ||'      AND h.org_id is null  ' ;
12085 
12086      IF MSC_CL_GMP_UTILITY.g_in_str_org  IS NOT NULL THEN
12087      v_sql_stmt := v_sql_stmt
12088      || '  AND i.organization_id ' || MSC_CL_GMP_UTILITY.g_in_str_org ;
12089      END IF;
12090 
12091     EXECUTE IMMEDIATE v_sql_stmt USING
12092       b_profile, b_profile, v_instance_id, pdoc_type, l_profile  ;
12093 
12094     END IF ;
12095 
12096     IF v_entity = 2 THEN
12097    log_message(MSC_CL_GMP_UTILITY.g_in_str_org);
12098 
12099    /* For Engine Reseration record inserted */
12100    v_sql_stmt := 'INSERT into msc_st_reservations ('
12101     || ' inventory_item_id,'
12102     || ' organization_id,'
12103     || ' sr_instance_id,'
12104     || ' transaction_id,'
12105     || ' parent_demand_id,'
12106     || ' disposition_id ,'
12107     || ' requirement_date,'
12108     || ' reserved_quantity,'
12109     || ' disposition_type,'
12110     || ' subinventory,'
12111     || ' reservation_type,'
12112     || ' demand_class,'
12113     || ' available_to_mrp,'
12114     || ' reservation_flag,'
12115     || ' planning_group,'
12116     || ' deleted_flag'
12117     || ' )'
12118     || ' SELECT '
12119     || '    i.aps_item_id, '
12120     || '    ool.organization_id, '
12121     || '    :p_instance_id , '
12122     || '    ((t.doc_id * 2 ) + 1), '  /* MTL_SALES_ORDERS.SALES_ORDER_ID */
12123     || '    ool.line_id, '
12124     || '    INV_SALESORDER.GET_SALESORDER_FOR_OEHEADER(ool.HEADER_ID), '
12125     || '    t.trans_date , '
12126     || '    (t.trans_qty * -1 ), '
12127     || '    2, '    /* DISPOSITION_TYPE */
12128     || '    NULL, ' /* SUBINVENTORY */
12129     || '    1,  '   /* RESERVATION_TYPE 1 is for Discrete ?? */
12130     || '    ool.demand_class, ' /* DEMAND_CLASS CODE */
12131     || '    NULL, ' /* AVAILABLE_TO_MRP */
12132     || '    2,  '   /* RESERVATION_FLAG */
12133     || '    NULL, ' /* PLANNING_GROUP */
12134     || '    2  '
12135     || ' FROM '
12136     || '   ic_tran_pnd' ||pdblink|| ' t,'
12137     || '   gmp_item_aps'||pdblink|| ' i,'
12138     || '   MRP_SN_ODR_LINES'||pdblink|| ' ool'
12139     || ' WHERE '
12140     || '     t.doc_type = :p_doctype '
12141     || ' AND t.item_id = i.item_id '
12142     || ' AND ool.line_id = t.line_id'
12143     || ' AND ( t.lot_id <> 0 OR '
12144     || '   t.location <> :loc_profile ) '
12145     || ' AND t.whse_code = i.whse_code '
12146     || ' AND t.orgn_code = i.plant_code '
12147     || ' AND t.completed_ind = 0 '
12148     || ' and ool.open_flag = ' || '''Y'''
12149     || ' AND t.trans_qty <> 0 '
12150     || ' AND t.delete_mark = 0 ' ;
12151 
12152      IF MSC_CL_GMP_UTILITY.g_in_str_org  IS NOT NULL THEN
12153      v_sql_stmt := v_sql_stmt
12154      || ' and i.organization_id ' || MSC_CL_GMP_UTILITY.g_in_str_org ;
12155      END IF;
12156 
12157     EXECUTE IMMEDIATE v_sql_stmt USING v_instance_id, pdoc_type, l_profile ;
12158 
12159     END IF; /* pentity */
12160 
12161 EXCEPTION
12162    WHEN NO_DATA_FOUND THEN
12163       log_message(' NO DATA FOUND exception in: MSC_CL_GMP_UTILITY.sales_order_allocation');
12164       return_status := TRUE;
12165     WHEN invalid_string_value  THEN
12166         log_message('Organization string is Invalid ' );
12167         return_status := FALSE;
12168     WHEN OTHERS THEN
12169       log_message('Failure occured during the sales_order_allocation extract');
12170       log_message(sqlerrm);
12171       return_status := FALSE;
12172 END sales_order_allocation;
12173 
12174 /************************************************************************
12175 *   NAME
12176 *	extract_forecasts
12177 *
12178 *   DESCRIPTION
12179 *
12180 *
12181 *
12182 *   HISTORY
12183 *       Created By : Abhay Satpute
12184 *		24-Oct-2003 Chnaged origincation_type to 29
12185 ************************************************************************/
12186 PROCEDURE extract_forecasts ( pdblink        IN  VARCHAR2,
12187                           pinstance_id   IN  NUMBER,
12188                           prun_date      IN  DATE,
12189                           pdelimiter     IN  VARCHAR2,
12190                           return_status  IN  OUT NOCOPY BOOLEAN)
12191 IS
12192 
12193 TYPE gmp_cursor_typ IS REF CURSOR;
12194 fcst_hdr   	gmp_cursor_typ;
12195 cur_fcst_dtl   	gmp_cursor_typ;
12196 
12197 l_design_stmt   	VARCHAR2(32000) ;
12198 l_fcst_stmt             VARCHAR2(32700) ; /* Bug # 5086464 */
12199 l_demands_stmt 		VARCHAR2(32000) ;
12200 l_insert_set_stmt 	VARCHAR2(32000);
12201 
12202 TYPE fcst_hdr_rec IS RECORD (
12203 fcst_id 		NUMBER,
12204 orig_forecast 		VARCHAR2(16),
12205 fcst_name 		VARCHAR2(10),
12206 fcst_set  		VARCHAR2(10),
12207 desgn_ind 		NUMBER,
12208 consumption_ind		NUMBER,
12209 backward_time_fence	NUMBER,
12210 forward_time_fence	NUMBER
12211 );
12212 TYPE fcst_dtl_rec_typ IS RECORD
12213    (
12214     inventory_item_id   NUMBER,
12215     organization_id     NUMBER,
12216     forecast_id         NUMBER,
12217     line_id             NUMBER,
12218     forecast            VARCHAR2(16),
12219     forecast_set        VARCHAR2(10),
12220     trans_date          DATE,
12221     orgn_code           VARCHAR2(4),
12222     trans_qty           NUMBER,
12223     use_fcst_flag       NUMBER
12224   );
12225 fcst_dtl_rec fcst_dtl_rec_typ ;
12226 
12227 TYPE fcst_hdr_tab_typ IS TABLE OF fcst_hdr_rec
12228 INDEX BY BINARY_INTEGER ;
12229 fcst_hdr_tbl fcst_hdr_tab_typ ;
12230 
12231 cnt             	NUMBER ;
12232 l_cnt           	NUMBER ;
12233 curr_cnt        	NUMBER ;
12234 temp_name       	VARCHAR2(10) ;
12235 i               	NUMBER ;
12236 j               	NUMBER ;
12237 k               	NUMBER ;
12238 x 			NUMBER ;
12239 duplicate_found 	BOOLEAN ;
12240 prev_org_id  		NUMBER ;
12241 prev_fcst_id	  	NUMBER ;
12242 prev_fcst_set		VARCHAR2(10);
12243 prev_fcst    		VARCHAR2(10);
12244 write_fcst		BOOLEAN ;
12245 write_fcst_set		BOOLEAN ;
12246 fcst_locn		NUMBER ;
12247 
12248 BEGIN
12249 cnt             	:= 0 ;
12250 l_cnt           	:= 1 ;
12251 curr_cnt        	:= 0 ;
12252 temp_name       	:= NULL ;
12253 i               	:= 1 ;
12254 j               	:= 10 ;
12255 k               	:= 0;
12256 x 			:= 1;
12257 duplicate_found 	:= FALSE ;
12258 prev_org_id  		:= 0 ;
12259 prev_fcst_id	  	:= 0 ;
12260 d_index                 := 0 ;
12261 i_index                 := 0 ;
12262 prev_fcst_set           := '-1' ;
12263 prev_fcst               := '-1';
12264 
12265     /* populate the org_string */
12266      IF MSC_CL_GMP_UTILITY.org_string(pinstance_id) THEN
12267         NULL ;
12268      ELSE
12269         RAISE invalid_string_value  ;
12270      END IF;
12271 
12272 l_fcst_stmt := 'SELECT '
12273           || ' msi.inventory_item_id, '
12274           || ' msi.organization_id, '
12275           || ' h.forecast_id, '
12276           || ' d.line_id, '
12277           || ' h.forecast, '
12278           || ' h.forecast_set  FSET , '
12279           || ' d.trans_date, '
12280           || ' d.orgn_code, '
12281           || ' (d.trans_qty * -1)  trans_qty, '
12282           || ' 0 use_fcst_flag '
12283           || ' FROM '
12284           || ' mtl_system_items'||pdblink||' msi, '
12285           || ' ic_item_mst'||pdblink||' iim, '
12286           || ' ic_whse_mst'||pdblink||' wm, '
12287           || ' fc_fcst_hdr'||pdblink||' h, '
12288           || ' fc_fcst_dtl'||pdblink||' d '
12289           || ' WHERE '
12290           || '     msi.organization_id = wm.mtl_organization_id ' ;
12291 
12292         IF MSC_CL_GMP_UTILITY.g_in_str_org  IS NOT NULL THEN
12293         l_fcst_stmt := l_fcst_stmt
12294           || ' and msi.organization_id ' || MSC_CL_GMP_UTILITY.g_in_str_org ;
12295         END IF;
12296 
12297         l_fcst_stmt := l_fcst_stmt
12298           || ' and msi.segment1 = iim.item_no '
12299           || ' and wm.delete_mark = 0 '
12300           || ' and h.forecast_id = d.forecast_id '
12301           || ' and d.forecast_id > 0  '
12302           || ' and d.item_id = iim.item_id '
12303           || ' and d.whse_code = wm.whse_code '
12304           || ' and d.orgn_code = wm.orgn_code '
12305           || ' and h.forecast_set is NOT NULL '
12306           || ' and h.delete_mark = 0 '
12307           || ' and d.delete_mark = 0 '
12308           || ' and d.trans_qty <> 0 '
12309           || ' ORDER BY wm.mtl_organization_id ,FSET DESC,h.forecast_id ' ;
12310 
12311 l_insert_set_stmt  :=
12312         ' INSERT INTO msc_st_designators ( '
12313       ||' designator,forecast_set, organization_id, sr_instance_id, '
12314       ||' description, mps_relief, inventory_atp_flag, '
12315       ||' designator_type,disable_date,consume_forecast, '
12316       ||' update_type,backward_update_time_fence,forward_update_time_fence, '
12317       ||' bucket_type,deleted_flag,refresh_id ) '
12318       ||' VALUES '
12319       ||' ( :p1, :p2, :p3,:p4, '
12320       ||'   :p5, :p6, :p7, '
12321       ||'   :p8, :p9, :p10, '
12322       ||'   :p11, :p12, :p13, '
12323       ||'   :p14,:p15,:p16 ) ';
12324 
12325 l_demands_stmt  :=
12326       ' INSERT INTO msc_st_demands ( '
12327     ||' organization_id, inventory_item_id, sr_instance_id, '
12328     ||' using_assembly_item_id, using_assembly_demand_date, '
12329     ||' using_requirement_quantity,demand_class,bucket_type, '
12330     ||' demand_type, origination_type, wip_entity_id, '
12331     ||' demand_schedule_name,forecast_designator, order_number,'
12332     ||' wip_entity_name,sales_order_line_id, selling_price, deleted_flag ) '
12333     ||' VALUES '
12334     ||' ( :p1, :p2, :p3,  '
12335     ||'   :p4, :p5, :p6, '
12336     ||'   :p7, :p8, :p9, '
12337     ||'   :p10,:p11,:p12, '
12338     ||'   :p13,:p14,:p15, '
12339     ||'   :p16,:p17,:p18 )' ;
12340 
12341 -- ===+++++++====++++ build designator++++=======++++=======
12342 l_design_stmt := 'SELECT '||
12343 ' forecast_id, '||
12344 ' forecast, '||
12345 ' substr(forecast,1,10) DESGN, '||
12346 ' nvl(forecast_set ,substr(forecast,1,10)) FSET,  '||
12347 ' 1 DESGN_IND ,' ||
12348 ' consumption_ind, '||
12349 ' backward_time_fence, '||
12350 ' forward_time_fence '||
12351 ' FROM fc_fcst_hdr'||pdbLink ||
12352 ' WHERE delete_mark = 0 '||
12353 ' UNION ALL '||
12354 -- Add forecast_sets to the list
12355 ' SELECT '||
12356 ' -1 , '||
12357 ' min(forecast), '||
12358 ' forecast_set DESGN , '||
12359 ' to_char(NULL) FSET,  '||
12360 ' 3 DESGN_IND, ' ||
12361 ' to_number(NULL), '||
12362 ' to_number(NULL), '||
12363 ' to_number(NULL) '||
12364 ' FROM fc_fcst_hdr'||pdblink ||
12365 ' WHERE delete_mark = 0 '||
12366 ' AND forecast_set is NOT NULL '||
12367 ' GROUP BY forecast_set '  ||
12368 ' ORDER BY FSET, 1 DESC , DESGN_IND ' ;
12369 -- Add fabricated forecast-set to the list
12370 /* Per discussions with Sam Tupe Forecast set name is NOT allowed to be changed
12371  Hence we should NOT collect the forecasts that do NOT have a forecast set */
12372 /*
12373 ' UNION ALL '||
12374 ' SELECT '||
12375 ' -1, '||
12376 ' forecast, '||
12377 ' substr(forecast,1,10) DESGN_IND , '||
12378 ' to_char(NULL) FSET, '||
12379 ' 2 DESGN_IND,  '||
12380 ' to_number(NULL), '||
12381 ' to_number(NULL), '||
12382 ' to_number(NULL) '||
12383 ' FROM fc_fcst_hdr'||pdblink ||
12384 ' WHERE delete_mark = 0 '||
12385 ' AND forecast_set is NULL '||
12386 --   With these changes some logic in designator generation has become redundant
12387 */
12388 
12389 OPEN  fcst_hdr for l_design_stmt ;
12390 LOOP
12391 FETCH fcst_hdr INTO fcst_hdr_tbl(l_cnt);
12392 EXIT WHEN fcst_hdr%NOTFOUND ;
12393 l_cnt := l_cnt + 1 ;
12394 END LOOP ;
12395 CLOSE fcst_hdr ;
12396 -- ===================== Logic ==============================
12397 LOOP
12398 EXIT  WHEN cnt + 1 > fcst_hdr_tbl.COUNT ;
12399 
12400 IF duplicate_found THEN
12401  cnt := cnt ;
12402  duplicate_found := FALSE ;
12403 ELSE
12404  IF temp_name is NOT NULL THEN
12405  IF (fcst_hdr_tbl(cnt).desgn_ind =  1
12406 	AND fcst_hdr_tbl(cnt).fcst_name <> temp_name )THEN
12407 --  	fcst_hdr_tbl(cnt).fcst_set := temp_name ;
12408    NULL ;
12409  ELSIF (fcst_hdr_tbl(cnt).desgn_ind =  3
12410 	AND fcst_hdr_tbl(cnt).fcst_name <> temp_name )THEN
12411   -- This means we changed a set name
12412   -- Now change the name in all resords of fcst that used this as set
12413   FOR y in 1..fcst_hdr_tbl.COUNT
12414   LOOP
12415    IF (fcst_hdr_tbl(y).fcst_set = fcst_hdr_tbl(cnt).fcst_name
12416 	AND fcst_hdr_tbl(y).desgn_ind =  1 ) THEN
12417 	fcst_hdr_tbl(y).fcst_set := temp_name  ;
12418    END IF ;
12419   END LOOP;
12420  ELSIF (fcst_hdr_tbl(cnt).desgn_ind = 2
12421             AND fcst_hdr_tbl(cnt).fcst_name <> temp_name )THEN
12422   -- This means we changed a set name that was "generated"
12423   -- Now change the name in the resord of fcst that used itself as set
12424   FOR y in 1..fcst_hdr_tbl.COUNT
12425   LOOP
12426    IF (fcst_hdr_tbl(y).orig_forecast = fcst_hdr_tbl(cnt).orig_forecast
12427 	AND fcst_hdr_tbl(y).desgn_ind  = 1 )THEN
12428         fcst_hdr_tbl(y).fcst_set := temp_name  ;
12429    END IF ;
12430   END LOOP;
12431  END IF ; -- desgn_ind check
12432  fcst_hdr_tbl(cnt).fcst_name := temp_name ;
12433 
12434  END IF ;
12435 
12436  cnt := cnt  + 1 ;
12437  j := 10 ;
12438  k := 0 ;
12439 END IF ;
12440 
12441  IF j < 10 THEN
12442     temp_name := substr(fcst_hdr_tbl(cnt).fcst_name,1,j)||to_char(k) ;
12443  ELSE
12444     temp_name := fcst_hdr_tbl(cnt).fcst_name ;
12445  END IF ;
12446 
12447 curr_cnt := cnt ;
12448 
12449 i := 1 ;
12450 
12451 LOOP
12452 EXIT WHEN i > fcst_hdr_tbl.COUNT ;
12453 
12454 IF i <> curr_cnt THEN
12455 -- so that record is not compared to itself
12456  IF temp_name  = fcst_hdr_tbl(i).fcst_name THEN
12457    duplicate_found := TRUE ;
12458    k := k + 1 ;
12459 
12460   IF k < 10 THEN
12461      j := 9 ;
12462   ELSIF k < 100 THEN
12463      j := 8 ;
12464   ELSIF k < 1000 THEN
12465      j := 7 ;
12466   ELSIF k < 10000 THEN
12467      j := 6 ;
12468   ELSIF k < 100000 THEN
12469      j := 5 ;
12470   END IF ;
12471 
12472   EXIT ;
12473 
12474  END IF ;
12475 END IF ; -- i <> curr_cnt
12476 
12477 i := i + 1 ;
12478 END LOOP ;
12479 
12480 
12481 END LOOP ; -- Outer loop
12482 
12483 /*
12484 FOR x in 1..fcst_hdr_tbl.COUNT
12485 LOOP
12486 log_message(fcst_hdr_tbl(x).fcst_id||
12487 		'='||fcst_hdr_tbl(x).orig_forecast ||
12488 		'='||fcst_hdr_tbl(x).desgn_ind ||
12489 		'='||fcst_hdr_tbl(x).fcst_name ||
12490 		'='||fcst_hdr_tbl(x).fcst_set ) ;
12491 END LOOP;
12492 */
12493 -- ===+++++++====++++ build designator++++=======++++=======
12494 
12495     OPEN cur_fcst_dtl FOR l_fcst_stmt;
12496     LOOP
12497 	write_fcst     := FALSE ;
12498 	write_fcst_set := FALSE ;
12499 
12500 	FETCH cur_fcst_dtl INTO fcst_dtl_rec;
12501 	EXIT WHEN cur_fcst_dtl%NOTFOUND;
12502 	IF fcst_dtl_rec.organization_id <> prev_org_id THEN
12503 	  -- Write an entry for forecast
12504 	  write_fcst     := TRUE ;
12505 	  write_fcst_set := TRUE ;
12506 	 prev_org_id := fcst_dtl_rec.organization_id ;
12507 	END IF ;
12508 	  -- also check if the set has changed ,if so write an entry for set
12509 	IF fcst_dtl_rec.forecast_id <> prev_fcst_id THEN
12510 	  write_fcst := TRUE ;
12511 	  -- get designator, forecast_name
12512 	  -- Temporarily putting a code - inefficient
12513 	  FOR i in 1..fcst_hdr_tbl.COUNT
12514 	  LOOP
12515 	    IF fcst_dtl_rec.forecast_id = fcst_hdr_tbl(i).fcst_id THEN
12516 		fcst_locn := i  ;
12517 		EXIT ;
12518 	    END IF ;
12519           END LOOP ;
12520 	  IF fcst_hdr_tbl(fcst_locn).fcst_set <> prev_fcst_set THEN
12521 	    -- insert set name for currrent org
12522 	    write_fcst_set := TRUE ;
12523 	  END IF ; -- end if for change of fcst_set
12524 	END IF ; -- endif of fcst_is change
12525 
12526 	prev_fcst	:= nvl(fcst_hdr_tbl(fcst_locn).fcst_name ,'-2');
12527 	prev_fcst_id := fcst_dtl_rec.forecast_id ;
12528 
12529 	IF write_fcst_set THEN
12530 
12531           i_index := i_index + 1 ;
12532           i_designator(i_index) :=  fcst_hdr_tbl(fcst_locn).fcst_set ;
12533           i_forecast_set(i_index) :=  to_char(NULL) ;
12534           i_organization_id(i_index) :=  fcst_dtl_rec.organization_id ;
12535           i_sr_instance_id(i_index) := pinstance_id ;
12536           i_description(i_index) :=  fcst_hdr_tbl(fcst_locn).fcst_set ;
12537           -- mps_relief(i_index) :=  0;  /* mps relief */
12538           -- inventory_atp_flag(i_index) := 0;  /* inventory atp flag */
12539           -- designator_type(i_index) := 6;  /* designator type */
12540           i_disable_date(i_index) := TO_DATE(NULL);  /* disable date */
12541           i_consume_forecast(i_index) := fcst_hdr_tbl(fcst_locn).consumption_ind ;
12542           -- update_type(i_index) := 6; /* Update type */
12543           i_backward_update_time_fence(i_index) :=  fcst_hdr_tbl(fcst_locn).backward_time_fence ;
12544           i_forward_update_time_fence(i_index) := fcst_hdr_tbl(fcst_locn).forward_time_fence ;
12545           -- bucket_type(i_index) := 1 ;  /* bucket type */ ;
12546           -- deleted_flag(i_index) := 2 ;
12547           -- refresh_id := 0 ; /* Refresh id */
12548 
12549 	  prev_fcst_set := fcst_hdr_tbl(fcst_locn).fcst_set ;
12550 
12551 	END IF ;
12552 
12553 	IF write_fcst THEN
12554 
12555           i_index := i_index + 1 ;
12556           i_designator(i_index) := fcst_hdr_tbl(fcst_locn).fcst_name ;
12557           i_forecast_set(i_index) := fcst_hdr_tbl(fcst_locn).fcst_set ;
12558           i_organization_id(i_index) := fcst_dtl_rec.organization_id ;
12559           i_sr_instance_id(i_index) := pinstance_id ;
12560           i_description(i_index) :=  fcst_hdr_tbl(fcst_locn).fcst_name ;
12561           -- mps_relief(i_index) :=  0;  /* mps relief */
12562           -- inventory_atp_flag(i_index) := 0;  /* inventory atp flag */
12563           -- designator_type(i_index) := 6;  /* designator type,For forecast the value will be 6 */
12564           i_disable_date(i_index) := TO_DATE(NULL);  /* disable date */
12565           i_consume_forecast(i_index) := fcst_hdr_tbl(fcst_locn).consumption_ind ;
12566           -- update_type(i_index) := 6; /* Update Type,For Process value will be 6 */
12567           i_backward_update_time_fence(i_index) :=  fcst_hdr_tbl(fcst_locn).backward_time_fence ;
12568           i_forward_update_time_fence(i_index) := fcst_hdr_tbl(fcst_locn).forward_time_fence ;
12569           -- bucket_type(i_index) := 1 ;  /* bucket type */ ;
12570           -- deleted_flag(i_index) := 2 ;
12571           -- refresh_id := 0 ; /* Refresh id */
12572 
12573 	END IF ;
12574 
12575 	  -- and now write the forecast details entry also.
12576          /* Demands Bulk inserts */
12577          d_index := d_index + 1 ;
12578          f_organization_id(d_index) := fcst_dtl_rec.organization_id ;
12579          f_inventory_item_id(d_index) := fcst_dtl_rec.inventory_item_id ;
12580          f_sr_instance_id(d_index) :=  pinstance_id ;
12581          f_assembly_item_id(d_index) := fcst_dtl_rec.inventory_item_id ;
12582          f_demand_date(d_index) := fcst_dtl_rec.trans_date ;
12583          f_requirement_quantity(d_index) :=  fcst_dtl_rec.trans_qty ;
12584          -- demand_class := null_value ;           /* Demand Class  */
12585          -- bucket_type(d_index) := 1 ;             /* Bucket type */
12586          -- demand_type(d_index) := 1 ;             /* demand type */
12587          -- origination_type(d_index) := 29 ;       /* origination type */
12588          -- wip_entity_id(d_index) := null_value ;  /* wip_entity id */
12589          -- demand_schedule(d_index) := null_value ; /* demand Schedule name */
12590 	 f_forecast_designator(d_index) :=
12591                 fcst_hdr_tbl(fcst_locn).fcst_name ; /* forecast designator */
12592          f_order_number(d_index)  := fcst_hdr_tbl(fcst_locn).fcst_name;  /* Order Number */
12593          -- wip_entity_name(d_index) := null_value ; /* wip entity name */
12594          f_sales_order_line_id(d_index) := fcst_dtl_rec.line_id ; /* Sales Order line Id */
12595          -- selling_price(d_index) :=  null_value ;   /* Selling Price */
12596          -- deleted_flag :=  2 ;
12597 
12598      END LOOP ;
12599      CLOSE cur_fcst_dtl;
12600 
12601 /* ----------------------- Demands Insert --------------------- */
12602       i := 1 ;
12603       log_message(f_organization_id.FIRST || ' *forecast*' || f_organization_id.LAST );
12604       IF f_organization_id.FIRST > 0 THEN
12605       FORALL i IN f_organization_id.FIRST..f_organization_id.LAST
12606         INSERT INTO msc_st_demands (
12607         organization_id,
12608         inventory_item_id,
12609         sr_instance_id,
12610         using_assembly_item_id,
12611         using_assembly_demand_date,
12612         using_requirement_quantity,
12613         demand_class,
12614         bucket_type,
12615         demand_type,
12616         origination_type,
12617         wip_entity_id,
12618         demand_schedule_name,
12619         forecast_designator,
12620         order_number,
12621         wip_entity_name,
12622         sales_order_line_id,
12623         selling_price,
12624         deleted_flag )
12625         VALUES (
12626         f_organization_id(i),
12627         f_inventory_item_id(i),
12628         f_sr_instance_id(i),
12629         f_assembly_item_id(i),
12630         f_demand_date(i),
12631         f_requirement_quantity(i),
12632         null_value,       /* demand_class  */
12633         1,                /* bucket_type  */
12634         1,                /* demand_type  */
12635         29,               /* origination_type */
12636         null_value,       /* wip_entity_id    */
12637         null_value,       /* demand_schedule_name */
12638         f_forecast_designator(i),
12639         f_order_number(i),
12640         null_value,                /* wip_entity_name */
12641         f_sales_order_line_id(i),
12642         null_value,                /* selling_price */
12643         2                          /* deleted_flag */
12644         ) ;
12645       END IF ;
12646 
12647 /* ----------------------- Designator Insert --------------------- */
12648       i := 1 ;
12649       log_message(i_organization_id.FIRST || ' *Designator*' || i_organization_id.LAST );
12650       IF i_organization_id.FIRST > 0 THEN
12651       FORALL i IN i_organization_id.FIRST..i_organization_id.LAST
12652           INSERT INTO msc_st_designators (
12653           designator,
12654           forecast_set,
12655           organization_id,
12656           sr_instance_id,
12657           description,
12658           mps_relief,
12659           inventory_atp_flag,
12660           designator_type,
12661           disable_date,
12662           consume_forecast,
12663           update_type,
12664           backward_update_time_fence,
12665           forward_update_time_fence,
12666           bucket_type,
12667           deleted_flag,
12668           refresh_id
12669           )
12670           VALUES (
12671           i_designator(i)     ,
12672           i_forecast_set(i)   ,
12673           i_organization_id(i),
12674           i_sr_instance_id(i) ,
12675           i_description(i)    ,
12676           0,           /* mps relief */
12677           0,           /* inventory atp flag  */
12678           6,           /* designator type,For forecast the value will be 6 */
12679           i_disable_date(i)    ,
12680           i_consume_forecast(i),
12681           6,           /* Update Type,For Process value will be 6 */
12682           i_backward_update_time_fence(i),
12683           i_forward_update_time_fence(i) ,
12684           1,           /* bucket_type */
12685           2,           /* deleted_flag */
12686           0            /* refresh_id  */
12687           ) ;
12688       END IF ;
12689 
12690       return_status := TRUE ;
12691 
12692 EXCEPTION
12693     WHEN invalid_string_value  THEN
12694         log_message('Organization string is Invalid ' );
12695         return_status := FALSE;
12696 
12697 	WHEN OTHERS THEN
12698 	log_message('Failure occured during the Forecast_extract');
12699 	log_message(sqlerrm);
12700         return_status := FALSE;
12701 
12702 END extract_forecasts ;
12703 
12704 
12705 /************************************************************************
12706 *   NAME
12707 *	 Log_message
12708 *
12709 *   DESCRIPTION
12710 *       Put the debug message in log file.
12711 *   HISTORY
12712 *       Created By : Rajesh Patangya
12713 ************************************************************************/
12714 PROCEDURE LOG_MESSAGE(pBUFF  IN  VARCHAR2) IS
12715 BEGIN
12716   IF v_cp_enabled THEN
12717      IF fnd_global.conc_request_id > 0  THEN
12718          FND_FILE.PUT_LINE( FND_FILE.LOG, pBUFF);
12719      ELSE
12720          null;
12721      END IF;
12722   ELSE
12723     null ;
12724   END IF;
12725   EXCEPTION
12726      WHEN OTHERS THEN
12727         RETURN;
12728 END LOG_MESSAGE;
12729 
12730 /* **************************************************************************
12731 *   NAME
12732 *	 associate_forecasts
12733 *
12734 *   DESCRIPTION
12735 *         For each schedule forecast combination, mark the forecast table
12736 *   HISTORY
12737 *        Created By : Rajesh Patangya
12738 ************************************************************************/
12739 FUNCTION associate_forecasts (	pschd_fcst_cnt	IN NUMBER,
12740       				pschd_id	IN NUMBER ) return BOOLEAN
12741 IS
12742    found_fcst 	BOOLEAN ;
12743    schd_cnt	NUMBER ;
12744    i       	NUMBER ;
12745    f1       	NUMBER ;
12746 BEGIN
12747    found_fcst 	:= FALSE ;
12748    schd_cnt	:= 1 ;
12749    i       	:= 1 ;
12750    f1       	:= 1 ;
12751 
12752     -- Clean the earlier associations
12753     FOR f1 in 1..gfcst_size
12754     LOOP
12755        fcst_dtl_tab(f1).use_fcst_flag := 0 ;
12756     END LOOP;
12757 
12758     FOR schd_cnt in pschd_fcst_cnt..gschd_fcst_size
12759     LOOP
12760       IF pschd_id > schd_fcst_dtl_tab(schd_cnt).schedule_id THEN
12761         NULL ;
12762       ELSIF pschd_id = schd_fcst_dtl_tab(schd_cnt).schedule_id THEN
12763         FOR i in 1..gfcst_size
12764         LOOP
12765            IF fcst_dtl_tab(i).forecast_id =
12766               schd_fcst_dtl_tab(schd_cnt).forecast_id THEN
12767                   fcst_dtl_tab(i).use_fcst_flag := 1 ;
12768                   found_fcst := TRUE ;
12769            END IF;
12770         END LOOP;
12771       ELSE
12772          /*  pschd_id < schd_fcst_dtl_tab(schd_cnt).schedule_id THEN */
12773           gschd_fcst_cnt := schd_cnt ;
12774           EXIT ;
12775       END IF;
12776     END LOOP ;
12777     RETURN found_fcst ;
12778 
12779 END associate_forecasts;
12780 
12781 /* **************************************************************************
12782 *   NAME
12783 *	 check_forecast
12784 *
12785 *   DESCRIPTION
12786 *    Inventory item, Warehouse combination check, hence reached to the
12787 *    record for further processing
12788 *   HISTORY
12789 *        Created By : Rajesh Patangya
12790 ************************************************************************/
12791 FUNCTION check_forecast(pfcst_counter		IN  NUMBER,
12792   			pinventory_item_id	IN  NUMBER,
12793   			porganization_id	IN  NUMBER) return BOOLEAN
12794 IS
12795 fcst_i        NUMBER ;
12796 BEGIN
12797 fcst_i        := 1 ;
12798     /*  Loop through the forecast table for the matching inventory_item_id
12799         and organization_id (Process warehouse)  */
12800 
12801    FOR fcst_i in pfcst_counter..gfcst_size
12802    LOOP
12803      IF (fcst_dtl_tab(fcst_i).use_fcst_flag = 1) THEN
12804 
12805         IF fcst_dtl_tab(fcst_i).inventory_item_id > pinventory_item_id THEN
12806              return FALSE ;
12807         ELSIF fcst_dtl_tab(fcst_i).inventory_item_id = pinventory_item_id THEN
12808            IF fcst_dtl_tab(fcst_i).organization_id > porganization_id THEN
12809              return FALSE ;
12810            ELSIF fcst_dtl_tab(fcst_i).organization_id = porganization_id THEN
12811              return TRUE ;
12812            END IF;
12813         END IF;
12814 
12815      END IF;   /* Use Flag If   */
12816    END LOOP;
12817    -- If no rows were found after looping the whole table, return false
12818    return FALSE ;
12819 
12820 END check_forecast ;
12821 
12822 /* **************************************************************************
12823 *   NAME
12824 *	 check_so
12825 *
12826 *   DESCRIPTION
12827 *    Inventory item, Warehouse combination check, hence reached to the
12828 *    record for further processing
12829 *   HISTORY
12830 *        Created By : Rajesh Patangya
12831 ************************************************************************/
12832 FUNCTION check_so( pso_counter		IN  NUMBER,
12833 		   pinventory_item_id	IN  NUMBER,
12834 		   porganization_id	IN  NUMBER) return BOOLEAN
12835 IS
12836 
12837 so_i     NUMBER ;
12838 BEGIN
12839 so_i     := 0;
12840     /*  Loop through the Sales order table for the matching inventroy item_id
12841         and organization_id(whse)   */
12842 
12843    FOR so_i in pso_counter..gso_size
12844    LOOP
12845       IF sales_dtl_tab(so_i).inventory_item_id > pinventory_item_id THEN
12846            return FALSE ;
12847       ELSIF sales_dtl_tab(so_i).inventory_item_id = pinventory_item_id THEN
12848          IF sales_dtl_tab(so_i).organization_id > porganization_id THEN
12849            return FALSE ;
12850          ELSIF sales_dtl_tab(so_i).organization_id = porganization_id THEN
12851            return TRUE ;
12852          END IF;
12853       END IF;
12854    END LOOP ;
12855    -- If no rows were found after looping the whole table, return false
12856    return FALSE ;
12857 
12858 END check_so ;
12859 
12860 /* **************************************************************************
12861 *   NAME
12862 *	 consume_forecast
12863 *
12864 *   DESCRIPTION
12865 *       This procedure will consume the forecast for the values that are
12866 *	are loaded into the sales and forecast pl/sql tables. The occurences
12867 *	are passed in as paramaters. The sales orders that fall on or after
12868 *	a forecast for the same item/whse but before the next forecast for the
12869 *	same will decrease the value of the forecast by the amount of the
12870 * 	sales order line until it is zero.
12871 *   HISTORY
12872 *        Created By : Rajesh Patangya
12873 *     P Dong
12874 *     09/14/01 - Added api_mode to pass to insert_demands
12875 ************************************************************************/
12876 PROCEDURE consume_forecast( pinventory_item_id	IN  NUMBER,
12877 			    porganization_id	IN  NUMBER,
12878 			    papi_mode	        IN  BOOLEAN )
12879 AS
12880 cfcst_cnt      NUMBER ;
12881 cso_cnt        NUMBER ;
12882 found_forecast BOOLEAN ;
12883 
12884 BEGIN
12885 
12886 cfcst_cnt      := 0 ;
12887 cso_cnt        := 0 ;
12888 found_forecast := FALSE ;
12889 
12890  FOR cfcst_cnt in gfcst_cnt..gfcst_size
12891  LOOP
12892 
12893   IF (fcst_dtl_tab(cfcst_cnt).use_fcst_flag = 1 )  THEN
12894 
12895    IF fcst_dtl_tab(cfcst_cnt).inventory_item_id = pinventory_item_id AND
12896         fcst_dtl_tab(cfcst_cnt).organization_id = porganization_id THEN
12897     found_forecast := TRUE ;     /* B2922488 */
12898     FOR cso_cnt in gso_cnt..gso_size
12899     LOOP
12900      IF fcst_dtl_tab(cfcst_cnt).inventory_item_id =
12901                      sales_dtl_tab(cso_cnt).inventory_item_id AND
12902         fcst_dtl_tab(cfcst_cnt).organization_id =
12903                       sales_dtl_tab(cso_cnt).organization_id THEN
12904 
12905         IF fcst_dtl_tab(cfcst_cnt).trans_date <=
12906               sales_dtl_tab(cso_cnt).sched_shipdate THEN
12907 
12908 	    IF fcst_dtl_tab(cfcst_cnt).consumed_qty > 0 THEN
12909                  fcst_dtl_tab(cfcst_cnt).consumed_qty :=
12910                       fcst_dtl_tab(cfcst_cnt).consumed_qty -
12911                       sales_dtl_tab(cso_cnt).trans_qty ;
12912             END IF ; /* consumed_qty match */
12913                  write_this_so(cso_cnt,papi_mode) ;
12914 
12915         ELSE /* The fcst date is greater than so date, therefore write fcst */
12916             IF fcst_dtl_tab(cfcst_cnt).consumed_qty > 0 THEN
12917                write_this_fcst (cfcst_cnt,papi_mode);
12918             -- B2596464, Modified by Rajesh Patangya 26-SEP-2002
12919             -- Once forecast is written, make the quantity = 0,
12920             -- so that outside the loop it will not be written again.
12921                fcst_dtl_tab(cfcst_cnt).consumed_qty := 0 ;
12922             END IF ;
12923               EXIT ;
12924         END IF ; /* trans_date match */
12925 
12926      ELSIF (fcst_dtl_tab(cfcst_cnt).inventory_item_id <
12927             sales_dtl_tab(cso_cnt).inventory_item_id ) OR
12928         (   fcst_dtl_tab(cfcst_cnt).inventory_item_id =
12929             sales_dtl_tab(cso_cnt).inventory_item_id  AND
12930             fcst_dtl_tab(cfcst_cnt).organization_id <
12931             sales_dtl_tab(cso_cnt).organization_id
12932         )  THEN
12933             EXIT ;
12934      END IF ;
12935     END LOOP;  /* SO loop */
12936       -- After Looping through all SO , if the forecast remains
12937       -- unconsumed, write it to the table
12938          IF fcst_dtl_tab(cfcst_cnt).consumed_qty > 0 THEN
12939                    write_this_fcst (cfcst_cnt,papi_mode);
12940          END IF ;
12941     ELSIF
12942      (fcst_dtl_tab(cfcst_cnt).inventory_item_id > pinventory_item_id) OR
12943      (fcst_dtl_tab(cfcst_cnt).inventory_item_id = pinventory_item_id AND
12944      fcst_dtl_tab(cfcst_cnt).organization_id > porganization_id ) THEN
12945 	gfcst_cnt := cfcst_cnt ;
12946         write_so(gso_cnt,pinventory_item_id,porganization_id,papi_mode);
12947         EXIT ;
12948     END IF ;
12949   END IF ; /* use_fcst_flag */
12950  END LOOP ;    /* FCST loop */
12951 
12952   IF NOT (found_forecast) THEN
12953         -- At last, if there is no forecast at all, then you have to write
12954         -- all the sales orders
12955         write_so(gso_cnt,pinventory_item_id,porganization_id,papi_mode);
12956   END IF;
12957 
12958  EXCEPTION
12959     WHEN OTHERS THEN
12960         log_message('Failure occured during write_forecast');
12961         log_message(sqlerrm);
12962       RAISE;
12963 END consume_forecast ;
12964 
12965 /* **************************************************************************
12966 *   NAME
12967 *	 write_forecast
12968 *
12969 *   DESCRIPTION
12970 *     Loop through the forecast table for the matching inventory item_id
12971 *     and organization_id(whse)
12972 *     and insert into the destination table
12973 *     exit when item_id changes after noting down the counter position
12974 *   HISTORY
12975 *        Created By : Rajesh Patangya
12976 *     P Dong
12977 *     09/14/01 - Added api_mode to pass to insert_demands
12978 ************************************************************************/
12979 PROCEDURE write_forecast( pfcst_counter   	IN  NUMBER,
12980   			  pinventory_item_id	IN  NUMBER,
12981   			  porganization_id	IN  NUMBER,
12982 		          papi_mode	        IN BOOLEAN)
12983 AS
12984 fcst_i   NUMBER ;
12985 
12986 BEGIN
12987 fcst_i   := 0 ;
12988    -- A safety can be installed here
12989    IF gfcst_size >= pfcst_counter THEN
12990 
12991 
12992    FOR fcst_i in pfcst_counter..gfcst_size
12993    LOOP
12994      IF (fcst_dtl_tab(fcst_i).use_fcst_flag = 1 ) THEN
12995 
12996         IF fcst_dtl_tab(fcst_i).inventory_item_id > pinventory_item_id THEN
12997              gfcst_cnt := fcst_i ;
12998              EXIT ;
12999         ELSIF fcst_dtl_tab(fcst_i).inventory_item_id = pinventory_item_id THEN
13000            IF fcst_dtl_tab(fcst_i).organization_id > porganization_id THEN
13001              gfcst_cnt := fcst_i ;
13002              EXIT ;
13003            ELSIF fcst_dtl_tab(fcst_i).organization_id = porganization_id THEN
13004 		IF fcst_dtl_tab(fcst_i).consumed_qty > 0 THEN
13005                   write_this_fcst(fcst_i,papi_mode) ;
13006 		END IF ;
13007            END IF;
13008         END IF;
13009 
13010      END IF;   /* Use Flag If   */
13011    END LOOP;
13012 
13013    END IF;   /* Safety feature */
13014 
13015  EXCEPTION
13016     WHEN OTHERS THEN
13017         log_message('Failure occured during write_forecast');
13018         log_message(sqlerrm);
13019       RAISE;
13020 END write_forecast ;
13021 
13022 /* **************************************************************************
13023 *   NAME
13024 *	 write_so
13025 *
13026 *   DESCRIPTION
13027 *     Loop through the Sales order table for the matching inventory item_id
13028 *     and organization_id(whse)
13029 *     and insert into the destination table
13030 *     exit when item_id changes after noting down the counter position
13031 *   HISTORY
13032 *        Created By : Rajesh Patangya
13033 *     P Dong
13034 *     09/14/01 - Added api_mode to pass to insert_demands
13035 ************************************************************************/
13036 PROCEDURE write_so( pso_counter		IN  NUMBER,
13037 		    pinventory_item_id	IN  NUMBER,
13038 		    porganization_id	IN  NUMBER,
13039 		    papi_mode	        IN  BOOLEAN)
13040 AS
13041 so_i      NUMBER ;
13042 
13043 BEGIN
13044 so_i      := 0 ;
13045    -- A safety can be installed here
13046    IF gso_size >= pso_counter THEN
13047 
13048    FOR so_i in pso_counter..gso_size
13049    LOOP
13050       IF sales_dtl_tab(so_i).inventory_item_id > pinventory_item_id THEN
13051            gso_cnt := so_i ;
13052            EXIT ;
13053       ELSIF sales_dtl_tab(so_i).inventory_item_id = pinventory_item_id THEN
13054          IF sales_dtl_tab(so_i).organization_id > porganization_id THEN
13055            gso_cnt := so_i ;
13056            EXIT ;
13057          ELSIF sales_dtl_tab(so_i).organization_id = porganization_id THEN
13058            write_this_so(so_i,papi_mode) ;
13059          END IF;
13060       END IF;
13061    END LOOP ;
13062 
13063    END IF;   /* Safety feature */
13064 
13065  EXCEPTION
13066     WHEN OTHERS THEN
13067         log_message('Failure occured during write_so');
13068         log_message(sqlerrm);
13069       RAISE;
13070 END write_so ;
13071 
13072 /* **************************************************************************
13073 *   NAME
13074 *	 write_this_so
13075 *
13076 *   DESCRIPTION
13077 *    Call to build designator to get unique designator,
13078 *    insert sales order into msc_st_demand
13079 *   HISTORY
13080 *        Created By : Rajesh Patangya
13081 *     P Dong
13082 *     09/14/01 - Added api_mode to pass to insert_demands
13083 *     05/21/03 - B2971996 - Populating request_date in msc_st_demands table
13084 ************************************************************************/
13085 PROCEDURE write_this_so(pcounter      IN NUMBER,
13086                         sapi_mode     IN BOOLEAN)
13087 AS
13088   statement_demands_api  VARCHAR2(32000) ;
13089   statement_demands      VARCHAR2(32000) ;
13090 
13091 BEGIN
13092   statement_demands_api  := NULL ;
13093   statement_demands      := NULL ;
13094     g_delimiter  := '/';
13095     build_designator(g_item_tbl_position, g_delimiter, gcurrent_designator);
13096 
13097 IF sapi_mode
13098 THEN
13099   BEGIN
13100     statement_demands_api  :=
13101       ' INSERT INTO gmp_demands_api ( '
13102     ||'  organization_id, schedule_id, inventory_item_id, demand_date, '
13103     ||'  demand_quantity, origination_type, doc_id, selling_price ) '
13104     ||' VALUES '
13105     ||' ( :p1, :p2, :p3, :p4, '
13106     ||'   :p5, :p6, :p7, :p8 ) ';
13107 
13108     EXECUTE IMMEDIATE statement_demands_api USING
13109         sales_dtl_tab(pcounter).organization_id,
13110         sched_dtl_tab(g_item_tbl_position).schedule_id,
13111         sales_dtl_tab(pcounter).inventory_item_id,
13112         sales_dtl_tab(pcounter).sched_shipdate,
13113         sales_dtl_tab(pcounter).trans_qty,
13114         6,				/* origination type */
13115         null_value,				/* wip_entity id */
13116         sales_dtl_tab(pcounter).net_price  ;
13117 
13118         /* Global vairable Updation to next record */
13119         /*  B2929759, Rajesh Patangya 28-APR-2003 */
13120          gso_cnt := pcounter + 1 ;
13121 
13122   EXCEPTION
13123     WHEN OTHERS THEN
13124         log_message('Failure occured during the insert into gmp_demands_api');
13125         log_message(sqlerrm);
13126       RAISE;
13127   END;
13128 ELSE
13129   BEGIN
13130 
13131     statement_demands  :=
13132       ' INSERT INTO msc_st_demands ( '
13133     ||' organization_id, inventory_item_id, sr_instance_id, '
13134     ||' using_assembly_item_id, using_assembly_demand_date, '
13135     ||' using_requirement_quantity, demand_type, origination_type, '
13136     ||' wip_entity_id, demand_schedule_name, order_number, '
13137     ||' wip_entity_name, selling_price,request_date,deleted_flag ) '  /*B2971996*/
13138     ||' VALUES '
13139     ||' ( :p1, :p2, :p3,  '
13140     ||'   :p4, :p5,       '
13141     ||'   :p6, :p7, :p8 , '
13142     ||'   :p9, :p10,:p11, '
13143     ||'   :p12,:p13,:p14,:p15 )' ;
13144 
13145     EXECUTE IMMEDIATE statement_demands USING
13146 	sales_dtl_tab(pcounter).organization_id,
13147 	sales_dtl_tab(pcounter).inventory_item_id,
13148 	g_instance_id,
13149 	sales_dtl_tab(pcounter).inventory_item_id,
13150 	sales_dtl_tab(pcounter).sched_shipdate,
13151 	sales_dtl_tab(pcounter).trans_qty,
13152 	1,				/* demand type */
13153         6,				/* origination type */
13154 	null_value,			/* wip_entity id */
13155 	gcurrent_designator,
13156 	sales_dtl_tab(pcounter).orgn_code || g_delimiter ||
13157 		sales_dtl_tab(pcounter).order_no,
13158 	null_value,			/* wip entity name */
13159 	sales_dtl_tab(pcounter).net_price,
13160         sales_dtl_tab(pcounter).request_date,   /* B2971996 */
13161         2 ;
13162 
13163         /* Global vairable Updation to next record */
13164         /*  B2929759, Rajesh Patangya 28-APR-2003 */
13165          gso_cnt := pcounter + 1 ;
13166 
13167  EXCEPTION
13168     WHEN OTHERS THEN
13169         log_message('Failure occured during write_this_so');
13170         log_message(sqlerrm);
13171       RAISE;
13172   END;
13173 
13174   END IF;
13175 END write_this_so ;
13176 
13177 /* **************************************************************************
13178 *   NAME
13179 *	 write_this_fcst
13180 *
13181 *   DESCRIPTION
13182 *    Call to build designator to get unique designator,
13183 *    insert forecast into msc_st_demand
13184 *   HISTORY
13185 *        Created By : Rajesh Patangya
13186 *     P Dong
13187 *     09/14/01 - Added api_mode to pass to insert_demands
13188 ************************************************************************/
13189 PROCEDURE write_this_fcst(pcounter      IN NUMBER,
13190                           fapi_mode     IN BOOLEAN)
13191 AS
13192 
13193   statement_demands_api   VARCHAR2(32000) ;
13194   statement_demands       VARCHAR2(32000) ;
13195 
13196 BEGIN
13197   statement_demands_api  := NULL ;
13198   statement_demands      := NULL ;
13199     g_delimiter  := '/';
13200     build_designator(g_item_tbl_position, g_delimiter, gcurrent_designator);
13201 
13202 IF fapi_mode
13203 THEN
13204   BEGIN
13205     statement_demands_api  :=
13206       ' INSERT INTO gmp_demands_api ( '
13207     ||'  organization_id, schedule_id, inventory_item_id, demand_date, '
13208     ||'  demand_quantity, origination_type, doc_id, selling_price ) '
13209     ||' VALUES '
13210     ||' ( :p1, :p2, :p3, :p4, '
13211     ||'   :p5, :p6, :p7, :p8 ) ';
13212 
13213     EXECUTE IMMEDIATE statement_demands_api USING
13214         fcst_dtl_tab(pcounter).organization_id,
13215         sched_dtl_tab(g_item_tbl_position).schedule_id,
13216         fcst_dtl_tab(pcounter).inventory_item_id,
13217         fcst_dtl_tab(pcounter).trans_date,
13218         fcst_dtl_tab(pcounter).consumed_qty,
13219         7,				/* origination type */
13220         null_value,			/* wip_entity id */
13221         null_value ;
13222 
13223         /* Global vairable Updation to next record */
13224         /*  B2929759, Rajesh Patangya 28-APR-2003 */
13225            gfcst_cnt := pcounter + 1 ;
13226 
13227   EXCEPTION
13228     WHEN OTHERS THEN
13229         log_message('Failure occured during the insert into gmp_demands_api');
13230         log_message(sqlerrm);
13231       RAISE;
13232   END;
13233 ELSE
13234   BEGIN
13235     statement_demands  :=
13236       ' INSERT INTO msc_st_demands ( '
13237     ||' organization_id, inventory_item_id, sr_instance_id, '
13238     ||' using_assembly_item_id, using_assembly_demand_date, '
13239     ||' using_requirement_quantity, demand_type, origination_type, '
13240     ||' wip_entity_id, demand_schedule_name, order_number, '
13241     ||' wip_entity_name, selling_price, deleted_flag ) '
13242     ||' VALUES '
13243     ||' ( :p1, :p2, :p3,  '
13244     ||'   :p4, :p5,       '
13245     ||'   :p6, :p7, :p8 , '
13246     ||'   :p9, :p10,:p11, '
13247     ||'   :p12,:p13,:p14 )' ;
13248 
13249     EXECUTE IMMEDIATE statement_demands USING
13250         fcst_dtl_tab(pcounter).organization_id,
13251         fcst_dtl_tab(pcounter).inventory_item_id,
13252         g_instance_id,
13253         fcst_dtl_tab(pcounter).inventory_item_id,
13254         fcst_dtl_tab(pcounter).trans_date,
13255         fcst_dtl_tab(pcounter).consumed_qty,
13256         1,				/* demand type */
13257         7,				/* origination type */
13258         null_value, 			/* wip_entity id */
13259         gcurrent_designator,
13260         fcst_dtl_tab(pcounter).forecast ,
13261         null_value,			/* wip entity name */
13262         null_value,
13263         2 ;
13264 
13265         /* Global vairable Updation to next record */
13266         /*  B2929759, Rajesh Patangya 28-APR-2003 */
13267            gfcst_cnt := pcounter + 1 ;
13268 
13269  EXCEPTION
13270     WHEN OTHERS THEN
13271         log_message('Failure occured during write_this_fcst');
13272         log_message(sqlerrm);
13273       RAISE;
13274   END;
13275 
13276 END IF;
13277 END write_this_fcst ;
13278 
13279 /* **************************************************************************
13280 *   NAME
13281 *        insert_designator
13282 *
13283 *   DESCRIPTION
13284 *     Insert all the designator for schedule/item/warehouse combination
13285 *   HISTORY
13286 *        Created By : Rajesh Patangya
13287 ************************************************************************/
13288 PROCEDURE insert_designator IS
13289 
13290 i	       NUMBER ;
13291 st_designators VARCHAR2(32000) ;
13292 
13293 BEGIN
13294 
13295   i	         := 1 ;
13296   st_designators := NULL ;
13297   g_delimiter    := '/';
13298     st_designators  :=
13299         ' INSERT INTO msc_st_designators ( '
13300       ||' designator, organization_id, sr_instance_id, '
13301       ||' description, mps_relief, inventory_atp_flag, '
13302       ||' designator_type ) '
13303       ||' VALUES '
13304       ||' ( :p1, :p2, :p3, '
13305       ||'   :p4, :p5, :p6, '
13306       ||'   :p7 ) ';
13307 
13308       FOR i IN 1..desig_tab.COUNT LOOP
13309 
13310       EXECUTE IMMEDIATE st_designators USING
13311           desig_tab(i).designator,
13312           desig_tab(i).organization_id,
13313           g_instance_id,
13314           desig_tab(i).orgn_code || g_delimiter || desig_tab(i).schedule
13315                                  || g_delimiter || desig_tab(i).whse_code,
13316           2,
13317           2,
13318           1  ;
13319 
13320       END LOOP;
13321   EXCEPTION
13322     WHEN OTHERS THEN
13323         log_message('Failure occured in insert_designator');
13324         log_message(sqlerrm);
13325       RAISE;
13326 END insert_designator;
13327 
13328 /***********************************************************************
13329 *
13330 *   NAME
13331 *	process_resource_rows
13332 *
13333 *   DESCRIPTION
13334 *	This procedure will process al of the resource rows for a step then
13335 *       call the insert for resource requirements.
13336 *   HISTORY
13337 *	M Craig
13338 ************************************************************************/
13339 PROCEDURE process_resource_rows(
13340   pfirst_row    IN  NUMBER,
13341   plast_row     IN  NUMBER,
13342   pfound_mtl    IN  NUMBER,
13343   porgn_id      IN  NUMBER,
13344   pinstance_id  IN  NUMBER,
13345   pinflate_wip  IN  NUMBER,
13346   pmin_xfer_qty IN  NUMBER)
13347 IS
13348 
13349   v_resource_usage NUMBER ;
13350   v_res_seq        NUMBER ;
13351   v_schedule_flag  NUMBER ;
13352   v_parent_seq_num NUMBER ;
13353   v_rsrc_cnt       NUMBER ;
13354   v_start_date     DATE ;
13355   v_end_date       DATE ;
13356   old_activity     NUMBER ;
13357   j                NUMBER ;
13358 
13359 BEGIN
13360   v_resource_usage := 0;
13361   v_res_seq        := 0;
13362   v_schedule_flag  := 0;
13363   v_parent_seq_num := 0;
13364   v_rsrc_cnt       := 0;
13365   v_start_date     := NULL;
13366   v_end_date       := NULL;
13367   old_activity     := -1;
13368   j                := 0;
13369 
13370  FOR j IN pfirst_row..plast_row
13371  LOOP
13372    /* if the actual completion date is null then the resource
13373       is pending or WIP and needs to be written. otherwise the
13374       resource is completed and does not need to be reported. */
13375 
13376    IF old_activity <> rsrc_tab(j).bs_activity_id OR
13377       old_activity = -1 THEN
13378      v_res_seq := v_res_seq + 1;
13379      old_activity := rsrc_tab(j).bs_activity_id;
13380 
13381     /* B3421856 , Schedule flag needs to be populated correctly */
13382 
13383      IF pfound_mtl = 1 THEN
13384 
13385         IF rsrc_tab(j).material_ind = 1 THEN
13386                 v_schedule_flag := 4;
13387         ELSE
13388                 IF v_schedule_flag < 4 THEN
13389                         v_schedule_flag := 3 ;
13390                 END IF ;
13391         END IF ;
13392 
13393      END IF;  /* pfound_mtl */
13394    END IF;   /* old_activity */
13395 
13396    IF rsrc_tab(j).material_ind = 0 AND pfound_mtl = 1 THEN
13397      rsrc_tab(j).schedule_flag := v_schedule_flag;
13398    END IF;
13399 
13400    IF NVL(rsrc_tab(j).actual_cmplt_date,v_null_date) = v_null_date THEN
13401 
13402      /* when the actual start is null the resource has not started
13403         and the plan start will be used.  */
13404      IF rsrc_tab(j).tran_seq_dep = 1 THEN
13405        v_parent_seq_num := v_res_seq;
13406        v_resource_usage := rsrc_tab(j).resource_usage;
13407        v_start_date := rsrc_tab(j).act_start_date;
13408        v_end_date := rsrc_tab(j).plan_start_date;
13409      ELSE
13410        v_parent_seq_num := TO_NUMBER(NULL);
13411        v_start_date := rsrc_tab(j).plan_start_date;
13412        v_end_date := rsrc_tab(j).plan_cmplt_date;
13413        IF pinflate_wip = 1 THEN
13414          v_resource_usage := rsrc_tab(j).resource_usage / rsrc_tab(j).utl_eff;
13415        ELSE
13416          v_resource_usage := rsrc_tab(j).resource_usage;
13417        END IF;
13418      END IF;
13419 
13420      /* If no actual resource exists then the resource has not
13421         started and the planned value will be used */
13422 
13423      IF rsrc_tab(j).actual_rsrc_count IS NULL THEN
13424        v_rsrc_cnt := rsrc_tab(j).plan_rsrc_count;
13425      ELSE
13426        v_rsrc_cnt := rsrc_tab(j).actual_rsrc_count;
13427      END IF;
13428 
13429      /* write the current resource detail row asscoiating it with the
13430         batch through the product line */
13431 
13432      IF v_resource_usage > 0 THEN
13433 
13434         /* Bulk Insert for insert_resource_requirements */
13435           rr_index := rr_index + 1 ;
13436           rr_organization_id(rr_index) := porgn_id ;
13437           rr_sr_instance_id(rr_index) := pinstance_id ;
13438           rr_supply_id(rr_index) :=  rsrc_tab(j).x_batch_id ; /* B1177070 encoded key */
13439           /* B1224660 new value to write resource seq num */
13440           rr_resource_seq_num(rr_index) := v_res_seq ;
13441           rr_resource_id(rr_index) := rsrc_tab(j).x_resource_id ; /* B1177070 encoded key */
13442           rr_start_date(rr_index) := v_start_date ;
13443           rr_end_date(rr_index)  :=  v_end_date ;
13444           rr_opr_hours_required(rr_index) :=  v_resource_usage ;
13445           rr_assigned_units(rr_index) := v_rsrc_cnt ;
13446           rr_department_id(rr_index) := ((porgn_id * 2) + 1) ;  /* B1177070 encoded key */
13447           rr_wip_entity_id(rr_index) :=  rsrc_tab(j).x_batch_id ; /* B1177070 encoded key */
13448           /* B1224660 write the step number for oper seq num */
13449           rr_operation_seq_num(rr_index)  :=   rsrc_tab(j).batchstep_no ;
13450           rr_firm_flag(rr_index) :=    rsrc_tab(j).firm_type ;
13451           rr_minimum_transfer_quantity(rr_index) := pmin_xfer_qty ;
13452           rr_parent_seq_num(rr_index) := v_parent_seq_num ;
13453           rr_schedule_flag(rr_index) := rsrc_tab(j).schedule_flag ;
13454       END IF;
13455    END IF;
13456   END LOOP;
13457 
13458 END process_resource_rows;
13459 
13460 /*Sowmya - As Per latest FDD changes - Start*/
13461 /***********************************************************************
13462 *
13463 *   NAME
13464 *	production_reservations
13465 *
13466 *   DESCRIPTION
13467 *	This procedure will fetch all salesorders against which production
13468 *       batches are reserved.
13469 *   HISTORY
13470 *
13471 ************************************************************************/
13472 
13473 PROCEDURE production_reservations ( pdblink        IN  VARCHAR2,
13474                           pinstance_id   IN  NUMBER,
13475                           prun_date      IN  DATE,
13476                           pdelimiter     IN  VARCHAR2,
13477                           return_status  IN OUT NOCOPY BOOLEAN)
13478 IS
13479         v_stmt_alt_rsrc VARCHAR2(32000);
13480 BEGIN
13481 
13482 v_stmt_alt_rsrc :=  'INSERT INTO MSC_ST_RESERVATIONS'
13483                 ||'  (  '
13484                 ||'        TRANSACTION_ID , '
13485                 ||'        INVENTORY_ITEM_ID ,  '
13486                 ||'        ORGANIZATION_ID, '
13487                 ||'        SR_INSTANCE_ID ,  '
13488                 ||'        REQUIREMENT_DATE , '
13489                 ||'        PARENT_DEMAND_ID , '
13490                 ||'        REVISION  , '
13491                 ||'        DISPOSITION_ID , '
13492                 ||'        RESERVED_QUANTITY , '
13493                 ||'        DISPOSITION_TYPE ,  '
13494                 ||'        SUBINVENTORY , '
13495                 ||'        RESERVATION_TYPE , '
13496                 ||'        DEMAND_CLASS , '
13497                 ||'        AVAILABLE_TO_MRP , '
13498                 ||'        RESERVATION_FLAG , '
13499                 ||'        PROJECT_ID , '
13500                 ||'        TASK_ID , '
13501                 ||'        PLANNING_GROUP , '
13502                 ||'        SUPPLY_SOURCE_HEADER_ID , '
13503                 ||'        SUPPLY_SOURCE_TYPE_ID , '
13504                 ||'        DELETED_FLAG '
13505                 ||'  ) '
13506                 ||'  SELECT '
13507                 ||'        ((gbo.batch_res_id * 2) + 1), '
13508                 ||'        gia.aps_item_id , '
13509                 ||'        gbo.organization_id, '
13510                 ||'        :p1, '
13511                 ||'        gbo.scheduled_ship_date, '
13512                 ||'        gbo.so_line_id , '
13513                 ||'        NULL , '
13514                 ||'        gbo.order_id , '
13515                 ||'        gbo.reserved_qty , '
13516                 ||'        :p2 ,'
13517                 ||'        NULL , '
13518                 ||'        :p3 ,'
13519                 ||'        ool.demand_class_code , '
13520                 ||'        NULL  , '
13521                 ||'        :p4 ,'
13522                 ||'        ool.project_id, '
13523                 ||'        ool.task_id, '
13524                 ||'        ppp.planning_group, '
13525                 ||'        ((gbo.batch_id * 2) + 1) , '
13526                 ||'        :p5 ,'
13527                 ||'        :p6 '
13528                 ||'   FROM '
13529                 ||'         gml_batch_so_reservations'||pdblink||' gbo, '
13530                 ||'        (SELECT  '
13531                 ||'                DISTINCT item_id, aps_item_id, organization_id , whse_code '
13532                 ||'         FROM gmp_item_aps'||pdblink||')  gia, '
13533                 ||'        oe_order_lines_all'||pdblink||' ool, '
13534                 ||'        pjm_project_parameters'||pdblink||' ppp  '
13535                 ||'   WHERE '
13536                 ||'         gbo.item_id = gia.item_id '
13537                 ||'        AND gbo.organization_id = gia.organization_id '
13538                 ||'        AND gbo.delete_mark = 0 '
13539                 ||'        AND gbo.so_line_id = ool.line_id '
13540                 ||'        AND ool.project_id = ppp.project_id (+) ';
13541 
13542                 IF MSC_CL_GMP_UTILITY.g_in_str_org  IS NOT NULL THEN
13543                         v_stmt_alt_rsrc := v_stmt_alt_rsrc
13544                          ||'   AND EXISTS ( SELECT 1 FROM sy_orgn_mst'||pdblink||' som '
13545                          ||'   WHERE gia.whse_code = som.resource_whse_code )' ;
13546                 END IF;
13547 
13548                 EXECUTE IMMEDIATE v_stmt_alt_rsrc USING
13549                 pinstance_id,2,1,2,5,2 ;    /*Sowmya - As per latest FDD changes -
13550                                              Changed the supply source id from 13 to 5 */
13551         EXCEPTION
13552                 WHEN OTHERS THEN
13553 	        log_message('Failure occured during the insert into msc_st_reservations');
13554 	        log_message(sqlerrm);
13555               	return_status := FALSE;
13556 
13557 END production_reservations;
13558 /*Sowmya - As Per latest FDD changes - End*/
13559 
13560 /***********************************************************************
13561 *
13562 *   NAME
13563 *	update_last_setup_id
13564 *
13565 *   DESCRIPTION
13566 *	This procedure is triggered by the concurrent program for
13567 *       updating the last setup id.
13568 *
13569 *   HISTORY
13570 *	Namit           14-09-2004      Procedure Created
13571 ************************************************************************/
13572 
13573 PROCEDURE update_last_setup_id (
13574    effbuf   OUT NOCOPY VARCHAR2,
13575    retcode      OUT NOCOPY NUMBER,
13576    f_orgn_code    IN  VARCHAR2,
13577    t_orgn_code    IN  VARCHAR2
13578 )
13579 IS
13580    cur_lsetup_id        ref_cursor_typ;
13581    resources            VARCHAR2(30);
13582    v_last_setup_id      NUMBER;
13583    v_resource_id        NUMBER;
13584    v_plant_code         VARCHAR2(10);
13585    v_batch_id           NUMBER;
13586    v_instance_id        NUMBER;
13587    x_select             VARCHAR2(32000);
13588    old_resource_id      NUMBER;
13589    old_instance_id      NUMBER;
13590    lsetup_updated       BOOLEAN;
13591    l_user_id            NUMBER;
13592 
13593 BEGIN
13594 
13595    x_select        := NULL;
13596    old_resource_id := -1;
13597    old_instance_id := -1;
13598    lsetup_updated  := TRUE;
13599 
13600     l_user_id :=  to_number(FND_PROFILE.VALUE('USER_ID'));
13601 
13602     X_select := ' SELECT '
13603     ||' gbsr.sequence_dependent_id, '
13604     ||' crd.resource_id, '
13605     ||' grt.instance_id, '
13606     ||' crd.orgn_code, '
13607     ||' gbsr.batch_id '
13608     ||' FROM    gme_batch_step_resources gbsr, '
13609     ||'    gme_resource_txns grt, '
13610     ||'    sy_orgn_usr sou, '
13611     ||'    cr_rsrc_dtl crd, '
13612     ||'    gme_batch_header gbh '
13613     ||' WHERE   gbsr.batch_id = grt.doc_id '
13614     ||'    AND  gbh.batch_id = gbsr.batch_id '
13615     ||'    AND  gbh.plant_code = crd.orgn_code '
13616     ||'    AND  crd.orgn_code = sou.orgn_code '
13617     ||'    AND  sou.user_id = :user_id '
13618     ||'    AND  gbsr.batchstep_resource_id = grt.line_id '
13619     ||'    AND  grt.completed_ind = 1 '
13620     ||'    AND  crd.resources = gbsr.resources '
13621     ||'    AND  crd.resources = grt.resources '
13622     ||'    AND  crd.schedule_ind = 2 '
13623     ||'    AND   grt.instance_id IS NOT NULL '
13624     ||'    AND     crd.delete_mark = 0 ';
13625 
13626     IF f_orgn_code IS NOT NULL THEN
13627        x_select := x_select
13628        ||'    AND     crd.orgn_code >= :frm_orgn ' ;
13629     END IF;
13630     IF t_orgn_code IS NOT NULL THEN
13631        x_select := x_select
13632        ||'    AND     crd.orgn_code <= :to_orgn ' ;
13633     END IF;
13634 
13635     x_select := x_select
13636     ||'    ORDER BY grt.resources, grt.instance_id, '
13637     ||'       grt.end_date DESC, grt.poc_trans_id ' ;
13638 
13639    IF f_orgn_code IS NOT NULL AND t_orgn_code IS NOT NULL THEN
13640       OPEN cur_lsetup_id FOR x_select USING l_user_id, f_orgn_code, t_orgn_code;
13641    ELSIF f_orgn_code IS NOT NULL AND t_orgn_code IS NULL THEN
13642       OPEN cur_lsetup_id FOR x_select USING l_user_id, f_orgn_code;
13643    ELSIF f_orgn_code IS NULL AND t_orgn_code IS NOT NULL THEN
13644       OPEN cur_lsetup_id FOR x_select USING l_user_id, t_orgn_code;
13645    ELSE
13646       OPEN cur_lsetup_id FOR x_select USING l_user_id;
13647    END IF;
13648 
13649    LOOP
13650       FETCH cur_lsetup_id INTO v_last_setup_id, v_resource_id, v_instance_id,
13651         v_plant_code, v_batch_id;
13652       EXIT WHEN cur_lsetup_id%NOTFOUND;
13653 
13654       IF (old_resource_id <> v_resource_id OR old_instance_id <> v_instance_id) THEN
13655          old_resource_id := v_resource_id;
13656          old_instance_id := v_instance_id;
13657          lsetup_updated := FALSE;
13658       END IF;
13659 
13660       IF NOT (lsetup_updated) THEN
13661          lsetup_updated := TRUE;
13662             UPDATE gmp_resource_instances gri
13663             SET gri.last_setup_id = v_last_setup_id
13664             WHERE gri.resource_id = v_resource_id
13665               AND gri.instance_id = v_instance_id;
13666       END IF;
13667    END LOOP;
13668       CLOSE cur_lsetup_id ;
13669    COMMIT;
13670 EXCEPTION
13671     WHEN NO_DATA_FOUND THEN
13672         log_message(' NO_DATA_FOUND exception raised in Procedure: MSC_CL_GMP_UTILITY.update_last_setup_id ' );
13673       	RAISE;
13674 
13675     WHEN OTHERS THEN
13676         log_message('Error in Last Setup ID Program: '||SQLERRM);
13677         RAISE;
13678 
13679 END update_last_setup_id;
13680 
13681 FUNCTION GMP_APSDS_UTILITY1_R10
13682             (
13683                           p_dblink      IN VARCHAR2,
13684                           p_delimiter   IN VARCHAR2,
13685                           p_instance    IN INTEGER,
13686                           p_run_date    IN DATE,
13687                           p_num1        IN NUMBER,
13688                           p_num2        IN NUMBER,
13689                           p_num3        IN NUMBER,
13690                           p_num4        IN NUMBER,
13691                           p_varchar1    IN VARCHAR2,
13692                           p_varchar2    IN VARCHAR2,
13693                           p_varchar3    IN VARCHAR2,
13694                           p_varchar4    IN VARCHAR2
13695             ) RETURN INTEGER IS
13696 BEGIN
13697     return 0;
13698 END GMP_APSDS_UTILITY1_R10;
13699 
13700 PROCEDURE GMP_APSDS_PROC1_R10
13701             (
13702                           p_dblink      IN VARCHAR2,
13703                           p_delimiter   IN VARCHAR2,
13704                           p_instance    IN INTEGER,
13705                           p_run_date    IN DATE,
13706                           p_num1        IN NUMBER,
13707                           p_num2        IN NUMBER,
13708                           p_num3        IN NUMBER,
13709                           p_num4        IN NUMBER,
13710                           p_varchar1    IN VARCHAR2,
13711                           p_varchar2    IN VARCHAR2,
13712                           p_varchar3    IN VARCHAR2,
13713                           p_varchar4    IN VARCHAR2,
13714                           return_status  OUT NOCOPY BOOLEAN
13715             ) IS
13716 BEGIN
13717     return_status := TRUE;
13718 END GMP_APSDS_PROC1_R10;
13719 
13720 -- --------------------OPM Production Order Package End ------------
13721 
13722 /*
13723 REM+==========================================================================+
13724 REM| PROCEDURE NAME                                                           |
13725 REM|    rsrc_extract                                                          |
13726 REM|                                                                          |
13727 REM| Type                                                                     |
13728 REM|    public                                                                |
13729 REM|                                                                          |
13730 REM| DESCRIPTION                                                              |
13731 REM|    The following procedure rows into msc_st_department_resources         |
13732 REM|                                                                          |
13733 REM| Input Parameters                                                         |
13734 REM|    p_instance_id - Instance Id                                           |
13735 REM|    p_db_link - Database Link                                             |
13736 REM|    return_status - Status return variable                                |
13737 REM|                                                                          |
13738 REM| Output Parameters                                                        |
13739 REM|    None                                                                  |
13740 REM|                                                                          |
13741 REM|                                                                          |
13742 REM| HISTORY                                                                  |
13743 REM|    Created 5th Aug 1999 by Sridhar Gidugu (OPM Development Oracle US)    |
13744 REM|    8/17/99 - Changed to Dynamic SQL , added db_link                      |
13745 REM|    10/13/99 - Added deleted_flag in the insert statement                 |
13746 REM|    11/23/99 - Changed value of aggregate_resource_flag from 1 to 2       |
13747 REM|    01/12/00 - Added owning_department_id column in the Insert statement  |
13748 REM|             - Bug# 1140113                                               |
13749 REM|    4/03/00 - using mtl_organization_id from ic_whse_mst instead of       |
13750 REM|            - organization_id from sy_orgn_mst - Bug# 1252322             |
13751 REM|    4/18/00 - Fixed Bug# 1273557 - Department count is Zero               |
13752 REM|            - Changes made to the insert statement, changed               |
13753 REM|            - s.organization_id to w.mtl_organization_id                  |
13754 REM|    12/26/01 - Adding Code changes for Resource Utilization and Resource  |
13755 REM|               Efficiency - B2163006                                      |
13756 REM|    12/20/02 - Sridhar Gidugu  B2714583, Populated 3 new columns for      |
13757 REM|                               msc_st_department_resources                |
13758 REM|                               1.Resource_excess_type,                    |
13759 REM|                               2.Resource_shortage_type                   |
13760 REM|                               3.User_time_fence                          |
13761 REM|    01/09/03 - Sridhar Gidugu  Used mrp_planning_exception_sets           |
13762 REM|                               instead of mrp_planning_exception_sets_v   |
13763 REM|                               also added extra join with Organization_id |
13764 REM|    01/22/03 - Sridhar Gidugu  Insert statement for Resource Groups       |
13765 REM|    05/11/03 - Rajesh Patangya Used to_number(NULL) in palce of NULL      |
13766 REM|    05/20/03 - Sridhar Gidugu  B2971120 Populating new columns            |
13767 REM|                               Over_utilized_percent and                  |
13768 REM|                               under_utilized_percent in dept_rsc table   |
13769 REM|  04/21/2004   - Navin Sinha - B3577871 -ST:OSFME2: collections failing   |
13770 REM|                                in planning data pull.                    |
13771 REM|                                Added handling of NO_DATA_FOUND Exception.|
13772 REM|                                And return the return_status as TRUE.     |
13773 REM|  12/30/04 - Arvind Karuppasamy - B4081551, Modified query in rsrc_extract|
13774 REM|                                  to select the resource description from |
13775 REM|                                  cr_rsrc_mst.			      |
13776 REM|  02/17/05 - Teresa Wong - B4179616 Increased length of variables holding |
13777 REM|                                   dynamic sql stmts with string of org   |
13778 REM|                                   codes.                                 |
13779 REM+==========================================================================+
13780 */
13781 
13782 PROCEDURE rsrc_extract(p_instance_id IN NUMBER,
13783                        p_db_link     IN VARCHAR2,
13784                        return_status OUT NOCOPY BOOLEAN) is
13785 
13786 ins_dept_res     varchar2(32000);
13787 ins_res_group    varchar2(32000);
13788 ins_res_instance varchar2(32000);
13789 dep_ref_cursor   ref_cursor_typ;
13790 BEGIN
13791 stmt_no          := 0 ;
13792 
13793 /*  New changes made for msc_st_department_resources - using mtl_organization_id
13794     from ic_whse_mst instead of organization_id from sy_orgn_mst
13795     table  - Bug # 1252322
13796     Commented the Where clause resource_whse_code is NOT NULL as whse code in
13797     ic_whse_mst is never NULL - 04/03/2000
13798 */
13799 
13800     IF return_status THEN
13801        v_cp_enabled := TRUE;
13802     ELSE
13803        v_cp_enabled := FALSE;
13804     END IF;
13805 
13806     /* populate the org_string */
13807      IF MSC_CL_GMP_UTILITY.org_string(p_instance_id) THEN
13808         NULL ;
13809      ELSE
13810         RAISE invalid_string_value  ;
13811      END IF;
13812 
13813         /* note that we introduced substr(resources) as the
13814           final msc table has the column at 10 char only. If and when the MSC
13815           column width increases we shall remove substr */
13816 
13817     /* AKARUPPA 12/30/2004 B4081551 - Modified query to select resource description from cr_rsrc_mst */
13818 
13819     stmt_no := 10 ;
13820     ins_dept_res := ' INSERT INTO msc_st_department_resources '
13821                || ' ( organization_id,  '
13822                || ' sr_instance_id, '
13823                || ' resource_id, '
13824                || ' department_id, '
13825                || ' resource_code, '
13826                || ' resource_description,  '
13827                || ' department_code, '
13828                || ' owning_department_id, '
13829                || ' line_flag, '
13830                || ' aggregated_resource_flag, '
13831                || ' capacity_units, '
13832                || ' available_24_hours_flag, '
13833                || ' resource_cost,  '
13834                || ' ctp_flag,     '
13835                || ' deleted_flag,  '
13836                || ' resource_excess_type,  '
13837                || ' resource_shortage_type,  '
13838                || ' user_time_fence,  '
13839                || ' over_utilized_percent,  '    /* B2971120 */
13840                || ' under_utilized_percent,  '   /* B2971120 */
13841                || ' efficiency,  '
13842                || ' utilization,  '
13843                || ' planning_exception_set,  '
13844                || ' resource_group_name,  '
13845                || ' bottleneck_flag,  '
13846                || ' chargeable_flag, '
13847                || ' capacity_tolerance, '
13848                || ' batchable_flag, '
13849                || ' batching_window, '
13850                || ' min_capacity, '
13851                || ' max_capacity, '
13852                || ' unit_of_measure, '
13853                || ' idle_time_tolerance, '
13854                || ' sds_scheduling_window, '
13855                || ' batching_penalty, '
13856                || ' schedule_to_instance, '
13857  /*B4487118 - HLINK GC:(RV): MULTIPLE ROWS ARE DISPALYED FOR A RESOURCE IN THE RV*/
13858                || ' resource_type '
13859                || ') '
13860                || '  SELECT w.mtl_organization_id , '
13861                || '  :instance_id, '
13862                || '  ((r.resource_id * 2) + 1),'         /* B1177070 encoded */
13863                || '  ((w.mtl_organization_id * 2) + 1),' /* B1177070 encoded */
13864                || '  substrb(r.resources,1,10), '
13865                || '  rsm.resource_desc, '                /* B4081551 */
13866                || '  w.whse_code   , '
13867                || '  ((w.mtl_organization_id * 2) + 1)  , ' /* B1177070 */
13868                || '  2, '            /* Line Flag */
13869                || '  2, '      /* Yes = 1 and No = 2 resource Flag */
13870                || '  r.assigned_qty, '
13871                || '  2, '      /* Avail 24 hrs flag */
13872                || '  r.nominal_cost, '
13873                || '  1,'     /* for ATP to check Resources (RDP)*/
13874                || '  2, '
13875                || '  mrp.resource_excess_type, '      /*  B2714583 */
13876                || '  mrp.resource_shortage_type, '    /* B2714583 */
13877                || '  mrp.user_time_fence, '           /* B2714583 */
13878                || '  mrp.over_utilized_percent, '     /* B2971120 */
13879                || '  mrp.under_utilized_percent, '    /* B2971120 */
13880                || '  r.efficiency, '                  /* B2163006 */
13881                || '  r.utilization, '                 /* B2163006 */
13882                || '  r.planning_exception_set, '      /* B2714583 */
13883                || '  r.group_resource, '
13884                || '  NULL, '
13885                || '  decode(r.capacity_constraint,1,1,2), '
13886                || '  r.capacity_tolerance, '
13887                || '  2, ' /* batchable_flag */
13888                || '  NULL, '
13889                || '  r.min_capacity, '
13890                || '  r.max_capacity, '
13891                || '  sou.uom_code, '
13892                || '  idle_time_tolerence, '
13893                || '  sds_window, '
13894                || '  NULL, '
13895             /* If the Resource is scheduled to Instance, then value is Yes else No */
13896                || '  decode(r.schedule_ind,2,1,2), '
13897    /*B4487118 - HLINK GC:(RV): MULTIPLE ROWS ARE DISPALYED FOR A RESOURCE IN THE RV*/
13898                || '  1 '
13899                || '  FROM   cr_rsrc_dtl'||p_db_link||' r, '
13900 	       || '         cr_rsrc_mst'||p_db_link||' rsm, ' /* B4081551 */
13901                || '         mrp_planning_exception_sets'||p_db_link||' mrp, '
13902                || '         sy_orgn_mst'||p_db_link||' p, '
13903                || '         ic_whse_mst'||p_db_link||' w, '
13904                ||'          sy_uoms_mst'||p_db_link||' sou '
13905                || '  WHERE  r.orgn_code = p.orgn_code '
13906                || '  AND    r.planning_exception_set = mrp.exception_set_name '
13907                || '  AND    w.mtl_organization_id = mrp.organization_id '
13908 	       || '  AND    r.resources = rsm.resources ' /* B4081551 */
13909                || '  AND    p.resource_whse_code = w.whse_code ' ;
13910 
13911         IF MSC_CL_GMP_UTILITY.g_in_str_org  IS NOT NULL THEN
13912          ins_dept_res := ins_dept_res
13913                    ||'   AND w.mtl_organization_id ' || MSC_CL_GMP_UTILITY.g_in_str_org ;
13914         END IF;
13915 
13916          ins_dept_res := ins_dept_res
13917                || '  AND    r.delete_mark = 0 '
13918                || '  AND    rsm.delete_mark = 0 ' /* B4081551 */
13919                || '  AND    p.delete_mark = 0 '
13920                || '  AND    w.delete_mark = 0 '
13921                ||'   AND sou.delete_mark = 0 '
13922                ||'   AND sou.um_code = r.capacity_uom '
13923                || '  UNION ALL '
13924                || '  SELECT w.mtl_organization_id , '
13925                || '  :instance_id1, '
13926                || '  ((r.resource_id * 2) + 1),'         /* B1177070 encoded */
13927                || '  ((w.mtl_organization_id * 2) + 1),' /* B1177070 encoded */
13928                || '  substrb(r.resources,1,10), '
13929                || '  rsm.resource_desc, '                /* B4081551 */
13930                || '  w.whse_code   , '
13931                || '  ((w.mtl_organization_id * 2) + 1)  , ' /* B1177070 */
13932                || '  2, '            /* Line Flag */
13933                || '  2, '      /* Yes = 1 and No = 2 resource Flag */
13934                || '  r.assigned_qty, '
13935                || '  2, '      /* Avail 24 hrs flag */
13936                || '  r.nominal_cost, '
13937                || '  1,'     /* for ATP to check Resources (RDP)*/
13938                || '  2, '
13939                || '  to_number(NULL), '      /*  B2714583 */
13940                || '  to_number(NULL), '      /*  B2714583 */
13941                || '  to_number(NULL), '      /*  B2714583 */
13942                || '  to_number(NULL), '      /*  B2971120 */
13943                || '  to_number(NULL), '      /*  B2971120 */
13944                || '  r.efficiency, '         /* B2163006 */
13945                || '  r.utilization, '        /* B2163006 */
13946                || '  r.planning_exception_set, ' /* B2714583 */
13947                || '  r.group_resource, '
13948                || '  NULL, '
13949                || '  decode(r.capacity_constraint,1,1,2), '
13950                || '  r.capacity_tolerance, '
13951                || '  2, ' /* batchable_flag */
13952                || '  NULL, '
13953                || '  r.min_capacity, '
13954                || '  r.max_capacity, '
13955                || '  sou.uom_code, '
13956                || '  idle_time_tolerence, '
13957                || '  sds_window, '
13958                || '  NULL, '
13959             /* If the Resource is scheduled to Instance, then value is Yes else No */
13960                || '  decode(r.schedule_ind,2,1,2), '
13961    /*B4487118 - HLINK GC:(RV): MULTIPLE ROWS ARE DISPALYED FOR A RESOURCE IN THE RV*/
13962                || '  1 '
13963                || '  FROM   cr_rsrc_dtl'||p_db_link||' r, '
13964 	       || '         cr_rsrc_mst'||p_db_link||' rsm, ' /* B4081551 */
13965                || '         sy_orgn_mst'||p_db_link||' p, '
13966                || '         ic_whse_mst'||p_db_link||' w, '
13967                ||'          sy_uoms_mst'||p_db_link||' sou '
13968                || '  WHERE  r.orgn_code = p.orgn_code '
13969                || '  AND    r.planning_exception_set IS NULL '
13970                || '  AND    p.resource_whse_code = w.whse_code '
13971 	       || '  AND    r.resources = rsm.resources ' /* B4081551 */
13972                || '  AND    r.delete_mark = 0 '
13973                || '  AND    rsm.delete_mark = 0 ' /* B4081551 */
13974                || '  AND    p.delete_mark = 0 '
13975                || '  AND    w.delete_mark = 0 '
13976                ||'   AND sou.delete_mark = 0 '
13977                ||'   AND sou.um_code = r.capacity_uom ';
13978 
13979         IF MSC_CL_GMP_UTILITY.g_in_str_org  IS NOT NULL THEN
13980          ins_dept_res := ins_dept_res
13981                ||'   AND w.mtl_organization_id ' || MSC_CL_GMP_UTILITY.g_in_str_org ;
13982         END IF;
13983 
13984          EXECUTE IMMEDIATE  ins_dept_res USING p_instance_id, p_instance_id;
13985 
13986     /* Insert into MSC_ST_RESOURCE_GROUPS for Bottleneck Resources
13987        Sending only those resources that are used in Planning for APS
13988     */
13989     stmt_no := 20 ;
13990     ins_res_group := ' INSERT INTO msc_st_resource_groups '
13991                || ' ( group_code,  '
13992                || '   meaning, '
13993                || '   description,  '
13994                || '   from_date,  '
13995                || '   to_date,  '
13996                || '   enabled_flag,  '
13997                || '   sr_instance_id '
13998                || ' ) '
13999                || '  SELECT distinct '
14000                || '   crd.group_resource , '
14001                || '   crm.resource_desc,'
14002                || '   crm.resource_desc,'
14003                || '   sysdate,'
14004                || '   NULL,'
14005                || '   1,'
14006                || '   :instance_id '
14007                || '  FROM  sy_orgn_mst'||p_db_link||' sy, '
14008                || '        cr_rsrc_dtl'||p_db_link||' crd, '
14009                || '        cr_rsrc_mst'||p_db_link||' crm '
14010                || '  WHERE sy.orgn_code = crd.orgn_code  '
14011                || '    AND sy.resource_whse_code is NOT NULL '
14012                || '    AND crd.resources = crm.resources '
14013                || '    AND crd.group_resource = crm.resources '
14014                || '    AND crd.delete_mark = 0 ';
14015 
14016         IF MSC_CL_GMP_UTILITY.g_in_str_org  IS NOT NULL THEN
14017          ins_res_group := ins_res_group
14018                || '    AND EXISTS ( SELECT 1 FROM gmp_item_aps'||p_db_link||' gia '
14019                || '    WHERE gia.whse_code = sy.resource_whse_code )' ;
14020         END IF;
14021 
14022          EXECUTE IMMEDIATE  ins_res_group USING p_instance_id;
14023 
14024         /* Now extract the resource instances too -
14025         The instance extraction was put under resource avaialbility
14026         extraction but to keep it in synch with Discrete collection, it is being
14027         moved here. */
14028 
14029      stmt_no := 30 ;
14030      ins_res_instance := ' INSERT INTO msc_st_dept_res_instances '
14031          ||' ( sr_instance_id, '
14032          ||'   res_instance_id, '
14033          ||'   resource_id, '
14034          ||'   department_id, '
14035          ||'   organization_id, '
14036          ||'   serial_number, '
14037          ||'   equipment_item_id, '
14038          ||'   last_known_setup, '
14039          ||'   effective_start_date, '
14040          ||'   effective_end_date, '
14041          ||'   deleted_flag '
14042          ||' ) '
14043          ||' SELECT :instance_id, '
14044          ||'   ((gri.instance_id * 2) + 1), '
14045          ||'   ((gri.resource_id * 2) + 1) x_resource_id,  '
14046          ||'   ((iwm.mtl_organization_id * 2) + 1) department_id,'  /* encoded */
14047          ||'   iwm.mtl_organization_id ,  '
14048          ||'   NVL(gri.eqp_serial_number, to_char(gri.instance_number)),  '
14049          ||'   gri.equipment_item_id,  '
14050          ||'   gri.last_setup_id, '  -- Conc Prog routine will populate this
14051          ||'   gri.eff_start_date,  '
14052          ||'   gri.eff_end_date, '
14053          ||'   2 '
14054          ||' FROM  '
14055          ||'   gmp_resource_instances'||p_db_link||' gri,  '
14056          ||'   cr_rsrc_dtl'||p_db_link||' crd, '
14057          ||'   sy_orgn_mst'||p_db_link||' som,'
14058          ||'   ic_whse_mst'||p_db_link||' iwm '
14059          ||' WHERE  '
14060          ||'       gri.resource_id = crd.resource_id '
14061          ||'   AND crd.schedule_ind = 2 '
14062          ||'   AND crd.orgn_code = som.orgn_code '
14063          ||'   AND gri.inactive_ind = 0  '
14064          ||'   AND crd.delete_mark = 0 '
14065          ||'   AND som.delete_mark = 0'
14066          ||'   AND iwm.delete_mark = 0'
14067          ||'   AND som.resource_whse_code = iwm.whse_code' ;
14068 
14069      IF MSC_CL_GMP_UTILITY.g_in_str_org  IS NOT NULL THEN
14070         ins_res_instance := ins_res_instance
14071          ||'   AND EXISTS ( SELECT 1 FROM gmp_item_aps'||p_db_link||' gia '
14072          ||'   WHERE gia.whse_code = som.resource_whse_code )' ;
14073      END IF;
14074 
14075      EXECUTE IMMEDIATE  ins_res_instance USING p_instance_id;
14076 
14077     return_status := TRUE;
14078 
14079 EXCEPTION
14080 
14081     WHEN invalid_string_value  THEN
14082         log_message('APS string is Invalid, check for Error condition' );
14083         return_status := FALSE;
14084     WHEN NO_DATA_FOUND THEN /* B3577871 */
14085         log_message(' NO_DATA_FOUND exception raised in Procedure: MSC_CL_GMP_UTILITY.Rsrc_extract ' );
14086         return_status := TRUE;
14087     WHEN  OTHERS THEN
14088         log_message('Error in department/Res Group Insert: '||p_instance_id);
14089         log_message('stmt_no: ' || stmt_no || '--' || sqlerrm);
14090         return_status := FALSE;
14091 
14092 END rsrc_extract;
14093 
14094 /*
14095 REM+==========================================================================+
14096 REM| PROCEDURE NAME                                                           |
14097 REM|    net_rsrc                                                              |
14098 REM|                                                                          |
14099 REM| Type                                                                     |
14100 REM|    public                                                                |
14101 REM|                                                                          |
14102 REM| DESCRIPTION                                                              |
14103 REM|    The following procedure inserts rows into                             |
14104 REM|    msc_st_net_rsrc_avail table                                           |
14105 REM|                                                                          |
14106 REM| Input Parameters                                                         |
14107 REM|    p_instance_id - Instance Id                                           |
14108 REM|    p_org_id - Organization id                                            |
14109 REM|    p_simulation_set - Simulation Set                                     |
14110 REM|    p_shift_no - Shift number                                             |
14111 REM|    p_cal_date - Calendar date                                            |
14112 REM|    p_from_time - shift starting time                                     |
14113 REM|    p_to_time - Shift Ending time                                         |
14114 REM|                                                                          |
14115 REM| Output Parameters                                                        |
14116 REM|    None                                                                  |
14117 REM|                                                                          |
14118 REM|                                                                          |
14119 REM| HISTORY                                                                  |
14120 REM|    Created 5th Aug 1999 by Sridhar Gidugu (OPM Development Oracle US)    |
14121 REM|    10/13/99 - Added deleted_flag in the insert statement                 |
14122 REM|    01/24/01 - Bug Fix - 1612090, Added new name to the unavailable view  |
14123 REM|                                                                          |
14124 REM|                                                                          |
14125 REM+==========================================================================+
14126 */
14127 
14128 PROCEDURE net_rsrc(p_instance_id    IN NUMBER,
14129                    p_org_id         IN NUMBER,
14130                    p_simulation_set IN VARCHAR2,
14131                    p_resource_id    IN NUMBER,
14132                    p_assigned_qty   IN NUMBER,
14133                    p_shift_num      IN NUMBER,
14134                    p_calendar_date  IN DATE,
14135                    p_from_time      IN NUMBER,
14136                    p_to_time        IN NUMBER ) IS
14137 BEGIN
14138 stmt_no          := 31;
14139     /*  Call Unavail_rsrc_proc */
14140       INSERT INTO msc_st_net_resource_avail
14141                             ( organization_id,
14142                             sr_instance_id,
14143                             resource_id,
14144                             department_id,
14145                             simulation_set,
14146                             shift_num,
14147                             shift_date,
14148                             from_time,
14149                             to_time,
14150                             capacity_units,
14151                             deleted_flag
14152                             )
14153                       values
14154                             ( p_org_id,
14155                             p_instance_id,
14156                             ((p_resource_id * 2) + 1), /* B1177070 */
14157                             ((p_org_id * 2) + 1),  /* B1177070 encoded key */
14158                             p_simulation_set,
14159                             p_shift_num,
14160                             p_calendar_date,
14161                             p_from_time,
14162                             p_to_time,
14163                             p_assigned_qty,
14164                             2
14165                             );
14166 EXCEPTION
14167     WHEN OTHERS THEN
14168       log_message('Failure:net_rsrc Occured ' || stmt_no);
14169 
14170 END net_rsrc;
14171 
14172 /*
14173 REM+==========================================================================+
14174 REM| PROCEDURE NAME                                                           |
14175 REM|    update_trading_partners                                               |
14176 REM|                                                                          |
14177 REM| Type                                                                     |
14178 REM|    public                                                                |
14179 REM|                                                                          |
14180 REM| DESCRIPTION                                                              |
14181 REM|                                                                          |
14182 REM|    This procedure updates the following table :                          |
14183 REM|                                                                          |
14184 REM|                      1. msc_st_trading_partners                          |
14185 REM|                                                                          |
14186 REM| Input Parameters                                                         |
14187 REM|    p_org_id - Organization_id                                            |
14188 REM|    p_cal_code - Calendar_code                                            |
14189 REM|                                                                          |
14190 REM| Output Parameters                                                        |
14191 REM|    None                                                                  |
14192 REM|                                                                          |
14193 REM|                                                                          |
14194 REM| HISTORY                                                                  |
14195 REM|    Created 5th Aug 1999 by Sridhar Gidugu (OPM Development Oracle US)    |
14196 REM|    8/30/99 - Removed the existing Trading Partner Procedure and changed  |
14197 REM|              to a single Update Procedure.                               |
14198 REM|    10/1/99 - Changed Updating Trading Partners,                          |
14199 REM|            - Updated Organization_typw with a value 2 and changed        |
14200 REM|            - partner_type = 3                                            |
14201 REM|                                                                          |
14202 REM|                                                                          |
14203 REM+==========================================================================+
14204 */
14205 PROCEDURE update_trading_partners(p_org_id      IN NUMBER,
14206                                   p_cal_code    IN VARCHAR2,
14207                                   return_status OUT NOCOPY BOOLEAN) IS
14208 BEGIN
14209 
14210     IF return_status THEN
14211        v_cp_enabled := TRUE;
14212     ELSE
14213        v_cp_enabled := FALSE;
14214     END IF;
14215 
14216       stmt_no  := 32;
14217     -- The Following Update statement the Trading Parters table with the
14218     -- Calendar Code for the Organization that uses the Calendar.
14219       UPDATE MSC_ST_TRADING_PARTNERS
14220       SET calendar_code = p_cal_code,
14221           organization_type = 2
14222       WHERE sr_tp_id = p_org_id
14223       AND partner_type = 3;
14224 
14225 
14226       return_status := TRUE;
14227 EXCEPTION
14228     WHEN OTHERS THEN
14229       log_message('Failure:Trading Partners Update Occured ' || stmt_no);
14230       return_status := FALSE;
14231 
14232 END update_trading_partners; /* End of Updating Trading partners */
14233 
14234 /*
14235 REM+==========================================================================+
14236 REM| PROCEDURE NAME                                                           |
14237 REM|    get_cal_no                                                            |
14238 REM|                                                                          |
14239 REM| Type                                                                     |
14240 REM|    public                                                                |
14241 REM|                                                                          |
14242 REM| DESCRIPTION                                                              |
14243 REM|    The following Procedure checks for the value of calendar no and       |
14244 REM|    assigns a new value if the lenght exceeds 10 characters               |
14245 REM|                                                                          |
14246 REM| Input Parameters                                                         |
14247 REM|    p_cal_id - Calendar Id                                                |
14248 REM|    p_cal_no - Calendar No                                                |
14249 REM|                                                                          |
14250 REM| Output Parameters                                                        |
14251 REM|    p_out_cal                                                             |
14252 REM|    p_already_prefixed                                                    |
14253 REM|                                                                          |
14254 REM|                                                                          |
14255 REM| HISTORY                                                                  |
14256 REM|    Created 24th Sep 1999 by Sridhar Gidugu (OPM Development Oracle US)   |
14257 REM|    05/03/2000 - Changed 14characters check to 10 Characters to include   |
14258 REM|                 Instance code as prefix to Calendar code which has       |
14259 REM|                 already has 4 Characters - Bug#1288143                   |
14260 REM|    07/07/2000 - Modified get_cal_no Function to a Procedure, comparisons |
14261 REM|                 with Calendar Code which has Instance Code Prefixes are  |
14262 REM|                 taken  care - Bug# 1337084                               |
14263 REM|                                                                          |
14264 REM|                                                                          |
14265 REM+==========================================================================+
14266 */
14267 
14268 PROCEDURE get_cal_no( p_cal_id           IN  NUMBER,
14269                       p_cal_no           IN  VARCHAR2,
14270                       p_icode            IN  VARCHAR2,
14271                       p_out_cal          OUT NOCOPY VARCHAR2,
14272                       p_already_prefixed OUT NOCOPY VARCHAR2 ) IS
14273 
14274   temp_cal_no          VARCHAR2(10) ;
14275   prefixed_temp_cal_no VARCHAR2(14) ;
14276   out_cal_no           VARCHAR2(14) ;
14277   i                    NUMBER;
14278   k                    NUMBER;
14279   j                    NUMBER;
14280   j_char               VARCHAR2(10) ;
14281   found                NUMBER ;
14282   already_prefixed     VARCHAR2(3) ;
14283 
14284 BEGIN
14285 
14286   temp_cal_no          := NULL;
14287   prefixed_temp_cal_no := NULL ;
14288   out_cal_no           := NULL;
14289   i                    := 0 ;
14290   k                    := 0 ;
14291   j                    := 0 ;
14292   j_char               := NULL;
14293   found                := 0;
14294   stmt_no              := 0;
14295   already_prefixed     := 'NO';
14296 
14297 /* If calendar no is less than 10 , return  */
14298 
14299   IF length(p_cal_no) < 10 or plsqltbl_rec.COUNT < 1 THEN
14300      out_cal_no := substrb(p_cal_no,1,10);
14301   ELSE
14302 
14303   /* The default name generation is the first 10 chars of the calendar no */
14304 
14305      temp_cal_no := substrb(p_cal_no,1,10);
14306 
14307  /* 07/07/2000 - Adding Instance code as a Prefix to the Calendar Code. */
14308 
14309      prefixed_temp_cal_no := p_icode||':'||temp_cal_no;
14310 
14311      out_cal_no := NULL;
14312 
14313   stmt_no   := 10;
14314   FOR i IN 1..plsqltbl_rec.COUNT
14315   LOOP
14316     /*  if a row has already been inserted for the calendar id
14317         use the value from that row and stop the loop  */
14318 
14319       IF plsqltbl_rec(i).calendar_id = p_cal_id
14320       THEN
14321 
14322      /* Commented the following statement and used substrb to pick first
14323         10 characters as it causes a buffer too small problem - Bug#1288143 */
14324 
14325           out_cal_no := substrb(plsqltbl_rec(i).calendar_no,1,14);
14326 
14327      /*
14328        07/07/2000 - Added a check flag to indicate the Instance is already prefixed
14329              and this check is being used at the time when the PLSQL table is
14330              constructed, where in it will not assign an Instance Prefix if the
14331              calendar_code is already prefixed - Bug# 1337084.
14332      */
14333 
14334           already_prefixed := 'YES';
14335           found := 1;
14336           EXIT;
14337       END IF;
14338 
14339   END LOOP; /* End loop for check in the PL/SQL tbl */
14340 
14341   IF found = 0 THEN
14342       k := 10;
14343       j := 0;
14344       j_char := NULL;
14345 
14346       /*
14347        the loop will try the default value then change it if necessary and
14348        until we have exhasted all of the values of 0-99999999999999 (10 chars of numbers)
14349       */
14350       stmt_no   := 20;
14351       LOOP
14352         /* { */
14353         temp_cal_no := j_char || substrb(p_cal_no,1,k);
14354       /*
14355          this loop goes through the current list to see if there is a duplicate
14356          if found we stop and generate a new value then try again
14357       */
14358 
14359         FOR i IN 1..plsqltbl_rec.COUNT LOOP
14360         /*  { */
14361 
14362 /*  07/07/00 - Comparing the Calendar number with Prefixed Calendar Code - Bug#1337084 */
14363 
14364           IF plsqltbl_rec(i).calendar_no = p_icode||':'||temp_cal_no THEN
14365             EXIT;
14366           END IF;
14367           IF i =  plsqltbl_rec.COUNT THEN
14368             found := 1;
14369             out_cal_no := temp_cal_no;
14370           END IF;
14371         /* }  */
14372         END LOOP ;
14373 
14374         /*  if we found a value or reached the max we stop */
14375         IF found = 1 or j = 9999999999 THEN
14376           EXIT;
14377         END IF;
14378 
14379         /*  to get a unique value we keep taking one char at a time from the
14380          the calendar_no.
14381         */
14382         j := j + 1;
14383         j_char := TO_CHAR(j);
14384         k := 10 - length(j_char);
14385 
14386       /* } */
14387       END LOOP;
14388   END IF;
14389 
14390   END IF ;
14391 
14392         p_out_cal := out_cal_no;
14393         p_already_prefixed := already_prefixed ;
14394 EXCEPTION
14395     WHEN OTHERS THEN
14396       log_message('Failure:get_cal_no Occured ' || stmt_no);
14397       p_out_cal := NULL ;
14398       p_already_prefixed := already_prefixed ;
14399 
14400 END get_cal_no; /* End of the Procedure GET_CAL_NO */
14401 /*
14402 REM+==========================================================================+
14403 REM| PROCEDURE NAME                                                           |
14404 REM|    retrieve_calendar_detail                                              |
14405 REM|                                                                          |
14406 REM| Type                                                                     |
14407 REM|    public                                                                |
14408 REM|                                                                          |
14409 REM| DESCRIPTION                                                              |
14410 REM|                                                                          |
14411 REM|                                                                          |
14412 REM| Input Parameters                                                         |
14413 REM|    p_orgn_code - Orgn Code                                               |
14414 REM|    p_org_id - Organization id                                            |
14415 REM|    p_cal_id - calendar_id                                                |
14416 REM|    p_instance_id - Instance Id                                           |
14417 REM|    p_delimiter - Delimiter                                               |
14418 REM|    p_db_link - Data Base Link                                            |
14419 REM|                                                                          |
14420 REM| Output Parameters                                                        |
14421 REM|    return_status                                                         |
14422 REM|                                                                          |
14423 REM|                                                                          |
14424 REM| HISTORY                                                                  |
14425 REM|    Created 5th Aug 1999 by Sridhar Gidugu (OPM Development Oracle US)    |
14426 REM|    9/20/99 - created the Retrieve calendar Procedure                     |
14427 REM|    10/13/99 - Added deleted_flag in the insert statement                 |
14428 REM|    10/18/99 - Changed value of Exception set Id from 1 to -1             |
14429 REM|    12/09/99 - Added Code to include all Calendar Days                    |
14430 REM|    12/17/99 - Fixed Code for Bug# 1117565                                |
14431 REM|    02/01/00 - next seq and prior seqs are made same as seq number in     |
14432 REM|             - msc_calendar_dates insert, bug#1175906                     |
14433 REM|             - similarly for next date and prior date are same as calendar|
14434 REM|             - dates                                                      |
14435 REM|    03/01/00 - Added Code to not to include rows which have               |
14436 REM|               shift_duration as zero seconds - Bug#1221285               |
14437 REM|    03/20/03 - Added Inserts to msc_st_shift_times table - 2213101        |
14438 REM|    03/20/03 - Added Inserts to msc_st_shift_dates table - 2213101        |
14439 REM|                                                                          |
14440 REM|                                                                          |
14441 REM+==========================================================================+
14442 */
14443 PROCEDURE retrieve_calendar_detail( p_cal_id      IN NUMBER,
14444                                     p_calendar_no IN VARCHAR2,
14445                                     p_cal_desc    IN VARCHAR2,
14446                                     p_run_date    IN DATE,
14447                                     p_db_link     IN VARCHAR2,
14448                                     p_instance_id IN NUMBER,
14449                                     p_usage       IN VARCHAR2,
14450                                     return_status OUT NOCOPY BOOLEAN) IS
14451 cal_cur             ref_cursor_typ;
14452 cal_count           NUMBER;
14453 cal_start_date      DATE;
14454 cal_end_date        DATE;
14455 sql_stmt2           VARCHAR2(32700);
14456 sql_stmt3           VARCHAR2(32700);
14457 v_cal_date          DATE;
14458 v_shift_num         NUMBER;
14459 v_from_time         NUMBER;
14460 v_to_time           NUMBER;
14461 old_occur           NUMBER;
14462 prior_occur         NUMBER;
14463 old_cal_date        DATE;
14464 seq_num             NUMBER;
14465 prior_seq_num       NUMBER;
14466 next_seq_num        NUMBER;
14467 shift_seq_num       NUMBER;
14468 shift_prior_seq_num NUMBER;
14469 shift_next_seq_num  NUMBER;
14470 shift_next_date     DATE;
14471 shift_prior_date    DATE;
14472 shift_old_date      DATE;
14473 v_prior_date        DATE;
14474 v_old_cal_date      DATE;
14475 v_seq_num           NUMBER;
14476 v_next_seq_num      NUMBER;
14477 v_prior_seq_num     NUMBER;
14478 i                   INTEGER;
14479 j                   INTEGER;
14480 x                   INTEGER;
14481 old_weekly          NUMBER ;
14482 prior_weekly        NUMBER ;
14483 old_period          NUMBER ;
14484 prior_period        NUMBER ;
14485 period_char         VARCHAR2(8);
14486 week_end            DATE;
14487 weekly_seq          NUMBER ;
14488 period_seq          NUMBER ;
14489 week_num            NUMBER ;
14490 /* 05-JAN-2002 Rajesh Patangya  */
14491 wps_index           INTEGER ;
14492 /* 12/13/02 - Rajesh Patangya B2710601, Added database link  */
14493 ins_stmt            VARCHAR2(32700) ;
14494 ins_stmt1           VARCHAR2(32700) ;
14495 shft_time           VARCHAR2(32700) ;
14496 temp_from_date      DATE ;
14497 temp_to_date        DATE ;
14498 temp_to_time        NUMBER ;
14499 temp_shift_num      NUMBER ;
14500 
14501 BEGIN
14502 
14503   cal_count         := 0;
14504   prior_occur       := 1;
14505   old_cal_date      :=  to_date('01/01/1959','DD/MM/YYYY');
14506   seq_num           := 0;
14507   prior_seq_num     := 1;
14508   shift_seq_num     := 0;
14509   shift_prior_seq_num := 1;
14510   shift_old_date    := to_date('01/01/1959','DD/MM/YYYY');
14511 
14512   i                 := 0;
14513   j                 := 0;
14514   x                 := 0;
14515   old_weekly        := 0;
14516   prior_weekly      := 0;
14517   old_period        := 0;
14518   prior_period      := 0;
14519   period_char       := NULL;
14520   weekly_seq        := 0;
14521   period_seq        := 0;
14522   week_num          := 0;
14523   wps_index         := 0;
14524   ins_stmt          := NULL;
14525   ins_stmt1         := NULL;
14526   shft_time         := NULL;
14527   temp_from_date    := NULL;
14528   temp_to_date      := NULL;
14529   temp_to_time      := 0 ;
14530   temp_shift_num    := 0 ;
14531   stmt_no           := 0;
14532 
14533        /* Insert for Net Resource starts here, The following select statement
14534           gets the period that are availble for a given calendar, From time
14535           and To Time are taken in seconds here.
14536        */
14537 
14538     IF return_status THEN
14539        v_cp_enabled := TRUE;
14540     ELSE
14541        v_cp_enabled := FALSE;
14542     END IF;
14543 
14544 --
14545        stmt_no := 10;
14546        sql_stmt3 := ' SELECT msd.calendar_date calendar_date,  '
14547                     || '      dd.shift_no  shift_no,                 '
14548                     || '      dd.shift_start  from_time,             '
14549                     || '      dd.shift_start + dd.shift_duration  to_time  '
14550                     || ' FROM   mr_shcl_dtl'||p_db_link||'  msd, '
14551                     || '        mr_shdy_hdr'||p_db_link||'  dh,  '
14552                     || '        mr_shdy_dtl'||p_db_link||'  dd   '
14553                     || ' WHERE msd.calendar_id = :curr_cal_id   '
14554                     || ' and   dh.shopday_no = msd.shopday_no   '
14555                     || ' AND dd.shopday_no = dh.shopday_no      '
14556                     || ' AND msd.delete_mark = 0                '
14557                     || ' AND dh.delete_mark  = 0                '
14558                     || ' AND dd.delete_mark  = 0                '
14559                     || ' AND dd.shift_duration  > 0             '
14560                     || ' ORDER BY  calendar_date,               '
14561                     || '           from_time,                   '
14562                     || '           to_time  ';
14563 
14564     /* The cursor is opened and the values are stored in a PL/SQL table
14565       for further processing If Pl/SQL Tbl new_rec  has any residual rows,
14566       we Need to clean before populating the New Table - 12/17/99 */
14567 
14568        IF new_rec.COUNT > 0 THEN
14569           new_rec.delete;
14570        END IF;
14571 
14572       /*      OPEN cal_cur FOR sql_stmt3 USING p_cal_id,trunc(p_run_date); */
14573 
14574        OPEN cal_cur FOR sql_stmt3 USING p_cal_id;
14575 
14576      stmt_no := 20;
14577      i := 0;
14578      LOOP
14579        FETCH cal_cur
14580        INTO  calendar_record;
14581        EXIT WHEN cal_cur%NOTFOUND;
14582 
14583        stmt_no := 30;
14584 
14585        /*  Check for the First record  */
14586        IF i = 0 THEN
14587          stmt_no := 40;
14588 
14589          /*  Check if the first row to time is spilling over  */
14590 
14591          IF calendar_record.to_time > no_of_secs THEN
14592            i := i + 1;
14593            new_rec(i).cal_date := calendar_record.cal_date ;
14594            new_rec(i).shift_num := calendar_record.shift_num ;
14595            new_rec(i).from_time := calendar_record.from_time;
14596            new_rec(i).to_time := no_of_secs ;
14597 
14598  /*           Add more record for the spilled over shift  */
14599            i := i +1 ;
14600 
14601            new_rec(i).cal_date := calendar_record.cal_date + 1 ;
14602            new_rec(i).shift_num := calendar_record.shift_num ;
14603            new_rec(i).from_time := 0 ;
14604            new_rec(i).to_time := calendar_record.to_time - no_of_secs ;
14605          ELSE
14606              /*  Else Store the values in the PL/sql table          */
14607 
14608            i := i + 1;
14609            new_rec(i).cal_date := calendar_record.cal_date ;
14610            new_rec(i).shift_num := calendar_record.shift_num ;
14611            new_rec(i).from_time := calendar_record.from_time;
14612            new_rec(i).to_time := calendar_record.to_time;
14613 
14614          END IF;
14615 
14616        /*   If not the first record, then check if the Calendar date
14617             is greater than the Previous cal date in the PL/sql table */
14618      ELSE
14619        IF calendar_record.cal_date >  new_rec(i).cal_date  THEN
14620 
14621           /*  Check if the Date, to_time is spilling over */
14622          IF calendar_record.to_time > no_of_secs THEN
14623            i := i + 1;
14624            new_rec(i).cal_date := calendar_record.cal_date;
14625            new_rec(i).from_time := calendar_record.from_time;
14626            new_rec(i).shift_num := calendar_record.shift_num;
14627            new_rec(i).to_time := no_of_secs;
14628 
14629        /*          Add more record for the spilled over shift  */
14630              i := i + 1;
14631              new_rec(i).cal_date := calendar_record.cal_date + 1;
14632              new_rec(i).shift_num := calendar_record.shift_num;
14633              new_rec(i).from_time := 0;
14634              new_rec(i).to_time := calendar_record.to_time - no_of_secs ;
14635          ELSE
14636              /*   Else Store the values in the PL/sql table          */
14637 
14638              i := i + 1 ;
14639              new_rec(i).cal_date := calendar_record.cal_date ;
14640              new_rec(i).shift_num := calendar_record.shift_num ;
14641              new_rec(i).from_time := calendar_record.from_time;
14642              new_rec(i).to_time := calendar_record.to_time;
14643 
14644          END IF;
14645 
14646        /*  If not the first record, then check if the Calendar date
14647            is equal to the Previous cal date in the PL/sql table */
14648 
14649      ELSIF calendar_record.cal_date =  new_rec(i).cal_date THEN
14650 
14651         /*  Checking if the Cursor from_time is greater than Previous record to_time */
14652 
14653           IF calendar_record.from_time >  new_rec(i).to_time  THEN
14654              /*  Check if the Date, to_time is spilling over */
14655              IF calendar_record.to_time > no_of_secs THEN
14656                i := i + 1;
14657                new_rec(i).cal_date := calendar_record.cal_date;
14658                new_rec(i).from_time := calendar_record.from_time;
14659                new_rec(i).shift_num := calendar_record.shift_num;
14660                new_rec(i).to_time := no_of_secs;
14661 
14662            /*  Add more record for the spilled over shift  */
14663                  i := i + 1;
14664                  new_rec(i).cal_date := calendar_record.cal_date + 1 ;
14665                  new_rec(i).from_time := 0 ;
14666                  new_rec(i).shift_num := calendar_record.shift_num;
14667                  new_rec(i).to_time := calendar_record.to_time - no_of_secs ;
14668              ELSE
14669                 i := i + 1;
14670                 new_rec(i).cal_date := calendar_record.cal_date ;
14671                 new_rec(i).shift_num := calendar_record.shift_num ;
14672                 new_rec(i).from_time := calendar_record.from_time;
14673                 new_rec(i).to_time := calendar_record.to_time;
14674             END IF ;
14675          ELSE      /* Merge time !!!
14676                       Shifts Merge is the start time of the shift is Less than
14677                       the Previous record to_time
14678                Checking if the record that is Merged is spilling Over to next day */
14679              IF calendar_record.to_time > no_of_secs THEN
14680                 new_rec(i).to_time := no_of_secs ;
14681                /* Add more record for the spilled over shift  */
14682                  i := i + 1;
14683                  new_rec(i).cal_date := calendar_record.cal_date + 1;
14684                  new_rec(i).from_time := 0 ;
14685                  new_rec(i).shift_num := calendar_record.shift_num;
14686                  new_rec(i).to_time := calendar_record.to_time - no_of_secs ;
14687               ELSE
14688                 IF  calendar_record.to_time > new_rec(i).to_time THEN
14689                   new_rec(i).to_time := calendar_record.to_time ;
14690                 END IF ;
14691               END IF  ;
14692           END IF ; /* End OF Merge time  */
14693 
14694        /*  checking if the Calendar date is less than the Previous cal date
14695            in the PL/sql table This check is useful when two shifts in a day
14696            are crossing Midnight Then in that case we need to compare the start
14697            time with the Previously completed shift end time and the dates too. */
14698 
14699         ELSIF calendar_record.cal_date <  new_rec(i).cal_date THEN
14700             IF calendar_record.to_time > no_of_secs THEN
14701               IF calendar_record.to_time - no_of_secs > new_rec(i).to_time THEN
14702                  new_rec(i).to_time := calendar_record.to_time - no_of_secs ;
14703               END IF;
14704             END IF ;
14705 
14706         END IF ; /* End if for date check */
14707      END IF; /* End if for i = 0 */
14708 
14709      END LOOP;
14710 
14711      /*  cal count gives the Number of rows after the Calendar is exploded */
14712      cal_count := new_rec.COUNT ;
14713      /*  Calendar Start date and End dates are Calculated here  */
14714      cal_start_date := new_rec(1).cal_date;
14715      cal_end_date := new_rec(cal_count).cal_date;
14716 
14717      CLOSE cal_cur;
14718 
14719    /* 05-JAN-2002 Rajesh Patangya  */
14720    /* Start writing the exploded Calendar dates into temp table */
14721    wps_index         := 1 ;
14722 
14723    /* 12/13/02 - Rajesh Patangya B2710601, Added database link  */
14724      ins_stmt := 'INSERT INTO gmp_calendar_detail_gtmp'||p_db_link
14725                           ||' ( '
14726                           ||'   calendar_id, '
14727                           ||'   shift_num, '
14728                           ||'   shift_date, '
14729                           ||'   from_time, '
14730                           ||'   to_time, '
14731                           ||'   from_date, '
14732                           ||'   to_date '
14733                           ||' ) '
14734                           ||' VALUES '
14735                           ||' ( :p1,:p2,:p3,:p4,:p5,:p6,:p7)';
14736 
14737 
14738      ins_stmt1 := 'INSERT INTO temp_cal'||p_db_link
14739                           ||' ( '
14740                           ||'   calendar_id, '
14741                           ||'   shift_num, '
14742                           ||'   shift_date, '
14743                           ||'   from_time, '
14744                           ||'   to_time, '
14745                           ||'   from_date, '
14746                           ||'   to_date '
14747                           ||' ) '
14748                           ||' VALUES '
14749                           ||' ( :p1,:p2,:p3,:p4,:p5,:p6,:p7)';
14750 --
14751    FOR wps_index IN 1..new_rec.COUNT
14752    LOOP
14753 
14754      temp_from_date := (new_rec(wps_index).cal_date +
14755                          (new_rec(wps_index).from_time/86400)) ;
14756 
14757      IF new_rec(wps_index).to_time = 86400 THEN
14758      temp_to_time   := new_rec(wps_index).to_time - 1 ;
14759      temp_shift_num := new_rec(wps_index).shift_num  + 99999 ;
14760      ELSE
14761      temp_to_time   := new_rec(wps_index).to_time  ;
14762      temp_shift_num := new_rec(wps_index).shift_num;
14763      END IF ;
14764 
14765      temp_to_date   := (new_rec(wps_index).cal_date + (temp_to_time /86400)) ;
14766 
14767      EXECUTE IMMEDIATE ins_stmt USING
14768                                 p_cal_id,
14769                                 temp_shift_num,
14770                                 new_rec(wps_index).cal_date,
14771                                 new_rec(wps_index).from_time,
14772                                 temp_to_time,
14773                                 temp_from_date,
14774                                 temp_to_date
14775                                ;
14776   /*
14777      EXECUTE IMMEDIATE ins_stmt1 USING
14778                                 p_cal_id,
14779                                 temp_shift_num,
14780                                 new_rec(wps_index).cal_date,
14781                                 new_rec(wps_index).from_time,
14782                                 temp_to_time,
14783                                 temp_from_date,
14784                                 temp_to_date
14785                                ;
14786   */
14787     END LOOP;
14788 --       log_message(to_char(sysdate,'MM/DD/YYYY HH24:MI:SS'));
14789 
14790    IF p_usage = 'APS' THEN
14791        /* Insert for msc_st_shift_times Starts Here - 2213101 */
14792        stmt_no := 41;
14793        shft_time := '  INSERT INTO msc_st_shift_times '
14794                     || ' (shift_num,                      '
14795                     || '  calendar_code,                  '
14796                     || '  from_time,                      '
14797                     || '  to_time,                        '
14798                     || '  deleted_flag,                   '
14799                     || '  sr_instance_id                  '
14800                     || ' )                                '
14801                     || ' SELECT distinct shift_num ,   '
14802                     || '  :calendar_no,                      '
14803                     || '  from_time,         '
14804                     || '  to_time,  '
14805                     || '  2  ,                    '
14806                     || '  :instance_id                      '
14807                     || ' FROM  gmp_calendar_detail_gtmp'||p_db_link||'  gtmp '
14808                     || ' WHERE calendar_id = :curr_cal_id   '
14809                     || ' ORDER BY shift_num,from_time, to_time ' ;
14810 
14811        EXECUTE IMMEDIATE shft_time USING p_calendar_no,
14812                                          p_instance_id,
14813                                          p_cal_id;
14814 
14815        /* Insert for msc_st_shift_times Ends Here - 2213101 */
14816 --
14817      /* Start writing the Calendar dates */
14818 
14819      old_occur := 1;
14820      old_cal_date := new_rec(1).cal_date;
14821 
14822      old_weekly := 1;
14823      prior_weekly := 1;
14824      old_period := 1;
14825      prior_period := 1;
14826 
14827      period_char := TO_CHAR(new_rec(old_period).cal_date,'MON-YYYY');
14828      weekly_seq := 0;
14829      period_seq := 0;
14830 
14831      SELECT to_char(new_rec(old_weekly).cal_date,'D') INTO week_num FROM dual;
14832      week_num := (week_num - 7) * -1;
14833      week_end := new_rec(old_weekly).cal_date + week_num;
14834 
14835      /*
14836       The PL/sql table thus Populated after exploding the Calendar is useful in
14837       Populating MSC_ST_CALENDAR_DATES here
14838      */
14839      stmt_no := 50;
14840      FOR j IN 1 ..cal_count
14841      LOOP
14842        IF new_rec(j).cal_date <> old_cal_date THEN
14843           seq_num := seq_num + 1;
14844           prior_seq_num := seq_num - 1;
14845           IF prior_seq_num < 1 THEN
14846              prior_seq_num := 1;
14847           END IF;
14848           next_seq_num := seq_num + 1;
14849          /* Code change to include all the Calendar Days in the
14850             Staging Calendar Table
14851          */
14852 
14853         /* After allowing the first row insert, check from the second row on
14854            if there are any gaps in the dates
14855         */
14856           IF seq_num >= 1 THEN
14857           /* using information from the Prior set values of sequences and dates */
14858 
14859              v_next_seq_num := next_seq_num;
14860              v_prior_seq_num := seq_num;
14861              v_old_cal_date := old_cal_date;
14862              v_prior_date := old_cal_date;
14863 
14864          /* Start of Code change to include all the Calendar Days in the
14865             Staging Calendar Table
14866          */
14867 
14868              stmt_no := 51;
14869              WHILE ( v_old_cal_date + 1 < new_rec(j).cal_date)
14870              LOOP
14871                   INSERT INTO msc_st_calendar_dates
14872                                   (calendar_date,
14873                                    calendar_code,
14874                                    exception_set_id,
14875                                    seq_num,
14876                                    next_seq_num,
14877                                    prior_seq_num,
14878                                    next_date,
14879                                    prior_date,
14880                                    calendar_start_date,
14881                                    calendar_end_date,
14882                                    description,
14883                                    sr_instance_id,
14884                                    deleted_flag
14885                                   )
14886                             values(v_old_cal_date + 1,
14887                                    p_calendar_no,
14888                                    -1,
14889                                    NULL,
14890                                    v_next_seq_num,
14891                                    v_prior_seq_num,
14892                                    new_rec(j).cal_date,
14893                                    v_prior_date,
14894                                    cal_start_date,
14895                                    cal_end_date,
14896                                    p_cal_desc,
14897                                    p_instance_id,
14898                                    2
14899                                    );
14900                  /* The Calendar Date needs to be incremented to check for
14901                     further gaps in the dates
14902                  */
14903                  v_old_cal_date := v_old_cal_date + 1;
14904              END LOOP;
14905           END IF;
14906 
14907          /* End of Code change to include all the Calendar Days in the
14908             Staging Calendar Table
14909          */
14910 
14911         /* New changes made to the calendar sequences, Bug#1175906
14912            nextseq, prior_seq are made same as seq number for working
14913            days, and similarly for next date and prior_dates are same as
14914            calendar_dates - 02/01/2000
14915         */
14916 
14917           stmt_no := 52;
14918           INSERT INTO msc_st_calendar_dates
14919                  (calendar_date,
14920                   calendar_code,
14921                   exception_set_id,
14922                   seq_num,
14923                   next_seq_num,
14924                   prior_seq_num,
14925                   next_date,
14926                   prior_date,
14927                   calendar_start_date,
14928                   calendar_end_date,
14929                   description,
14930                   sr_instance_id,
14931                   deleted_flag
14932                  )
14933            VALUES(new_rec(old_occur).cal_date,
14934                   p_calendar_no,
14935                   -1,
14936                   seq_num,
14937                   seq_num,
14938                   seq_num,
14939                   new_rec(old_occur).cal_date,
14940                   new_rec(old_occur).cal_date,
14941                   cal_start_date,
14942                   cal_end_date,
14943                   p_cal_desc,
14944                   p_instance_id,
14945                   2
14946                  );
14947 
14948              /*  write weekly bucket */
14949              stmt_no := 53;
14950              IF new_rec(j).cal_date > week_end THEN
14951                weekly_seq := weekly_seq + 1;
14952                INSERT INTO msc_st_cal_week_start_dates
14953                  ( CALENDAR_CODE         ,
14954                    EXCEPTION_SET_ID       ,
14955                    WEEK_START_DATE        ,
14956                    NEXT_DATE              ,
14957                    PRIOR_DATE             ,
14958                    SEQ_NUM                ,
14959                    DELETED_FLAG           ,
14960                    SR_INSTANCE_ID)
14961                VALUES
14962                  ( p_calendar_no ,
14963                    -1,
14964                    new_rec(old_weekly).cal_date,
14965                    new_rec(j).cal_date,
14966                    new_rec(prior_weekly).cal_date,
14967                    weekly_seq,
14968                    2,
14969                    p_INSTANCE_ID) ;
14970 
14971                week_num := 0;
14972                SELECT TO_CHAR(new_rec(j).cal_date,'D') INTO week_num FROM dual;
14973                week_num := (week_num - 7) * -1;
14974                prior_weekly := old_weekly;
14975                old_weekly := j;
14976                week_end := new_rec(old_weekly).cal_date + week_num;
14977 
14978                /*  write period bucket */
14979                IF period_char <> TO_CHAR(new_rec(j).cal_date,'MON-YYYY') THEN
14980                  period_seq := period_seq + 1;
14981 
14982                  stmt_no := 54;
14983                  INSERT INTO msc_st_period_start_dates
14984                  ( CALENDAR_CODE         ,
14985                    EXCEPTION_SET_ID       ,
14986                    PERIOD_START_DATE      ,
14987                    PERIOD_SEQUENCE_NUM    ,
14988                    PERIOD_NAME            ,
14989                    NEXT_DATE              ,
14990                    PRIOR_DATE             ,
14991                    DELETED_FLAG           ,
14992                    SR_INSTANCE_ID)
14993                  VALUES
14994                  ( p_calendar_no ,
14995                    -1,
14996                    new_rec(old_period).cal_date,
14997                    period_seq,
14998                    TO_CHAR(new_rec(old_period).cal_date, 'MON'),
14999                    new_rec(j).cal_date,
15000                    new_rec(prior_period).cal_date,
15001                    2,
15002                    p_INSTANCE_ID);
15003 
15004                  prior_period := old_period;
15005                  old_period := j;
15006                  period_char := TO_CHAR(new_rec(old_period).cal_date,'MON-YYYY');
15007                END IF;
15008              END IF;
15009 
15010              old_cal_date := new_rec(j).cal_date;
15011              prior_occur := old_occur;
15012              old_occur := j;
15013              prior_seq_num := seq_num;
15014        END IF;
15015      END LOOP;
15016 
15017      /* Insert for the last record */
15018 
15019      stmt_no := 60;
15020      INSERT INTO msc_st_calendar_dates
15021        ( calendar_date,
15022          calendar_code,
15023          exception_set_id,
15024          seq_num,
15025          next_seq_num,
15026          prior_seq_num,
15027          next_date,
15028          prior_date,
15029          calendar_start_date,
15030          calendar_end_date,
15031          description,
15032          sr_instance_id
15033          )
15034       VALUES
15035        ( new_rec(old_occur).cal_date,
15036          p_calendar_no,
15037          -1,
15038          seq_num + 1,
15039          seq_num + 1,
15040          seq_num + 1,
15041          new_rec(old_occur).cal_date,
15042          new_rec(old_occur).cal_date,
15043          cal_start_date,
15044          cal_end_date,
15045          p_cal_desc,
15046          p_instance_id
15047        );
15048 
15049      weekly_seq := weekly_seq + 1;
15050 
15051      stmt_no := 61;
15052      INSERT INTO msc_st_cal_week_start_dates
15053        ( CALENDAR_CODE         ,
15054          EXCEPTION_SET_ID       ,
15055          WEEK_START_DATE        ,
15056          NEXT_DATE              ,
15057          PRIOR_DATE             ,
15058          SEQ_NUM                ,
15059          DELETED_FLAG           ,
15060          SR_INSTANCE_ID)
15061      VALUES
15062        ( p_calendar_no ,
15063          -1,
15064          new_rec(old_weekly).cal_date,
15065          new_rec(old_weekly).cal_date,
15066          new_rec(prior_weekly).cal_date,
15067          weekly_seq,
15068          2,
15069          p_INSTANCE_ID) ;
15070 
15071 
15072      period_seq := period_seq + 1;
15073 
15074      stmt_no := 63;
15075      INSERT INTO msc_st_period_start_dates
15076      ( CALENDAR_CODE         ,
15077        EXCEPTION_SET_ID       ,
15078        PERIOD_START_DATE      ,
15079        PERIOD_SEQUENCE_NUM    ,
15080        PERIOD_NAME            ,
15081        NEXT_DATE              ,
15082        PRIOR_DATE             ,
15083        DELETED_FLAG           ,
15084        SR_INSTANCE_ID
15085      )
15086      VALUES
15087      (p_calendar_no ,
15088       -1,
15089       new_rec(old_period).cal_date,
15090       period_seq,
15091       TO_CHAR(new_rec(old_period).cal_date, 'MON'),
15092       new_rec(old_period).cal_date,
15093       new_rec(prior_period).cal_date,
15094       2,
15095       p_INSTANCE_ID);
15096 
15097       /* B2213101 - Code added for Insert into msc_st_shift_dates */
15098      stmt_no := 70;
15099      shift_prior_date := new_rec(1).cal_date;
15100 
15101      FOR h IN 1 ..new_rec.COUNT
15102      LOOP
15103 
15104          shift_seq_num := shift_seq_num + 1;
15105 
15106          shift_prior_seq_num := shift_seq_num - 1;
15107          IF shift_prior_seq_num < 1 THEN
15108              shift_prior_seq_num := 1;
15109          END IF;
15110 
15111          shift_next_seq_num := shift_seq_num + 1;
15112          IF shift_next_seq_num > new_rec.COUNT THEN
15113             shift_next_seq_num := shift_next_seq_num - 1;
15114          END IF;
15115 
15116          IF new_rec(1).shift_num = new_rec(h).shift_num THEN
15117             IF shift_seq_num = 1 THEN
15118                shift_prior_date := new_rec(h).cal_date;
15119                shift_next_date  := shift_prior_date + 1;
15120             ELSE
15121                shift_prior_date := new_rec(h-1).cal_date;
15122                shift_next_date  := new_rec(h).cal_date + 1;
15123             END IF;
15124          END IF;
15125 
15126 
15127          INSERT INTO msc_st_shift_dates
15128            ( calendar_code,
15129              exception_set_id,
15130              shift_num,
15131              shift_date,
15132              seq_num,
15133              next_seq_num,
15134              prior_seq_num,
15135              next_date,
15136              prior_date,
15137              deleted_flag,
15138              sr_instance_id
15139            )
15140          VALUES
15141            ( p_calendar_no,
15142              -1,
15143              new_rec(h).shift_num,
15144              new_rec(h).cal_date,
15145              shift_seq_num,
15146              shift_next_seq_num,
15147              shift_prior_seq_num,
15148              shift_next_date,
15149              shift_prior_date,
15150              2,
15151              p_instance_id
15152            );
15153 
15154      END LOOP;
15155 
15156       /* B2213101 - End of changes for  Insert into msc_st_shift_dates */
15157 
15158   END IF ; /*  End if for usage */
15159 
15160   return_status := TRUE;
15161 
15162 EXCEPTION
15163    WHEN NO_DATA_FOUND THEN
15164     log_message('Calendar has no days set in the Calendar Detail : '||p_calendar_no);
15165     log_message('stmt_no = ' || stmt_no || '--' || sqlerrm);
15166     return_status := FALSE;
15167 
15168    WHEN OTHERS THEN
15169     log_message('Error in retrieve Calendar Detail : ' || sqlerrm);
15170     return_status := FALSE;
15171 
15172 END retrieve_calendar_detail;
15173 
15174 /*
15175 REM+==========================================================================+
15176 REM| PROCEDURE NAME                                                           |
15177 REM|    net_rsrc_insert                                                       |
15178 REM|                                                                          |
15179 REM| Type                                                                     |
15180 REM|    public                                                                |
15181 REM|                                                                          |
15182 REM| DESCRIPTION                                                              |
15183 REM|                                                                          |
15184 REM|                                                                          |
15185 REM| Input Parameters                                                         |
15186 REM|    p_org_id - Organization id                                            |
15187 REM|    p_orgn_code - Orgn Code                                               |
15188 REM|    p_calendar_id - calendar_id                                           |
15189 REM|    p_instance_id - Instance Id                                           |
15190 REM|    p_usage - Used foir APS or WPS                                        |
15191 REM|    p_db_link - Data Base Link                                            |
15192 REM|                                                                          |
15193 REM| Output Parameters                                                        |
15194 REM|    return_status                                                         |
15195 REM|                                                                          |
15196 REM| HISTORY                                                                  |
15197 REM|    Created on 4th Jan 2002 By Rajesh Patangya                            |
15198 REM|    7th Mar 2003 -- Performance issue fix and B2671540 00:00 shift fix    |
15199 REM| B3161696 - 26-SEP-2003 TARGETTED RESOURCE AVAILABILITY PLACEHOLDER BUG   |
15200 REM| B4309093 - 20-APR-2005 Modified code to TO ADD TIME OR A SHIFT TO A      |
15201 REM|                        PLANT RESOURCE                                    |
15202 REM+==========================================================================+
15203 */
15204 PROCEDURE net_rsrc_insert(p_org_id         IN NUMBER,
15205                           p_orgn_code      IN VARCHAR2,
15206                           p_simulation_set IN VARCHAR2,
15207                           p_db_link        IN VARCHAR2,
15208                           p_instance_id    IN NUMBER,
15209                           p_run_date       IN DATE ,
15210                           p_calendar_id    IN NUMBER,
15211                           p_usage          IN VARCHAR2,
15212                           return_status    OUT NOCOPY BOOLEAN) IS
15213 
15214 ri_shift_interval	ref_cursor_typ;
15215 
15216 gsql_stmt		varchar2(10000) ;
15217 sql_stmt1		varchar2(32000) ;
15218 sql_shifts 		varchar2(32000) ;
15219 i         		INTEGER ;
15220 j         		INTEGER ;
15221 g_calendar_id 		NUMBER  ;
15222 
15223 BEGIN
15224          /* 8i Database does not support BULK COLLECT - B3881832 */
15225          stmt_no	 := 0;
15226          i     		 := 1;
15227          j     		 := 1;
15228          resource_count  := empty_num_table;
15229          resource_id     := empty_num_table;
15230          instance_id     := empty_num_table;
15231          instance_number := empty_num_table;
15232          shift_num       := empty_num_table;
15233          f_date          := empty_dat_table;
15234          t_date          := empty_dat_table;
15235 
15236          /* 8i Database does not support BULK COLLECT - B3881832 */
15237          dbms_session.free_unused_user_memory;
15238 
15239          stmt_no := 72;
15240          -- Rajesh Patangya B4692705, When the calendar is not assigned to
15241          -- resource then organization calendar should be considered
15242 	 g_calendar_id 	:= 0 ;
15243          gsql_stmt :=  '  SELECT mfg_calendar_id '
15244                     || '  FROM  sy_orgn_mst'||p_db_link
15245                     || '  WHERE orgn_code = :orgn_code1 ';
15246 
15247          EXECUTE IMMEDIATE gsql_stmt INTO g_calendar_id USING p_orgn_code ;
15248 
15249          IF g_calendar_id = 0 THEN
15250             log_message('Warning : '||p_orgn_code||
15251                     ' does not have manufacturing calendar, continuing ...') ;
15252          END IF;
15253 
15254     /* Interval Cursor gives the all the point of inflections  */
15255 
15256        stmt_no := 73;
15257        -- HW B4309093 Check for calendar id in cr_rsrc_dtl
15258        sql_stmt1 :=  ' SELECT /*+ ALL_ROWS */ '
15259                   || ' 	decode(rt.interval_date,rt.lead_idate,rt.assigned_qty,decode(rt.rsum,0,rt.assigned_qty,rt.assigned_qty-rt.rsum)) resource_count  '
15260                   || ' 	,rt.resource_id '
15261                   || ' 	,0 instance_id '
15262                   || ' 	,0 instance_number '
15263                   || ' 	,rt.shift_num '
15264                   || ' 	,rt.interval_date	from_date  '
15265                   || ' 	,rt.lead_idate		to_date '
15266                   || ' FROM '
15267                   || ' ( '
15268                   || ' SELECT '
15269                   || ' 	t.resource_id '
15270                   || ' 	,t.shift_num  '
15271                   || ' 	,t.interval_date '
15272                   || ' 	,t.assigned_qty  '
15273                   || ' 	,nvl(sum(u.resource_units),0) rsum  '
15274                   || ' 	,max(t.lead_idate) lead_idate '
15275                   || ' FROM '
15276                   || ' ( '
15277                   || ' SELECT unique resource_id,instance_number,from_date, '
15278                   || ' to_date to_date1,resource_units '
15279                   || ' FROM ( '
15280                   || ' SELECT un.resource_id, '
15281                   || '        gri.instance_number, '
15282                   || '        un.from_date,  '
15283                   || '        un.to_date,    '
15284                   || '        1 resource_units'
15285                   || ' FROM   cr_rsrc_dtl '||p_db_link||'  crd, '
15286                   || '        gmp_rsrc_unavail_dtl_v '||p_db_link||' un, '
15287                   || '        gmp_resource_instances '||p_db_link||' gri '
15288                   || ' WHERE  crd.resource_id = un.resource_id  '
15289                   || ' AND    crd.resource_id = gri.resource_id  '
15290                   || ' AND    un.instance_id  = gri.instance_id  '
15291                   || ' AND    crd.orgn_code = :orgn_code ' ;
15292 
15293     IF (p_usage = 'BASED') THEN   /* Usage APS */
15294     sql_stmt1 := sql_stmt1
15295                   || ' AND    crd.calendar_id = :l_cal_id ' ;
15296     ELSE
15297     sql_stmt1 := sql_stmt1
15298                   || ' AND    nvl(crd.calendar_id,:g_default_cal_id)=:l_cal_id';
15299     END IF ;
15300 
15301     sql_stmt1 := sql_stmt1
15302                   || ' AND    crd.schedule_ind = 2 '
15303                   || ' AND    crd.delete_mark = 0 ' ;
15304 
15305     IF (v_from_rsrc IS NOT NULL AND v_to_rsrc IS NOT NULL) THEN
15306     sql_stmt1 := sql_stmt1 || '  AND crd.resources BETWEEN :frsrc and :trsrc ' ;
15307     END IF ;
15308 
15309 -- HW B4309093 Check for calendar id in cr_rsrc_dtl
15310     sql_stmt1 := sql_stmt1
15311                   || ' AND    nvl(un.instance_id,0) <> 0  '
15312                   || ' UNION ALL '
15313                   || ' SELECT un.resource_id, '
15314                   || '        gri.instance_number, '
15315                   || '        un.from_date,  '
15316                   || '        un.to_date,    '
15317                   || '        1 resource_units'
15318                   || ' FROM   cr_rsrc_dtl '||p_db_link||'  crd, '
15319                   || '        gmp_rsrc_unavail_dtl_v '||p_db_link||' un, '
15320                   || '        gmp_resource_instances '||p_db_link||' gri '
15321                   || ' WHERE  crd.resource_id = un.resource_id  '
15322                   || ' AND    crd.resource_id = gri.resource_id  '
15323                   || ' AND    crd.orgn_code = :orgn_code1 ' ;
15324 
15325     IF (p_usage = 'BASED') THEN   /* Usage APS */
15326     sql_stmt1 := sql_stmt1
15327                   || ' AND    crd.calendar_id = :l_cal_id1 ' ;
15328     ELSE
15329     sql_stmt1 := sql_stmt1
15330                   || ' AND    nvl(crd.calendar_id ,:g_default_cal_id1)= :l_cal_id1 ';
15331     END IF ;
15332     sql_stmt1 := sql_stmt1
15333                   || ' AND    crd.delete_mark = 0 '
15334                   || ' AND    crd.schedule_ind = 2 '
15335                   || ' AND    nvl(un.instance_id,0) = 0  ' ;
15336 
15337     IF (v_from_rsrc IS NOT NULL AND v_to_rsrc IS NOT NULL) THEN
15338     sql_stmt1 := sql_stmt1 || '  AND crd.resources BETWEEN :frsrc and :trsrc ' ;
15339     END IF ;
15340 
15341 -- HW B4309093 Check for calendar id in cr_rsrc_dtl
15342     sql_stmt1 := sql_stmt1
15343                   || ' AND    gri.instance_number in '
15344                   || '      ( select tgri.instance_number '
15345                   || '      FROM gmp_resource_instances '||p_db_link||' tgri '
15346                   || '      WHERE tgri.resource_id = crd.resource_id '
15347                   || '      AND rownum <= un.resource_units '
15348                   || '      ) '
15349                   || ' UNION ALL  '
15350                   || ' SELECT un.resource_id, '
15351                   || '        0 instance_number,  '
15352                   || '        un.from_date,  '
15353                   || '        un.to_date,    '
15354                   || '        un.resource_units '
15355                   || ' FROM   cr_rsrc_dtl '||p_db_link||'  crd, '
15356                   || '        gmp_rsrc_unavail_dtl_v ' ||p_db_link||'  un'
15357                   || ' WHERE  crd.resource_id = un.resource_id  '
15358                   || ' AND    crd.orgn_code = :orgn_code2 ' ;
15359 
15360     IF (p_usage = 'BASED') THEN   /* Usage APS */
15361     sql_stmt1 := sql_stmt1
15362                   || ' AND    crd.calendar_id = :l_cal_id2 ' ;
15363     ELSE
15364     sql_stmt1 := sql_stmt1
15365                   || ' AND    nvl(crd.calendar_id ,:g_default_cal_id2)= :l_cal_id2 ' ;
15366     END IF;
15367     sql_stmt1 := sql_stmt1
15368                   || ' AND    crd.delete_mark = 0 ' ;
15369 
15370     IF (v_from_rsrc IS NOT NULL AND v_to_rsrc IS NOT NULL) THEN
15371     sql_stmt1 := sql_stmt1 || '  AND crd.resources BETWEEN :frsrc and :trsrc ' ;
15372     END IF ;
15373 
15374 -- HW B4309093 Check for calendar id in cr_rsrc_dtl
15375     sql_stmt1 := sql_stmt1
15376                   || ' AND NOT EXISTS '
15377                   || ' (SELECT 1 '
15378                   || '  FROM gmp_resource_instances  ' ||p_db_link||' gri '
15379                   || '  WHERE gri.resource_id = un.resource_id ) '
15380                   || ' ) '
15381                   || ' ) u, '
15382                   || ' 	( '
15383                   || ' 	SELECT resource_id,shift_num,interval_date, '
15384                   || '          assigned_qty,lead_idate '
15385                   || ' 	FROM '
15386                   || ' 		( '
15387                   || ' 	        SELECT resource_id,shift_num,interval_date, '
15388                   || '                 assigned_qty '
15389                   || ' 			,lead(resource_id,1) over(order by '
15390                   || '  resource_id,interval_date,shift_num) as lead_rid '
15391                   || ' 			,lead(interval_date,1) over(order by '
15392                   || '  resource_id,interval_date,shift_num) as lead_idate '
15393                   || ' 			,lead(shift_num,1) over(order by '
15394                   || '  resource_id,interval_date,shift_num) as lead_snum '
15395                   || ' 		FROM '
15396                   || ' 			( '
15397                   || ' SELECT unique cmd.resource_id, '
15398                   || ' 0 , '
15399                   || ' exp.shift_num, '
15400                   || ' 0 , '
15401                   || ' cmd.interval_date, '
15402                   || ' cmd.assigned_qty '
15403                   || ' FROM ( '
15404                   || ' SELECT un.resource_id resource_id, '
15405                   || '        gri.instance_number instance_number,'
15406                   || '        0 shift_num,'
15407                   || '        0 resource_count,'
15408                   || '        un.from_date interval_date, '
15409                   || '        crd.assigned_qty assigned_qty '
15410                   || ' FROM   cr_rsrc_dtl '||p_db_link||'  crd, '
15411                   || '        gmp_rsrc_unavail_dtl_v '||p_db_link||' un, '
15412                   || '        gmp_resource_instances '||p_db_link||' gri '
15413                   || ' WHERE  crd.resource_id = un.resource_id  '
15414                   || ' AND    crd.resource_id = gri.resource_id  '
15415                   || ' AND    un.instance_id  = gri.instance_id  '
15416                   || ' AND    crd.orgn_code = :orgn_code1 ' ;
15417 
15418     IF (p_usage = 'BASED') THEN   /* Usage APS */
15419     sql_stmt1 := sql_stmt1
15420                   || ' AND    crd.calendar_id = :l_cal_id2 ' ;
15421     ELSE
15422     sql_stmt1 := sql_stmt1
15423                   || ' AND    nvl(crd.calendar_id ,:g_default_cal_id4)= :l_cal_id4 ' ;
15424     END IF;
15425 
15426     sql_stmt1 := sql_stmt1
15427                   || ' AND    crd.schedule_ind = 2 '
15428                   || ' AND    crd.delete_mark = 0 '
15429                   || ' AND    nvl(un.instance_id,0) <> 0  ' ;
15430 
15431     IF (v_from_rsrc IS NOT NULL AND v_to_rsrc IS NOT NULL) THEN
15432     sql_stmt1 := sql_stmt1 || '  AND crd.resources BETWEEN :frsrc and :trsrc ' ;
15433     END IF ;
15434 
15435 -- HW B4309093 Check for calendar id in cr_rsrc_dtl
15436     sql_stmt1 := sql_stmt1
15437                   || ' UNION ALL '
15438                   || ' SELECT un.resource_id resource_id, '
15439                   || '        gri.instance_number instance_number,'
15440                   || '        0 shift_num,'
15441                   || '        0 resource_count,'
15442                   || '        un.to_date interval_date, '
15443                   || '        crd.assigned_qty assigned_qty '
15444                   || ' FROM   cr_rsrc_dtl '||p_db_link||'  crd, '
15445                   || '        gmp_rsrc_unavail_dtl_v '||p_db_link||' un, '
15446                   || '        gmp_resource_instances '||p_db_link||' gri '
15447                   || ' WHERE  crd.resource_id = un.resource_id  '
15448                   || ' AND    crd.resource_id = gri.resource_id  '
15449                   || ' AND    un.instance_id  = gri.instance_id  '
15450                   || ' AND    crd.orgn_code = :orgn_code2 ' ;
15451 
15452     IF (p_usage = 'BASED') THEN   /* Usage APS */
15453     sql_stmt1 := sql_stmt1
15454                   || ' AND    crd.calendar_id = :l_cal_id2 ' ;
15455     ELSE
15456     sql_stmt1 := sql_stmt1
15457                   || ' AND    nvl(crd.calendar_id ,:g_default_cal_id5)= :l_cal_id5 ' ;
15458     END IF;
15459 
15460     sql_stmt1 := sql_stmt1
15461                   || ' AND    crd.schedule_ind = 2 '
15462                   || ' AND    crd.delete_mark = 0 '
15463                   || ' AND    nvl(un.instance_id,0) <> 0  ' ;
15464 
15465     IF (v_from_rsrc IS NOT NULL AND v_to_rsrc IS NOT NULL) THEN
15466     sql_stmt1 := sql_stmt1 || '  AND crd.resources BETWEEN :frsrc and :trsrc ' ;
15467     END IF ;
15468 
15469 -- HW B4309093 Check for calendar id in cr_rsrc_dtl
15470     sql_stmt1 := sql_stmt1
15471                   || ' UNION ALL '
15472                   || ' SELECT un.resource_id resource_id, '
15473                   || '        gri.instance_number instance_number,'
15474                   || '        0 shift_num,'
15475                   || '        0 resource_count,'
15476                   || '        un.from_date interval_date, '
15477                   || '        crd.assigned_qty assigned_qty '
15478                   || ' FROM   cr_rsrc_dtl '||p_db_link||'  crd, '
15479                   || '        gmp_rsrc_unavail_dtl_v '||p_db_link||' un, '
15480                   || '        gmp_resource_instances '||p_db_link||' gri '
15481                   || ' WHERE  crd.resource_id = un.resource_id  '
15482                   || ' AND    crd.resource_id = gri.resource_id  '
15483                   || ' AND    crd.orgn_code = :orgn_code3 ' ;
15484 
15485     IF (p_usage = 'BASED') THEN   /* Usage APS */
15486     sql_stmt1 := sql_stmt1
15487                   || ' AND    crd.calendar_id = :l_cal_id2 ' ;
15488     ELSE
15489     sql_stmt1 := sql_stmt1
15490                   || ' AND    nvl(crd.calendar_id ,:g_default_cal_id6)= :l_cal_id6 ' ;
15491     END IF;
15492 
15493     sql_stmt1 := sql_stmt1
15494                   || ' AND    crd.schedule_ind = 2 '
15495                   || ' AND    crd.delete_mark = 0 '
15496                   || ' AND    nvl(un.instance_id,0) = 0  ' ;
15497 
15498     IF (v_from_rsrc IS NOT NULL AND v_to_rsrc IS NOT NULL) THEN
15499     sql_stmt1 := sql_stmt1 || '  AND crd.resources BETWEEN :frsrc and :trsrc ' ;
15500     END IF ;
15501 
15502 -- HW B4309093 Check for calendar id in cr_rsrc_dtl
15503     sql_stmt1 := sql_stmt1
15504                   || ' AND    gri.instance_number in '
15505                   || '      ( select tgri.instance_number '
15506                   || '      FROM gmp_resource_instances '||p_db_link||' tgri '
15507                   || '      WHERE tgri.resource_id = crd.resource_id '
15508                   || '      AND rownum <= un.resource_units '
15509                   || '      ) '
15510                   || ' UNION ALL '
15511                   || ' SELECT un.resource_id resource_id, '
15512                   || '        gri.instance_number instance_number,'
15513                   || '        0 shift_num,'
15514                   || '        0 resource_count,'
15515                   || '        un.to_date interval_date, '
15516                   || '        crd.assigned_qty assigned_qty '
15517                   || ' FROM   cr_rsrc_dtl '||p_db_link||'  crd, '
15518                   || '        gmp_rsrc_unavail_dtl_v '||p_db_link||' un, '
15519                   || '        gmp_resource_instances '||p_db_link||' gri '
15520                   || ' WHERE  crd.resource_id = un.resource_id  '
15521                   || ' AND    crd.resource_id = gri.resource_id  '
15522                   || ' AND    crd.orgn_code = :orgn_code4 ' ;
15523 
15524     IF (p_usage = 'BASED') THEN   /* Usage APS */
15525     sql_stmt1 := sql_stmt1
15526                   || ' AND    crd.calendar_id = :l_cal_id2 ' ;
15527     ELSE
15528     sql_stmt1 := sql_stmt1
15529                   || ' AND    nvl(crd.calendar_id ,:g_default_cal_id7)= :l_cal_id7 ';
15530     END IF ;
15531 
15532     sql_stmt1 := sql_stmt1
15533                   || ' AND    crd.delete_mark = 0 '
15534                   || ' AND    crd.schedule_ind = 2 '
15535                   || ' AND    nvl(un.instance_id,0) = 0  ' ;
15536 
15537     IF (v_from_rsrc IS NOT NULL AND v_to_rsrc IS NOT NULL) THEN
15538     sql_stmt1 := sql_stmt1 || '  AND crd.resources BETWEEN :frsrc and :trsrc ' ;
15539     END IF ;
15540 
15541     sql_stmt1 := sql_stmt1
15542                   || ' AND    gri.instance_number in '
15543                   || '      ( select tgri.instance_number '
15544                   || '      FROM gmp_resource_instances '||p_db_link||' tgri '
15545                   || '      WHERE tgri.resource_id = crd.resource_id '
15546                   || '      AND rownum <= un.resource_units '
15547                   || '      ) '
15548                   || ' UNION ALL '
15549                   || ' SELECT un.resource_id, '
15550                   || '        0 instance_number,  '
15551                   || '        0 shift_num,'
15552                   || '        0 resource_count,'
15553                   || '        un.from_date interval_date, '
15554                   || '        crd.assigned_qty assigned_qty '
15555                   || ' FROM   cr_rsrc_dtl '||p_db_link||'  crd, '
15556                   || '        gmp_rsrc_unavail_dtl_v '||p_db_link||' un '
15557                   || ' WHERE  crd.resource_id = un.resource_id  '
15558                   || ' AND    crd.orgn_code = :orgn_code44 ' ;
15559 
15560     IF (p_usage = 'BASED') THEN   /* Usage APS */
15561     sql_stmt1 := sql_stmt1
15562                   || ' AND    crd.calendar_id = :l_cal_id2 ' ;
15563     ELSE
15564     sql_stmt1 := sql_stmt1
15565                   || ' AND    nvl(crd.calendar_id ,:g_default_cal_id8)= :l_cal_id8 ' ;
15566     END IF;
15567 
15568     sql_stmt1 := sql_stmt1
15569                   || ' AND    crd.delete_mark = 0 ' ;
15570 
15571     IF (v_from_rsrc IS NOT NULL AND v_to_rsrc IS NOT NULL) THEN
15572     sql_stmt1 := sql_stmt1 || '  AND crd.resources BETWEEN :frsrc and :trsrc ' ;
15573     END IF ;
15574 
15575 -- HW B4309093 Check for calendar id in cr_rsrc_dtl
15576     sql_stmt1 := sql_stmt1
15577                   || ' AND NOT EXISTS '
15578                   || '       (SELECT 1 '
15579                   || '        FROM gmp_resource_instances '||p_db_link||' gri '
15580                   || '        WHERE gri.resource_id = un.resource_id ) '
15581                   || ' UNION ALL '
15582                   || ' SELECT un.resource_id, '
15583                   || '        0 instance_number,  '
15584                   || '        0 shift_num,'
15585                   || '        0 resource_count,'
15586                   || '        un.to_date interval_date, '
15587                   || '        crd.assigned_qty assigned_qty '
15588                   || ' FROM   cr_rsrc_dtl '||p_db_link||'  crd, '
15589                   || '        gmp_rsrc_unavail_dtl_v '||p_db_link||' un '
15590                   || ' WHERE  crd.resource_id = un.resource_id  '
15591                   || ' AND    crd.orgn_code = :orgn_code444 ' ;
15592 
15593     IF (p_usage = 'BASED') THEN   /* Usage APS */
15594     sql_stmt1 := sql_stmt1
15595                   || ' AND    crd.calendar_id = :l_cal_id2 ' ;
15596     ELSE
15597     sql_stmt1 := sql_stmt1
15598                   || ' AND    nvl(crd.calendar_id ,:g_default_cal_id9)= :l_cal_id9 ' ;
15599     END IF;
15600 
15601     sql_stmt1 := sql_stmt1
15602                   || ' AND    crd.delete_mark = 0 ' ;
15603 
15604     IF (v_from_rsrc IS NOT NULL AND v_to_rsrc IS NOT NULL) THEN
15605     sql_stmt1 := sql_stmt1 || '  AND crd.resources BETWEEN :frsrc and :trsrc ' ;
15606     END IF ;
15607 
15608     sql_stmt1 := sql_stmt1
15609                   || ' AND NOT EXISTS '
15610                   || '       (SELECT 1 '
15611                   || '        FROM gmp_resource_instances '||p_db_link||' gri '
15612                   || '        WHERE gri.resource_id = un.resource_id ) '
15613                   || '    )   cmd,  '
15614                   || '        gmp_calendar_detail_gtmp ' ||p_db_link||' exp  '
15615                   || '      WHERE  exp.calendar_id = :curr_cal1 '
15616                   || '        AND  cmd.interval_date  BETWEEN '
15617                   || '             exp.from_date AND exp.to_date '
15618                   || ' UNION ALL '
15619                   || ' SELECT crd.resource_id , '
15620                   || '        0 , '
15621                   || '        exp.shift_num,  '
15622                   || '        0 , '
15623                   || '        exp.from_date interval_date, '
15624                   || '        crd.assigned_qty assigned_qty '
15625                   || ' FROM   cr_rsrc_dtl '||p_db_link||'  crd, '
15626                   || '        gmp_calendar_detail_gtmp ' ||p_db_link||' exp  '
15627                   || ' WHERE  crd.orgn_code = :orgn_code5 ' ;
15628 
15629     IF (p_usage = 'BASED') THEN   /* Usage APS */
15630     sql_stmt1 := sql_stmt1
15631                   || ' AND    crd.calendar_id = :l_cal_id2 ' ;
15632     ELSE
15633     sql_stmt1 := sql_stmt1
15634                   || ' AND    nvl(crd.calendar_id ,:g_default_cal_id10)= :l_cal_id10 ' ;
15635     END IF;
15636 
15637     sql_stmt1 := sql_stmt1
15638                   || ' AND    crd.delete_mark = 0 ' ;
15639 
15640     IF (v_from_rsrc IS NOT NULL AND v_to_rsrc IS NOT NULL) THEN
15641     sql_stmt1 := sql_stmt1 || '  AND crd.resources BETWEEN :frsrc and :trsrc ' ;
15642     END IF ;
15643 
15644 -- HW B4309093 Check for calendar id in cr_rsrc_dtl
15645     sql_stmt1 := sql_stmt1
15646                   || ' AND    exp.calendar_id = :curr_cal2 '
15647                   || ' UNION ALL '
15648                   || ' SELECT crd.resource_id , '
15649                   || '        0 , '
15650                   || '        exp.shift_num,  '
15651                   || '        0 , '
15652                   || '        exp.to_date interval_date, '
15653                   || '        crd.assigned_qty assigned_qty '
15654                   || ' FROM   cr_rsrc_dtl '||p_db_link||'  crd, '
15655                   || '        gmp_calendar_detail_gtmp ' ||p_db_link||' exp  '
15656                   || ' WHERE  crd.orgn_code = :orgn_code6 ' ;
15657 
15658     IF (p_usage = 'BASED') THEN   /* Usage APS */
15659     sql_stmt1 := sql_stmt1
15660                   || ' AND    crd.calendar_id = :l_cal_id2 ' ;
15661     ELSE
15662     sql_stmt1 := sql_stmt1
15663                   || ' AND    nvl(crd.calendar_id ,:g_default_cal_id11)= :l_cal_id11 ' ;
15664     END IF;
15665 
15666     sql_stmt1 := sql_stmt1
15667                   || ' AND    crd.delete_mark = 0 ' ;
15668 
15669     IF (v_from_rsrc IS NOT NULL AND v_to_rsrc IS NOT NULL) THEN
15670     sql_stmt1 := sql_stmt1 || '  AND crd.resources BETWEEN :frsrc and :trsrc ' ;
15671     END IF ;
15672 
15673     sql_stmt1 := sql_stmt1
15674                   || ' AND    exp.calendar_id = :curr_cal3 '
15675                   || ' 			) '
15676                   || ' 		) '
15677                   || ' 	WHERE '
15678                   || ' 		resource_id = lead_rid '
15679                   || ' 	    AND trunc(interval_date) = trunc(lead_idate) '
15680                   || ' 	    AND interval_date < lead_idate '
15681                   || ' 	    AND shift_num = lead_snum  '
15682                   || ' 	) t '
15683                   || ' WHERE '
15684                   || ' 	    t.interval_date >= u.from_date(+) '
15685                   || '  AND t.lead_idate <= u.to_date1 (+) '
15686                   || ' 	AND t.resource_id = u.resource_id(+) '
15687                   || ' GROUP BY '
15688                   || ' 	 t.resource_id '
15689                   || ' 	,t.shift_num '
15690                   || ' 	,t.interval_date '
15691                   || ' 	,t.assigned_qty '
15692                   || ' ) rt '
15693                   || ' WHERE '
15694                   || ' 	(rt.interval_date = rt.lead_idate OR rt.rsum=0) '
15695                   || ' 	OR '
15696                   || ' 	(    rt.interval_date <> rt.lead_idate '
15697                   || '   AND rt.rsum <> 0 '
15698                   || '   AND rt.assigned_qty>rsum) '
15699                   || ' ORDER BY 2,6,5 ';
15700 
15701 
15702     IF (v_from_rsrc IS NOT NULL AND v_to_rsrc IS NOT NULL) THEN
15703 -- HW B4309093 Pass correct parameters
15704     OPEN ri_shift_interval FOR sql_stmt1 USING
15705            p_orgn_code,p_calendar_id,p_calendar_id, V_FROM_RSRC, V_TO_RSRC ,
15706            p_orgn_code,p_calendar_id,p_calendar_id, V_FROM_RSRC, V_TO_RSRC ,
15707            p_orgn_code,p_calendar_id,p_calendar_id, V_FROM_RSRC, V_TO_RSRC ,
15708            p_orgn_code,p_calendar_id,p_calendar_id, V_FROM_RSRC, V_TO_RSRC ,
15709            p_orgn_code,p_calendar_id,p_calendar_id, V_FROM_RSRC, V_TO_RSRC ,
15710            p_orgn_code,p_calendar_id,p_calendar_id, V_FROM_RSRC, V_TO_RSRC ,
15711            p_orgn_code,p_calendar_id,p_calendar_id, V_FROM_RSRC, V_TO_RSRC ,
15712            p_orgn_code,p_calendar_id,p_calendar_id, V_FROM_RSRC, V_TO_RSRC ,
15713            p_orgn_code,p_calendar_id,p_calendar_id, V_FROM_RSRC, V_TO_RSRC ,
15714            p_calendar_id ,
15715            p_orgn_code,p_calendar_id,p_calendar_id, V_FROM_RSRC, V_TO_RSRC ,
15716            p_calendar_id ,
15717            p_orgn_code,p_calendar_id,p_calendar_id, V_FROM_RSRC, V_TO_RSRC ,
15718            p_calendar_id  ;
15719 
15720     ELSE
15721 
15722 -- HW B4309093 Pass correct parameters
15723       IF (p_usage = 'BASED') THEN   /* Usage APS */
15724        OPEN ri_shift_interval FOR sql_stmt1 USING
15725                 p_orgn_code,p_calendar_id,
15726 		p_orgn_code,p_calendar_id,
15727 		p_orgn_code,p_calendar_id,
15728                 p_orgn_code,p_calendar_id,
15729 		p_orgn_code,p_calendar_id,
15730                 p_orgn_code,p_calendar_id,
15731 		p_orgn_code,p_calendar_id,
15732                 p_orgn_code,p_calendar_id,
15733 		p_orgn_code,p_calendar_id, p_calendar_id,
15734                 p_orgn_code,p_calendar_id, p_calendar_id,
15735                 p_orgn_code,p_calendar_id, p_calendar_id ;
15736 
15737       ELSE
15738        OPEN ri_shift_interval FOR sql_stmt1 USING
15739                 p_orgn_code,g_calendar_id,p_calendar_id,
15740 		p_orgn_code,g_calendar_id,p_calendar_id,
15741 		p_orgn_code,g_calendar_id,p_calendar_id,
15742                 p_orgn_code,g_calendar_id,p_calendar_id,
15743 		p_orgn_code,g_calendar_id,p_calendar_id,
15744                 p_orgn_code,g_calendar_id,p_calendar_id,
15745 		p_orgn_code,g_calendar_id,p_calendar_id,
15746                 p_orgn_code,g_calendar_id,p_calendar_id,
15747 		p_orgn_code,g_calendar_id,p_calendar_id,
15748                 p_calendar_id,
15749                 p_orgn_code, g_calendar_id,p_calendar_id,
15750 		p_calendar_id,
15751                 p_orgn_code, g_calendar_id,p_calendar_id,
15752 		p_calendar_id ;
15753       END IF ;
15754     END IF;
15755 
15756     /* B3347284, Performance Issue */
15757     j := 1 ;
15758     LOOP
15759        FETCH ri_shift_interval INTO resource_count(j), resource_id(j),
15760          instance_id(j), instance_number(j), shift_num(j),
15761          f_date(j), t_date(j);
15762        EXIT WHEN ri_shift_interval%NOTFOUND;
15763 
15764     BEGIN
15765     stmt_no := 74;
15766     i := 1 ;
15767     IF (resource_id.FIRST > 0) AND (j = 75000) THEN  /* Only if any resource */
15768 
15769        IF ((p_usage = 'APS') OR (p_usage = 'BASED')) THEN /* Usage APS/BASED */
15770 
15771         FORALL i IN resource_id.FIRST..resource_id.LAST
15772           INSERT INTO msc_st_net_resource_avail
15773             ( organization_id,
15774               sr_instance_id,
15775               resource_id,
15776               department_id,
15777               simulation_set,
15778               shift_num,
15779               shift_date,
15780               from_time,
15781               to_time,
15782               capacity_units,
15783               deleted_flag
15784               )
15785            VALUES
15786             ( p_org_id,
15787               p_instance_id,
15788               ((resource_id(i) * 2) + 1), /* B1177070 */
15789               ((p_org_id * 2) + 1),  /* B1177070 encoded key */
15790               p_simulation_set,
15791               shift_num(i),
15792               trunc(f_date(i)),
15793               ((f_date(i) - trunc(f_date(i))) * 86400 ),
15794               ((t_date(i) - trunc(t_date(i))) * 86400 ),
15795               resource_count(i),
15796               2
15797               );
15798 
15799        ELSIF (p_usage = 'WPS') THEN   /* Usage WPS     */
15800 
15801         FORALL i IN resource_id.FIRST..resource_id.LAST
15802          INSERT INTO gmp_resource_avail
15803          (
15804           instance_id, plant_code, resource_id,
15805           calendar_id, resource_instance_id, shift_num,
15806           shift_date, from_time, to_time,
15807           resource_units, creation_date, created_by,
15808           last_update_date, last_updated_by, last_update_login
15809          )  VALUES
15810          (
15811             p_instance_id,
15812             p_orgn_code,
15813             resource_id(i),
15814             p_calendar_id,
15815             instance_id(i),
15816             shift_num(i),
15817             trunc(f_date(i)),
15818             ((f_date(i) - trunc(f_date(i))) * 86400 ),
15819             ((t_date(i) - trunc(t_date(i))) * 86400 ),
15820             resource_count(i),
15821             sysdate,
15822             FND_GLOBAL.USER_ID,
15823             sysdate,
15824             FND_GLOBAL.USER_ID,
15825             FND_GLOBAL.USER_ID
15826           )           ;
15827 
15828        END IF;   /* APS or WPS */
15829 
15830          resource_count  := empty_num_table;
15831          resource_id     := empty_num_table;
15832          instance_id     := empty_num_table;
15833          instance_number := empty_num_table;
15834          shift_num       := empty_num_table;
15835          f_date          := empty_dat_table;
15836          t_date          := empty_dat_table;
15837          j:= 0 ;
15838          /* 8i Database does not support BULK COLLECT - B3881832 */
15839          dbms_session.free_unused_user_memory;
15840          COMMIT ;
15841 
15842     END IF;   /* Only if any resource */
15843     END;
15844 
15845     j := j + 1 ;
15846     END LOOP ;
15847     CLOSE ri_shift_interval;
15848 
15849     BEGIN
15850     stmt_no := 75;
15851     i := 1 ;
15852     IF (resource_id.FIRST > 0) THEN  /* Only if any resource */
15853 
15854        IF ((p_usage = 'APS') OR (p_usage = 'BASED')) THEN /* Usage APS/BASED */
15855 
15856         FORALL i IN resource_id.FIRST..resource_id.LAST
15857           INSERT INTO msc_st_net_resource_avail
15858             ( organization_id,
15859               sr_instance_id,
15860               resource_id,
15861               department_id,
15862               simulation_set,
15863               shift_num,
15864               shift_date,
15865               from_time,
15866               to_time,
15867               capacity_units,
15868               deleted_flag
15869               )
15870            VALUES
15871             ( p_org_id,
15872               p_instance_id,
15873               ((resource_id(i) * 2) + 1), /* B1177070 */
15874               ((p_org_id * 2) + 1),  /* B1177070 encoded key */
15875               p_simulation_set,
15876               shift_num(i),
15877               trunc(f_date(i)),
15878               ((f_date(i) - trunc(f_date(i))) * 86400 ),
15879               ((t_date(i) - trunc(t_date(i))) * 86400 ),
15880               resource_count(i),
15881               2
15882               );
15883 
15884        ELSIF (p_usage = 'WPS') THEN   /* Usage WPS     */
15885 
15886         FORALL i IN resource_id.FIRST..resource_id.LAST
15887          INSERT INTO gmp_resource_avail
15888          (
15889           instance_id, plant_code, resource_id,
15890           calendar_id, resource_instance_id, shift_num,
15891           shift_date, from_time, to_time,
15892           resource_units, creation_date, created_by,
15893           last_update_date, last_updated_by, last_update_login
15894          )  VALUES
15895          (
15896             p_instance_id,
15897             p_orgn_code,
15898             resource_id(i),
15899             p_calendar_id,
15900             instance_id(i),
15901             shift_num(i),
15902             trunc(f_date(i)),
15903             ((f_date(i) - trunc(f_date(i))) * 86400 ),
15904             ((t_date(i) - trunc(t_date(i))) * 86400 ),
15905             resource_count(i),
15906             sysdate,
15907             FND_GLOBAL.USER_ID,
15908             sysdate,
15909             FND_GLOBAL.USER_ID,
15910             FND_GLOBAL.USER_ID
15911           )           ;
15912 
15913        END IF;   /* APS or WPS */
15914 
15915          resource_count  := empty_num_table;
15916          resource_id     := empty_num_table;
15917          instance_id     := empty_num_table;
15918          instance_number := empty_num_table;
15919          shift_num       := empty_num_table;
15920          f_date          := empty_dat_table;
15921          t_date          := empty_dat_table;
15922          /* 8i Database does not support BULK COLLECT - B3881832 */
15923          dbms_session.free_unused_user_memory;
15924 
15925     END IF;   /* Only if any resource */
15926     END ;
15927 
15928     /* Insert for msc_st_resource_shifts Starts here - 2213101 */
15929        stmt_no := 80;
15930        sql_shifts := ' INSERT INTO msc_st_resource_shifts '
15931             || '  ( department_id,                  '
15932             || '  shift_num,                      '
15933             || '  resource_id,                    '
15934             || '  deleted_flag,                   '
15935             || '  sr_instance_id,                 '
15936             || '  capacity_units                  '
15937             || '  )                                 '
15938             || ' SELECT unique '
15939             || '  ((ic.mtl_organization_id*2)+1) organization_id, '
15940             || '  gtmp.shift_num,            '
15941             || '  ((crd.resource_id*2)+1),  '
15942             || '  2,                        '
15943             || '  :instance_id,             '
15944             || '  crd.assigned_qty          '
15945             || ' FROM gmp_calendar_detail_gtmp'||p_db_link||'  gtmp, '
15946             || '      sy_orgn_mst'||p_db_link||'  som,   '
15947             || '      ic_whse_mst'||p_db_link||'  ic,   '
15948             || '      cr_rsrc_dtl'||p_db_link||'  crd   '
15949             || ' WHERE gtmp.calendar_id = :curr_cal_id   '
15950             || ' AND NVL(crd.calendar_id,som.mfg_calendar_id)=gtmp.calendar_id '
15951             || ' AND som.orgn_code = crd.orgn_code   '
15952             || ' AND som.resource_whse_code IS NOT NULL  '
15953             || ' AND crd.delete_mark  = 0                ' ;
15954 
15955      IF ((p_usage = 'APS') OR (p_usage = 'BASED')) THEN /* Usage APS/BASED */
15956      EXECUTE IMMEDIATE sql_shifts USING p_instance_id,p_calendar_id;
15957      END IF;
15958 
15959     /* End of Inserts to msc_st_resource_shifts - 2213101  */
15960 
15961   return_status := TRUE;
15962 
15963 EXCEPTION
15964   WHEN NO_DATA_FOUND THEN
15965     log_message('NO DATA FOUND : MSC_CL_GMP_UTILITY.net_rsrc_insert' || stmt_no);
15966     return_status := TRUE;
15967   WHEN OTHERS THEN
15968     log_message('Error in Net Resource Insert: '||stmt_no);
15969     log_message(sqlerrm);
15970     return_status := FALSE;
15971 
15972 END net_rsrc_insert;
15973 
15974 /*
15975 REM+==========================================================================+
15976 REM| PROCEDURE NAME                                                           |
15977 REM|    insert_simulation_sets                                                |
15978 REM|                                                                          |
15979 REM| Type                                                                     |
15980 REM|    public                                                                |
15981 REM|                                                                          |
15982 REM| DESCRIPTION                                                              |
15983 REM|                                                                          |
15984 REM|                                                                          |
15985 REM| Input Parameters                                                         |
15986 REM|    p_org_id - Organization id                                            |
15987 REM|    p_rsrc_whse_code - Resource Whse Code                                 |
15988 REM|    p_instance_id - Instance Id                                           |
15989 REM|    p_delimiter - Delimiter                                               |
15990 REM|                                                                          |
15991 REM| Output Parameters                                                        |
15992 REM|    return_status                                                         |
15993 REM|                                                                          |
15994 REM|                                                                          |
15995 REM| HISTORY                                                                  |
15996 REM|    Created 23th Sep 1999 by Sridhar Gidugu (OPM Development Oracle US)   |
15997 REM|    10/01/1999 - Chaged passing of Parameters to insert_simulation_sets   |
15998 REM|               - Added p_simulation_sets as a parameter and removed       |
15999 REM|               - p_rsrc_whse_code parameter                               |
16000 REM|    10/13/1999 - Added deleted_flag in the insert statement               |
16001 REM|                                                                          |
16002 REM|                                                                          |
16003 REM+==========================================================================+
16004 */
16005 PROCEDURE insert_simulation_sets(p_org_id         IN NUMBER,
16006                                  p_instance_id    IN NUMBER,
16007                                  p_simulation_set IN VARCHAR2,
16008                                  return_status    OUT NOCOPY BOOLEAN) IS
16009 BEGIN
16010 
16011     IF return_status THEN
16012        v_cp_enabled := TRUE;
16013     ELSE
16014        v_cp_enabled := FALSE;
16015     END IF;
16016 
16017           INSERT INTO msc_st_simulation_sets
16018                                         (organization_id,
16019                                          sr_instance_id,
16020                                          simulation_set,
16021                                          description,
16022                                          use_in_wip_flag,
16023                                          deleted_flag
16024                                          )
16025                              values     (p_org_id,
16026                                          p_instance_id,
16027                                          p_simulation_set,
16028                                          p_simulation_set,
16029                                          2,
16030                                          2
16031                                         ); /* Simulation Set Insert ends here */
16032 
16033      return_status := TRUE;
16034 
16035 EXCEPTION
16036    WHEN  OTHERS THEN
16037       log_message('Error in insert simulation: ');
16038       log_message(sqlerrm);
16039       return_status := FALSE;
16040 
16041 END insert_simulation_sets;
16042 
16043 /*
16044 REM+==========================================================================+
16045 REM| PROCEDURE NAME                                                           |
16046 REM|    populate_rsrc_cal                                                     |
16047 REM|                                                                          |
16048 REM| Type                                                                     |
16049 REM|    public                                                                |
16050 REM|                                                                          |
16051 REM| DESCRIPTION                                                              |
16052 REM|                                                                          |
16053 REM|                                                                          |
16054 REM| Input Parameters                                                         |
16055 REM|    p_orgn_code - Orgn Code                                               |
16056 REM|    p_org_id - Organization id                                            |
16057 REM|    p_cal_id - calendar_id                                                |
16058 REM|    p_instance_id - Instance Id                                           |
16059 REM|    p_delimiter - Delimiter                                               |
16060 REM|    p_db_link - Data Base Link                                            |
16061 REM|    p_nra_enabled - flag to build net resource available                  |
16062 REM|                                                                          |
16063 REM| Output Parameters                                                        |
16064 REM|    return_status                                                         |
16065 REM|                                                                          |
16066 REM|                                                                          |
16067 REM| HISTORY                                                                  |
16068 REM|    Created 5th Aug 1999 by Sridhar Gidugu (OPM Development Oracle US)    |
16069 REM|    9/1/99 - Main Proc calls the populate_cal_dates                       |
16070 REM|             Update trading Partners and net_rsrc_insert procedure.       |
16071 REM|                                                                          |
16072 REM|    9/7/99 - Changed the Main Procedure, removed UNION ALL for main cursor|
16073 REM|    9/28/99 - Changed the main query ordering by Organization Id and      |
16074 REM|            - changed logic for populating plsqltbl                       |
16075 REM|    4/03/00 - using mtl_organization_id from ic_whse_mst instead of       |
16076 REM|            - organization_id from sy_orgn_mst - Bug# 1252322             |
16077 REM|    5/03/00 - Add instance code as a prefix to the calendar code          |
16078 REM|            - Bug # 1288143                                               |
16079 REM|    7/07/00 - Anchor Date Problem Fixed in the Calendar Code              |
16080 REM|            - Bug # 1337084.                                              |
16081 REM|    7/12/00 - Removed the Debugging Statement shcl.calendar_id in         |
16082 REM|            - (121,126) - bug#1353845                                     |
16083 REM|    10/18/01 - B2041247 - Modified the cursor to consider Calendars       |
16084 REM|            associated with the OPM Plants                                |
16085 REM|                                                                          |
16086 REM|    7th Mar 2003 -- Performance issue fix and B2671540 00:00 shift fix    |
16087 REM|  04/21/2004   - Navin Sinha - B3577871 -ST:OSFME2: collections failing   |
16088 REM|                                in planning data pull.                    |
16089 REM|                                Added handling of NO_DATA_FOUND Exception.|
16090 REM|                                And return the return_status as TRUE.     |
16091 REM|                                                                          |
16092 REM|   07-May-2004 - Sowmya - B3599089 - ST: ORG SPECIFIC COMPLETE COLLETION  |
16093 REM|                          FOR OPM ORGS TAKING MORE TIME.                  |
16094 REM|                          As the varaibale l_org_specific was not getting |
16095 REM|                          refreshed,the resource availability             |
16096 REM|                          was getting collected irrespective of whether or|
16097 REM|                          not the org is enabled. To overcome this, added |
16098 REM|                          if clause containing the l_cur%NOTFOUND.So when |
16099 REM|                          the no values are returned the l_org_specific= 0|
16100 REM|                                                                          |
16101 REM+==========================================================================+
16102 REM
16103 */
16104 
16105 PROCEDURE populate_rsrc_cal(p_run_date    IN DATE,
16106                             p_instance_id IN NUMBER,
16107                             p_delimiter   IN VARCHAR2,
16108                             p_db_link     IN VARCHAR2,
16109                             p_nra_enabled IN NUMBER,
16110                             return_status OUT NOCOPY BOOLEAN) IS
16111 
16112 /* Local Array Defintions */
16113 TYPE interval_typ_a is RECORD
16114 (
16115   organization_id 	NUMBER,
16116   simulation_set  	VARCHAR2(10),
16117   resource_id     	NUMBER,
16118   shift_date      	DATE,
16119   shift_num       	NUMBER,
16120   capacity_units  	NUMBER,
16121   from_time       	NUMBER,
16122   to_time         	NUMBER
16123 );
16124 
16125 TYPE interval_tab_a is table of interval_typ_a index by BINARY_INTEGER;
16126 interval_record_aps     interval_typ_a;
16127 
16128 TYPE interval_typ_b is RECORD
16129 (
16130   organization_id 	NUMBER,
16131   Department_id 	NUMBER,
16132   resource_id     	NUMBER,
16133   res_instance_id     	NUMBER,
16134   equipment_item_id    	NUMBER,
16135   serial_number  	VARCHAR2(30),
16136   shift_date      	DATE,
16137   shift_num       	NUMBER,
16138   from_time       	NUMBER,
16139   to_time         	NUMBER
16140 );
16141 
16142 TYPE interval_tab_b is table of interval_typ_b index by BINARY_INTEGER;
16143 inst_record_aps     interval_typ_b;
16144 
16145 union_cal_ref      ref_cursor_typ;
16146 l_cur              ref_cursor_typ;
16147 ri_assembly	   ref_cursor_typ;
16148 r_inst_assembly	   ref_cursor_typ;
16149 sql_allcal         VARCHAR2(32000);
16150 inst_stmt          VARCHAR2(32000);
16151 inst_resavl  	   VARCHAR2(32000);
16152 Upd_Process_Org    VARCHAR2(32000);
16153 sqlstmt  	   VARCHAR2(32000);
16154 upd_res_avl  	   VARCHAR2(32000);
16155 l_stmt             VARCHAR2(32700);/* Bug # 5086464 */
16156 ins_res_avl        VARCHAR2(32700);
16157 n                  INTEGER;
16158 i                  INTEGER;
16159 j                  INTEGER;
16160 k                  INTEGER;
16161 x                  INTEGER;
16162 y                  INTEGER;
16163 v_icode            VARCHAR2(4);
16164 fetch_cal          NUMBER;
16165 found              NUMBER;
16166 old_org_id         NUMBER;
16167 v_out_cal_no       VARCHAR2(16);
16168 v_already_prefixed VARCHAR2(3);
16169 instance_prefix    VARCHAR2(4);
16170 simulation_set     VARCHAR2(10);
16171 l_opm_org          VARCHAR2(2000);
16172 f_resource_id      NUMBER;
16173 l_org_specific     NUMBER;
16174 
16175 BEGIN
16176 
16177 n              := 0;
16178 i              := 0;
16179 j              := 0;
16180 k              := 0;
16181 x              := 0;
16182 y              := 0;
16183 v_icode        := '';
16184 fetch_cal      := 0;
16185 found          := 0;
16186 old_org_id     := 0 ;
16187 v_out_cal_no   := '';
16188 v_already_prefixed := '';
16189 instance_prefix    := '';
16190 simulation_set     := NULL;
16191 
16192 inst_resavl  	:= NULL;
16193 sqlstmt  	:= NULL;
16194 f_resource_id   := 0;
16195 l_opm_org       := NULL;
16196 l_org_specific  := 0;
16197 l_stmt          := NULL;
16198 
16199      /* Following statements are added to include the instance Code as
16200         a Prefix to the Calendar Code, this done to maintain the uniqueness
16201         of a calendar code across instances, prior to this change the
16202         calendar code was not prefixed with Instance code and this caused
16203         unique constraint problems - Bug# 1288143
16204      */
16205 
16206     IF return_status THEN
16207        v_cp_enabled := TRUE;
16208     ELSE
16209        v_cp_enabled := FALSE;
16210     END IF;
16211 
16212     /* Retrieving the Instance code from MSC_APPS_INSTANCES - Bug#1288143 */
16213      stmt_no := 05;
16214      inst_stmt :=  ' SELECT instance_code '
16215                 || ' FROM msc_apps_instances WHERE instance_id = :instance_id ';
16216 
16217      EXECUTE IMMEDIATE inst_stmt INTO v_icode USING p_instance_id ;
16218 
16219      /* Cursor statement to retrieve the calendar_id and the plant that the
16220         calendar is asociated with and the Organization_id that uses the
16221         calendar, here the ordering is done by Organization_id,
16222         resource_whse_code and calendar_id, in that way the primary row
16223         is always retrieved first and the rest can be skipped
16224      */
16225      /* New changes made for main Calendar Cursor - using mtl_organization_id
16226         from ic_whse_mst instead of organization_id from sy_orgn_mst table
16227         - Bug# 1252322 */
16228      /* B2041247 - The following Calendar Cursor has been modified to reflect
16229         the design changes planned for WPS Process integration. Now The
16230         calendars that are associated with the OPM plant are considered */
16231 
16232      stmt_no := 10;
16233      sql_allcal :=  ' SELECT sy.mfg_calendar_id, '
16234                  || ' shcl.calendar_no, '
16235                  || ' shcl.calendar_desc, '
16236                  || ' sy.orgn_code,    '
16237                  || ' decode(whse.whse_code,sy.resource_whse_code, '
16238                  || '        sy.resource_whse_code,NULL) resource_whse_code, '
16239                  || ' ic.mtl_organization_id  organization_id,  '
16240                  || ' 0  '
16241                  || ' FROM ps_schd_hdr'||p_db_link||' h, '
16242                  || '      ps_schd_dtl'||p_db_link||' d, '
16243                  || '      mr_shcl_hdr'||p_db_link||' shcl, '
16244                  || '      (select distinct plant_code,whse_code '
16245                  || '       from ps_whse_eff'||p_db_link|| ') whse, '
16246                  || '      sy_orgn_mst'||p_db_link||' sy, '
16247                  || '      ic_whse_mst'||p_db_link||' ic  '
16248                  || ' WHERE  d.schedule_id = h.schedule_id '
16249                  || ' AND    d.orgn_code = sy.orgn_code '
16250                  || ' AND    shcl.calendar_id = sy.mfg_calendar_id ' /* B2041247 */
16251                  || ' AND    whse.plant_code = sy.orgn_code '
16252                  || ' AND    whse.whse_code = ic.whse_code '
16253                  || ' AND    h.active_ind = 1 '
16254                  || ' AND    shcl.active_ind = 1 '
16255                  || ' AND    h.delete_mark = 0 '
16256                  || ' AND    shcl.delete_mark = 0 '
16257                  || ' ORDER BY organization_id, '
16258                  || '          resource_whse_code, '
16259                  || '          mfg_calendar_id ';
16260 
16261      /* The following cursor fetch statement retrieves rows from the Main
16262         cursor and inserts rows into plsqltbl when the organization_id changes */
16263      stmt_no := 20;
16264      i := 0;
16265      OPEN  union_cal_ref FOR sql_allcal;
16266      LOOP
16267           FETCH union_cal_ref INTO cursor_rec;
16268           EXIT WHEN union_cal_ref%NOTFOUND;
16269           IF cursor_rec.organization_id <> old_org_id THEN
16270               i := i + 1;
16271      /* Prefixing the Instance Code to the calendar code - Bug#1288143 */
16272      /* Bug# 1337084 - Changed get_cal_no Function to a Procedure - 07/06/00 */
16273 
16274               stmt_no := 22;
16275               get_cal_no(cursor_rec.calendar_id,
16276                          cursor_rec.calendar_no,
16277                          v_icode,
16278                          v_out_cal_no,
16279                          v_already_prefixed);
16280 
16281      /* 07/07/2000 - Added a check flag to indicate the Instance is already prefixed
16282         and this check is being used at the time when the PLSQL table is
16283         constructed, where in it will not assign an Instance Prefix if the
16284         calendar_code is already prefixed. - Bug# 1337084. */
16285 
16286               stmt_no := 23;
16287               IF v_already_prefixed = 'YES' THEN
16288                    plsqltbl_rec(i).calendar_no := v_out_cal_no ;
16289               ELSE
16290                    plsqltbl_rec(i).calendar_no := v_icode||':'||v_out_cal_no ;
16291               END IF ;
16292 
16293               plsqltbl_rec(i).calendar_id := cursor_rec.calendar_id;
16294               plsqltbl_rec(i).calendar_desc := cursor_rec.calendar_desc;
16295               plsqltbl_rec(i).orgn_code := cursor_rec.orgn_code;
16296               plsqltbl_rec(i).resource_whse_code :=
16297                               cursor_rec.resource_whse_code;
16298               plsqltbl_rec(i).organization_id := cursor_rec.organization_id;
16299               plsqltbl_rec(i).posted := cursor_rec.posted;
16300           END IF;
16301 
16302           old_org_id := cursor_rec.organization_id;
16303           v_already_prefixed := 'NO';
16304           v_out_cal_no := '';
16305      END LOOP; /* End loop for Main Cursor */
16306      CLOSE union_cal_ref;
16307 
16308      /* INSERT A LOOP TO SPIT OUT ALL THE ROWS IN PL/SQL TABLE HERE  */
16309 
16310    stmt_no := 30;
16311    WHILE y = 0 LOOP
16312 
16313      FOR k in 1 .. plsqltbl_rec.COUNT
16314      LOOP
16315 
16316      /* Checking if there are any rows in PL/SQL that were processed */
16317      IF plsqltbl_rec(k).posted = 0 THEN
16318         found := 1;
16319 
16320          IF fetch_cal = 0 THEN
16321 	    fetch_cal := plsqltbl_rec(k).calendar_id;
16322 
16323            /* Calling the retrieve Calendar Procedure,which explodes the calendar
16324               for a given Calendar Id */
16325 
16326            stmt_no := 40;
16327            retrieve_calendar_detail(plsqltbl_rec(k).calendar_id,
16328                                     plsqltbl_rec(k).calendar_no,
16329                                     plsqltbl_rec(k).calendar_desc,
16330                                     p_run_date,
16331                                     p_db_link,
16332                                     p_instance_id,
16333                                     V_APS,
16334                                     return_status
16335                                    );
16336          END IF;
16337 
16338        IF plsqltbl_rec(k).calendar_id = fetch_cal THEN
16339 
16340            /* Calling the Update Trading Partner Procedure,which updates the
16341               MSC_ST_TRADING_PARTNERS with the Calendar Code for a given Organization
16342               Id
16343            */
16344            stmt_no := 50;
16345            update_trading_partners(plsqltbl_rec(k).organization_id,
16346                                    plsqltbl_rec(k).calendar_no,
16347                                    return_status
16348                                    );
16349 
16350          IF plsqltbl_rec(k).resource_whse_code IS NOT NULL  THEN
16351 
16352           /* Check if the org string have the organization */
16353            BEGIN
16354             stmt_no := 51;
16355             IF MSC_CL_GMP_UTILITY.org_string(p_instance_id) THEN
16356                NULL ;
16357             ELSE
16358                RAISE invalid_string_value  ;
16359             END IF;
16360 
16361             l_opm_org := plsqltbl_rec(k).organization_id ;
16362 
16363             IF MSC_CL_GMP_UTILITY.g_in_str_org IS NOT NULL THEN
16364              l_stmt := 'SELECT 1 FROM dual WHERE '||
16365                         l_opm_org||MSC_CL_GMP_UTILITY.g_in_str_org ;
16366                 OPEN l_cur for l_stmt ;
16367                 FETCH l_cur INTO l_org_specific ;
16368                 IF l_cur%NOTFOUND THEN
16369                         l_org_specific := 0;
16370                 END IF;
16371                 /*B3599089 - sowsubra - When the organization is not in the list ,
16372                 the resource  availability was getting collected
16373                 irrespective of whether or not the org is enabled . So
16374                 added this to reset the value of l_org_specific. */
16375                 CLOSE l_cur ;
16376             END IF;
16377 
16378            EXCEPTION
16379               WHEN NO_DATA_FOUND THEN
16380                 l_org_specific := 0 ;
16381                 NULL ;
16382               WHEN OTHERS THEN
16383                 log_message('Error in org string decision:  '||stmt_no);
16384                 log_message(sqlerrm);
16385                 l_org_specific := 0 ;
16386                 return_status := FALSE;
16387            END;
16388 
16389              IF l_org_specific = 1 THEN
16390 
16391                /* B3452373, Simulation set should be null, as OPM stops sending this
16392                   information to APS and hence related code is commented */
16393                  simulation_set := NULL ;
16394 
16395                IF p_nra_enabled = V_YES THEN
16396                  /* Populating Net Resource Insert Table */
16397                  stmt_no := 65;
16398                  net_rsrc_insert(plsqltbl_rec(k).organization_id,
16399                                  plsqltbl_rec(k).orgn_code,
16400                                  simulation_set,
16401                                  p_db_link,
16402                                  p_instance_id,
16403                                  p_run_date,
16404                                  plsqltbl_rec(k).calendar_id,
16405                                  V_APS,
16406                                  return_status
16407                                  );
16408         /* Populate Net Resource Instance rows  PS Integration */
16409            net_rsrc_avail_calculate(plsqltbl_rec(k).organization_id,
16410                                     plsqltbl_rec(k).orgn_code,
16411                                     plsqltbl_rec(k).calendar_id,
16412                                     p_instance_id,
16413                                     p_db_link,
16414                                     V_APS,
16415                                     return_status)  ;
16416                END IF;
16417              END IF;  /* org_specific */
16418 
16419          END IF;  /* rsrc whse code not null */
16420 
16421          /* Marking that particular as being Posted, after making all the calls
16422             to the Procedure */
16423          plsqltbl_rec(k).posted := 1;
16424 
16425        END IF;  /* cal_id = fetch_cal */
16426 
16427      END IF;  /* postd = 0 */
16428      END LOOP;  /* End loop for PL/SQL table */
16429 
16430      IF found = 1 THEN
16431        fetch_cal := 0;
16432        found := 0;
16433      ELSE
16434        y := 1;
16435      END IF;
16436    END LOOP;  /* End Loop for While */
16437 
16438      /* B5001619 Rajesh All the process orgs should have organization_type=2 */
16439       BEGIN
16440        stmt_no := 67 ;
16441        Upd_Process_Org := 'UPDATE MSC_ST_TRADING_PARTNERS '
16442        ||' SET organization_type = 2 '
16443        ||' WHERE sr_tp_id in (SELECT organization_id '
16444        ||'                    FROM  mtl_parameters'||p_db_link
16445        ||'                    WHERE process_enabled_flag = '||''''||'Y'||'''' || ')'
16446        ||' AND partner_type = 3' ;
16447 
16448        EXECUTE IMMEDIATE  Upd_Process_Org;
16449        log_message('Trading Partner Update is Done' );
16450 
16451       EXCEPTION
16452         WHEN NO_DATA_FOUND THEN
16453            NULL ;
16454         WHEN OTHERS THEN
16455           log_message('Error in UPDATE TRADING_PARTNERS  '||stmt_no);
16456           log_message(SQLERRM);
16457           return_status := FALSE;
16458       END ;
16459 
16460    /* Addition of shifts/Datetime in resource calendar functionlality */
16461     IF p_nra_enabled = V_YES THEN
16462         log_message('Enter rsrcal_based_availability ');
16463         rsrcal_based_availability(p_run_date ,
16464                                   p_instance_id ,
16465                                   p_db_link ,
16466                                   return_status) ;
16467         log_message('Return From rsrcal_based_availability ');
16468     END IF;
16469 
16470    /* 7th Mar 2003 -- Performance issue fix and B2671540 00:00 shift fix */
16471    /* This logic introduced for Net resource availablility to
16472        write consolidated rows once final available rows are in place */
16473     stmt_no := 75;
16474 
16475    ins_res_avl :=  ' SELECT '
16476    || '        net.organization_id, '
16477    || '        net.simulation_set, '
16478    || '        net.resource_id , '
16479    || '        net.shift_date  , '
16480    || '        net.shift_num   , '
16481    || '        net.capacity_units , '
16482    || '        min(net.from_time) from_time, '
16483    || '        max(net.lead_tt) to_time '
16484    || ' FROM  ( '
16485    || '        SELECT organization_id , '
16486    || '               simulation_set, '
16487    || '               resource_id, '
16488    || '               shift_date  , '
16489    || '               shift_num , '
16490    || '               capacity_units , '
16491    || '               from_time , '
16492    || '               to_time , '
16493    || '  lead(organization_id,1) '
16494    || '  over(order by organization_id,simulation_set, '
16495    || '  resource_id,shift_date, shift_num,from_time,to_time,capacity_units) '
16496    || '  as lead_iid, '
16497    || '  lead(simulation_set,1) '
16498    || '  over(order by organization_id,simulation_set,'
16499    || '  resource_id,shift_date, shift_num,from_time,to_time,capacity_units) '
16500    || '  as lead_ss, '
16501    || '  lead(resource_id,1) '
16502    || '  over(order by organization_id,simulation_set,'
16503    || '  resource_id,shift_date, shift_num,from_time,to_time,capacity_units) '
16504    || '  as lead_rid, '
16505    || '  lead(shift_date,1) '
16506    || '  over(order by organization_id,simulation_set,'
16507    || '  resource_id,shift_date, shift_num,from_time,to_time,capacity_units) '
16508    || '  as lead_sdt, '
16509    || '  lead(shift_num,1) '
16510    || '  over(order by organization_id,simulation_set,'
16511    || '  resource_id,shift_date, shift_num,from_time,to_time,capacity_units) '
16512    || '  as lead_sn, '
16513    || '  lead(from_time,1) '
16514    || '  over(order by organization_id,simulation_set,'
16515    || '  resource_id,shift_date, shift_num,from_time,to_time,capacity_units) '
16516    || '  as lead_ft, '
16517    || '  lead(to_time,1) '
16518    || '  over(order by organization_id,simulation_set,'
16519    || '  resource_id,shift_date, shift_num,from_time,to_time,capacity_units) '
16520    || '  as lead_tt, '
16521    || '  lead(capacity_units,1) '
16522    || '  over(order by organization_id,simulation_set,'
16523    || '  resource_id,shift_date, shift_num,from_time,to_time,capacity_units) '
16524    || '  as lead_rc '
16525    || '          FROM msc_st_net_resource_avail '
16526    || '          WHERE sr_instance_id = :inst_id '
16527    || '              ) net '
16528    || '      WHERE net.resource_id     = net.lead_rid '
16529    || '        AND net.organization_id = net.lead_iid '
16530    || '        AND net.simulation_set  = net.lead_ss '
16531    || '        AND net.shift_num       = net.lead_sn '
16532    || '        AND net.shift_date      = net.lead_sdt '
16533    || '        AND net.to_time         = net.lead_ft '
16534    || '        AND net.capacity_units  = net.lead_rc '
16535    || ' GROUP BY '
16536    || '        net.organization_id , '
16537    || '        net.simulation_set , '
16538    || '        net.resource_id , '
16539    || '        net.shift_date , '
16540    || '        net.shift_num , '
16541    || '        net.capacity_units ' ;
16542 
16543     stmt_no := 76;
16544     OPEN ri_assembly FOR ins_res_avl  USING p_instance_id ;
16545     LOOP
16546        FETCH ri_assembly INTO  interval_record_aps;
16547        EXIT WHEN ri_assembly%NOTFOUND;
16548 
16549      sqlstmt := ' DELETE FROM msc_st_net_resource_avail '
16550              || ' WHERE organization_id  = :org_id '
16551              || '   AND simulation_set = :sim_set '
16552              || '   AND sr_instance_id = :inst_id '
16553              || '   AND resource_id = :prid '
16554              || '   AND shift_date = :psdt '
16555              || '   AND shift_num  = :psn  '
16556              || '   AND capacity_units = :prc '
16557              || '   AND from_time  >= :pft '
16558              || '   AND to_time  <= :ptt '  ;
16559 
16560     stmt_no := 77;
16561        EXECUTE immediate sqlstmt USING
16562        interval_record_aps.organization_id ,
16563        interval_record_aps.simulation_set ,
16564        p_instance_id ,
16565        interval_record_aps.resource_id,
16566        interval_record_aps.shift_date,
16567        interval_record_aps.shift_num,
16568        interval_record_aps.capacity_units,
16569        interval_record_aps.from_time,
16570        interval_record_aps.to_time  ;
16571 
16572        f_resource_id :=  (interval_record_aps.resource_id - 1 )/ 2 ;
16573 
16574     stmt_no := 78;
16575          net_rsrc(
16576             p_instance_id,
16577             interval_record_aps.organization_id,
16578             interval_record_aps.simulation_set,
16579             f_resource_id,
16580             interval_record_aps.capacity_units,
16581             interval_record_aps.shift_num,
16582             trunc(interval_record_aps.shift_date),
16583             interval_record_aps.from_time ,
16584             interval_record_aps.to_time
16585                   );
16586 
16587 	f_resource_id  := 0 ;
16588        COMMIT ;
16589     END LOOP;
16590     CLOSE ri_assembly;
16591 
16592     stmt_no := 79;
16593     upd_res_avl := null ;
16594     upd_res_avl := 'UPDATE msc_st_net_resource_avail '
16595             ||' SET to_time   = 86400 '
16596             ||' WHERE to_time = 86399 '
16597             ||'   AND shift_num >= 99999 ' ;
16598 
16599        EXECUTE immediate upd_res_avl;
16600 
16601     stmt_no := 80;
16602     upd_res_avl := null ;
16603     upd_res_avl := 'UPDATE msc_st_net_resource_avail '
16604             ||' SET shift_num = (shift_num - 99999) '
16605             ||' WHERE shift_num >= 99999 ' ;
16606 
16607        EXECUTE immediate upd_res_avl;
16608        COMMIT ;
16609 
16610    /* Final rows for msc_st_net_res_inst_avail */
16611    stmt_no := 81;
16612    inst_resavl :=  null;
16613 
16614    inst_resavl := ' SELECT '
16615    || '        net.organization_id, '
16616    || '        net.Department_id, '
16617    || '        net.resource_id , '
16618    || '        net.res_instance_id , '
16619    || '        net.equipment_item_id , '
16620    || '        net.serial_number, '
16621    || '        net.shift_date  , '
16622    || '        net.shift_num   , '
16623    || '        min(net.from_time) from_time, '
16624    || '        max(net.lead_tt) to_time '
16625    || ' FROM  ( '
16626    || '        SELECT organization_id , '
16627    || '               Department_id, '
16628    || '               resource_id, '
16629    || '               res_instance_id, '
16630    || '               equipment_item_id, '
16631    || '               serial_number, '
16632    || '               shift_date  , '
16633    || '               shift_num , '
16634    || '               from_time , '
16635    || '               to_time , '
16636    || '  lead(organization_id,1) '
16637    || '  over(order by organization_id,Department_id,resource_id,res_instance_id, '
16638    || '  equipment_item_id,serial_number, shift_date,shift_num,from_time,to_time) '
16639    || '  as lead_iid, '
16640    || '  lead(Department_id,1) '
16641    || '  over(order by organization_id,Department_id,resource_id,res_instance_id, '
16642    || '  equipment_item_id,serial_number, shift_date,shift_num,from_time,to_time) '
16643    || '  as lead_did, '
16644    || '  lead(resource_id,1) '
16645    || '  over(order by organization_id,Department_id,resource_id,res_instance_id, '
16646    || '  equipment_item_id,serial_number, shift_date,shift_num,from_time,to_time) '
16647    || '  as lead_rid, '
16648    || '  lead(res_instance_id,1) '
16649    || '  over(order by organization_id,Department_id,resource_id,res_instance_id, '
16650    || '  equipment_item_id,serial_number, shift_date,shift_num,from_time,to_time) '
16651    || '  as lead_r_inst_id, '
16652    || '  lead(equipment_item_id,1) '
16653    || '  over(order by organization_id,Department_id,resource_id,res_instance_id, '
16654    || '  equipment_item_id,serial_number, shift_date,shift_num,from_time,to_time) '
16655    || '  as lead_eid, '
16656    || '  lead(serial_number,1) '
16657    || '  over(order by organization_id,Department_id,resource_id,res_instance_id, '
16658    || '  equipment_item_id,serial_number, shift_date,shift_num,from_time,to_time) '
16659    || '  as lead_sr_no, '
16660    || '  lead(shift_date,1) '
16661    || '  over(order by organization_id,Department_id,resource_id,res_instance_id, '
16662    || '  equipment_item_id,serial_number, shift_date,shift_num,from_time,to_time) '
16663    || '  as lead_sdt, '
16664    || '  lead(shift_num,1) '
16665    || '  over(order by organization_id,Department_id,resource_id,res_instance_id, '
16666    || '  equipment_item_id,serial_number, shift_date,shift_num,from_time,to_time) '
16667    || '  as lead_sn, '
16668    || '  lead(from_time,1) '
16669    || '  over(order by organization_id,Department_id,resource_id,res_instance_id, '
16670    || '  equipment_item_id,serial_number, shift_date,shift_num,from_time,to_time) '
16671    || '  as lead_ft, '
16672    || '  lead(to_time,1) '
16673    || '  over(order by organization_id,Department_id,resource_id,res_instance_id, '
16674    || '  equipment_item_id,serial_number, shift_date,shift_num,from_time,to_time) '
16675    || '  as lead_tt '
16676    || '          FROM msc_st_net_res_inst_avail '
16677    || '          WHERE sr_instance_id = :inst_id '
16678    || '              ) net '
16679    || '      WHERE '
16680    || '            net.organization_id   = net.lead_iid '
16681    || '        AND net.Department_id     = net.lead_did '
16682    || '        AND net.resource_id       = net.lead_rid '
16683    || '        AND net.res_instance_id   = net.lead_r_inst_id '
16684    || '        AND net.equipment_item_id = net.lead_eid '
16685    || '        AND net.serial_number     = net.lead_sr_no '
16686    || '        AND net.shift_date        = net.lead_sdt '
16687    || '        AND net.shift_num         = net.lead_sn '
16688    || '        AND net.to_time           = net.lead_ft '
16689    || ' GROUP BY '
16690    || '        net.organization_id, '
16691    || '        net.Department_id, '
16692    || '        net.resource_id , '
16693    || '        net.res_instance_id , '
16694    || '        net.equipment_item_id , '
16695    || '        net.serial_number, '
16696    || '        net.shift_date  , '
16697    || '        net.shift_num   ' ;
16698 
16699     stmt_no := 82;
16700     OPEN r_inst_assembly FOR inst_resavl  USING p_instance_id ;
16701     LOOP
16702        FETCH r_inst_assembly INTO  inst_record_aps;
16703        EXIT WHEN r_inst_assembly%NOTFOUND;
16704 
16705      sqlstmt := ' DELETE FROM msc_st_net_res_inst_avail '
16706              || ' WHERE organization_id  = :org_id '
16707              || '   AND Department_id  = :dept_id '
16708              || '   AND sr_instance_id = :inst_id '
16709              || '   AND resource_id = :prid '
16710              || '   AND res_instance_id = :pr_inst_id '
16711              || '   AND equipment_item_id = :pe_id '
16712              || '   AND serial_number = :ps_no '
16713              || '   AND shift_date = :psdt '
16714              || '   AND shift_num  = :psn  '
16715              || '   AND from_time  >= :pft '
16716              || '   AND to_time  <= :ptt '  ;
16717 
16718     stmt_no := 83;
16719        EXECUTE immediate sqlstmt USING
16720        inst_record_aps.organization_id ,
16721        inst_record_aps.Department_id ,
16722        p_instance_id ,
16723        inst_record_aps.resource_id,
16724        inst_record_aps.res_instance_id,
16725        inst_record_aps.equipment_item_id,
16726        inst_record_aps.serial_number ,
16727        inst_record_aps.shift_date,
16728        inst_record_aps.shift_num,
16729        inst_record_aps.from_time,
16730        inst_record_aps.to_time  ;
16731 
16732     stmt_no := 84;
16733 
16734         INSERT INTO msc_st_net_res_inst_avail
16735           ( Organization_Id,
16736             Department_id,
16737             sr_instance_id,
16738             Resource_Id,
16739             res_instance_id,
16740             serial_number,
16741             equipment_item_id,
16742             Shift_Num,
16743             Shift_Date,
16744             From_Time,
16745             To_Time
16746          )  VALUES
16747          (  inst_record_aps.organization_id ,
16748             inst_record_aps.Department_id ,
16749             p_instance_id  ,
16750             inst_record_aps.resource_id,
16751             inst_record_aps.res_instance_id,
16752             inst_record_aps.equipment_item_id,
16753             inst_record_aps.serial_number ,
16754             inst_record_aps.shift_num,
16755             inst_record_aps.shift_date,
16756             inst_record_aps.from_time,
16757             inst_record_aps.to_time
16758          )  ;
16759 
16760        COMMIT ;
16761     END LOOP;
16762     CLOSE r_inst_assembly;
16763 
16764     stmt_no := 85;
16765     sqlstmt := null ;
16766     sqlstmt := 'UPDATE msc_st_net_res_inst_avail '
16767             ||' SET to_time   = 86400 '
16768             ||' WHERE to_time = 86399 '
16769             ||'   AND shift_num >= 99999 ' ;
16770 
16771        EXECUTE immediate sqlstmt;
16772     sqlstmt := null ;
16773     stmt_no := 86;
16774     sqlstmt := 'UPDATE msc_st_net_res_inst_avail '
16775             ||' SET shift_num = (shift_num - 99999) '
16776             ||' WHERE shift_num >= 99999 ' ;
16777 
16778        EXECUTE immediate sqlstmt;
16779        COMMIT ;
16780 
16781    return_status := TRUE;
16782 
16783 EXCEPTION
16784     WHEN invalid_string_value  THEN
16785       log_message('APS string is Invalid, check for Error condition' );
16786       return_status := FALSE;
16787     WHEN NO_DATA_FOUND THEN /* B3577871 */
16788       log_message(' NO_DATA_FOUND exception : MSC_CL_GMP_UTILITY.Populate_rsrc_cal ' );
16789       return_status := TRUE;
16790     WHEN OTHERS THEN
16791       log_message('Error in Populate Rsrc cal construct: '||stmt_no);
16792       log_message('Error : '||v_icode);
16793       log_message(SQLERRM);
16794       return_status := FALSE;
16795 
16796 END populate_rsrc_cal;  /* End of Main Procedure */
16797 
16798 /*
16799 REM+==========================================================================+
16800 REM| PROCEDURE NAME                                                           |
16801 REM|    rsrcal_based_availability                                             |
16802 REM|                                                                          |
16803 REM| Type                                                                     |
16804 REM|    private                                                               |
16805 REM|                                                                          |
16806 REM| DESCRIPTION                                                              |
16807 REM|    This Procedure will calcaulate net resource availability              |
16808 REM|    for all the resources having their own calendars different            |
16809 REM|    from plant's manufacturing calendar                                   |
16810 REM| Input Parameters                                                         |
16811 REM|    p_run_date    - Running Date                                          |
16812 REM|    p_instance_id - Instance Id                                           |
16813 REM|    p_db_link - Data Base Link                                            |
16814 REM|                                                                          |
16815 REM| Output Parameters                                                        |
16816 REM|    return_status                                                         |
16817 REM|                                                                          |
16818 REM| HISTORY                                                                  |
16819 REM|    06/07/2005  by Rajesh Patangya (OPM Development Oracle US)            |
16820 REM+==========================================================================+
16821 REM
16822 */
16823 PROCEDURE rsrcal_based_availability(p_run_date    IN DATE,
16824                                     p_instance_id IN NUMBER,
16825                                     p_db_link     IN VARCHAR2,
16826                                     return_status OUT NOCOPY BOOLEAN) IS
16827 
16828   /*  Declare  Cursor Types */
16829   cur_get_cal      ref_cursor_typ;
16830 
16831   TYPE cal_org_typ is RECORD
16832   ( calendar_id      number,
16833     calendar_no      varchar2(16),
16834     calendar_desc    varchar2(40),
16835     orgn_code        varchar2(4),
16836     organization_id  number
16837   );
16838   calorg_record  cal_org_typ;
16839 
16840   sql_get_cal      VARCHAR2(32700);/* Bug # 5086464 */
16841   old_calendar_id  NUMBER ;
16842 
16843 BEGIN
16844   stmt_no          := 0 ;
16845   old_calendar_id  := -1;
16846 
16847          stmt_no := 610;
16848          /* populate the org_string */
16849          IF MSC_CL_GMP_UTILITY.org_string(p_instance_id) THEN
16850             NULL ;
16851          ELSE
16852             RAISE invalid_string_value  ;
16853          END IF;
16854 
16855          sql_get_cal :=  ' SELECT distinct crd.calendar_id,  '
16856             ||' shcl.calendar_no, shcl.calendar_desc, '
16857             ||' sy.orgn_code, iwm.mtl_organization_id '
16858             ||' FROM mr_shcl_hdr'||p_db_link||' shcl, '
16859             ||'      sy_orgn_mst'||p_db_link||' sy,  '
16860             ||'      cr_rsrc_dtl'||p_db_link||' crd,  '
16861             ||'      ic_whse_mst'||p_db_link||' iwm  '
16862             ||' WHERE sy.orgn_code = crd.orgn_code '
16863 	    ||'   AND sy.mfg_calendar_id <> crd.calendar_id '
16864             ||'   AND crd.calendar_id IS NOT NULL '
16865             ||'   AND crd.calendar_id = shcl.calendar_id '
16866             ||'   AND iwm.whse_code = sy.resource_whse_code ' ;
16867 
16868         IF MSC_CL_GMP_UTILITY.g_in_str_org  IS NOT NULL THEN
16869          sql_get_cal := sql_get_cal
16870             ||'   AND iwm.mtl_organization_id '||MSC_CL_GMP_UTILITY.g_in_str_org;
16871         END IF;
16872 
16873          sql_get_cal := sql_get_cal
16874             ||'   AND shcl.delete_mark = 0 '
16875             ||'   AND crd.delete_mark = 0 '
16876             ||' ORDER BY crd.calendar_id  ' ;
16877 
16878      OPEN cur_get_cal FOR sql_get_cal ;
16879      LOOP
16880      FETCH cur_get_cal INTO calorg_record ;
16881      EXIT WHEN cur_get_cal%NOTFOUND ;
16882 
16883       log_message('BASED: ' || calorg_record.calendar_id );
16884       IF calorg_record.calendar_id <> old_calendar_id THEN
16885          stmt_no := 611 ;
16886          COMMIT;  -- To Empty the _GTMP Table
16887 
16888       log_message('BASED 1 ' );
16889          retrieve_calendar_detail(calorg_record.calendar_id,
16890                                   calorg_record.calendar_no,
16891                                   calorg_record.calendar_desc,
16892                                   p_run_date,
16893                                   p_db_link,
16894                                   p_instance_id,
16895                                   V_WPS,
16896                                   return_status
16897                                   );
16898       END IF ;
16899 
16900       log_message('BASED 2 ' );
16901          stmt_no := 622;
16902          /* Populating Net Resource Insert Table */
16903          net_rsrc_insert(calorg_record.organization_id,
16904                          calorg_record.orgn_code,
16905                          NULL,    -- simulation_set,
16906                          p_db_link,
16907                          p_instance_id,
16908                          p_run_date,
16909                          calorg_record.calendar_id,
16910                          V_BASED,
16911                          return_status
16912                          );
16913 
16914       log_message('BASED 3 ' );
16915         /* Populate Net Resource Instance rows  PS Integration */
16916            net_rsrc_avail_calculate(calorg_record.organization_id,
16917                                     calorg_record.orgn_code,
16918                                     calorg_record.calendar_id,
16919                                     p_instance_id,
16920                                     p_db_link,
16921                                     V_BASED,
16922                                     return_status)  ;
16923       log_message('BASED 4 ' );
16924     COMMIT ;
16925 
16926       old_calendar_id := calorg_record.calendar_id ;
16927 
16928      END LOOP ;
16929      CLOSE cur_get_cal ;
16930      return_status := TRUE;
16931 
16932 EXCEPTION
16933     WHEN invalid_string_value  THEN
16934       log_message('APS string is Invalid, check for Error condition' );
16935       return_status := FALSE;
16936     WHEN NO_DATA_FOUND THEN
16937       log_message('NO DATA FOUND exception: MSC_CL_GMP_UTILITY.rsrcal_based_availability');
16938       return_status := TRUE;
16939     WHEN OTHERS THEN
16940       log_message('Error in MSC_CL_GMP_UTILITY.rsrcal_based_availability '||p_instance_id);
16941       log_message(sqlerrm);
16942       return_status := FALSE;
16943 
16944 END rsrcal_based_availability;
16945 
16946 /*
16947 REM+==========================================================================+
16948 REM| PROCEDURE NAME                                                           |
16949 REM|    insert_gmp_resource_avail                                             |
16950 REM|                                                                          |
16951 REM| Type                                                                     |
16952 REM|    public                                                                |
16953 REM|                                                                          |
16954 REM| DESCRIPTION                                                              |
16955 REM|                                                                          |
16956 REM| Input Parameters                                                         |
16957 REM|    p_orgn_code - Orgn Code                                               |
16958 REM|                                                                          |
16959 REM| Output Parameters                                                        |
16960 REM|    errbuf and retcode                                                    |
16961 REM|                                                                          |
16962 REM| HISTORY                                                                  |
16963 REM|    Created on 4th Jan 2002 By Rajesh Patangya                            |
16964 REM| B3161696 - 26-SEP-2003 TARGETTED RESOURCE AVAILABILITY PLACEHOLDER BUG   |
16965 REM| B4309093 - 20-APR-2005 Modified code to TO ADD TIME OR A SHIFT TO A      |
16966 REM|                        PLANT RESOURCE                                    |
16967 REM+==========================================================================+
16968 */
16969 PROCEDURE insert_gmp_resource_avail( errbuf        OUT NOCOPY VARCHAR2,
16970                                      retcode       OUT NOCOPY NUMBER  ,
16971                                      p_orgn_code   IN VARCHAR2 ,
16972                                      p_from_rsrc   IN VARCHAR2 ,
16973                                      p_to_rsrc     IN VARCHAR2 ,
16974                                      p_calendar_id IN NUMBER   ) IS
16975 
16976   cal_detail_ref    ref_cursor_typ;
16977   cur_get_def_cal   ref_cursor_typ;
16978   cur_get_cal       ref_cursor_typ;
16979   l_calendar_no     varchar2(16) ;
16980   l_calendar_desc   varchar2(40) ;
16981   l_calendar_id     NUMBER  ;
16982   i                 integer ;
16983   l_message         varchar2(1000) ;
16984   ret_status        boolean ;
16985   sql_stmt1	    VARCHAR2(32000) ;
16986   sql_stmt2	    VARCHAR2(32000) ;
16987   delete_stmt	    VARCHAR2(32000) ;
16988   sql_get_cal	    VARCHAR2(32000) ;
16989   sql_get_def_cal   VARCHAR2(32000) ;
16990 
16991 BEGIN
16992   i                 := 1 ;
16993   stmt_no	    := 0 ;
16994   l_message         := NULL ;
16995   sql_stmt1         := NULL;
16996   sql_stmt2         := NULL;
16997   sql_get_cal       := NULL;
16998   delete_stmt       := NULL;
16999   l_calendar_id     := 0 ;
17000 
17001   V_FROM_RSRC := p_from_rsrc;
17002   V_TO_RSRC   := p_to_rsrc ;
17003   l_calendar_id := p_calendar_id ;
17004 
17005 
17006 --HW B4309093 Case I - Calendar is blank
17007 IF p_calendar_id is NULL THEN
17008 
17009 -- This also covers if From and To resources are blank
17010     sql_get_cal :=  ' SELECT '
17011          ||'  DISTINCT NVL(r.calendar_id,sy.mfg_calendar_id), '
17012          ||' shcl.calendar_no, shcl.calendar_desc '
17013          ||' FROM mr_shcl_hdr shcl, '
17014          ||'      sy_orgn_mst sy, '
17015          ||'      cr_rsrc_dtl r   '
17016          ||' WHERE sy.orgn_code = r.orgn_code '
17017 	 ||'   AND NVL(r.calendar_id,sy.mfg_calendar_id)=shcl.calendar_id '
17018 	 ||'   AND r.orgn_code = :lorgn_code '
17019          ||'   AND shcl.delete_mark = 0 ' ;
17020 
17021 -- Case A - From Resource is entered and To Resource is blank
17022 
17023    IF (v_from_rsrc IS NOT NULL AND v_to_rsrc IS NULL) THEN
17024      sql_get_cal := sql_get_cal  || ' AND r.resources >= :frsrc ' ;
17025      OPEN cur_get_cal FOR sql_get_cal USING p_orgn_code , p_from_rsrc;
17026 
17027 -- Case B - From and TO resources are entered
17028 
17029    ELSE
17030      IF (v_from_rsrc IS NOT NULL AND v_to_rsrc IS NOT NULL) THEN
17031        sql_get_cal := sql_get_cal  || ' AND resources BETWEEN :frsrc and :trsrc ';
17032        OPEN cur_get_cal FOR sql_get_cal USING p_orgn_code , p_from_rsrc, p_to_rsrc ;
17033 
17034 -- Case C - From and TO resources are blank
17035 -- Statement is already constrcut at top
17036      ELSIF ( v_from_rsrc IS NULL AND v_to_rsrc IS NULL) THEN
17037       OPEN cur_get_cal FOR sql_get_cal USING p_orgn_code ;
17038      END IF ;
17039 
17040    END IF;
17041 
17042 -- Case II Calendar is entered
17043 ELSE
17044 -- Case A- Both from and To resources are entered
17045       sql_get_cal := 'Select calendar_id, '
17046 		||' calendar_no,calendar_desc '
17047 		||' FROM mr_shcl_hdr '
17048 		||' WHERE calendar_id = :cal_id ' ;
17049       OPEN cur_get_cal FOR sql_get_cal USING p_calendar_id ;
17050 END IF ;
17051 
17052 -- HW B4309093 Loop through the calendars
17053 LOOP
17054 FETCH cur_get_cal INTO l_calendar_id, l_calendar_no, l_calendar_desc ;
17055 EXIT WHEN cur_get_cal%NOTFOUND ;
17056 
17057      stmt_no := 1 ;
17058      delete_stmt := 'DELETE FROM gmp_resource_avail '||
17059                     ' WHERE calendar_id = :cal_id '  ||
17060                     '   AND plant_code  = :Plant_code1 ';
17061 
17062     IF (v_from_rsrc IS NOT NULL AND v_to_rsrc IS NOT NULL) THEN
17063       delete_stmt := delete_stmt ||' AND resource_id in (select resource_id '
17064                             ||' FROM cr_rsrc_dtl '
17065                             ||' WHERE orgn_code = :Plant_code2 '
17066                             ||' AND resources BETWEEN :frsrc and :trsrc ) ';
17067      EXECUTE IMMEDIATE delete_stmt USING l_calendar_id, p_orgn_code,
17068                    p_orgn_code, v_from_rsrc, v_to_rsrc;
17069     ELSIF (v_from_rsrc IS NOT NULL AND v_to_rsrc IS NULL) THEN
17070       delete_stmt := delete_stmt ||' AND resource_id in (select resource_id '
17071                             ||' FROM cr_rsrc_dtl '
17072                             ||' WHERE orgn_code = :Plant_code2 '
17073                             ||' AND resources > :frsrc ) ';
17074      EXECUTE IMMEDIATE delete_stmt USING l_calendar_id, p_orgn_code,
17075                    p_orgn_code, v_from_rsrc;
17076 
17077     ELSIF (v_from_rsrc IS NULL AND v_to_rsrc IS NULL) THEN
17078      EXECUTE IMMEDIATE delete_stmt USING l_calendar_id, p_orgn_code ;
17079 
17080     END IF ;
17081 
17082     COMMIT;
17083 
17084     retrieve_calendar_detail(l_calendar_id,
17085                              l_calendar_no,
17086                              l_calendar_desc,
17087                              null,
17088                              null,
17089                              null,
17090                              V_WPS,
17091                              ret_status)  ;
17092 
17093     /* Summary rows for WPS */
17094     net_rsrc_insert(null,
17095                     p_orgn_code,
17096                     null,
17097                     null,
17098                     0,
17099                     sysdate,
17100                     l_calendar_id,
17101                     V_WPS,
17102                     ret_status)  ;
17103     COMMIT ;
17104 
17105     /* Instance number rows for WPS */
17106     net_rsrc_avail_calculate(null,
17107                              p_orgn_code,
17108                              l_calendar_id,
17109                              null,   /* MSC INSTANCE */
17110                              null,   /* DB LINK */
17111                              V_WPS,
17112                              ret_status)  ;
17113     COMMIT ;
17114 
17115 END LOOP ;
17116 CLOSE cur_get_cal ; -- HW B4309093
17117 
17118     retcode := 0 ;
17119 
17120 EXCEPTION
17121    WHEN NO_DATA_FOUND THEN
17122        l_message := 'Manufacturing Calendar is not assigned to '|| p_orgn_code ;
17123        log_message(l_message);
17124        retcode := 1 ;
17125    WHEN OTHERS THEN
17126        log_message(sqlerrm);
17127        retcode := 1 ;
17128 
17129 END insert_gmp_resource_avail;
17130 
17131 /*
17132 REM+==========================================================================+
17133 REM| PROCEDURE NAME                                                           |
17134 REM|    net_rsrc_avail_calculate                                              |
17135 REM|                                                                          |
17136 REM| Type                                                                     |
17137 REM|    public                                                                |
17138 REM|                                                                          |
17139 REM| DESCRIPTION                                                              |
17140 REM|                                                                          |
17141 REM| Input Parameters                                                         |
17142 REM|    p_nstance_id - Instance_id                                            |
17143 REM|    p_orgn_code - Orgn Code                                               |
17144 REM|    p_instance_id - Instance Id                                           |
17145 REM|    p_db_link - Data Base Link                                            |
17146 REM|                                                                          |
17147 REM| Output Parameters                                                        |
17148 REM|    return_status                                                         |
17149 REM|                                                                          |
17150 REM| HISTORY                                                                  |
17151 REM|    Created on 4th Jan 2002 By Rajesh Patangya                            |
17152 REM|    7th Mar 2003 -- Performance issue fix and B2671540 00:00 shift fix    |
17153 REM| B3161696 - 26-SEP-2003 TARGETTED RESOURCE AVAILABILITY PLACEHOLDER BUG   |
17154 REM| B4309093 - 20-APR-2005 Modified code to TO ADD TIME OR A SHIFT TO A      |
17155 REM|                        PLANT RESOURCE                                    |
17156 REM+==========================================================================+
17157 */
17158 
17159 PROCEDURE net_rsrc_avail_calculate(
17160                           p_org_id       IN NUMBER,
17161                           p_orgn_code    IN VARCHAR2,
17162                           p_calendar_id  IN NUMBER,
17163                           p_instance_id  IN NUMBER,
17164                           p_db_link      IN VARCHAR2,
17165                           p_usage        IN VARCHAR2,   /* OPM-PS */
17166                           return_status  OUT NOCOPY BOOLEAN) IS
17167 
17168 /* For GMP_RESOURCE_AVAIL array definition */
17169 TYPE interval_typ is RECORD
17170 (
17171   resource_id           NUMBER,
17172   resource_instance_id  NUMBER,
17173   shift_date            DATE,
17174   shift_num             NUMBER,
17175   resource_units        NUMBER,
17176   from_time             NUMBER,
17177   to_time               NUMBER
17178 );
17179 
17180 TYPE interval_tab is table of interval_typ index by BINARY_INTEGER;
17181 
17182 interval_record		interval_typ;
17183 interval_rec		interval_tab;
17184 
17185 ri_assembly	        ref_cursor_typ;
17186 ri_shift_interval	ref_cursor_typ;
17187 
17188 sqlstmt		        VARCHAR2(32000) ;
17189 sqlupt 		        VARCHAR2(32000) ;
17190 sql_stmt1		VARCHAR2(32000) ;
17191 sql_stmt2		VARCHAR2(32000) ;
17192 
17193 k         		INTEGER ;
17194 i         		INTEGER ;
17195 j         		INTEGER ;
17196 g_calendar_id           NUMBER  ;
17197 x_dept_id               NUMBER  ;
17198 
17199 BEGIN
17200 
17201          /* 8i Database does not support BULK COLLECT - B3881832 */
17202          sqlstmt	 := NULL;
17203          sqlupt 	 := NULL;
17204          sql_stmt1	 := NULL;
17205          sql_stmt2	 := NULL;
17206          stmt_no	 := 0 ;
17207          x_dept_id       := 0 ;
17208          k         	 := 1;
17209          i         	 := 1;
17210          j         	 := 1;
17211          resource_count  := empty_num_table;
17212          resource_id     := empty_num_table;
17213          instance_id     := empty_num_table;
17214          instance_number := empty_num_table;
17215          shift_num       := empty_num_table;
17216          f_date          := empty_dat_table;
17217          t_date          := empty_dat_table;
17218          /* 8i Database does not support BULK COLLECT - B3881832 */
17219          dbms_session.free_unused_user_memory;
17220 
17221          stmt_no := 60;
17222          -- Rajesh Patangya B4692705, When the calendar is not assigned to
17223          -- resource then organization calendar should be considered
17224 	 g_calendar_id 	:= 0 ;
17225          sql_stmt1 :=  '  SELECT mfg_calendar_id '
17226                     || '  FROM sy_orgn_mst'||p_db_link
17227                     || '  WHERE orgn_code = :orgn_code1 ';
17228 
17229          EXECUTE IMMEDIATE sql_stmt1 INTO g_calendar_id USING p_orgn_code ;
17230 
17231          IF g_calendar_id = 0 THEN
17232             log_message('Warning : '||p_orgn_code||
17233                     ' does not have manufacturing calendar, continuing ...') ;
17234          END IF;
17235 
17236     /* Interval Cursor gives the all the point of inflections  */
17237 
17238     stmt_no := 63;
17239     /*  03/26/02 Rajesh Patangya B2282409, Filter extra resource information */
17240     -- HW B4309093 Check for calendar id in cr_rsrc_dtl
17241        sql_stmt1 :=  ' SELECT /*+ ALL_ROWS */ '
17242                   || '  decode(rt.interval_date,rt.lead_idate,rt.assigned_qty,'
17243                   || '  (rt.assigned_qty-nvl(rt.rsum,0))) resource_count '
17244                   || '  ,rt.resource_id '
17245                   || '  ,rt.instance_id '
17246                   || '  ,rt.shift_num '
17247                   || '  ,rt.interval_date '
17248                   || '  ,rt.lead_idate    '
17249                -- for OPM-PS
17250                   || '  ,NVL(gri.eqp_serial_number, to_char(gri.instance_number)) '
17251                   || '  ,gri.equipment_item_id '
17252                   || '  ,((rt.resource_id * 2) + 1) '
17253                   || '  ,((rt.instance_id * 2) + 1) '
17254                   || ' FROM '
17255                   || ' ( '
17256                   || ' SELECT '
17257                   || '  t.resource_id '
17258                   || '  ,t.instance_id '
17259                   || '  ,t.shift_num  '
17260                   || '  ,t.interval_date '
17261                   || '  ,t.assigned_qty  '
17262                   || '  ,nvl(u.resource_units,0) rsum  '
17263                   || '  ,max(t.lead_idate) lead_idate '
17264                   || ' FROM ( '
17265                   || ' SELECT unique resource_id,instance_id,from_date, '
17266                   || ' to_date to_date1,resource_units '
17267                   || ' FROM ( '
17268                   || ' SELECT un.resource_id, '
17269                   || '        gri.instance_id, '
17270                   || '        un.from_date,  '
17271                   || '        un.to_date,    '
17272                   || '        1 resource_units'
17273                   || ' FROM   cr_rsrc_dtl '||p_db_link||'  crd, '
17274                   || '        gmp_rsrc_unavail_dtl_v '||p_db_link||' un, '
17275                   || '        gmp_resource_instances '||p_db_link||' gri '
17276                   || ' WHERE  crd.resource_id = un.resource_id  '
17277                   || ' AND    crd.resource_id = gri.resource_id  '
17278                   || ' AND    un.instance_id  = gri.instance_id  '
17279                   || ' AND    crd.orgn_code = :orgn_code1 ' ;
17280 
17281     IF (p_usage = 'BASED') THEN   /* Usage APS */
17282     sql_stmt1 := sql_stmt1
17283                   || ' AND    crd.calendar_id = :l_cal_id1 ' ;
17284     ELSE
17285     sql_stmt1 := sql_stmt1
17286                   || ' AND    nvl(crd.calendar_id,:g_default_cal_id1)=:l_cal_id1 ';
17287     END IF ;
17288 
17289     sql_stmt1 := sql_stmt1
17290                   || ' AND    crd.schedule_ind = 2 '
17291                   || ' AND    crd.delete_mark = 0 '
17292                   || ' AND    nvl(un.instance_id,0) <> 0  ' ;
17293 
17294     IF (v_from_rsrc IS NOT NULL AND v_to_rsrc IS NOT NULL) THEN
17295     sql_stmt1 := sql_stmt1 || '  AND crd.resources BETWEEN :frsrc1 and :trsrc2 ' ;
17296     END IF ;
17297 
17298 -- HW B4309093 Check for calendar id in cr_rsrc_dtl
17299     sql_stmt1 := sql_stmt1
17300                   || ' UNION ALL '
17301                   || ' SELECT un.resource_id, '
17302                   || '        gri.instance_id, '
17303                   || '        un.from_date,  '
17304                   || '        un.to_date,    '
17305                   || '        1 resource_units'
17306                   || ' FROM   cr_rsrc_dtl '||p_db_link||'  crd, '
17307                   || '        gmp_rsrc_unavail_dtl_v '||p_db_link||' un, '
17308                   || '        gmp_resource_instances '||p_db_link||' gri '
17309                   || ' WHERE  crd.resource_id = un.resource_id  '
17310                   || ' AND    crd.resource_id = gri.resource_id  '
17311                   || ' AND    crd.orgn_code = :orgn_code2 ' ;
17312 
17313     IF (p_usage = 'BASED') THEN   /* Usage APS */
17314     sql_stmt1 := sql_stmt1
17315                   || ' AND    crd.calendar_id = :l_cal_id2 ' ;
17316     ELSE
17317     sql_stmt1 := sql_stmt1
17318                   || ' AND    nvl(crd.calendar_id ,:g_default_cal_id2)= :l_cal_id2 ' ;
17319     END IF;
17320 
17321     sql_stmt1 := sql_stmt1
17322                   || ' AND    crd.delete_mark = 0 '
17323                   || ' AND    crd.schedule_ind = 2 '
17324                   || ' AND    nvl(un.instance_id,0) = 0  ' ;
17325 
17326     IF (v_from_rsrc IS NOT NULL AND v_to_rsrc IS NOT NULL) THEN
17327     sql_stmt1 := sql_stmt1 || '  AND crd.resources BETWEEN :frsrc2 and :trsrc2 ' ;
17328     END IF ;
17329 -- HW B4309093 Check for calendar id in cr_rsrc_dtl
17330     sql_stmt1 := sql_stmt1
17331                   || ' AND    gri.instance_number in '
17332                   || '      ( select tgri.instance_number '
17333                   || '      FROM gmp_resource_instances '||p_db_link||' tgri '
17334                   || '      WHERE tgri.resource_id = crd.resource_id '
17335                   || '      AND rownum <= un.resource_units '
17336                   || '      ) '
17337                   || '   ) '
17338                   || ' ) u, '
17339                   || ' 	( '
17340                   || '  SELECT	resource_id,instance_id, shift_num, '
17341                   || '          interval_date,assigned_qty,lead_idate '
17342                   || ' 	FROM '
17343                   || ' 		( '
17344                   || ' 		SELECT '
17345                   || ' 			resource_id,instance_id,shift_num, '
17346                   || '                  interval_date,1 assigned_qty, '
17347                   || ' 			lead(resource_id,1) over(order by '
17348     || ' resource_id,instance_id,interval_date,shift_num) as lead_rid, '
17349                   || ' 			lead(instance_id,1) over(order by '
17350     || ' resource_id,instance_id,interval_date,shift_num) as lead_iid, '
17351                   || ' 			lead(interval_date,1) over(order by '
17352     || ' resource_id,instance_id,interval_date,shift_num) as lead_idate, '
17353                   || ' 			lead(shift_num,1) over(order by '
17354     || ' resource_id,instance_id,interval_date,shift_num) as lead_snum '
17355                   || ' 		FROM '
17356                   || ' 			( '
17357                   || ' SELECT unique cmd.resource_id, '
17358                   || ' cmd.instance_id, '
17359                   || ' exp.shift_num, '
17360                   || ' 1 , '
17361                   || ' cmd.interval_date '
17362                   || ' FROM ( '
17363                   || ' SELECT un.resource_id resource_id, '
17364                   || '        gri.instance_id instance_id,'
17365                   || '        0 shift_num,'
17366                   || '        1 resource_count,'
17367                   || '        un.from_date interval_date '
17368                   || ' FROM   cr_rsrc_dtl '||p_db_link||'  crd, '
17369                   || '        gmp_rsrc_unavail_dtl_v '||p_db_link||' un, '
17370                   || '        gmp_resource_instances '||p_db_link||' gri '
17371                   || ' WHERE  crd.resource_id = un.resource_id  '
17372                   || ' AND    crd.resource_id = gri.resource_id  '
17373                   || ' AND    un.instance_id  = gri.instance_id  '
17374                   || ' AND    crd.orgn_code = :orgn_code3 ' ;
17375 
17376     IF (p_usage = 'BASED') THEN   /* Usage APS */
17377     sql_stmt1 := sql_stmt1
17378                   || ' AND    crd.calendar_id = :l_cal_id3 ' ;
17379     ELSE
17380     sql_stmt1 := sql_stmt1
17381                   || ' AND    nvl(crd.calendar_id ,:g_default_cal_id3)= :l_cal_id3 ' ;
17382     END IF;
17383 
17384     sql_stmt1 := sql_stmt1
17385                   || ' AND    crd.schedule_ind = 2 '
17386                   || ' AND    crd.delete_mark = 0 '
17387                   || ' AND    nvl(un.instance_id,0) <> 0  ' ;
17388 
17389     IF (v_from_rsrc IS NOT NULL AND v_to_rsrc IS NOT NULL) THEN
17390     sql_stmt1 := sql_stmt1 || '  AND crd.resources BETWEEN :frsrc3 and :trsrc3 ' ;
17391     END IF ;
17392 
17393 -- HW B4309093 Check for calendar id in cr_rsrc_dtl
17394     sql_stmt1 := sql_stmt1
17395                   || ' UNION ALL '
17396                   || ' SELECT un.resource_id resource_id, '
17397                   || '        gri.instance_id instance_id,'
17398                   || '        0 shift_num,'
17399                   || '        1 resource_count,'
17400                   || '        un.to_date interval_date '
17401                   || ' FROM   cr_rsrc_dtl '||p_db_link||'  crd, '
17402                   || '        gmp_rsrc_unavail_dtl_v '||p_db_link||' un, '
17403                   || '        gmp_resource_instances '||p_db_link||' gri '
17404                   || ' WHERE  crd.resource_id = un.resource_id  '
17405                   || ' AND    crd.resource_id = gri.resource_id  '
17406                   || ' AND    un.instance_id  = gri.instance_id  '
17407                   || ' AND    crd.orgn_code = :orgn_code4 ' ;
17408     IF (p_usage = 'BASED') THEN   /* Usage APS */
17409     sql_stmt1 := sql_stmt1
17410                   || ' AND    crd.calendar_id = :l_cal_id4 ' ;
17411     ELSE
17412     sql_stmt1 := sql_stmt1
17413                   || ' AND    nvl(crd.calendar_id ,:g_default_cal_id4)= :l_cal_id4 ' ;
17414     END IF;
17415 
17416     sql_stmt1 := sql_stmt1
17417                   || ' AND    crd.schedule_ind = 2 '
17418                   || ' AND    crd.delete_mark = 0 '
17419                   || ' AND    nvl(un.instance_id,0) <> 0  ' ;
17420 
17421     IF (v_from_rsrc IS NOT NULL AND v_to_rsrc IS NOT NULL) THEN
17422     sql_stmt1 := sql_stmt1 || '  AND crd.resources BETWEEN :frsrc4 and :trsrc4 ' ;
17423     END IF ;
17424 
17425 -- HW B4309093 Check for calendar id in cr_rsrc_dtl
17426     sql_stmt1 := sql_stmt1
17427                   || ' UNION ALL '
17428                   || ' SELECT un.resource_id resource_id, '
17429                   || '        gri.instance_id instance_id,'
17430                   || '        0 shift_num,'
17431                   || '        1 resource_count,'
17432                   || '        un.from_date interval_date '
17433                   || ' FROM   cr_rsrc_dtl '||p_db_link||'  crd, '
17434                   || '        gmp_rsrc_unavail_dtl_v '||p_db_link||' un, '
17435                   || '        gmp_resource_instances '||p_db_link||' gri '
17436                   || ' WHERE  crd.resource_id = un.resource_id  '
17437                   || ' AND    crd.resource_id = gri.resource_id  '
17438                   || ' AND    crd.orgn_code = :orgn_code5 ' ;
17439     IF (p_usage = 'BASED') THEN   /* Usage APS */
17440     sql_stmt1 := sql_stmt1
17441                   || ' AND    crd.calendar_id = :l_cal_id5 ' ;
17442     ELSE
17443     sql_stmt1 := sql_stmt1
17444                   || ' AND    nvl(crd.calendar_id ,:g_default_cal_id5)= :l_cal_id5 ' ;
17445     END IF;
17446 
17447     sql_stmt1 := sql_stmt1
17448                   || ' AND    crd.schedule_ind = 2 '
17449                   || ' AND    crd.delete_mark = 0 '
17450                   || ' AND    nvl(un.instance_id,0) = 0  ' ;
17451 
17452     IF (v_from_rsrc IS NOT NULL AND v_to_rsrc IS NOT NULL) THEN
17453     sql_stmt1 := sql_stmt1 || '  AND crd.resources BETWEEN :frsrc5 and :trsrc5 ' ;
17454     END IF ;
17455 
17456 -- HW B4309093 Check for calendar id in cr_rsrc_dtl
17457     sql_stmt1 := sql_stmt1
17458                   || ' AND    gri.instance_number in '
17459                   || '      ( select tgri.instance_number '
17460                   || '      FROM gmp_resource_instances '||p_db_link||' tgri '
17461                   || '      WHERE tgri.resource_id = crd.resource_id '
17462                   || '      AND rownum <= un.resource_units '
17463                   || '      ) '
17464                   || ' UNION ALL '
17465                   || ' SELECT un.resource_id resource_id, '
17466                   || '        gri.instance_id instance_id,'
17467                   || '        0 shift_num,'
17468                   || '        1 resource_count,'
17469                   || '        un.to_date interval_date '
17470                   || ' FROM   cr_rsrc_dtl '||p_db_link||'  crd, '
17471                   || '        gmp_rsrc_unavail_dtl_v '||p_db_link||' un, '
17472                   || '        gmp_resource_instances '||p_db_link||' gri '
17473                   || ' WHERE  crd.resource_id = un.resource_id  '
17474                   || ' AND    crd.resource_id = gri.resource_id  '
17475                   || ' AND    crd.orgn_code = :orgn_code6 ' ;
17476 
17477     IF (p_usage = 'BASED') THEN   /* Usage APS */
17478     sql_stmt1 := sql_stmt1
17479                   || ' AND    crd.calendar_id = :l_cal_id6 ' ;
17480     ELSE
17481     sql_stmt1 := sql_stmt1
17482                   || ' AND    nvl(crd.calendar_id ,:g_default_cal_id6)= :l_cal_id6 ' ;
17483     END IF;
17484 
17485     sql_stmt1 := sql_stmt1
17486                   || ' AND    crd.delete_mark = 0 '
17487                   || ' AND    crd.schedule_ind = 2 '
17488                   || ' AND    nvl(un.instance_id,0) = 0  ' ;
17489 
17490     IF (v_from_rsrc IS NOT NULL AND v_to_rsrc IS NOT NULL) THEN
17491     sql_stmt1 := sql_stmt1 || '  AND crd.resources BETWEEN :frsrc6 and :trsrc6 ' ;
17492     END IF ;
17493 
17494 -- HW B4309093 Check for calendar id in cr_rsrc_dtl
17495     sql_stmt1 := sql_stmt1
17496                   || ' AND    gri.instance_number in '
17497                   || '      ( select tgri.instance_number '
17498                   || '      FROM gmp_resource_instances '||p_db_link||' tgri '
17499                   || '      WHERE tgri.resource_id = crd.resource_id '
17500                   || '      AND rownum <= un.resource_units '
17501                   || '      ) '
17502                   || '    )   cmd,  '
17503                   || '        gmp_calendar_detail_gtmp ' ||p_db_link||' exp  '
17504                   || '      WHERE  exp.calendar_id = :curr_cal1 '
17505                   || '        AND  cmd.interval_date  BETWEEN '
17506                   || '             exp.from_date AND exp.to_date '
17507                   || ' UNION ALL '
17508                   || ' SELECT crd.resource_id , '
17509                   || '        gri.instance_id, '
17510                   || '        exp.shift_num,  '
17511                   || '        1 , '
17512                   || '        (exp.shift_date + '
17513                   || '               (exp.from_time/86400)) interval_date '
17514                   || ' FROM   cr_rsrc_dtl '||p_db_link||'  crd, '
17515                   || '        gmp_calendar_detail_gtmp ' ||p_db_link||' exp, '
17516                   || '        gmp_resource_instances '||p_db_link||' gri '
17517                   || ' WHERE  crd.orgn_code = :orgn_code7 ' ;
17518 
17519     IF (p_usage = 'BASED') THEN   /* Usage APS */
17520     sql_stmt1 := sql_stmt1
17521                   || ' AND    crd.calendar_id = :l_cal_id7 ' ;
17522     ELSE
17523     sql_stmt1 := sql_stmt1
17524                   || ' AND    nvl(crd.calendar_id ,:g_default_cal_id7)= :l_cal_id7 ' ;
17525     END IF;
17526 
17527     sql_stmt1 := sql_stmt1
17528                   || ' AND    exp.calendar_id = :curr_cal2 '
17529                   || ' AND    crd.resource_id = gri.resource_id  '
17530                   || ' AND    crd.delete_mark = 0 '
17531                   || ' AND    crd.schedule_ind = 2 ' ;
17532 
17533     IF (v_from_rsrc IS NOT NULL AND v_to_rsrc IS NOT NULL) THEN
17534     sql_stmt1 := sql_stmt1 || '  AND crd.resources BETWEEN :frsrc7 and :trsrc7 ' ;
17535     END IF ;
17536 
17537 -- HW B4309093 Check for calendar id in cr_rsrc_dtl
17538     sql_stmt1 := sql_stmt1
17539                   || ' UNION ALL '
17540                   || ' SELECT crd.resource_id , '
17541                   || '        gri.instance_id, '
17542                   || '        exp.shift_num,  '
17543                   || '        1 , '
17544                   || '        (exp.shift_date + '
17545                   || '               (exp.to_time/86400)) interval_date '
17546                   || ' FROM   cr_rsrc_dtl '||p_db_link||'  crd, '
17547                   || '        gmp_calendar_detail_gtmp ' ||p_db_link||' exp, '
17548                   || '        gmp_resource_instances '||p_db_link||' gri '
17549                   || ' WHERE  crd.orgn_code = :orgn_code8 ' ;
17550 
17551     IF (p_usage = 'BASED') THEN   /* Usage APS */
17552     sql_stmt1 := sql_stmt1
17553                   || ' AND    crd.calendar_id = :l_cal_id8 ' ;
17554     ELSE
17555     sql_stmt1 := sql_stmt1
17556                   || ' AND    nvl(crd.calendar_id ,:g_default_cal_id8)= :l_cal_id8 ' ;
17557     END IF;
17558 
17559     sql_stmt1 := sql_stmt1
17560                   || ' AND    exp.calendar_id = :curr_cal3 '
17561                   || ' AND    crd.resource_id = gri.resource_id  '
17562                   || ' AND    crd.delete_mark = 0 ' ;
17563 
17564     IF (v_from_rsrc IS NOT NULL AND v_to_rsrc IS NOT NULL) THEN
17565     sql_stmt1 := sql_stmt1 || '  AND crd.resources BETWEEN :frsrc8 and :trsrc8 ' ;
17566     END IF ;
17567 
17568     sql_stmt1 := sql_stmt1
17569                   || ' AND    crd.schedule_ind = 2 '
17570                   || '                  ) '
17571                   || '          ) '
17572                   || '    WHERE resource_id = lead_rid '
17573                   || '      AND instance_id = lead_iid '
17574                   || '      AND trunc(interval_date) = trunc(lead_idate) '
17575                   || '      AND interval_date < lead_idate '
17576                   || '      AND shift_num = lead_snum  '
17577                   || '  ) t '
17578                   || ' WHERE '
17579                   || '      t.interval_date >= u.from_date(+) '
17580                   || '  AND t.lead_idate <= u.to_date1 (+) '
17581                   || '  AND t.resource_id = u.resource_id(+) '
17582                   || '  AND t.instance_id = u.instance_id(+) '
17583                   || ' GROUP BY '
17584                   || '   t.resource_id '
17585                   || '  ,t.instance_id '
17586                   || '  ,t.shift_num '
17587                   || '  ,t.interval_date '
17588                   || '  ,u.resource_units '
17589                   || '  ,t.assigned_qty '
17590                   || ' ) rt, '
17591                   || '   gmp_resource_instances '||p_db_link||' gri '
17592                   || ' WHERE '
17593                   || '  decode(rt.interval_date,rt.lead_idate,rt.assigned_qty,'
17594                   || '        (rt.assigned_qty - nvl(rt.rsum,0))) > 0 '
17595                   || '  AND rt.resource_id = gri.resource_id '
17596                   || '  AND rt.instance_id = gri.instance_id '
17597                   || ' ORDER BY rt.resource_id ,rt.instance_id, '
17598                   || '  rt.interval_date,rt.shift_num ' ;
17599 
17600     IF (v_from_rsrc IS NOT NULL AND v_to_rsrc IS NOT NULL) THEN
17601 
17602 -- HW B4309093 Pass correct parameters
17603     OPEN ri_shift_interval FOR sql_stmt1 USING
17604       p_orgn_code,p_calendar_id, p_calendar_id,V_FROM_RSRC, V_TO_RSRC,
17605       p_orgn_code, p_calendar_id,p_calendar_id,V_FROM_RSRC, V_TO_RSRC,
17606       p_orgn_code, p_calendar_id,p_calendar_id,V_FROM_RSRC, V_TO_RSRC,
17607       p_orgn_code, p_calendar_id,p_calendar_id,V_FROM_RSRC, V_TO_RSRC,
17608       p_orgn_code, p_calendar_id,p_calendar_id,V_FROM_RSRC, V_TO_RSRC,
17609       p_orgn_code, p_calendar_id,p_calendar_id,V_FROM_RSRC, V_TO_RSRC,
17610       p_calendar_id,
17611       p_orgn_code, p_calendar_id,p_calendar_id,p_calendar_id, V_FROM_RSRC, V_TO_RSRC,
17612       p_orgn_code, p_calendar_id,p_calendar_id,p_calendar_id, V_FROM_RSRC, V_TO_RSRC ;
17613 
17614     ELSE
17615 -- HW B4309093 Pass correct parameters
17616       IF (p_usage = 'BASED') THEN   /* Usage APS */
17617         OPEN ri_shift_interval FOR sql_stmt1 USING
17618 	    p_orgn_code,p_calendar_id,
17619     	    p_orgn_code,p_calendar_id,
17620 	    p_orgn_code,p_calendar_id,
17621 	    p_orgn_code,p_calendar_id,
17622 	    p_orgn_code,p_calendar_id,
17623             p_orgn_code,p_calendar_id, p_calendar_id,
17624             p_orgn_code,p_calendar_id,p_calendar_id,
17625             p_orgn_code,p_calendar_id, p_calendar_id ;
17626 
17627        ELSE
17628         OPEN ri_shift_interval FOR sql_stmt1 USING
17629 	    p_orgn_code,g_calendar_id,p_calendar_id,
17630     	    p_orgn_code,g_calendar_id,p_calendar_id,
17631 	    p_orgn_code,g_calendar_id,p_calendar_id,
17632 	    p_orgn_code,g_calendar_id,p_calendar_id,
17633 	    p_orgn_code,g_calendar_id,p_calendar_id,
17634             p_orgn_code,g_calendar_id,p_calendar_id, p_calendar_id,
17635             p_orgn_code,g_calendar_id, p_calendar_id,p_calendar_id,
17636             p_orgn_code,g_calendar_id,p_calendar_id, p_calendar_id ;
17637 
17638 
17639       END IF;
17640     END IF;
17641 
17642     /* B3347284, Performance Issue */
17643     stmt_no := 644;
17644     j := 1 ;
17645     LOOP
17646        FETCH ri_shift_interval INTO resource_count(j), resource_id(j),
17647              instance_id(j), shift_num(j), f_date(j), t_date(j), msc_serial_number(j),
17648              equipment_item_id(j), x_resource_id(j), x_instance_id(j);
17649 
17650        EXIT WHEN ri_shift_interval%NOTFOUND;
17651 
17652     stmt_no := 665;
17653     i := 1 ;
17654     x_dept_id := ((p_org_id * 2) + 1) ;
17655     IF (resource_id.FIRST > 0) AND (j = 75000) THEN  /* Only if any resource */
17656 
17657        IF ((p_usage = 'APS') OR (p_usage = 'BASED')) THEN /* Usage APS/BASED */
17658 
17659         FORALL i IN resource_id.FIRST..resource_id.LAST
17660 
17661         INSERT INTO msc_st_net_res_inst_avail
17662           ( Organization_Id,
17663             Department_id,
17664             sr_instance_id ,
17665             Resource_Id,
17666             res_instance_id,
17667             serial_number,
17668             equipment_item_id,
17669             Shift_Num,
17670             Shift_Date,
17671             From_Time,
17672             To_Time
17673          )  VALUES
17674          (
17675             p_org_id,
17676             x_dept_id,
17677             p_instance_id ,
17678             x_resource_id(i),
17679             x_instance_id(i),
17680             msc_serial_number(i),
17681             equipment_item_id(i),
17682             shift_num(i),
17683             trunc(f_date(i)),
17684             ((f_date(i) - trunc(f_date(i))) * 86400 ),
17685             ((t_date(i) - trunc(t_date(i))) * 86400 )
17686           )                     ;
17687 
17688        ELSIF (p_usage = 'WPS') THEN   /* Usage WPS     */
17689 
17690         FORALL i IN resource_id.FIRST..resource_id.LAST
17691         INSERT INTO gmp_resource_avail
17692          (
17693           instance_id, plant_code, resource_id,
17694           calendar_id, resource_instance_id, shift_num,
17695           shift_date, from_time, to_time,
17696           resource_units, creation_date, created_by,
17697           last_update_date, last_updated_by, last_update_login
17698          )  VALUES
17699          (
17700             p_instance_id,
17701             p_orgn_code,
17702             resource_id(i),
17703             p_calendar_id,
17704             instance_id(i),
17705             shift_num(i),
17706             trunc(f_date(i)),
17707             ((f_date(i) - trunc(f_date(i))) * 86400 ),
17708             ((t_date(i) - trunc(t_date(i))) * 86400 ),
17709             resource_count(i),
17710             sysdate,
17711             FND_GLOBAL.USER_ID,
17712             sysdate,
17713             FND_GLOBAL.USER_ID,
17714             FND_GLOBAL.USER_ID
17715           )                     ;
17716 
17717        END IF;   /* APS or WPS */
17718 
17719          resource_count     := empty_num_table;
17720          resource_id        := empty_num_table;
17721          x_resource_id      := empty_num_table;
17722          instance_id        := empty_num_table;
17723          x_instance_id      := empty_num_table;
17724          shift_num          := empty_num_table;
17725          msc_serial_number  := emp_serial_number;
17726          equipment_item_id  := empty_num_table;
17727          f_date             := empty_dat_table;
17728          t_date             := empty_dat_table;
17729          j := 0 ;
17730          /* 8i Database does not support BULK COLLECT - B3881832 */
17731          dbms_session.free_unused_user_memory;
17732 
17733    END IF;   /* Only if any resource */
17734 
17735    j := j + 1 ;
17736    END LOOP ;
17737    CLOSE ri_shift_interval;
17738 
17739     stmt_no := 666;
17740     i := 1 ;
17741     x_dept_id := ((p_org_id * 2) + 1) ;
17742     IF (resource_id.FIRST > 0) THEN  /* Only if any resource */
17743 
17744        IF ((p_usage = 'APS') OR (p_usage = 'BASED')) THEN /* Usage APS/BASED */
17745 
17746         FORALL i IN resource_id.FIRST..resource_id.LAST
17747         INSERT INTO msc_st_net_res_inst_avail
17748           ( Organization_Id,
17749             Department_id,
17750             sr_instance_id ,
17751             Resource_Id,
17752             res_instance_id,
17753             serial_number,
17754             equipment_item_id,
17755             Shift_Num,
17756             Shift_Date,
17757             From_Time,
17758             To_Time
17759          )  VALUES
17760          (
17761             p_org_id,
17762             x_dept_id,
17763             p_instance_id ,
17764             x_resource_id(i),
17765             x_instance_id(i),
17766             msc_serial_number(i),
17767             equipment_item_id(i),
17768             shift_num(i),
17769             trunc(f_date(i)),
17770             ((f_date(i) - trunc(f_date(i))) * 86400 ),
17771             ((t_date(i) - trunc(t_date(i))) * 86400 )
17772           )                     ;
17773 
17774        ELSIF (p_usage = 'WPS') THEN   /* Usage WPS     */
17775 
17776         FORALL i IN resource_id.FIRST..resource_id.LAST
17777         INSERT INTO gmp_resource_avail
17778          (
17779           instance_id, plant_code, resource_id,
17780           calendar_id, resource_instance_id, shift_num,
17781           shift_date, from_time, to_time,
17782           resource_units, creation_date, created_by,
17783           last_update_date, last_updated_by, last_update_login
17784          )  VALUES
17785          (
17786             p_instance_id,
17787             p_orgn_code,
17788             resource_id(i),
17789             p_calendar_id,
17790             instance_id(i),
17791             shift_num(i),
17792             trunc(f_date(i)),
17793             ((f_date(i) - trunc(f_date(i))) * 86400 ),
17794             ((t_date(i) - trunc(t_date(i))) * 86400 ),
17795             resource_count(i),
17796             sysdate,
17797             FND_GLOBAL.USER_ID,
17798             sysdate,
17799             FND_GLOBAL.USER_ID,
17800             FND_GLOBAL.USER_ID
17801           )                     ;
17802 
17803        END IF;   /* APS or WPS */
17804 
17805          resource_count     := empty_num_table;
17806          resource_id        := empty_num_table;
17807          x_resource_id      := empty_num_table;
17808          instance_id        := empty_num_table;
17809          x_instance_id      := empty_num_table;
17810          shift_num          := empty_num_table;
17811          msc_serial_number  := emp_serial_number;
17812          equipment_item_id  := empty_num_table;
17813          f_date             := empty_dat_table;
17814          t_date             := empty_dat_table;
17815          /* 8i Database does not support BULK COLLECT - B3881832 */
17816          dbms_session.free_unused_user_memory;
17817          COMMIT ;
17818 
17819    END IF;   /* Only if any resource */
17820 
17821    /* This logic introduced for Net resource availablility to
17822        write consolidated rows once final available rows are in place */
17823    stmt_no := 666;
17824    sql_stmt2 := NULL;
17825 
17826    sql_stmt2 :=  ' SELECT  /*+ ALL_ROWS */ '
17827    || '        net.resource_id , '
17828    || '        net.resource_instance_id, '
17829    || '        net.shift_date  , '
17830    || '        net.shift_num   , '
17831    || '        net.resource_units , '
17832    || '        min(net.from_time) from_time, '
17833    || '        max(net.lead_tt) to_time '
17834    || ' FROM  ( '
17835    || '        SELECT resource_id , '
17836    || '               resource_instance_id, '
17837    || '               shift_date  , '
17838    || '               shift_num , '
17839    || '               from_time , '
17840    || '               to_time , '
17841    || '               resource_units , '
17842    || '  lead(resource_id,1) over(order by resource_id,resource_instance_id, '
17843    || '  shift_date, shift_num,from_time,to_time,resource_units) as lead_rid, '
17844    || '  lead(resource_instance_id,1) over(order by resource_id, '
17845    || '  resource_instance_id, '
17846    || '  shift_date, shift_num,from_time,to_time,resource_units) as lead_iid, '
17847    || '  lead(shift_date,1) over(order by resource_id,resource_instance_id, '
17848    || '  shift_date, shift_num,from_time,to_time,resource_units) as lead_sdt, '
17849    || '  lead(shift_num,1) over(order by resource_id,resource_instance_id, '
17850    || '  shift_date, shift_num,from_time,to_time,resource_units) as lead_sn, '
17851    || '  lead(from_time,1) over(order by resource_id,resource_instance_id, '
17852    || '  shift_date, shift_num,from_time,to_time,resource_units) as lead_ft, '
17853    || '  lead(to_time,1) over(order by resource_id,resource_instance_id, '
17854    || '  shift_date, shift_num,from_time,to_time,resource_units) as lead_tt, '
17855    || '  lead(resource_units,1) over(order by resource_id, '
17856    || '  resource_instance_id, '
17857    || '  shift_date, shift_num,from_time,to_time,resource_units) as lead_rc '
17858    || '          FROM gmp_resource_avail'
17859    || '          WHERE plant_code = :orgn_code1 '
17860    || '            AND calendar_id = :cal_id ' ;
17861 
17862    IF (v_from_rsrc IS NOT NULL AND v_to_rsrc IS NOT NULL) THEN
17863 
17864    sql_stmt2 := sql_stmt2 ||' AND resource_id in (select resource_id '
17865                           ||' from cr_rsrc_dtl '||p_db_link
17866                           ||' WHERE orgn_code = :orgn_code2 '
17867                           ||' AND resources BETWEEN :frsrc and :trsrc )' ;
17868    END IF ;
17869 
17870    sql_stmt2 := sql_stmt2 || '              ) net '
17871    || '      WHERE net.resource_id          = net.lead_rid '
17872    || '        AND net.resource_instance_id = net.lead_iid '
17873    || '        AND net.shift_num      = net.lead_sn '
17874    || '        AND net.shift_date     = net.lead_sdt '
17875    || '        AND net.to_time        = net.lead_ft '
17876    || '        AND net.resource_units = net.lead_rc '
17877    || ' GROUP BY '
17878    || '        net.resource_id , '
17879    || '        net.resource_instance_id , '
17880    || '        net.shift_date , '
17881    || '        net.shift_num , '
17882    || '        net.resource_units ' ;
17883 
17884     stmt_no := 66;
17885 
17886     IF (v_from_rsrc IS NOT NULL AND v_to_rsrc IS NOT NULL) THEN
17887      OPEN ri_assembly FOR sql_stmt2 USING p_orgn_code, p_calendar_id,
17888           p_orgn_code, v_from_rsrc, v_to_rsrc ;
17889     ELSE
17890      OPEN ri_assembly FOR sql_stmt2 USING p_orgn_code, p_calendar_id ;
17891     END IF;
17892 
17893     LOOP
17894        FETCH ri_assembly INTO  interval_record;
17895        EXIT WHEN ri_assembly%NOTFOUND;
17896 
17897      sqlstmt := 'DELETE FROM gmp_resource_avail'
17898              || ' WHERE plant_code  = :Plant_code1 '
17899              || '   AND calendar_id = :cal_id '
17900              || '   AND resource_id = :prid '
17901              || '   AND resource_instance_id = :piid '
17902              || '   AND shift_date = :psdt '
17903              || '   AND shift_num  = :psn  '
17904              || '   AND from_time  >= :pft '
17905              || '   AND to_time  <= :ptt '
17906              || '   AND resource_units = :prc ' ;
17907 
17908    stmt_no := 67;
17909        EXECUTE immediate sqlstmt USING
17910        p_orgn_code , p_calendar_id ,
17911        interval_record.resource_id,
17912        interval_record.resource_instance_id,
17913        trunc(interval_record.shift_date),
17914        interval_record.shift_num,
17915        interval_record.from_time, interval_record.to_time,
17916        interval_record.resource_units  ;
17917 
17918    stmt_no := 68;
17919          net_rsrc_avail_insert(
17920             p_instance_id,
17921             p_orgn_code,
17922             interval_record.resource_instance_id,
17923             p_calendar_id,
17924             interval_record.resource_id,
17925             interval_record.resource_units,
17926             interval_record.shift_num,
17927             interval_record.shift_date,
17928             interval_record.from_time,
17929             interval_record.to_time
17930                   );
17931 
17932        COMMIT ;
17933     END LOOP;
17934     CLOSE ri_assembly;
17935 
17936    stmt_no := 69;
17937      sqlupt := 'UPDATE gmp_resource_avail'
17938             ||' SET to_time   = 86400 '
17939             ||' WHERE to_time = 86399 '
17940             ||'   AND shift_num >= 99999 ' ;
17941 
17942        EXECUTE immediate sqlupt ;
17943      sqlupt := null ;
17944      sqlupt := 'UPDATE gmp_resource_avail'
17945             ||' SET shift_num = (shift_num - 99999) '
17946             ||' WHERE shift_num >= 99999 ' ;
17947 
17948        EXECUTE immediate sqlupt ;
17949        COMMIT ;
17950 
17951     return_status := TRUE ;
17952   EXCEPTION
17953   WHEN NO_DATA_FOUND THEN
17954    log_message('NO DATA FOUND exception: MSC_CL_GMP_UTILITY.net_rsrc_avail_calculate');
17955    return_status := TRUE;
17956   WHEN  OTHERS THEN
17957    log_message('Error in Net Resource Instance Insert: '||stmt_no);
17958    log_message(sqlerrm);
17959    return_status := FALSE ;
17960 
17961 end net_rsrc_avail_calculate;
17962 
17963 /*
17964 REM+==========================================================================+
17965 REM| PROCEDURE NAME                                                           |
17966 REM|    net_rsrc_avail_insert                                                 |
17967 REM|                                                                          |
17968 REM| Type                                                                     |
17969 REM|    public                                                                |
17970 REM|                                                                          |
17971 REM| DESCRIPTION                                                              |
17972 REM|    The following procedure inserts rows into gmp_resource_avail          |
17973 REM|                                                                          |
17974 REM| Input Parameters                                                         |
17975 REM|    p_instance_id - Instance Id                                           |
17976 REM|    p_orgn_code - Plant Code                                              |
17977 REM|    p_resource_instance_id - Resource Instance Id                         |
17978 REM|    p_Calendar_id - Calendar id                                           |
17979 REM|    p_resource_id - Resource Id                                           |
17980 REM|    p_assigned_qty -  Resource units                                      |
17981 REM|    p_shift_num - Shift number                                            |
17982 REM|    p_calendar_date - Calendar date                                       |
17983 REM|    p_from_time - shift starting time                                     |
17984 REM|    p_to_time - Shift Ending time                                         |
17985 REM|                                                                          |
17986 REM| Output Parameters                                                        |
17987 REM|    None                                                                  |
17988 REM|                                                                          |
17989 REM| HISTORY                                                                  |
17990 REM|    Created on 4th Jan 2002 By Rajesh Patangya                            |
17991 REM|                                                                          |
17992 REM+==========================================================================+
17993 */
17994 
17995 PROCEDURE net_rsrc_avail_insert(p_instance_id          IN NUMBER,
17996                                 p_orgn_code            IN VARCHAR2,
17997                                 p_resource_instance_id IN NUMBER,
17998                                 p_calendar_id          IN NUMBER,
17999                                 p_resource_id          IN NUMBER,
18000                                 p_assigned_qty         IN NUMBER,
18001                                 p_shift_num            IN NUMBER,
18002                                 p_calendar_date        IN DATE,
18003                                 p_from_time            IN NUMBER,
18004                                 p_to_time              IN NUMBER ) IS
18005 
18006 BEGIN
18007    IF nvl(p_from_time,0) = 0  AND nvl(p_to_time,0) = 0 THEN
18008      NULL ;
18009    ELSE
18010      INSERT INTO gmp_resource_avail (
18011      instance_id, plant_code, resource_id,
18012      calendar_id, resource_instance_id, shift_num,
18013      shift_date, from_time, to_time,
18014      resource_units, creation_date, created_by,
18015      last_update_date, last_updated_by, last_update_login )
18016      VALUES (
18017              p_instance_id,
18018              p_orgn_code,
18019              p_resource_id,
18020              p_calendar_id,
18021              p_resource_instance_id,
18022              p_shift_num,
18023              p_calendar_date,
18024              p_from_time,
18025              p_to_time,
18026              p_assigned_qty,
18027              sysdate,
18028              FND_GLOBAL.USER_ID,
18029              sysdate,
18030              FND_GLOBAL.USER_ID,
18031              FND_GLOBAL.USER_ID ) ;
18032     END IF;
18033 EXCEPTION
18034   WHEN  OTHERS THEN
18035      log_message('Error in Net Resource Avail Insert ' || sqlerrm);
18036 
18037 END net_rsrc_avail_insert;
18038 
18039 /*
18040 REM+=========================================================================+
18041 REM| FUNCTION NAME                                                           |
18042 REM|    ORG_STRING                                                           |
18043 REM| DESCRIPTION                                                             |
18044 REM|    To find out the organization string                                  |
18045 REM| HISTORY                                                                 |
18046 REM| 12/21/2005   Rajesh Patangya                                            |
18047 REM+=========================================================================+
18048 */
18049 FUNCTION ORG_STRING(instance_id IN NUMBER) return BOOLEAN IS
18050 
18051  sql_stmt         varchar2(32000);
18052  c_str            ref_cursor_typ ;
18053  l_aps_compatible number ;
18054  org_str          varchar2(32767) ;
18055  in_position      number ;
18056 
18057 BEGIN
18058  sql_stmt           := NULL ;
18059  l_aps_compatible   := 0 ;
18060  org_str            := NULL ;
18061  in_position        := -10 ;
18062 
18063     SELECT MSC_CL_GMP_UTILITY.is_aps_compatible
18064     INTO l_aps_compatible  FROM DUAL ;
18065 
18066     IF l_aps_compatible = 1 THEN
18067 
18068        /*sql_stmt := 'SELECT MSC_CL_PULL.get_org_str(' || instance_id || ') FROM dual ' ;
18069        OPEN c_str FOR sql_stmt ;
18070        FETCH c_str INTO org_str ;
18071        log_message(' String From APS : ' || org_str);
18072        CLOSE c_str ;*/
18073 
18074        org_str := MSC_CL_PULL.get_org_str(instance_id); /* Bug # 5086464 Commented the code above and added this line */
18075 
18076 --  org_str := 'IN (1381,1382)' ;
18077          in_position := instr(org_str,'IN');
18078 
18079          /* B3450303, For all org or specific org, APS will provide valid org string
18080             We have to find the IN part in the string, otherwise have to raise
18081             Exception message for error condition */
18082 
18083          IF in_position > 0 THEN
18084          	MSC_CL_GMP_UTILITY.g_in_str_org  := org_str ;
18085         	return TRUE  ;
18086          ELSE
18087          	MSC_CL_GMP_UTILITY.g_in_str_org := NULL ;
18088         	return FALSE ;
18089          END IF;
18090 
18091 
18092     ELSE
18093      /* For older patchset This value should be TRUE */
18094         MSC_CL_GMP_UTILITY.g_in_str_org := NULL ;
18095         return TRUE  ;
18096     END IF;
18097 
18098    EXCEPTION
18099      WHEN OTHERS THEN
18100        log_message('Error in org_string ' || sqlerrm);
18101        MSC_CL_GMP_UTILITY.g_in_str_org := NULL ;
18102        return FALSE ;
18103 END ORG_STRING;
18104 
18105 FUNCTION GMP_CAL_UTILITY1_R10
18106             (
18107                           p_dblink      IN VARCHAR2,
18108                           p_delimiter   IN VARCHAR2,
18109                           p_instance    IN INTEGER,
18110                           p_run_date    IN DATE,
18111                           p_num1        IN NUMBER,
18112                           p_num2        IN NUMBER,
18113                           p_num3        IN NUMBER,
18114                           p_num4        IN NUMBER,
18115                           p_varchar1    IN VARCHAR2,
18116                           p_varchar2    IN VARCHAR2,
18117                           p_varchar3    IN VARCHAR2,
18118                           p_varchar4    IN VARCHAR2
18119             ) RETURN INTEGER IS
18120 BEGIN
18121     return 0;
18122 END GMP_CAL_UTILITY1_R10;
18123 
18124 PROCEDURE GMP_CAL_PROC1_R10
18125             (
18126                           p_dblink      IN VARCHAR2,
18127                           p_delimiter   IN VARCHAR2,
18128                           p_instance    IN INTEGER,
18129                           p_run_date    IN DATE,
18130                           p_num1        IN NUMBER,
18131                           p_num2        IN NUMBER,
18132                           p_num3        IN NUMBER,
18133                           p_num4        IN NUMBER,
18134                           p_varchar1    IN VARCHAR2,
18135                           p_varchar2    IN VARCHAR2,
18136                           p_varchar3    IN VARCHAR2,
18137                           p_varchar4    IN VARCHAR2,
18138                           return_status  OUT NOCOPY BOOLEAN
18139             ) IS
18140 BEGIN
18141     return_status := TRUE;
18142 END GMP_CAL_PROC1_R10;
18143 
18144 -- --------------------OPM Calendar Package End --------------
18145 
18146 
18147  FUNCTION is_aps_compatible RETURN NUMBER IS
18148  BEGIN
18149   RETURN 1 ;
18150  END is_aps_compatible ;
18151 
18152  END MSC_CL_GMP_UTILITY;