DBA Data[Home] [Help]

PACKAGE BODY: APPS.MSC_ATP_PEG

Source


1 PACKAGE BODY MSC_ATP_PEG AS
2 /* $Header: MSCAPEGB.pls 120.2 2007/12/12 10:18:41 sbnaik ship $  */
3 
4 MAXVALUE                CONSTANT NUMBER := 999999;
5 
6 PG_DEBUG varchar2(1) := NVL(FND_PROFILE.value('MSC_ATP_DEBUG'), 'N');
7 G_PKG_NAME              CONSTANT VARCHAR2(30) := 'MSC_ATP_PEG';
8 
9 -- Bug 3344102 Allocation related global variables.
10 G_ALLOC_ATP                     VARCHAR2(1);
11 G_CLASS_HRCHY                   NUMBER;
12 G_ALLOC_METHOD                  NUMBER;
13 -- End Bug 3344102
14 
15 -- Bug 3701093 Constants to mark how the Forecasts have been consumed.
16 C_CONFIG_FCST_CONSUMED          NUMBER := 2;
17 C_MODEL_FCST_CONSUMED           NUMBER := 1;
18 C_NO_FCST_CONSUMED              NUMBER := 0;
19 -- End Bug 3701093
20 -- Control for stopping calculation of relief_quantities.
21 C_ZERO_APPROXIMATOR             NUMBER := 0.000001;
22 
23 /* Currently the ATP Pegging Record Types will be defined local to this package. */
24 -- This record will hold the ATP simplified Pegging Data.
25 -- Corresponds to the table msc_atp_pegging
26 TYPE ATP_Simple_Peg_Typ is RECORD (
27      reference_item_id       MRP_ATP_PUB.number_arr := MRP_ATP_PUB.number_arr(),
28      base_item_id            MRP_ATP_PUB.number_arr := MRP_ATP_PUB.number_arr(),
29      inventory_item_id       MRP_ATP_PUB.number_arr := MRP_ATP_PUB.number_arr(),
30      plan_id                 MRP_ATP_PUB.number_arr := MRP_ATP_PUB.number_arr(),
31      sr_instance_id          MRP_ATP_PUB.number_arr := MRP_ATP_PUB.number_arr(),
32      organization_id         MRP_ATP_PUB.number_arr := MRP_ATP_PUB.number_arr(),
33      bom_item_type           MRP_ATP_PUB.number_arr := MRP_ATP_PUB.number_arr(),
34      fixed_lt                MRP_ATP_PUB.number_arr := MRP_ATP_PUB.number_arr(),
35      variable_lt             MRP_ATP_PUB.number_arr := MRP_ATP_PUB.number_arr(),
36      sales_order_qty         MRP_ATP_PUB.number_arr := MRP_ATP_PUB.number_arr(),
37      sales_order_line_id     MRP_ATP_PUB.number_arr := MRP_ATP_PUB.number_arr(),
38      demand_source_type      MRP_ATP_PUB.number_arr := MRP_ATP_PUB.number_arr(),--cmro
39      transaction_date        MRP_ATP_PUB.date_arr := MRP_ATP_PUB.date_arr(),
40      demand_id               MRP_ATP_PUB.number_arr := MRP_ATP_PUB.number_arr(),
41      demand_quantity         MRP_ATP_PUB.number_arr := MRP_ATP_PUB.number_arr(),
42      disposition_id          MRP_ATP_PUB.number_arr := MRP_ATP_PUB.number_arr(),
43      demand_class            MRP_ATP_PUB.char30_arr := MRP_ATP_PUB.char30_arr(),
44      consumed_qty            MRP_ATP_PUB.number_arr := MRP_ATP_PUB.number_arr(),
45      overconsumption_qty     MRP_ATP_PUB.number_arr := MRP_ATP_PUB.number_arr(),
46      supply_id               MRP_ATP_PUB.number_arr := MRP_ATP_PUB.number_arr(),
47      supply_quantity         MRP_ATP_PUB.number_arr := MRP_ATP_PUB.number_arr(),
48      allocated_quantity      MRP_ATP_PUB.number_arr := MRP_ATP_PUB.number_arr(),
49      tot_relief_qty          MRP_ATP_PUB.number_arr := MRP_ATP_PUB.number_arr(),
50      resource_id             MRP_ATP_PUB.number_arr := MRP_ATP_PUB.number_arr(),
51      department_id           MRP_ATP_PUB.number_arr := MRP_ATP_PUB.number_arr(),
52      resource_hours          MRP_ATP_PUB.number_arr := MRP_ATP_PUB.number_arr(),
53      daily_resource_hours    MRP_ATP_PUB.number_arr := MRP_ATP_PUB.number_arr(),
54      start_date              MRP_ATP_PUB.date_arr := MRP_ATP_PUB.date_arr(),
55      end_date                MRP_ATP_PUB.date_arr := MRP_ATP_PUB.date_arr(),
56      relief_type             MRP_ATP_PUB.number_arr := MRP_ATP_PUB.number_arr(),
57      relief_quantity         MRP_ATP_PUB.number_arr := MRP_ATP_PUB.number_arr(),
58      daily_relief_qty        MRP_ATP_PUB.number_arr := MRP_ATP_PUB.number_arr(),
59      end_pegging_id          MRP_ATP_PUB.number_arr := MRP_ATP_PUB.number_arr(),
60      pegging_id              MRP_ATP_PUB.number_arr := MRP_ATP_PUB.number_arr(),
61      prev_pegging_id         MRP_ATP_PUB.number_arr := MRP_ATP_PUB.number_arr(),
62      -- CTO_PF_PRJ changes.
63      end_demand_id           MRP_ATP_PUB.number_arr := MRP_ATP_PUB.number_arr(),
64      -- CTO-PF
65      atf_date                MRP_ATP_PUB.date_arr := MRP_ATP_PUB.date_arr(),
66      product_family_id       MRP_ATP_PUB.number_arr := MRP_ATP_PUB.number_arr(),
67      -- Bug 3805136 -- Add end_item_usage to handle no forecast consumption.
68      end_item_usage          MRP_ATP_PUB.number_arr := MRP_ATP_PUB.number_arr(),
69      -- Exclude flag helps in excluding supplies
70      -- during relef data calculation.
71      exclude_flag            MRP_ATP_PUB.number_arr := MRP_ATP_PUB.number_arr()
72      -- End Bug 3805136
73    );
74 
75 -- This record will hold the Detailed ATP Pegging Data.
76 -- Corresponds to the table msc_atp_detail_peg_temp
77 TYPE ATP_Detail_Peg_Typ is RECORD (
78      reference_item_id       MRP_ATP_PUB.number_arr := MRP_ATP_PUB.number_arr(),
79      base_item_id            MRP_ATP_PUB.number_arr := MRP_ATP_PUB.number_arr(),
80      inventory_item_id       MRP_ATP_PUB.number_arr := MRP_ATP_PUB.number_arr(),
81      plan_id                 MRP_ATP_PUB.number_arr := MRP_ATP_PUB.number_arr(),
82      sr_instance_id          MRP_ATP_PUB.number_arr := MRP_ATP_PUB.number_arr(),
83      organization_id         MRP_ATP_PUB.number_arr := MRP_ATP_PUB.number_arr(),
84      end_item_usage          MRP_ATP_PUB.number_arr := MRP_ATP_PUB.number_arr(),
85      bom_item_type           MRP_ATP_PUB.number_arr := MRP_ATP_PUB.number_arr(),
86      fixed_lt                MRP_ATP_PUB.number_arr := MRP_ATP_PUB.number_arr(),
87      variable_lt             MRP_ATP_PUB.number_arr := MRP_ATP_PUB.number_arr(),
88      sales_order_line_id     MRP_ATP_PUB.number_arr := MRP_ATP_PUB.number_arr(),
89      demand_source_type      MRP_ATP_PUB.number_arr := MRP_ATP_PUB.number_arr(),--cmro
90      sales_order_qty         MRP_ATP_PUB.number_arr := MRP_ATP_PUB.number_arr(),
91      demand_id               MRP_ATP_PUB.number_arr := MRP_ATP_PUB.number_arr(),
92      demand_date             MRP_ATP_PUB.date_arr := MRP_ATP_PUB.date_arr(),
93      demand_quantity         MRP_ATP_PUB.number_arr := MRP_ATP_PUB.number_arr(),
94      disposition_id          MRP_ATP_PUB.number_arr := MRP_ATP_PUB.number_arr(),
95      demand_class            MRP_ATP_PUB.char30_arr := MRP_ATP_PUB.char30_arr(),
96      demand_type             MRP_ATP_PUB.number_arr := MRP_ATP_PUB.number_arr(),
97      original_demand_id      MRP_ATP_PUB.number_arr := MRP_ATP_PUB.number_arr(),
98      fcst_organization_id    MRP_ATP_PUB.number_arr := MRP_ATP_PUB.number_arr(),
99      forecast_qty            MRP_ATP_PUB.number_arr := MRP_ATP_PUB.number_arr(),
100      consumed_qty            MRP_ATP_PUB.number_arr := MRP_ATP_PUB.number_arr(),
101      overconsumption_qty     MRP_ATP_PUB.number_arr := MRP_ATP_PUB.number_arr(),
102      process_seq_id          MRP_ATP_PUB.number_arr := MRP_ATP_PUB.number_arr(),
103      supply_id               MRP_ATP_PUB.number_arr := MRP_ATP_PUB.number_arr(),
104      supply_date             MRP_ATP_PUB.date_arr := MRP_ATP_PUB.date_arr(),
105      supply_quantity         MRP_ATP_PUB.number_arr := MRP_ATP_PUB.number_arr(),
106      allocated_quantity      MRP_ATP_PUB.number_arr := MRP_ATP_PUB.number_arr(),
107      tot_relief_qty          MRP_ATP_PUB.number_arr := MRP_ATP_PUB.number_arr(),
108      supply_type             MRP_ATP_PUB.number_arr := MRP_ATP_PUB.number_arr(),
109      firm_planned_type       MRP_ATP_PUB.number_arr := MRP_ATP_PUB.number_arr(),
110      release_status          MRP_ATP_PUB.number_arr := MRP_ATP_PUB.number_arr(),
111      exclude_flag            MRP_ATP_PUB.number_arr := MRP_ATP_PUB.number_arr(),
112      order_number            MRP_ATP_PUB.char62_arr := MRP_ATP_PUB.char62_arr(),
113      end_pegging_id          MRP_ATP_PUB.number_arr := MRP_ATP_PUB.number_arr(),
114      pegging_id              MRP_ATP_PUB.number_arr := MRP_ATP_PUB.number_arr(),
115      prev_pegging_id         MRP_ATP_PUB.number_arr := MRP_ATP_PUB.number_arr(),
116      -- CTO_PF_PRJ changes.
117      end_demand_id           MRP_ATP_PUB.number_arr := MRP_ATP_PUB.number_arr(),
118      -- CTO-PF
119      atf_date                MRP_ATP_PUB.date_arr := MRP_ATP_PUB.date_arr(),
120      product_family_id       MRP_ATP_PUB.number_arr := MRP_ATP_PUB.number_arr()
121    );
122 
123 -- This record is for holding data obtained from msc_forecast_updates
124 -- and msc_system_items.
125 TYPE ATP_Fcst_Cons_Typ is RECORD (
126      plan_id                 MRP_ATP_PUB.number_arr := MRP_ATP_PUB.number_arr(),
127      sr_instance_id          MRP_ATP_PUB.number_arr := MRP_ATP_PUB.number_arr(),
128      inventory_item_id       MRP_ATP_PUB.number_arr := MRP_ATP_PUB.number_arr(),
129      parent_item_id          MRP_ATP_PUB.number_arr := MRP_ATP_PUB.number_arr(),
130      organization_id         MRP_ATP_PUB.number_arr := MRP_ATP_PUB.number_arr(),
131      fcst_organization_id    MRP_ATP_PUB.number_arr := MRP_ATP_PUB.number_arr(),
132      fcst_demand_id          MRP_ATP_PUB.number_arr := MRP_ATP_PUB.number_arr(),
133      sales_order_id          MRP_ATP_PUB.number_arr := MRP_ATP_PUB.number_arr(),
134      sales_order_qty         MRP_ATP_PUB.number_arr := MRP_ATP_PUB.number_arr(),
135      forecast_qty            MRP_ATP_PUB.number_arr := MRP_ATP_PUB.number_arr(),
136      consumed_qty            MRP_ATP_PUB.number_arr := MRP_ATP_PUB.number_arr(),
137      overconsumption_qty     MRP_ATP_PUB.number_arr := MRP_ATP_PUB.number_arr(),
138      bom_item_type           MRP_ATP_PUB.number_arr := MRP_ATP_PUB.number_arr(),
139      fixed_lt                MRP_ATP_PUB.number_arr := MRP_ATP_PUB.number_arr(),
140      variable_lt             MRP_ATP_PUB.number_arr := MRP_ATP_PUB.number_arr(),
141      -- Bug 3701093 Flag to indicate if config item's forecast is consumed (2)
142      -- or if model's forecast is overconsumed (1) or no forecast consumption (0).
143      cons_config_mod_flag    MRP_ATP_PUB.number_arr := MRP_ATP_PUB.number_arr()
144     );
145 
146 -- This record holds data resource_requirements
147 -- and corrsponding relief data.
148 TYPE ATP_Res_Peg_Typ is RECORD (
149      plan_id                 MRP_ATP_PUB.number_arr := MRP_ATP_PUB.number_arr(),
150      sr_instance_id          MRP_ATP_PUB.number_arr := MRP_ATP_PUB.number_arr(),
151      organization_id         MRP_ATP_PUB.number_arr := MRP_ATP_PUB.number_arr(),
152      inventory_item_id       MRP_ATP_PUB.number_arr := MRP_ATP_PUB.number_arr(),
153      supply_id               MRP_ATP_PUB.number_arr := MRP_ATP_PUB.number_arr(),
154      resource_id             MRP_ATP_PUB.number_arr := MRP_ATP_PUB.number_arr(),
155      department_id           MRP_ATP_PUB.number_arr := MRP_ATP_PUB.number_arr(),
156      resource_hours          MRP_ATP_PUB.number_arr := MRP_ATP_PUB.number_arr(),
157      daily_resource_hours    MRP_ATP_PUB.number_arr := MRP_ATP_PUB.number_arr(),
158      start_date              MRP_ATP_PUB.date_arr := MRP_ATP_PUB.date_arr(),
159      end_date                MRP_ATP_PUB.date_arr := MRP_ATP_PUB.date_arr(),
160      relief_type             MRP_ATP_PUB.number_arr := MRP_ATP_PUB.number_arr(),
161      relief_quantity         MRP_ATP_PUB.number_arr := MRP_ATP_PUB.number_arr(),
162      daily_relief_qty        MRP_ATP_PUB.number_arr := MRP_ATP_PUB.number_arr()
163     );
164 
165 -- Bug 3750638
166 -- Fix for Multiple (N) Level of Config Items using Loop
167 -- Define Record Type to correspond to a specific Sales Order Demand.
168 -- This corresponds to the CURSOR defined in Procedure Generate_Simplified_Pegging.
169 
170 TYPE ATP_End_Config_Dmd_Typ is RECORD (
171    ITEM_NAME                VARCHAR2(256),
172    INVENTORY_ITEM_ID        NUMBER,
173    SR_INVENTORY_ITEM_ID     NUMBER,
174    SR_INSTANCE_ID           NUMBER,
175    BASE_ITEM_ID             NUMBER,
176    SALES_ORDER_LINE_ID      NUMBER,
177    DEMAND_SOURCE_TYPE       NUMBER,
178    DEMAND_CLASS             VARCHAR2(34),
179    DEMAND_ID                NUMBER
180   );
181 
182 -- Bug 3750638
183 -- Fix for Multiple (N) Level of Config Items using Loop
184 -- Define PL/SQL Record of Arrays Type to correspond to
185 -- Config Item Supplies being processed in the Pegging Retrieval loop.
186 TYPE ATP_Config_Sup_Typ is RECORD (
187    INVENTORY_ITEM_ID        MRP_ATP_PUB.number_arr := MRP_ATP_PUB.number_arr(),
188    SR_INSTANCE_ID           MRP_ATP_PUB.number_arr := MRP_ATP_PUB.number_arr(),
189    BASE_ITEM_ID             MRP_ATP_PUB.number_arr := MRP_ATP_PUB.number_arr(),
190    SALES_ORDER_LINE_ID      MRP_ATP_PUB.number_arr := MRP_ATP_PUB.number_arr(),
191    DEMAND_SOURCE_TYPE       MRP_ATP_PUB.number_arr := MRP_ATP_PUB.number_arr(),
192    END_DEMAND_ID            MRP_ATP_PUB.number_arr := MRP_ATP_PUB.number_arr(),
193    SUPPLY_ID                MRP_ATP_PUB.number_arr := MRP_ATP_PUB.number_arr(),
194    PEGGING_ID               MRP_ATP_PUB.number_arr := MRP_ATP_PUB.number_arr(),
195    END_PEGGING_ID           MRP_ATP_PUB.number_arr := MRP_ATP_PUB.number_arr()
196   );
197 -- End Bug 3750638
198 
199 /* Procedures for CTO Re-architecture and Resource Capacity Enhancements */
200 
201 -- Procedure to update the summary flag for a plan.
202 PROCEDURE Update_Summary_Flag (
203         p_plan_id       IN      number,
204         p_status        IN      number,
205         x_return_status OUT NOCOPY    varchar2
206 ) IS
207 BEGIN
208 
209    IF PG_DEBUG in ('Y', 'C') THEN
210     msc_util.msc_log ('*****--- Update_Summary_Flag ---*****');
211     msc_util.msc_log (' Plan ID : '|| p_plan_id || '   Status : ' || p_status);
212    END IF;
213 
214     x_return_status := FND_API.G_RET_STS_SUCCESS;
215 
216     update msc_plans
217        set summary_flag = p_status
218      where plan_id = p_plan_id;
219 
220 EXCEPTION
221     WHEN OTHERS THEN
222       IF PG_DEBUG in ('Y', 'C') THEN
223         msc_util.msc_log ('Cannot Update. Error : ' || sqlerrm);
224       END IF;
225         x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
226 
227 END Update_Summary_Flag;
228 
229 --p_index is the length by which the record has to be extended, default is 1.
230 -- This procedure extends the ATP Simple Peg Record of Tables by p_index.
231 PROCEDURE Extend_Atp_Peg (atp_peg_tab      IN  OUT NOCOPY ATP_Simple_Peg_Typ,
232                           x_return_status  OUT NOCOPY     VARCHAR2,
233                           p_index          IN             NUMBER := 1
234                          )
235 IS
236 BEGIN
237    IF PG_DEBUG in ('Y', 'C') THEN
238       msc_util.msc_log('***** Begin Extend_Atp_Peg Procedure *****');
239       msc_util.msc_log ('p_index : ' || p_index);
240    END IF;
241 
242    x_return_status := FND_API.G_RET_STS_SUCCESS;
243 
244    atp_peg_tab.reference_item_id.Extend(p_index);
245    atp_peg_tab.base_item_id.Extend(p_index);
246    atp_peg_tab.inventory_item_id.Extend(p_index);
247    atp_peg_tab.plan_id.Extend(p_index);
248    atp_peg_tab.sr_instance_id.Extend(p_index);
249    atp_peg_tab.organization_id.Extend(p_index);
250    atp_peg_tab.bom_item_type.Extend(p_index);
251    atp_peg_tab.fixed_lt.Extend(p_index);
252    atp_peg_tab.variable_lt.Extend(p_index);
253    atp_peg_tab.sales_order_qty.Extend(p_index);
254    atp_peg_tab.sales_order_line_id.Extend(p_index);
255    atp_peg_tab.demand_source_type.Extend(p_index);--cmro
256    atp_peg_tab.transaction_date.Extend(p_index);
257    atp_peg_tab.demand_id.Extend(p_index);
258    atp_peg_tab.demand_quantity.Extend(p_index);
259    atp_peg_tab.disposition_id.Extend(p_index);
260 
261    atp_peg_tab.demand_class.Extend(p_index);
262 
263    atp_peg_tab.consumed_qty.Extend(p_index);
264    atp_peg_tab.overconsumption_qty.Extend(p_index);
265    atp_peg_tab.supply_id.Extend(p_index);
266    atp_peg_tab.supply_quantity.Extend(p_index);
267    atp_peg_tab.allocated_quantity.Extend(p_index);
268    atp_peg_tab.tot_relief_qty.Extend(p_index);
269 
270    atp_peg_tab.resource_id.Extend(p_index);
271    atp_peg_tab.department_id.Extend(p_index);
272    atp_peg_tab.resource_hours.Extend(p_index);
273    atp_peg_tab.daily_resource_hours.Extend(p_index);
274    atp_peg_tab.start_date.Extend(p_index);
275    atp_peg_tab.end_date.Extend(p_index);
276    atp_peg_tab.relief_type.Extend(p_index);
277    atp_peg_tab.relief_quantity.Extend(p_index);
278 
279    atp_peg_tab.daily_relief_qty.Extend(p_index);
280 
281    atp_peg_tab.end_pegging_id.Extend(p_index);
282    atp_peg_tab.pegging_id.Extend(p_index);
283    atp_peg_tab.prev_pegging_id.Extend(p_index);
284    -- CTO_PF_PRJ changes.
285    atp_peg_tab.end_demand_id.Extend(p_index);
286    -- CTO-PF
287    atp_peg_tab.atf_date.Extend(p_index);
288    atp_peg_tab.product_family_id.Extend(p_index);
289    -- Bug 3805136 -- Add end_item_usage to handle no forecast consumption.
290    atp_peg_tab.end_item_usage.Extend(p_index);
291    -- Exclude flag helps in excluding supplies
292    -- during relef data calculation.
293    atp_peg_tab.exclude_flag.Extend(p_index);
294    -- End Bug 3805136
295 
296    IF PG_DEBUG in ('Y', 'C') THEN
297       msc_util.msc_log('***** End Extend_Atp_Peg Procedure *****');
298    END IF;
299 EXCEPTION
300    WHEN OTHERS THEN
301    IF PG_DEBUG in ('Y', 'C') THEN
302      msc_util.msc_log ('Extend_Atp_Peg: Problems in Extending record ERROR:'|| sqlerrm);
303    END IF;
304    x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
305 
306 END Extend_Atp_Peg;
307 
308 -- This procedure initializes the ATP PEgging PL/SQL Array
309 PROCEDURE Init_Atp_Peg (atp_peg_tab      IN  OUT NOCOPY ATP_Simple_Peg_Typ,
310                           x_return_status  OUT NOCOPY     VARCHAR2
311                          )
312 IS
313 BEGIN
314    IF PG_DEBUG in ('Y', 'C') THEN
315       msc_util.msc_log('***** Begin Extend_Atp_Peg Procedure *****');
316    END IF;
317 
318    x_return_status := FND_API.G_RET_STS_SUCCESS;
319 
320      atp_peg_tab.reference_item_id    :=   MRP_ATP_PUB.number_arr();
321      atp_peg_tab.base_item_id         :=   MRP_ATP_PUB.number_arr();
322      atp_peg_tab.inventory_item_id    :=   MRP_ATP_PUB.number_arr();
323      atp_peg_tab.plan_id              :=   MRP_ATP_PUB.number_arr();
324      atp_peg_tab.sr_instance_id       :=   MRP_ATP_PUB.number_arr();
325      atp_peg_tab.organization_id      :=   MRP_ATP_PUB.number_arr();
326      atp_peg_tab.bom_item_type        :=   MRP_ATP_PUB.number_arr();
327      atp_peg_tab.fixed_lt             :=   MRP_ATP_PUB.number_arr();
328      atp_peg_tab.variable_lt          :=   MRP_ATP_PUB.number_arr();
329      atp_peg_tab.sales_order_qty      :=   MRP_ATP_PUB.number_arr();
330      atp_peg_tab.sales_order_line_id  :=   MRP_ATP_PUB.number_arr();
331      atp_peg_tab.demand_source_type   :=   MRP_ATP_PUB.number_arr();--cmro
332      atp_peg_tab.transaction_date     :=   MRP_ATP_PUB.date_arr();
333      atp_peg_tab.demand_id            :=   MRP_ATP_PUB.number_arr();
334      atp_peg_tab.demand_quantity      :=   MRP_ATP_PUB.number_arr();
335      atp_peg_tab.disposition_id       :=   MRP_ATP_PUB.number_arr();
336      atp_peg_tab.demand_class         :=   MRP_ATP_PUB.char30_arr();
337      atp_peg_tab.consumed_qty         :=   MRP_ATP_PUB.number_arr();
338      atp_peg_tab.overconsumption_qty  :=   MRP_ATP_PUB.number_arr();
339      atp_peg_tab.supply_id            :=   MRP_ATP_PUB.number_arr();
340      atp_peg_tab.supply_quantity      :=   MRP_ATP_PUB.number_arr();
341      atp_peg_tab.allocated_quantity   :=   MRP_ATP_PUB.number_arr();
342      atp_peg_tab.tot_relief_qty       :=   MRP_ATP_PUB.number_arr();
343      atp_peg_tab.resource_id          :=   MRP_ATP_PUB.number_arr();
344      atp_peg_tab.department_id        :=   MRP_ATP_PUB.number_arr();
345      atp_peg_tab.resource_hours       :=   MRP_ATP_PUB.number_arr();
346      atp_peg_tab.daily_resource_hours :=   MRP_ATP_PUB.number_arr();
347      atp_peg_tab.start_date           :=   MRP_ATP_PUB.date_arr();
348      atp_peg_tab.end_date             :=   MRP_ATP_PUB.date_arr();
349      atp_peg_tab.relief_type          :=   MRP_ATP_PUB.number_arr();
350      atp_peg_tab.relief_quantity      :=   MRP_ATP_PUB.number_arr();
351      atp_peg_tab.daily_relief_qty     :=   MRP_ATP_PUB.number_arr();
352      atp_peg_tab.end_pegging_id       :=   MRP_ATP_PUB.number_arr();
353      atp_peg_tab.pegging_id           :=   MRP_ATP_PUB.number_arr();
354      atp_peg_tab.prev_pegging_id      :=   MRP_ATP_PUB.number_arr();
355      -- CTO_PF_PRJ changes.
356      atp_peg_tab.end_demand_id        :=   MRP_ATP_PUB.number_arr();
357      -- CTO-PF
358      atp_peg_tab.atf_date             :=   MRP_ATP_PUB.date_arr();
359      atp_peg_tab.product_family_id    :=   MRP_ATP_PUB.number_arr();
360      -- Bug 3805136 -- Add end_item_usage to handle no forecast consumption.
361      atp_peg_tab.end_item_usage       :=   MRP_ATP_PUB.number_arr();
362      -- Exclude flag helps in excluding supplies
363      -- during relef data calculation.
364      atp_peg_tab.exclude_flag         :=   MRP_ATP_PUB.number_arr();
365      -- End Bug 3805136
366 
367    IF PG_DEBUG in ('Y', 'C') THEN
368       msc_util.msc_log('***** End Init_Atp_Peg Procedure *****');
369       msc_util.msc_log('Init_Atp_Peg Rowcount is ' || atp_peg_tab.reference_item_id.COUNT);
370    END IF;
371 EXCEPTION
372    WHEN OTHERS THEN
373    IF PG_DEBUG in ('Y', 'C') THEN
374      msc_util.msc_log ('Init_Atp_Peg: Problems in Extending record ERROR:'|| sqlerrm);
375    END IF;
376    x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
377 
378 END Init_Atp_Peg;
379 
380 -- This procedure extends the ATP Detail Peg Record of Tables by p_index.
381 PROCEDURE Extend_Atp_Peg_Det (atp_peg_det      IN  OUT NOCOPY ATP_Detail_Peg_Typ,
382                               x_return_status  OUT NOCOPY     VARCHAR2,
383                               p_index          IN             NUMBER := 1
384                               )
385 IS
386 BEGIN
387    IF PG_DEBUG in ('Y', 'C') THEN
388       msc_util.msc_log('***** Begin Extend_Atp_Peg_Det Procedure *****');
389       msc_util.msc_log ('p_index : ' || p_index);
390    END IF;
391 
392    x_return_status := FND_API.G_RET_STS_SUCCESS;
393 
394    atp_peg_det.reference_item_id.Extend(p_index);
395    atp_peg_det.base_item_id.Extend(p_index);
396    atp_peg_det.inventory_item_id.Extend(p_index);
397    atp_peg_det.plan_id.Extend(p_index);
398    atp_peg_det.sr_instance_id.Extend(p_index);
399    atp_peg_det.organization_id.Extend(p_index);
400    atp_peg_det.bom_item_type.Extend(p_index);
401    atp_peg_det.end_item_usage.Extend(p_index);
402    atp_peg_det.fixed_lt.Extend(p_index);
403    atp_peg_det.variable_lt.Extend(p_index);
404    atp_peg_det.sales_order_qty.Extend(p_index);
405    atp_peg_det.sales_order_line_id.Extend(p_index);
406    atp_peg_det.demand_source_type.Extend(p_index); --cmro
407    atp_peg_det.demand_id.Extend(p_index);
408    atp_peg_det.demand_date.Extend(p_index);
409    atp_peg_det.demand_quantity.Extend(p_index);
410    atp_peg_det.disposition_id.Extend(p_index);
411 
412    atp_peg_det.demand_class.Extend(p_index);
413    atp_peg_det.demand_type.Extend(p_index);
414    atp_peg_det.original_demand_id.Extend(p_index);
415 
416    atp_peg_det.fcst_organization_id.Extend(p_index);
417    atp_peg_det.forecast_qty.Extend(p_index);
418    atp_peg_det.consumed_qty.Extend(p_index);
419    atp_peg_det.overconsumption_qty.Extend(p_index);
420 
421    atp_peg_det.process_seq_id.Extend(p_index);
422    atp_peg_det.supply_id.Extend(p_index);
423    atp_peg_det.supply_date.Extend(p_index);
424    atp_peg_det.supply_quantity.Extend(p_index);
425    atp_peg_det.allocated_quantity.Extend(p_index);
426    atp_peg_det.tot_relief_qty.Extend(p_index);
427 
428    atp_peg_det.supply_type.Extend(p_index);
429    atp_peg_det.firm_planned_type.Extend(p_index);
430    atp_peg_det.release_status.Extend(p_index);
431    atp_peg_det.exclude_flag.Extend(p_index);
432 
433    atp_peg_det.order_number.Extend(p_index);
434 
435    atp_peg_det.end_pegging_id.Extend(p_index);
436    atp_peg_det.pegging_id.Extend(p_index);
437    atp_peg_det.prev_pegging_id.Extend(p_index);
438    -- CTO_PF_PRJ changes.
439    atp_peg_det.end_demand_id.Extend(p_index);
440    --CTO-PF
441    atp_peg_det.atf_date.Extend(p_index);
442    atp_peg_det.product_family_id.Extend(p_index);
443 
444    IF PG_DEBUG in ('Y', 'C') THEN
445       msc_util.msc_log('***** End Extend_Atp_Peg_Det Procedure *****');
446    END IF;
447 EXCEPTION
448    WHEN OTHERS THEN
449    IF PG_DEBUG in ('Y', 'C') THEN
450      msc_util.msc_log ('Extend_Atp_Peg_Det: Problems in Extending record ERROR:'|| sqlerrm);
451    END IF;
452    x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
453 
454 END Extend_Atp_Peg_Det;
455 
456 
457 -- This procedure calculates the relief quantities for items.
458 PROCEDURE Calculate_Relief_Quantities ( x_atp_peg_tab         IN  OUT NoCopy ATP_Simple_Peg_Typ,
459                                         p_pegging_id          IN             NUMBER,
460                                         p_fixed_lt            IN             NUMBER,
461                                         p_variable_lt         IN             NUMBER,
462                                         p_tot_relief_qty      IN             NUMBER,
463                                         -- Bug 3701093 Introducte relief ratio for pegging path.
464                                         p_peg_relief_ratio    IN             NUMBER,
465                                         -- Bug 3805136 Introduce offset_qty to alloc_qty ratio
466                                         p_peg_alloc_rel_ratio IN             NUMBER,
467                                         p_peg_tot_rel_qty     IN             NUMBER,
468                                         p_end_item_usage      IN             NUMBER,
469                                         -- End Bug 3805136
470                                         -- Bug 3761805 Introduce inventory_item_id for
471                                         -- config item, end_pegging_id, supply_id to be processed.
472                                         p_inventory_item_id   IN             NUMBER,
473                                         p_end_pegging_id      IN             NUMBER,
474                                         p_supply_id           IN             NUMBER,
475                                         -- End Bug 3761805
476                                         p_transaction_date    IN             DATE,
477                                         x_return_status       IN OUT NoCopy  VARCHAR2  )
478 IS
479 l_prev_peg_id             NUMBER;
480 i                         NUMBER;
481 j                         NUMBER;
482 l_sales_order_qty         NUMBER;
483 l_inventory_item_id       NUMBER;
484 l_relief_quantity         NUMBER;
485 l_tot_relief_qty          NUMBER;
486 l_rem_relief_qty          NUMBER;
487 l_row_count               NUMBER;
488 l_process_lt              NUMBER;
489 
490 -- Bug 3761805 Introduce a variable to track how much offsets have already been
491 -- accounted for already.
492 l_proc_relief_tot         NUMBER;
493 l_peg_relief_ratio        NUMBER;
494 -- Bug 3805136 Ratio of Relief Qty to Allocated Qty.
495 l_peg_alloc_rel_ratio     NUMBER;
496 l_proc_supply_flag        NUMBER;  -- Values 0 False 1 True
497 BEGIN
498 
499     IF PG_DEBUG in ('Y', 'C') THEN
500        msc_util.msc_log('***** Begin Calculate_Relief_Quantities Procedure *****');
501        msc_util.msc_log (' p_pegging_id : '|| p_pegging_id);
502        msc_util.msc_log (' p_fixed_lt : '|| p_fixed_lt);
503        msc_util.msc_log (' p_variable_lt : '|| p_variable_lt);
504        msc_util.msc_log (' p_tot_relief_qty : '|| p_tot_relief_qty);
505        msc_util.msc_log (' p_inventory_item_id : '|| p_inventory_item_id);
506        msc_util.msc_log (' p_end_pegging_id : '|| p_end_pegging_id);
507        msc_util.msc_log (' p_supply_id : '|| p_supply_id);
508        msc_util.msc_log (' Calculate_Relief_Quantities Transaction Date for Config : '
509                                                                   || p_transaction_date);
510        msc_util.msc_log (' Relief Ratio for this Pegging Path p_peg_relief_ratio: '
511                                                                   || p_peg_relief_ratio);
512        msc_util.msc_log (' Relief_Qty to Alloc_Qty Ratio for Pegging Path p_peg_alloc_rel_ratio: '
513                                                                   || p_peg_alloc_rel_ratio);
514        msc_util.msc_log (' Total Relief_Qty of parent for Pegging Path p_peg_tot_rel_qty: '
515                                                                   || p_peg_tot_rel_qty);
516        msc_util.msc_log (' End Item Usage of parent -- p_end_item_usage: '
517                                                                   || p_end_item_usage);
518     END IF;
519 
520     x_return_status := FND_API.G_RET_STS_SUCCESS;
521 
522     l_row_count := x_atp_peg_tab.pegging_id.COUNT;
523 
524     IF PG_DEBUG in ('Y', 'C') THEN
525       msc_util.msc_log (' l_row_count : '|| l_row_count);
526     END IF;
527 
528     FOR  i in 1..l_row_count
529     LOOP
530 
531        IF (x_atp_peg_tab.pegging_id(i) = p_pegging_id AND
532            -- Bug 3761805
533            -- Adhere to End Peg Path
534            x_atp_peg_tab.end_pegging_id(i) = p_end_pegging_id AND
535            --- Only process the top level pegging in supply chain
536            x_atp_peg_tab.prev_pegging_id(i) IS NULL ) THEN
537 
538           -- if the item is a configuration item
539           -- First set the inventory_item_id to be processed.
540           l_inventory_item_id := x_atp_peg_tab.inventory_item_id(i);
541           -- Set the total relief_quantity
542           -- Bug 3701093
543           l_tot_relief_qty := p_tot_relief_qty;
544           --l_tot_relief_qty := x_atp_peg_tab.tot_relief_qty(i);
545           -- Reset the current relief_quantity to 0
546           l_relief_quantity := 0;
547           -- Initilize the remaining relief_qty
548           l_rem_relief_qty := l_tot_relief_qty ;
549 
550           IF PG_DEBUG in ('Y', 'C') THEN
551              msc_util.msc_log (' Pegging Id Match : ' || p_pegging_id);
552              msc_util.msc_log (' l_inventory_item_id : '|| l_inventory_item_id);
553              msc_util.msc_log (' l_tot_relief_qty : '|| l_tot_relief_qty);
554              msc_util.msc_log (' x_atp_peg_tab.consumed_qty(i) : '||
555                                                 x_atp_peg_tab.consumed_qty(i));
556              msc_util.msc_log (' x_atp_peg_tab.allocated_quantity(i) : '||
557                                                 x_atp_peg_tab.allocated_quantity(i));
558           END IF;
559 
560           IF (x_atp_peg_tab.relief_type(i) = 2 ) THEN
561 
562                x_atp_peg_tab.relief_quantity(i) :=
563                   GREATEST(l_rem_relief_qty,
564                      -- Bug 3827097 Pick smallest of consumption - allocated_qty
565                      -- and relief_quantity for this path.
566                      p_peg_tot_rel_qty,
567                    NVL(x_atp_peg_tab.consumed_qty(i), 0) -
568                    x_atp_peg_tab.allocated_quantity(i) );
569 
570           ELSIF (x_atp_peg_tab.relief_type(i) = 3 ) THEN
571 
572                 IF (l_rem_relief_qty = 0) THEN
573                    x_atp_peg_tab.relief_quantity(i) :=  -1 * x_atp_peg_tab.demand_quantity(i);
574                 ELSE
575                    x_atp_peg_tab.relief_quantity(i) :=
576                           GREATEST(l_rem_relief_qty,
577                                 -1 * x_atp_peg_tab.demand_quantity(i) );
578                 END IF;
579 
580           END IF;
581           -- Update the current relief_quantity
582           l_relief_quantity := l_relief_quantity + x_atp_peg_tab.relief_quantity(i);
583           -- Update the remaining relief_qty.
584           l_rem_relief_qty := l_tot_relief_qty - l_relief_quantity;
585 
586           IF PG_DEBUG in ('Y', 'C') THEN
587                msc_util.msc_log (' Relief type : '|| x_atp_peg_tab.relief_type(i));
588                msc_util.msc_log (' l_relief_quantity : '|| l_relief_quantity);
589                msc_util.msc_log (' l_rem_relief_qty : '|| l_rem_relief_qty);
590           END IF;
591        ELSIF (NVL(x_atp_peg_tab.prev_pegging_id(i), -1) = p_pegging_id AND
592               -- Bug 3761805 Honor the End Pegging Path.
593               x_atp_peg_tab.end_pegging_id(i) = p_end_pegging_id) THEN
594 
595           -- First set the inventory_item_id to be processed.
596           l_inventory_item_id := x_atp_peg_tab.inventory_item_id(i);
597           -- Set the total relief_quantity
598           -- Bug 3805136 Handle absence of forecast data.
599           IF (x_atp_peg_tab.tot_relief_qty(i) IS NULL ) THEN
600               -- x_atp_peg_tab.inventory_item_id(i) <> p_inventory_item_id) THEN
601              IF (x_atp_peg_tab.bom_item_type(i) = 4 AND
602                   x_atp_peg_tab.base_item_id(i) IS NOT NULL ) THEN
603                 -- Bug 3827097 Use the offset_qty/total_offset_qty ratio consistently.
604                 l_tot_relief_qty := p_tot_relief_qty *  p_peg_relief_ratio *
605                                        x_atp_peg_tab.end_item_usage(i)/ p_end_item_usage;
606                                     -- The Yield and Usage will be factored later.
607                                     --x_atp_peg_tab.end_item_usage(i) * p_peg_relief_ratio;
608                 l_peg_alloc_rel_ratio := p_peg_alloc_rel_ratio;
609                 x_atp_peg_tab.tot_relief_qty(i) := p_tot_relief_qty *
610                                        x_atp_peg_tab.end_item_usage(i)/ p_end_item_usage;
611              ELSE
612                 -- Bug 3827097 Use the offset_qty/total_offset_qty ratio  consistently.
613                 l_tot_relief_qty := p_tot_relief_qty * p_peg_relief_ratio *
614                                        x_atp_peg_tab.end_item_usage(i)/ p_end_item_usage;
615                 l_peg_alloc_rel_ratio := p_peg_alloc_rel_ratio;
616              END IF;
617           ELSE
618              l_peg_alloc_rel_ratio := p_peg_alloc_rel_ratio;
619              -- Bug 3827097 Dealing with Supply, Use Configuration Item's total_relief_qty
620              IF (x_atp_peg_tab.relief_type(i) = 2) THEN
621                 l_tot_relief_qty := x_atp_peg_tab.tot_relief_qty(i) * p_peg_relief_ratio;
622              ELSE  -- Dealing with Demand, Use parent Configuration Item's total_relief_qty
623                 -- Bug 3827097 Use the offset_qty/total_offset_qty ratio  consistently.
624                 l_tot_relief_qty := p_tot_relief_qty * p_peg_relief_ratio *
625                                        x_atp_peg_tab.end_item_usage(i)/ p_end_item_usage;
626              END IF;
627              -- End Bug 3827097
628           END IF;
629           -- Config Item Forecast completely consumes demand
630           IF (l_tot_relief_qty = 0) THEN
631              -- estimate total relief_quantity.
632              -- Bug 3827097 Use the offset_qty/total_offset_qty ratio  consistently.
633              l_tot_relief_qty := p_tot_relief_qty *  p_peg_relief_ratio *
634                                        x_atp_peg_tab.end_item_usage(i)/ p_end_item_usage;
635              l_proc_supply_flag := 0; -- Flag that supplies should not get offset.
636           ELSE
637              -- Default create offsets for supply.
638              l_proc_supply_flag := 1;
639           END IF;
640           -- Bug 3805136
641           -- Reset the current relief_quantity to 0
642           l_relief_quantity := 0;
643           -- Initilize the remaining relief_qty
644           l_rem_relief_qty := l_tot_relief_qty ;
645           -- Bug 3761805
646           -- Initialize the proc relief total
647           l_proc_relief_tot := 0;
648 
649           IF PG_DEBUG in ('Y', 'C') THEN
650              msc_util.msc_log (' Previous Pegging_id Match : ' || x_atp_peg_tab.prev_pegging_id(i));
651              msc_util.msc_log (' Pegging_id is : ' || x_atp_peg_tab.pegging_id(i));
652              msc_util.msc_log (' l_inventory_item_id : '|| l_inventory_item_id);
653              msc_util.msc_log (' Total Relief For Item : '|| x_atp_peg_tab.tot_relief_qty(i));
654              msc_util.msc_log (' l_tot_relief_qty : '|| l_tot_relief_qty);
655              msc_util.msc_log (' l_proc_supply_flag : '|| l_proc_supply_flag);
656              msc_util.msc_log (' l_peg_alloc_rel_ratio : '|| l_peg_alloc_rel_ratio);
657              msc_util.msc_log (' Relief_Type : '|| x_atp_peg_tab.relief_type(i) );
658              msc_util.msc_log (' Relief_Quantity : '|| x_atp_peg_tab.relief_quantity(i) );
659           END IF;
660           -- Bug 3701093
661           -- If the total relief quantity for the config Item Id is 0
662           -- then set the relief quantity to 0 for the component.
663           IF (p_tot_relief_qty = 0) THEN
664              x_atp_peg_tab.relief_quantity(i) := 0;
665              -- Re-set the total relief_quantity as well.
666              -- so that any config item below this level will also not be offset
667              x_atp_peg_tab.tot_relief_qty(i) := 0;
668              IF PG_DEBUG in ('Y', 'C') THEN
669                msc_util.msc_log (' Force set of Relief_Qty : '||
670                                            x_atp_peg_tab.relief_quantity(i));
671                msc_util.msc_log (' Force Set of Tot Relief_Qty : '||
672                                            x_atp_peg_tab.tot_relief_qty(i));
673              END IF;
674           -- End Bug 3701093 Changed IF to ELSIF below.
675           -- Bug 3761805 Added relief_qty filter for performance.
676           ELSIF (l_tot_relief_qty <> 0 AND x_atp_peg_tab.relief_quantity(i) IS NULL) THEN
677           --ELSIF (l_tot_relief_qty <> 0 ) THEN
678             -- nothing needs to be done if total relief qty is 0.
679             FOR  j in 1..l_row_count
680             -- Same item may show up multiple times hence two loops are needed.
681             LOOP
682               IF (x_atp_peg_tab.prev_pegging_id(j) = p_pegging_id AND
683                   -- Bug 3761805 Honor the End Pegging Path.
684                   x_atp_peg_tab.end_pegging_id(j) = p_end_pegging_id AND
685                   x_atp_peg_tab.relief_type(j) = x_atp_peg_tab.relief_type(i) AND
686                   ABS(l_tot_relief_qty) > ABS(l_proc_relief_tot) AND
687                  -- End Bug 3761805
688                   x_atp_peg_tab.inventory_item_id(j) = l_inventory_item_id AND
689                   -- Bug 3362558 We need to calculate relief_quantity only if it
690                   -- has not been already calculated.
691                   x_atp_peg_tab.relief_quantity(j) IS NULL) THEN
692                   -- The above conditions ensures that we are processing
693                   -- the same item identified in the outer loop.
694                   -- Hence even though i and j refer to different indexes
695                   -- the item being processed is the same.
696 
697 
698                  IF (x_atp_peg_tab.bom_item_type(i) = 4 AND
699                      x_atp_peg_tab.base_item_id(i) IS NOT NULL ) THEN
700 
701                     -- if the item is a configuration item
702 
703                     IF (x_atp_peg_tab.relief_type(i) = 2
704                        ) THEN
705 
706                       -- Bug 3805136 Once the complete offsets have been applied
707                       IF (ABS(l_tot_relief_qty - l_relief_quantity) < C_ZERO_APPROXIMATOR) OR
708                          -- Do not process excluded supplies
709                          (NVL(x_atp_peg_tab.exclude_flag(j),0) = 1) OR
710                          (l_proc_supply_flag = 0) THEN
711                          -- Set the rest to 0 for rest of the peggings.
712                          x_atp_peg_tab.relief_quantity(j) := 0;
713                       ELSE
714                         x_atp_peg_tab.relief_quantity(j) :=
715                           GREATEST(l_rem_relief_qty,
716                              NVL(x_atp_peg_tab.consumed_qty(j), 0) -
717                                 x_atp_peg_tab.allocated_quantity(j) )
718                                 -- Bug 3805136 Apply relief/alloc ratio
719                                 * l_peg_alloc_rel_ratio;
720                       END IF;
721                       -- End Bug 3805136
722                       IF PG_DEBUG in ('Y', 'C') THEN
723                          msc_util.msc_log (' x_atp_peg_tab.relief_quantity(j) : '||
724                                                           x_atp_peg_tab.relief_quantity(j));
725                       END IF;
726 
727                     ELSIF (x_atp_peg_tab.relief_type(i) = 3 ) THEN
728 
729                       -- Bug 3805136 Once the complete offsets have been applied
730                       IF ABS(l_tot_relief_qty - l_relief_quantity) < C_ZERO_APPROXIMATOR THEN
731                          -- Set the rest to 0 for rest of the peggings.
732                          x_atp_peg_tab.relief_quantity(j) := 0;
733                       ELSE
734                         x_atp_peg_tab.relief_quantity(j) :=
735                           GREATEST(l_rem_relief_qty,
736                                 -1 * x_atp_peg_tab.demand_quantity(j),
737                                 -- Bug 3362558 Get the mininimum of
738                                 -- demand_quantity and allocated_quantity
739                                 -1 * x_atp_peg_tab.allocated_quantity(j) )
740                                 -- Bug 3805136 Apply relief/alloc ratio
741                                 * l_peg_alloc_rel_ratio;
742                       END IF;
743                       -- End Bug 3805136
744 
745                     END IF;
746 
747                  ELSE -- for all others we are processing just the demands
748 
749                    -- Note Greatest is used against negative values
750                    IF (x_atp_peg_tab.bom_item_type(i) in (1, 2) AND   -- Model or OC.
751                        x_atp_peg_tab.disposition_id(i) = p_supply_id ) THEN
752                        -- Bug 3362558 Also relieve Option Classes
753                      IF PG_DEBUG in ('Y', 'C') THEN
754                        msc_util.msc_log (' x_atp_peg_tab.consumed_qty(j) : '||
755                                                            x_atp_peg_tab.consumed_qty(j));
756                      END IF;
757                      -- Bug 3805136 Once the complete offsets have been applied
758                      IF ABS(l_tot_relief_qty - l_relief_quantity) < C_ZERO_APPROXIMATOR THEN
759                         -- Set the rest to 0 for rest of the peggings.
760                         x_atp_peg_tab.relief_quantity(j) := 0;
761                      ELSE
762                       x_atp_peg_tab.relief_quantity(j) :=
763                          GREATEST(l_rem_relief_qty,
764                           -1 * (NVL(x_atp_peg_tab.consumed_qty(j), 0) +
765                          NVL(x_atp_peg_tab.overconsumption_qty(j), 0) ) )
766                           -- Bug 3805136 Apply relief/alloc ratio
767                                 * l_peg_alloc_rel_ratio;
768                      END IF;
769                      -- End Bug 3805136
770 
771                    ELSIF x_atp_peg_tab.disposition_id(i) = p_supply_id THEN
772 
773                      -- Bug 3805136 Once the complete offsets have been applied
774                      IF ABS(l_tot_relief_qty - l_relief_quantity) < C_ZERO_APPROXIMATOR THEN
775                         -- Set the rest to 0 for rest of the peggings.
776                         x_atp_peg_tab.relief_quantity(j) := 0;
777                      ELSE
778                        -- Otherwise Calculate the offset_quantity
779                        x_atp_peg_tab.relief_quantity(j) :=
780                           GREATEST(l_rem_relief_qty,
781                                 -1 * x_atp_peg_tab.demand_quantity(j),
782                                 -- Bug 3362558 Get the mininimum of
783                                 -- demand_quantity and allocated_quantity
784                                 -1 * x_atp_peg_tab.allocated_quantity(j) )
785                           -- Bug 3805136 Apply relief/alloc ratio
786                                 * l_peg_alloc_rel_ratio;
787                      END IF;
788                      -- End Bug 3805136
789 
790                    END IF;
791                  END IF;
792 
793                  -- Bug 3445664 Fix transaction date calculation
794 
795                  IF (x_atp_peg_tab.bom_item_type(j) = 2 OR  -- option class
796                      x_atp_peg_tab.transaction_date(j) IS NULL) THEN -- phantom
797                      -- Apply offset.
798                      -- Old stuff l_process_lt := CEIL((p_fixed_lt +
799                      -- Commented out                  (p_variable_lt
800                      l_process_lt := CEIL((x_atp_peg_tab.fixed_lt(j) +
801                                        (x_atp_peg_tab.variable_lt(j)
802                                         * ABS(x_atp_peg_tab.relief_quantity(j)) ))
803                                           -- Ensure Processing Lead Time calculation is
804                                           -- consistent for both +ve and -ve reliefs
805                                          * (1 + MSC_ATP_PVT.G_MSO_LEAD_TIME_FACTOR));
806 
807                      IF PG_DEBUG in ('Y', 'C') THEN
808                         msc_util.msc_log (' Calculate_Relief_Quantities Before calc. '
809                             || 'Transaction Date for Item: ' || x_atp_peg_tab.transaction_date(j));
810                      END IF;
811                      x_atp_peg_tab.transaction_date(j) :=
812                               MSC_CALENDAR.DATE_OFFSET
813                                        (x_atp_peg_tab.organization_id(i),
814                                         x_atp_peg_tab.sr_instance_id(i),
815                                         1,
816                                         p_transaction_date, -- Config Item's Transaction Date
817                                          -1 * l_process_lt); -- negative offset
818 
819                      IF PG_DEBUG in ('Y', 'C') THEN
820                         msc_util.msc_log('Calculate_Relief_Quantities: '
821                             || 'l_mso_lead_time_factor := ' || MSC_ATP_PVT.G_MSO_LEAD_TIME_FACTOR);
822                         msc_util.msc_log('Calculate_Relief_Quantities: '
823                             || 'Inventory Item Id := ' || x_atp_peg_tab.inventory_item_id(j));
824                         msc_util.msc_log('Calculate_Relief_Quantities: '
825                             || 'fixed_lt : = ' || x_atp_peg_tab.fixed_lt(j));
826                         msc_util.msc_log('Calculate_Relief_Quantities: '
827                             || 'variable_lt : = ' || x_atp_peg_tab.variable_lt(j));
828                         msc_util.msc_log('Calculate_Relief_Quantities: '
829                             || 'l_process_lt : = ' || l_process_lt);
830                         msc_util.msc_log (' Calculate_Relief_Quantities '
831                             || 'Transaction Date for Item: ' || x_atp_peg_tab.transaction_date(j));
832                      END IF;
833                  END IF;
834                  --  End Bug 3445664 Fix transaction date calculation
835 
836                 -- Update the current relief_quantity
837                 l_relief_quantity := l_relief_quantity + x_atp_peg_tab.relief_quantity(j);
838                 -- Update the remaining relief_qty.
839                 l_rem_relief_qty := l_tot_relief_qty - l_relief_quantity;
840 
841                 IF PG_DEBUG in ('Y', 'C') THEN
842                    msc_util.msc_log (' l_relief_quantity : '|| l_relief_quantity);
843                    msc_util.msc_log (' l_rem_relief_qty : '|| l_rem_relief_qty);
844                 END IF;
845                 -- Changed the exit condition to account for relief_ratio.
846                 -- Bug 3701093
847                 -- EXIT WHEN l_tot_relief_qty = l_relief_quantity;
848                 -- Bug 3805136 EXIT statement commented out.
849                 -- EXIT WHEN ABS(l_tot_relief_qty - l_relief_quantity) < C_ZERO_APPROXIMATOR;
850                 -- Once the total offsets are reached, rest is set to 0 above.
851                 -- End Bug 3805136
852               -- Bug 3761805 Track the already processed reliefs.
853               ELSIF (x_atp_peg_tab.prev_pegging_id(j) = p_pegging_id AND
854                   x_atp_peg_tab.end_pegging_id(j) = p_end_pegging_id AND
855                   x_atp_peg_tab.relief_type(j) = x_atp_peg_tab.relief_type(i) AND
856                   x_atp_peg_tab.inventory_item_id(j) = l_inventory_item_id AND
857                   x_atp_peg_tab.demand_id(j) = x_atp_peg_tab.demand_id(i) AND
858                   x_atp_peg_tab.supply_id(j) = x_atp_peg_tab.supply_id(i) AND
859                   x_atp_peg_tab.relief_quantity(j) IS NOT NULL) THEN
860                 IF PG_DEBUG in ('Y', 'C') THEN
861                    msc_util.msc_log (' l_proc_relief_tot Before : '|| l_proc_relief_tot);
862                    msc_util.msc_log (' l_rem_relief_qty Before : '|| l_rem_relief_qty);
863                 END IF;
864                 -- Update the already processed relief_total.
865                 l_proc_relief_tot := l_proc_relief_tot + x_atp_peg_tab.relief_quantity(j);
866                 -- Update the remaining relief_qty.
867                 l_rem_relief_qty := l_tot_relief_qty - x_atp_peg_tab.relief_quantity(j);
868                 IF PG_DEBUG in ('Y', 'C') THEN
869                    msc_util.msc_log (' l_proc_relief_tot After : '|| l_proc_relief_tot);
870                    msc_util.msc_log (' l_rem_relief_qty After : '|| l_rem_relief_qty);
871                 END IF;
872               -- End Bug 3761805
873               END IF;
874 
875 
876             END LOOP;
877 
878            -- Bug 3805136 (Config Item Forecast completely consumes balance SO QTY)
879           ELSE
880 
881              -- Create adjustments against Config Demands but none against Config supply.
882              IF (x_atp_peg_tab.bom_item_type(i) = 4 AND
883                  x_atp_peg_tab.base_item_id(i) IS NOT NULL AND
884                  x_atp_peg_tab.relief_type(i) = 3  AND
885                  x_atp_peg_tab.disposition_id(i) = p_supply_id AND
886                  l_tot_relief_qty = 0 AND x_atp_peg_tab.relief_quantity(i) IS NULL ) THEN
887 
888                  x_atp_peg_tab.relief_quantity(i) :=
889                       GREATEST(
890                              -1 * x_atp_peg_tab.demand_quantity(i),
891                              -- Bug 3362558 Get the mininimum of
892                              -- demand_quantity and allocated_quantity
893                              -1 * x_atp_peg_tab.allocated_quantity(i) )
894                              -- Bug 3805136 Apply relief/alloc ratio
895                              * l_peg_alloc_rel_ratio ;
896                 -- If the total passed down relief_quantity is less than
897                 -- that calculated then set the offset to be the same as that passed down.
898                 IF ABS(x_atp_peg_tab.relief_quantity(i)) >
899                                                 ABS(p_tot_relief_qty * l_peg_alloc_rel_ratio) THEN
900                     x_atp_peg_tab.relief_quantity(i) := p_tot_relief_qty * l_peg_alloc_rel_ratio;
901                 END IF;
902                 -- End Bug 3805136
903                 IF PG_DEBUG in ('Y', 'C') THEN
904                   msc_util.msc_log (' Config Item Forecast consumes Demand');
905                   msc_util.msc_log (' x_atp_peg_tab.relief_quantity ' || x_atp_peg_tab.relief_quantity(i));
906                 END IF;
907              END IF;
908              -- End Bug 3805136
909 
910           END IF;
911           -- If the current item is a configuration item then
912           -- Call the procedure recursively.
913           IF (x_atp_peg_tab.bom_item_type(i) = 4 AND
914               x_atp_peg_tab.base_item_id(i) IS NOT NULL AND
915               x_atp_peg_tab.pegging_id(i) IS NOT NULL ) THEN
916 
917               -- Bug 3761805
918               -- Process Top Config at lower levels of Pegging only if it is the parameter
919               -- Adhere to the End Pegging Path.
920               IF (x_atp_peg_tab.end_pegging_id(i) = p_end_pegging_id AND
921                   ABS(NVL(x_atp_peg_tab.relief_quantity(i), 0)) > 0 AND
922                   -- Bug 3805136 Do not process excluded supplies
923                   NVL(x_atp_peg_tab.exclude_flag(i),0) <> 1 AND
924                   x_atp_peg_tab.relief_type(i) = 2 ) THEN
925                 IF x_atp_peg_tab.inventory_item_id(i) = x_atp_peg_tab.reference_item_id(i) THEN
926                    -- Top level Config Item, Carry the same ratio.
927                    l_peg_alloc_rel_ratio := 1;
928                    -- Bug 3827097 The ratio needs to be re-calculated
929                    -- just in case here the demand is pegged to multiple supplies
930                    -- either in the same org or different one.
931                    l_peg_relief_ratio := x_atp_peg_tab.relief_quantity(i) / x_atp_peg_tab.tot_relief_qty(i) ;
932                    -- Bug 3805136
933                 ELSE
934                    -- Ratio gets implicity applied since only
935                    -- part of lower level config is relieved if parent is partly offset.
936                    -- Bug 3805136
937                    l_peg_relief_ratio := 1;
938                    -- Bug 3805136 Apply the relief/alloc ratio to config comps.
939                    /*
940                    IF ((x_atp_peg_tab.allocated_quantity(i) < ABS(l_tot_relief_qty))
941                        -- OR (x_atp_peg_tab.allocated_quantity(i) > ABS(l_tot_relief_qty) AND
942                        --ABS( x_atp_peg_tab.relief_quantity(i) ) < x_atp_peg_tab.allocated_quantity(i) )
943                       ) THEN
944                        l_peg_alloc_rel_ratio := ABS( x_atp_peg_tab.relief_quantity(i) ) /
945                                                  x_atp_peg_tab.allocated_quantity(i);
946                        l_peg_relief_ratio := 1;
947                    ELSE
948                        l_peg_alloc_rel_ratio := 1;
949                        l_peg_relief_ratio := p_peg_relief_ratio;
950                    END IF;
951                    */
952                    -- Bug 3827097 Coment out old code above.
953                    -- The ratio now gets used consistently, it was also
954                    -- used for the sales order reference config item.
955                    l_peg_alloc_rel_ratio := 1; -- This ratio no longer needed now.
956                    l_peg_relief_ratio := x_atp_peg_tab.relief_quantity(i) / x_atp_peg_tab.tot_relief_qty(i);
957                    -- End Bug 3827097
958                 END IF;
959                 IF PG_DEBUG in ('Y', 'C') THEN
960                   msc_util.msc_log (' Calling Calculate_Relief_Quantities again');
961                   msc_util.msc_log (' x_atp_peg_tab.consumed_qty ' || x_atp_peg_tab.consumed_qty(i));
962                   msc_util.msc_log (' x_atp_peg_tab.relief_quantity ' || x_atp_peg_tab.relief_quantity(i));
963                   msc_util.msc_log (' x_atp_peg_tab.tot_relief_quantity ' || x_atp_peg_tab.tot_relief_qty(i));
964                   msc_util.msc_log (' x_atp_peg_tab.allocated_quantity ' || x_atp_peg_tab.allocated_quantity(i));
965                   msc_util.msc_log (' x_atp_peg_tab.exclude_flag ' || x_atp_peg_tab.exclude_flag(i));
966                   msc_util.msc_log (' l_peg_relief_ratio ' || l_peg_relief_ratio);
967                 END IF;
968                 Calculate_Relief_Quantities(x_atp_peg_tab,
969                                         x_atp_peg_tab.pegging_id(i),
970                                         x_atp_peg_tab.fixed_lt(i),
971                                         x_atp_peg_tab.variable_lt(i),
972                                         -- Bug 3701093
973                                         x_atp_peg_tab.tot_relief_qty(i),
974                                         l_peg_relief_ratio,
975                                         -- End Bug 3701093
976                                         -- Bug 3805136 relief/alloc ratio
977                                         l_peg_alloc_rel_ratio,
978                                         x_atp_peg_tab.relief_quantity(i),
979                                         x_atp_peg_tab.end_item_usage(i),
980                                         -- End Bug 3805136
981                                         -- Bug 3761805 Change in Signature
982                                         x_atp_peg_tab.inventory_item_id(i),
983                                         p_end_pegging_id,
984                                         x_atp_peg_tab.supply_id(i),
985                                         -- End Bug 3761805
986                                         x_atp_peg_tab.transaction_date(i),
987                                         x_return_status
988                                         );
989               END IF;
990               -- End Bug 3761805
991           END IF;
992        ELSE
993           IF PG_DEBUG in ('Y', 'C') THEN
994               msc_util.msc_log (' Non Match Item ' || x_atp_peg_tab.inventory_item_id(i) ||
995                                 ' Pegging ' || x_atp_peg_tab.pegging_id(i) ||
996                                 ' Prev Pegging ' || x_atp_peg_tab.prev_pegging_id(i));
997           END IF;
998        END IF;
999     END LOOP;
1000 
1001     IF PG_DEBUG in ('Y', 'C') THEN
1002         msc_util.msc_log (' ***** END Calculate_Relief_Quantities. ***** ');
1003     END IF;
1004 EXCEPTION
1005     WHEN OTHERS THEN
1006       IF PG_DEBUG in ('Y', 'C') THEN
1007         msc_util.msc_log ('Calculate_Relief_Quantities. '|| sqlcode || ': ' || sqlerrm);
1008       END IF;
1009         x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
1010 
1011 END Calculate_Relief_Quantities;
1012 
1013 -- This procedure creates the pegging for resources and also
1014 -- calculates the relief quantities.
1015 
1016 PROCEDURE  Generate_Resource_Pegging (atp_peg_tab  IN OUT NoCopy  ATP_Simple_Peg_Typ,
1017                                       x_return_status OUT NOCOPY  varchar2)
1018 IS
1019 
1020 i                    NUMBER;
1021 j                    NUMBER;
1022 l_relief_quantity    NUMBER;
1023 
1024 l_loop_count         NUMBER;
1025 l_res_count          NUMBER;
1026 l_new_count          NUMBER;
1027 l_return_status      VARCHAR2(10);
1028 l_tot_count          NUMBER;
1029 
1030 res_peg_tab          ATP_Res_Peg_Typ;
1031 
1032 BEGIN
1033 
1034     IF PG_DEBUG in ('Y', 'C') THEN
1035        msc_util.msc_log('***** Begin Generate_Resource_Pegging Procedure *****');
1036     END IF;
1037 
1038       x_return_status := FND_API.G_RET_STS_SUCCESS;
1039 
1040       l_loop_count := atp_peg_tab.inventory_item_id.COUNT;
1041       l_new_count := l_loop_count ;
1042 
1043       -- PSEUDOCODE
1044       -- Loop for all the items in the pegging
1045       -- Obtain Resource pegging and relief data
1046       -- Append the resource data for each config item to the
1047       -- the original pegging array.
1048 
1049       -- cannot use FORALL and BULK COLLECT INTO together in SELECT statements
1050       -- Loop for all the items in the pegging
1051       FOR i in 1..l_loop_count LOOP
1052        -- Obtain Resource pegging and relief data
1053        SELECT
1054                req.plan_id, req.sr_instance_id,
1055                req.organization_id, req.assembly_item_id, req.transaction_id,
1056                req.resource_id,
1057                req.department_id,
1058                -- Bug 3321897 For Line Based Resources,
1059                -- Resource_ID is not NULL but -1
1060                DECODE(REQ.RESOURCE_ID, -1, REQ.LOAD_RATE,
1061                              REQ.RESOURCE_HOURS)  RESOURCE_HOURS,
1062                -- Bug 3321897 For Line Based Resources,
1063                -- Resource_ID is not NULL but -1
1064                DECODE(REQ.RESOURCE_ID, -1, REQ.LOAD_RATE,
1065                       DECODE(REQ.END_DATE, NULL, REQ.RESOURCE_HOURS,
1066                    -- Bug 3348095
1067                         DECODE(REQ.record_source, 2, REQ.RESOURCE_HOURS,
1068                                  REQ.DAILY_RESOURCE_HOURS))) DAILY_RESOURCE_HOURS,
1069                    -- For ATP created records use resource_hours
1070                    -- End Bug 3348095
1071                TRUNC(start_date) start_date,
1072                TRUNC(end_date) end_date,
1073                -- Bug 3321897 For Line Based Resources,
1074                -- Resource_ID is not NULL but -1
1075                -- Bug 3455997
1076                -- For lot based resources either the complete req. is relieved or none at all.
1077                ( DECODE(REQ.RESOURCE_ID, -1, REQ.LOAD_RATE,
1078                    REQ.RESOURCE_HOURS)  * decode (atp_peg_tab.supply_quantity(i),0 ,0,
1079                                              decode(basis_type,
1080                    1, ABS(atp_peg_tab.relief_quantity(i))/atp_peg_tab.supply_quantity(i),
1081                    2, FLOOR (ABS(atp_peg_tab.relief_quantity(i))/atp_peg_tab.supply_quantity(i) )))
1082                    * SIGN (atp_peg_tab.relief_quantity(i)) ) RELIEF_QUANTITY,
1083                -- End Bug 3455997
1084                -- Bug 3321897 For Line Based Resources,
1085                -- Resource_ID is not NULL but -1
1086                -- Bug 3455997
1087                -- For lot based resources either the complete req. is relieved or none at all.
1088                ( DECODE(REQ.RESOURCE_ID, -1, REQ.LOAD_RATE,
1089                       DECODE(REQ.END_DATE, NULL, REQ.RESOURCE_HOURS,
1090                    -- Bug 3348095
1091                         DECODE(REQ.record_source, 2, REQ.RESOURCE_HOURS,
1092                                  REQ.DAILY_RESOURCE_HOURS)))
1093                    -- For ATP created records use resource_hours
1094                    -- End Bug 3348095
1095                             * decode (atp_peg_tab.supply_quantity(i),0 ,0,
1096                             Decode (basis_type,
1097                     1, ABS(atp_peg_tab.relief_quantity(i))/atp_peg_tab.supply_quantity (i),
1098                     2, FLOOR(ABS(atp_peg_tab.relief_quantity(i))/atp_peg_tab.supply_quantity(i))))
1099                    * SIGN (atp_peg_tab.relief_quantity(i)) ) DAILY_RELIEF_QTY
1100                -- End Bug 3455997
1101        BULK COLLECT
1102        INTO    res_peg_tab.plan_id, res_peg_tab.sr_instance_id, res_peg_tab.organization_id,
1103                res_peg_tab.inventory_item_id, res_peg_tab.supply_id, res_peg_tab.resource_id,
1104                res_peg_tab.department_id, res_peg_tab.resource_hours, res_peg_tab.daily_resource_hours,
1105                res_peg_tab.start_date, res_peg_tab.end_date, res_peg_tab.relief_quantity,
1106                res_peg_tab.daily_relief_qty
1107        FROM    msc_resource_requirements req
1108        WHERE   req.plan_id = atp_peg_tab.plan_id(i)
1109        AND     req.sr_instance_id = atp_peg_tab.sr_instance_id(i)
1110        AND     req.organization_id = atp_peg_tab.organization_id(i)
1111        AND     req.supply_id = atp_peg_tab.supply_id(i)
1112        AND     req.assembly_item_id = atp_peg_tab.inventory_item_id(i)
1113                -- Bug 3362558 Exclude Department Id -1
1114                -- No need to fetch resource_consumption that is 0.
1115        AND     REQ.DEPARTMENT_ID <> -1
1116        AND     ( DECODE(REQ.RESOURCE_ID, -1, REQ.LOAD_RATE,
1117                              REQ.RESOURCE_HOURS) > 0
1118                  OR
1119                  DECODE(REQ.RESOURCE_ID, -1, REQ.LOAD_RATE,
1120                       DECODE(REQ.END_DATE, NULL, REQ.RESOURCE_HOURS,
1121                    -- Bug 3348095
1122                         DECODE(REQ.record_source, 2, REQ.RESOURCE_HOURS,
1123                                  REQ.DAILY_RESOURCE_HOURS))) > 0
1124                    -- For ATP created records use resource_hours
1125                    -- End Bug 3348095
1126                )
1127                -- End Bug 3362558
1128                -- Bug 3455997 Ensure that relief_quantity is greater than 0.
1129                -- For lot based resources either the complete req. is relieved or none at all.
1130        AND     ( DECODE(REQ.RESOURCE_ID, -1, REQ.LOAD_RATE,
1131                    REQ.RESOURCE_HOURS)  * decode (atp_peg_tab.supply_quantity(i),0 ,0,
1132                                              decode(basis_type,
1133                    1, ABS(atp_peg_tab.relief_quantity(i))/atp_peg_tab.supply_quantity(i),
1134                    2, FLOOR (ABS(atp_peg_tab.relief_quantity(i))/atp_peg_tab.supply_quantity(i) )))
1135                ) > 0
1136                -- Here the SIGN multiplier is not used to
1137                -- Ensure that relief_quantity is greater than 0.
1138                -- End Bug 3455997
1139        AND     atp_peg_tab.bom_item_type(i) = 4
1140        AND     atp_peg_tab.base_item_id(i) IS NOT NULL
1141        AND     atp_peg_tab.relief_type(i) = 2
1142                ;
1143 
1144        l_res_count := res_peg_tab.resource_id.COUNT  ;
1145 
1146        IF (l_res_count > 0) THEN
1147           -- Append the resource data for each config item to the
1148           -- the original pegging array.
1149           -- First extend the pegging array by the resource data count.
1150           Extend_Atp_Peg (atp_peg_tab, l_return_status, l_res_count);
1151 
1152           FOR j in 1..l_res_count LOOP
1153 
1154                l_new_count := l_new_count + 1;
1155                -- Append to the array
1156                -- Uses data from the assembly items
1157                -- and the data from resources
1158                -- while creating the information.
1159                atp_peg_tab.reference_item_id(l_new_count) := atp_peg_tab.reference_item_id(i);
1160                atp_peg_tab.inventory_item_id(l_new_count) := atp_peg_tab.inventory_item_id(i);
1161                atp_peg_tab.plan_id(l_new_count) := atp_peg_tab.plan_id(i);
1162                atp_peg_tab.sr_instance_id(l_new_count) := atp_peg_tab.sr_instance_id(i);
1163                atp_peg_tab.organization_id(l_new_count) := atp_peg_tab.organization_id(i);
1164                atp_peg_tab.bom_item_type(l_new_count) := atp_peg_tab.bom_item_type(i);
1165                atp_peg_tab.sales_order_qty(l_new_count) := atp_peg_tab.sales_order_qty(i);
1166                atp_peg_tab.sales_order_line_id(l_new_count) := atp_peg_tab.sales_order_line_id(i);
1167                atp_peg_tab.demand_source_type(l_new_count) := atp_peg_tab.demand_source_type(i);--cmro
1168                atp_peg_tab.transaction_date(l_new_count) := atp_peg_tab.transaction_date(i);
1169                atp_peg_tab.demand_class(l_new_count) := atp_peg_tab.demand_class(i);
1170                atp_peg_tab.supply_id(l_new_count) := res_peg_tab.supply_id(j);
1171                atp_peg_tab.supply_quantity(l_new_count) := atp_peg_tab.supply_quantity(i);
1172                atp_peg_tab.allocated_quantity(l_new_count) := atp_peg_tab.allocated_quantity(i);
1173                atp_peg_tab.pegging_id(l_new_count) := atp_peg_tab.pegging_id(i);
1174                atp_peg_tab.end_pegging_id(l_new_count) := atp_peg_tab.end_pegging_id(i);
1175                atp_peg_tab.prev_pegging_id(l_new_count) := atp_peg_tab.prev_pegging_id(i);
1176 
1177                atp_peg_tab.resource_id(l_new_count) := res_peg_tab.resource_id(j);
1178                atp_peg_tab.department_id(l_new_count) := res_peg_tab.department_id(j);
1179                atp_peg_tab.resource_hours(l_new_count) := res_peg_tab.resource_hours(j);
1180                atp_peg_tab.daily_resource_hours(l_new_count) := res_peg_tab.daily_resource_hours(j);
1181                atp_peg_tab.start_date(l_new_count) := res_peg_tab.start_date(j);
1182                atp_peg_tab.end_date(l_new_count) := res_peg_tab.end_date(j);
1183                atp_peg_tab.relief_type(l_new_count) := 4;   -- RES
1184                atp_peg_tab.transaction_date(l_new_count) := res_peg_tab.start_date(j);
1185                atp_peg_tab.relief_quantity(l_new_count) := res_peg_tab.relief_quantity(j);
1186                atp_peg_tab.daily_relief_qty(l_new_count) := res_peg_tab.daily_relief_qty(j);
1187 
1188                -- CTO_PF_PRJ changes.
1189                atp_peg_tab.end_demand_id(l_new_count) := atp_peg_tab.end_demand_id(i);
1190 
1191           END LOOP;
1192 
1193        END IF; --IF (l_res_count > 0)
1194 
1195       END LOOP;
1196 
1197 EXCEPTION
1198     WHEN OTHERS THEN
1199       IF PG_DEBUG in ('Y', 'C') THEN
1200         msc_util.msc_log ('Generate_Resource_Pegging. Error : ' || sqlerrm);
1201       END IF;
1202         x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
1203 
1204 END Generate_Resource_Pegging ;
1205 
1206 -- This procedures obtains the forecast consumption for Configuration Items
1207 -- and ATO models.
1208 -- It also fetches the phantom items that were included in the Sales Order
1209 -- and their corresponding consumption and overconsumption used for estimating demands.
1210 
1211 PROCEDURE Get_Forecast_Consumption (atp_peg_tab        IN            ATP_Detail_Peg_Typ ,
1212                                     p_array_idx        IN            NUMBER,
1213                                     x_fcst_data_tab    IN OUT NoCopy ATP_Fcst_Cons_Typ,
1214                                  -- Bug 3417410 Name change from fcst_data_tab to x_fcst_data_tab
1215                                     x_return_status    OUT NOCOPY    VARCHAR2)
1216 IS
1217 i                   PLS_INTEGER;
1218 k                   PLS_INTEGER;
1219 l_item_typ          MRP_ATP_PUB.Number_Arr := MRP_ATP_PUB.Number_Arr();
1220 l_process_seq_id    NUMBER;
1221 l_routing_seq_id    NUMBER;
1222 l_bill_seq_id       NUMBER;
1223 
1224 -- Bug 3417410 Use local record of table
1225 l_fcst_data_tab     ATP_Fcst_Cons_Typ;
1226 l_fcst_mod_flag     NUMBER := 0;
1227 l_fcst_cnt          PLS_INTEGER;
1228 BEGIN
1229 
1230     k := p_array_idx;  -- assign to a variable for simplicity.
1231 
1232     IF PG_DEBUG in ('Y', 'C') THEN
1233        msc_util.msc_log('***** Begin Get_Forecast_Consumption Procedure *****');
1234        msc_util.msc_log(' Instance Id atp_peg_tab.sr_instance_id(k) : ' ||
1235                                                       atp_peg_tab.sr_instance_id(k) );
1236        msc_util.msc_log(' Plan Id : ' || atp_peg_tab.plan_id(k) );
1237        msc_util.msc_log(' Organization Id : ' || atp_peg_tab.organization_id(k) );
1238        msc_util.msc_log(' Sales Order/Origianl Demand Id : ' ||
1239                                                   atp_peg_tab.original_demand_id(k) );
1240        msc_util.msc_log(' Parent(Config) Item Id : ' ||
1241                                                   atp_peg_tab.inventory_item_id(k) );
1242        msc_util.msc_log(' Base Model Id : ' || atp_peg_tab.base_item_id(k) );
1243     END IF;
1244 
1245     x_return_status := FND_API.G_RET_STS_SUCCESS;
1246 
1247     -- Initialize Variables
1248     l_fcst_mod_flag := 0;
1249 
1250     /* Commented SQL for Bug 6046524
1251     -- Bug 3562722 Setup a SUM and group by since SO could get consumed
1252     -- through combination of several forecasts.
1253     SELECT msi.plan_id, msi.sr_instance_id,
1254            fcst.inventory_item_id, fcst.parent_item_id,
1255            msi.organization_id, fcst.organization_id fcst_organization_id,
1256            -- Bug 3562722 forecast_demand_id is immaterial since SO will get
1257            -- get consumed against one forecast set.
1258            -1 forecast_demand_id, fcst.sales_order_id, sales_order_qty,
1259            -- Forecast Qty is not used in ATP Post Plan Pegging computation
1260            SUM(fcst.forecast_qty) forecast_qty, SUM(fcst.consumed_qty) consumed_qty,
1261            SUM(NVL(fcst.overconsumption_qty, 0)) overconsumption_qty,
1262            msi.bom_item_type, msi.fixed_lead_time, msi.variable_lead_time,
1263            -- Bug 3701093
1264            1, -- Overconsumption of Model Forecast happens
1265            decode(fcst.inventory_item_id, fcst.parent_item_id, 0, -- config first
1266                                      atp_peg_tab.base_item_id(k), 1, -- model second
1267                                      fcst.inventory_item_id)  -- others later
1268     -- End Bug 3562722
1269     BULK COLLECT
1270            -- Bug 3417410 Collect into return record.
1271     INTO   x_fcst_data_tab.plan_id, x_fcst_data_tab.sr_instance_id,
1272            x_fcst_data_tab.inventory_item_id, x_fcst_data_tab.parent_item_id,
1273            x_fcst_data_tab.organization_id, x_fcst_data_tab.fcst_organization_id,
1274            x_fcst_data_tab.fcst_demand_id, x_fcst_data_tab.sales_order_id,
1275            x_fcst_data_tab.sales_order_qty, x_fcst_data_tab.forecast_qty,
1276            x_fcst_data_tab.consumed_qty, x_fcst_data_tab.overconsumption_qty,
1277            x_fcst_data_tab.bom_item_type, x_fcst_data_tab.fixed_lt,
1278            x_fcst_data_tab.variable_lt,
1279            -- Bug 3701093, flag overconsumption
1280            x_fcst_data_tab.cons_config_mod_flag, l_item_typ
1281            -- End Bug 3417410 Collect into return record.
1282     FROM   msc_forecast_updates fcst, msc_system_items msi
1283     WHERE  fcst.sr_instance_id = atp_peg_tab.sr_instance_id(k)
1284     AND    fcst.plan_id = atp_peg_tab.plan_id(k)
1285     AND    (fcst.organization_id = atp_peg_tab.organization_id(k)
1286             OR    fcst.organization_id = -1)
1287            -- First check for local forecast
1288            -- CTO_PF_PRJ changes. Use end_demand_id
1289     AND    (fcst.sales_order_id = atp_peg_tab.original_demand_id(k)
1290             OR
1291             fcst.sales_order_id = atp_peg_tab.end_demand_id(k)
1292            )
1293            -- CTO_PF_PRJ
1294     AND    fcst.parent_item_id = atp_peg_tab.inventory_item_id(k)
1295     AND    msi.plan_id = fcst.plan_id
1296     AND    msi.sr_instance_id = fcst.sr_instance_id
1297     AND    msi.organization_id = atp_peg_tab.organization_id(k)
1298     AND    (msi.wip_supply_type = 6 or msi.bom_item_type = 1)
1299          -- only phantom items or models are obtained
1300          -- forecast updates may contain lower level models and configuration
1301          -- items. Ensure that they are not obtained
1302     AND    msi.inventory_item_id = decode(msi.bom_item_type,
1303                                          --1, atp_peg_tab.base_item_id(k),
1304                                          4, decode(msi.base_item_id,
1305                                               NULL, fcst.inventory_item_id,
1306                                                         fcst.parent_item_id),
1307                                          fcst.inventory_item_id )
1308     -- Bug 3562722 Setup a SUM and group by since SO could get consumed
1309     -- through combination of several forecasts.
1310     GROUP  BY msi.plan_id, msi.sr_instance_id,
1311            fcst.inventory_item_id, fcst.parent_item_id,
1312            msi.organization_id, fcst.organization_id ,
1313            -1 , fcst.sales_order_id, sales_order_qty,
1314            msi.bom_item_type, msi.fixed_lead_time, msi.variable_lead_time,
1315            -- Bug 3701093
1316            1, -- Overconsumption of Model/OC Forecast happens
1317            decode(fcst.inventory_item_id, fcst.parent_item_id, 0, -- config first
1318                                      atp_peg_tab.base_item_id(k), 1, -- model second
1319                                      fcst.inventory_item_id)  -- others later
1320       -- End Bug 3562722
1321     ORDER BY decode(fcst.inventory_item_id, fcst.parent_item_id, 0,
1322                                      atp_peg_tab.base_item_id(k), 1,
1323                                      fcst.inventory_item_id)
1324     ;
1325         */
1326     --Start Modified SQL for Bug 6046524
1327     SELECT fcst1.plan_id,
1328       fcst1.sr_instance_id,
1329       fcst1.inventory_item_id,
1330       fcst1.parent_item_id,
1331       fcst1.organization_id,
1332       fcst1.fcst_organization_id fcst_organization_id,
1333       -1 forecast_demand_id,
1334       fcst1.sales_order_id,
1335       fcst1.sales_order_qty,
1336       SUM(fcst1.forecast_qty) forecast_qty,
1337       SUM(fcst1.consumed_qty) consumed_qty,
1338       SUM(nvl(fcst1.overconsumption_qty,   0)) overconsumption_qty,
1339       fcst1.bom_item_type,
1340       fcst1.fixed_lead_time,
1341       fcst1.variable_lead_time,
1342       1,
1343       decode(fcst1.inventory_item_id,   fcst1.parent_item_id,   0,   atp_peg_tab.base_item_id(k),   1,   fcst1.inventory_item_id)
1344     BULK COLLECT
1345     INTO   x_fcst_data_tab.plan_id,
1346            x_fcst_data_tab.sr_instance_id,
1347            x_fcst_data_tab.inventory_item_id,
1348            x_fcst_data_tab.parent_item_id,
1349            x_fcst_data_tab.organization_id,
1350            x_fcst_data_tab.fcst_organization_id,
1351            x_fcst_data_tab.fcst_demand_id,
1352            x_fcst_data_tab.sales_order_id,
1353            x_fcst_data_tab.sales_order_qty,
1354            x_fcst_data_tab.forecast_qty,
1355            x_fcst_data_tab.consumed_qty,
1356            x_fcst_data_tab.overconsumption_qty,
1357            x_fcst_data_tab.bom_item_type,
1358            x_fcst_data_tab.fixed_lt,
1359            x_fcst_data_tab.variable_lt,
1360            x_fcst_data_tab.cons_config_mod_flag,
1361            l_item_typ
1362     FROM
1363       (SELECT msi.plan_id,
1364          msi.sr_instance_id,
1365          fcst.inventory_item_id,
1366          fcst.parent_item_id,
1367          msi.organization_id,
1368          fcst.organization_id fcst_organization_id,
1369          -1 forecast_demand_id,
1370          fcst.sales_order_id,
1371          sales_order_qty,
1372          fcst.forecast_qty forecast_qty,
1373          fcst.consumed_qty consumed_qty,
1374          nvl(fcst.overconsumption_qty,    0) overconsumption_qty,
1375          msi.bom_item_type,
1376          msi.fixed_lead_time,
1377          msi.variable_lead_time,
1378          1,
1379          decode(fcst.inventory_item_id,    fcst.parent_item_id,    0,    atp_peg_tab.base_item_id(k),    1,    fcst.inventory_item_id)
1380        FROM msc_forecast_updates fcst,
1381          msc_system_items msi
1382        WHERE fcst.sr_instance_id = atp_peg_tab.sr_instance_id(k)
1383        AND fcst.plan_id = atp_peg_tab.plan_id(k)
1384        AND(fcst.organization_id = atp_peg_tab.organization_id(k) OR fcst.organization_id = -1)
1385        AND(fcst.sales_order_id = atp_peg_tab.original_demand_id(k) OR fcst.sales_order_id = atp_peg_tab.end_demand_id(k))
1386        AND fcst.parent_item_id = atp_peg_tab.inventory_item_id(k)
1387        AND msi.plan_id = fcst.plan_id
1388        AND msi.sr_instance_id = fcst.sr_instance_id
1389        AND msi.organization_id = atp_peg_tab.organization_id(k)
1390        AND msi.bom_item_type = 1
1391        AND msi.inventory_item_id = fcst.inventory_item_id
1392        UNION ALL
1393        SELECT msi.plan_id,
1394          msi.sr_instance_id,
1395          fcst.inventory_item_id,
1396          fcst.parent_item_id,
1397          msi.organization_id,
1398          fcst.organization_id fcst_organization_id,
1399          -1 forecast_demand_id,
1400          fcst.sales_order_id,
1401          sales_order_qty,
1402          fcst.forecast_qty forecast_qty,
1403          fcst.consumed_qty consumed_qty,
1404          nvl(fcst.overconsumption_qty,    0) overconsumption_qty,
1405          msi.bom_item_type,
1406          msi.fixed_lead_time,
1407          msi.variable_lead_time,
1408          1,
1409          decode(fcst.inventory_item_id,    fcst.parent_item_id,    0,    atp_peg_tab.base_item_id(k),    1,    fcst.inventory_item_id)
1410        FROM msc_forecast_updates fcst,
1411          msc_system_items msi
1412        WHERE fcst.sr_instance_id = atp_peg_tab.sr_instance_id(k)
1413        AND fcst.plan_id = atp_peg_tab.plan_id(k)
1414        AND(fcst.organization_id = atp_peg_tab.organization_id(k) OR fcst.organization_id = -1)
1415        AND(fcst.sales_order_id = atp_peg_tab.original_demand_id(k) OR fcst.sales_order_id = atp_peg_tab.end_demand_id(k))
1416        AND fcst.parent_item_id = atp_peg_tab.inventory_item_id(k)
1417        AND msi.plan_id = fcst.plan_id
1418        AND msi.sr_instance_id = fcst.sr_instance_id
1419        AND msi.organization_id = atp_peg_tab.organization_id(k)
1420        AND msi.wip_supply_type = 6
1421        AND msi.bom_item_type <> 1
1422        AND msi.inventory_item_id = decode(msi.bom_item_type,4,decode(msi.base_item_id,
1423                                                                      NULL,fcst.inventory_item_id,
1424                                                                      fcst.parent_item_id),
1425                                                                      fcst.inventory_item_id)) fcst1
1426     GROUP BY fcst1.plan_id,
1427       fcst1.sr_instance_id,
1428       fcst1.inventory_item_id,
1429       fcst1.parent_item_id,
1430       fcst1.organization_id,
1431       fcst1.fcst_organization_id,
1432       -1,
1433       fcst1.sales_order_id,
1434       sales_order_qty,
1435       fcst1.bom_item_type,
1436       fcst1.fixed_lead_time,
1437       fcst1.variable_lead_time,
1438       1,
1439       decode(fcst1.inventory_item_id,   fcst1.parent_item_id,   0,   atp_peg_tab.base_item_id(k),   1,   fcst1.inventory_item_id)
1440     ORDER BY decode(fcst1.inventory_item_id,   fcst1.parent_item_id,   0,   atp_peg_tab.base_item_id(k),   1,   fcst1.inventory_item_id);
1441     --End Modified SQL for Bug 6046524
1442     IF PG_DEBUG in ('Y', 'C') THEN
1443         msc_util.msc_log(' Count After Model Overconsumption Check : ' ||
1444                             x_fcst_data_tab.inventory_item_id.COUNT);
1445     END IF;
1446 
1447     -- Bug 3701093 pure Config Item consumption data only when Model overconsumption
1448     -- data is not found.
1449     IF x_fcst_data_tab.inventory_item_id.COUNT = 0 THEN
1450        SELECT msi.plan_id, msi.sr_instance_id,
1451               fcst.inventory_item_id, fcst.parent_item_id,
1452               msi.organization_id, fcst.organization_id fcst_organization_id,
1453               -1 forecast_demand_id, fcst.sales_order_id, sales_order_qty,
1454               SUM(fcst.forecast_qty) forecast_qty, SUM(fcst.consumed_qty) consumed_qty,
1455               SUM(NVL(fcst.overconsumption_qty,0)) overconsumption_qty,
1456               msi.bom_item_type, msi.fixed_lead_time, msi.variable_lead_time,
1457               2 -- only config item is consumed
1458        BULK COLLECT
1459        INTO   x_fcst_data_tab.plan_id, x_fcst_data_tab.sr_instance_id,
1460               x_fcst_data_tab.inventory_item_id, x_fcst_data_tab.parent_item_id,
1461               x_fcst_data_tab.organization_id, x_fcst_data_tab.fcst_organization_id,
1462               x_fcst_data_tab.fcst_demand_id, x_fcst_data_tab.sales_order_id,
1463               x_fcst_data_tab.sales_order_qty, x_fcst_data_tab.forecast_qty,
1464               x_fcst_data_tab.consumed_qty, x_fcst_data_tab.overconsumption_qty,
1465               x_fcst_data_tab.bom_item_type, x_fcst_data_tab.fixed_lt,
1466               x_fcst_data_tab.variable_lt, x_fcst_data_tab.cons_config_mod_flag
1467        FROM   msc_forecast_updates fcst, msc_system_items msi
1468        WHERE  fcst.sr_instance_id = atp_peg_tab.sr_instance_id(k)
1469        AND    fcst.plan_id = atp_peg_tab.plan_id(k)
1470        AND    (fcst.organization_id = atp_peg_tab.organization_id(k)
1471                  OR    fcst.organization_id = -1)
1472                 -- First check for local forecast
1473                 -- CTO_PF_PRJ changes. Use end_demand_id
1474        AND    (fcst.sales_order_id = atp_peg_tab.original_demand_id(k)
1475                  OR
1476                  fcst.sales_order_id = atp_peg_tab.end_demand_id(k)
1477                 )
1478                 -- CTO_PF_PRJ
1479        AND    fcst.inventory_item_id = atp_peg_tab.inventory_item_id(k)
1480        -- Only get records where config item's forecast is consumed
1481        AND    fcst.forecast_qty > 0
1482        AND    (fcst.consumed_qty + NVL(fcst.overconsumption_qty,0)) > 0
1483                                      -- Bug 3805136        atp_peg_tab.allocated_quantity(k)
1484        -- and there is no overconsumption of corresponding base model's forecast.
1485        AND    msi.plan_id = fcst.plan_id
1486        AND    msi.sr_instance_id = fcst.sr_instance_id
1487        AND    msi.organization_id = atp_peg_tab.organization_id(k)
1488        AND    msi.inventory_item_id =  fcst.inventory_item_id
1489        GROUP  BY msi.plan_id, msi.sr_instance_id,
1490                 fcst.inventory_item_id, fcst.parent_item_id,
1491                 msi.organization_id, fcst.organization_id ,
1492                 -1 , fcst.sales_order_id, sales_order_qty,
1493                 msi.bom_item_type, msi.fixed_lead_time, msi.variable_lead_time,
1494                 2 -- only config item is consumed
1495        -- Bug 3805136 (Uncomment HAVING clause)
1496        HAVING SUM(fcst.consumed_qty) + SUM(NVL(fcst.overconsumption_qty, 0))
1497                                                           >= fcst.sales_order_qty
1498        ;
1499 
1500        IF PG_DEBUG in ('Y', 'C') THEN
1501           msc_util.msc_log(' Count After Config Check : ' ||
1502                               x_fcst_data_tab.inventory_item_id.COUNT);
1503           msc_util.msc_log(' Allocated Quantity : ' || atp_peg_tab.allocated_quantity(k));
1504        END IF;
1505        -- End Bug 3701093
1506     END IF;
1507     -- End Bug 3701093
1508 
1509 
1510     -- Bug 3362558
1511     -- Global forecasting situation, org_id is -1.
1512     -- CTO_PF_PRJ Query present below removed. The use of
1513     -- end_demand_id obviates the need for SQL that joins with msc_atp_detail_peg_temp.
1514     -- Changes here in relation to Bug 3362558 not needed anymore.
1515     -- End Bug 3362558
1516 
1517         -- Bug 3362499
1518         -- No data in msc_forecast_updates.
1519     -- Bug 3417410 Determine if model line is present in data
1520     IF x_fcst_data_tab.inventory_item_id.COUNT = 0 THEN
1521        l_fcst_mod_flag := 0;
1522     ELSE
1523        FOR i in 1..x_fcst_data_tab.inventory_item_id.COUNT
1524        LOOP
1525           IF ( (x_fcst_data_tab.inventory_item_id(i) =
1526                                atp_peg_tab.base_item_id(k) ) OR
1527                (x_fcst_data_tab.inventory_item_id(i) =
1528                                atp_peg_tab.inventory_item_id(k) ) ) THEN
1529              -- The config item or model has been forecast
1530              l_fcst_mod_flag := 1;
1531              IF PG_DEBUG in ('Y', 'C') THEN
1532                 msc_util.msc_log('Get_Fcst_Cons: Model or Config in Forecast Data');
1533                 msc_util.msc_log('Get_Fcst_Cons: Forecast Inventory_Item_id : '||
1534                                                     x_fcst_data_tab.inventory_item_id(i));
1535              END IF;
1536           END IF;
1537        END LOOP;
1538     END IF;
1539     -- End Bug 3417410 Determine if model line is present in data
1540 
1541     IF l_fcst_mod_flag = 0 THEN -- Bug 3417410 If no model line is present in forecast
1542        IF PG_DEBUG in ('Y', 'C') THEN
1543           msc_util.msc_log('Get Data from msc_system_items for base_item_id');
1544           msc_util.msc_log('Provide default values for other forecast fields ');
1545        END IF;
1546         -- Get data from msc_system_items for the base_item_id
1547         -- and provide default values for other forecast related fields.
1548         -- Note Local forecast is assumed as a default.
1549         SELECT msi.plan_id, msi.sr_instance_id,
1550                msi.inventory_item_id, atp_peg_tab.inventory_item_id(k),
1551                msi.organization_id, msi.organization_id fcst_organization_id,
1552                -1 forecast_demand_id, atp_peg_tab.original_demand_id(k) sales_order_id,
1553                0 sales_order_qty, 0 forecast_qty, 0 consumed_qty,
1554                atp_peg_tab.allocated_quantity(k)  overconsumption_qty,
1555                msi.bom_item_type, msi.fixed_lead_time, msi.variable_lead_time,
1556                -- Bug 3701093
1557                0  -- No forecast Consumption Happens,
1558                                    -- Generating data based on allocated quantities.
1559         BULK COLLECT
1560              -- Bug 3417410 Collect into local record.
1561         INTO   l_fcst_data_tab.plan_id, l_fcst_data_tab.sr_instance_id,
1562                l_fcst_data_tab.inventory_item_id, l_fcst_data_tab.parent_item_id,
1563                l_fcst_data_tab.organization_id, l_fcst_data_tab.fcst_organization_id,
1564                l_fcst_data_tab.fcst_demand_id, l_fcst_data_tab.sales_order_id,
1565                l_fcst_data_tab.sales_order_qty, l_fcst_data_tab.forecast_qty,
1566                l_fcst_data_tab.consumed_qty, l_fcst_data_tab.overconsumption_qty,
1567                l_fcst_data_tab.bom_item_type, l_fcst_data_tab.fixed_lt,
1568                l_fcst_data_tab.variable_lt,
1569                -- Bug 3701093 Model overconsumption does not happen
1570                l_fcst_data_tab.cons_config_mod_flag
1571                -- Just get the data from msc_system_items
1572                -- and default the rest of the values.
1573              -- End Bug 3417410 Collect into local record.
1574         FROM   msc_system_items msi
1575         WHERE  msi.plan_id = atp_peg_tab.plan_id(k)
1576         AND    msi.sr_instance_id = atp_peg_tab.sr_instance_id(k)
1577         AND    msi.organization_id = atp_peg_tab.organization_id(k)
1578         AND    (msi.wip_supply_type = 6 or msi.bom_item_type = 1)
1579                -- only phantom model info is obtained
1580         AND    msi.inventory_item_id =  atp_peg_tab.base_item_id(k)
1581         ;
1582 
1583         -- Bug 3417410 Assign the default model data into the output record.
1584         x_fcst_data_tab.plan_id.EXTEND;
1585         x_fcst_data_tab.sr_instance_id.EXTEND;
1586         x_fcst_data_tab.inventory_item_id.EXTEND;
1587         x_fcst_data_tab.parent_item_id.EXTEND;
1588         x_fcst_data_tab.organization_id.EXTEND;
1589         x_fcst_data_tab.fcst_organization_id.EXTEND;
1590         x_fcst_data_tab.fcst_demand_id.EXTEND;
1591         x_fcst_data_tab.sales_order_id.EXTEND;
1592         x_fcst_data_tab.sales_order_qty.EXTEND;
1593         x_fcst_data_tab.forecast_qty.EXTEND;
1594         x_fcst_data_tab.consumed_qty.EXTEND;
1595         x_fcst_data_tab.overconsumption_qty.EXTEND;
1596         x_fcst_data_tab.bom_item_type.EXTEND;
1597         x_fcst_data_tab.fixed_lt.EXTEND;
1598         x_fcst_data_tab.variable_lt.EXTEND;
1599         -- Bug 3701093 Extend the new field.
1600         x_fcst_data_tab.cons_config_mod_flag.EXTEND;
1601 
1602         l_fcst_cnt :=  x_fcst_data_tab.inventory_item_id.COUNT;
1603 
1604         IF PG_DEBUG in ('Y', 'C') THEN
1605            msc_util.msc_log('Get_Fcst_Cons-Total Forecasted Items : '|| l_fcst_cnt);
1606         END IF;
1607 
1608         -- Bug 3701093 COUNT > 0 check only, changed from <>
1609         IF l_fcst_data_tab.inventory_item_id.COUNT > 0 THEN
1610            x_fcst_data_tab.plan_id(l_fcst_cnt)           := l_fcst_data_tab.plan_id(1);
1611            x_fcst_data_tab.sr_instance_id(l_fcst_cnt)    := l_fcst_data_tab.sr_instance_id(1);
1612            x_fcst_data_tab.inventory_item_id(l_fcst_cnt) := l_fcst_data_tab.inventory_item_id(1);
1613            x_fcst_data_tab.parent_item_id(l_fcst_cnt)    := l_fcst_data_tab.parent_item_id(1);
1614            x_fcst_data_tab.organization_id(l_fcst_cnt)   := l_fcst_data_tab.organization_id(1);
1615            x_fcst_data_tab.fcst_organization_id(l_fcst_cnt) :=
1616                                                       l_fcst_data_tab.fcst_organization_id(1);
1617            x_fcst_data_tab.fcst_demand_id(l_fcst_cnt)    := l_fcst_data_tab.fcst_demand_id(1);
1618            x_fcst_data_tab.sales_order_id(l_fcst_cnt)    := l_fcst_data_tab.sales_order_id(1);
1619            x_fcst_data_tab.sales_order_qty(l_fcst_cnt)   := l_fcst_data_tab.sales_order_qty(1);
1620            x_fcst_data_tab.forecast_qty(l_fcst_cnt)      := l_fcst_data_tab.forecast_qty(1);
1621            x_fcst_data_tab.consumed_qty(l_fcst_cnt)      := l_fcst_data_tab.consumed_qty(1);
1622            x_fcst_data_tab.overconsumption_qty(l_fcst_cnt) :=
1623                                                       l_fcst_data_tab.overconsumption_qty(1);
1624            -- Bug 3805136
1625            -- Lower Level Config No Forecast .
1626            IF (atp_peg_tab.inventory_item_id(k) <> atp_peg_tab.reference_item_id(k) ) THEN
1627               x_fcst_data_tab.forecast_qty(l_fcst_cnt)      := NULL;
1628               x_fcst_data_tab.consumed_qty(l_fcst_cnt)      := NULL;
1629               x_fcst_data_tab.overconsumption_qty(l_fcst_cnt) := NULL;
1630            END IF;
1631            -- End Bug 3805136
1632            x_fcst_data_tab.bom_item_type(l_fcst_cnt)     := l_fcst_data_tab.bom_item_type(1);
1633            x_fcst_data_tab.fixed_lt(l_fcst_cnt)          := l_fcst_data_tab.fixed_lt(1);
1634            x_fcst_data_tab.variable_lt(l_fcst_cnt)       := l_fcst_data_tab.variable_lt(1);
1635            -- Bug 3701093
1636            x_fcst_data_tab.cons_config_mod_flag(l_fcst_cnt) := C_NO_FCST_CONSUMED;
1637            -- Bug 3701093 Model and Config forecast consumption does not happen
1638         ELSE
1639            -- No data in msc_system_items for the base model
1640            -- Print out a Warning message.
1641            IF PG_DEBUG in ('Y', 'C') THEN
1642               msc_util.msc_log ( 'No plan data for Base Model ' ||
1643                                                         atp_peg_tab.base_item_id(k)  );
1644               msc_util.msc_log('Get_Fcst_Cons-No plan data for Base Model : '||
1645                                                         atp_peg_tab.base_item_id(k) );
1646            END IF;
1647            x_fcst_data_tab.plan_id(l_fcst_cnt)           := atp_peg_tab.plan_id(k);
1648            x_fcst_data_tab.sr_instance_id(l_fcst_cnt)    := atp_peg_tab.sr_instance_id(k);
1649            x_fcst_data_tab.inventory_item_id(l_fcst_cnt) := atp_peg_tab.base_item_id(k);
1650            x_fcst_data_tab.parent_item_id(l_fcst_cnt)    := atp_peg_tab.inventory_item_id(k);
1651            x_fcst_data_tab.organization_id(l_fcst_cnt)   := atp_peg_tab.organization_id(k);
1652            x_fcst_data_tab.fcst_organization_id(l_fcst_cnt) :=
1653                                                       atp_peg_tab.organization_id(k);
1654            x_fcst_data_tab.fcst_demand_id(l_fcst_cnt)    := -1;
1655            x_fcst_data_tab.sales_order_id(l_fcst_cnt)    := atp_peg_tab.original_demand_id(k);
1656            x_fcst_data_tab.sales_order_qty(l_fcst_cnt)   := 0;
1657            x_fcst_data_tab.forecast_qty(l_fcst_cnt)      := 0;
1658            x_fcst_data_tab.consumed_qty(l_fcst_cnt)      := 0;
1659            x_fcst_data_tab.overconsumption_qty(l_fcst_cnt) :=
1660                                                       atp_peg_tab.allocated_quantity(k);
1661            -- Bug 3805136
1662            -- Lower Level Config No Forecast .
1663            IF (atp_peg_tab.inventory_item_id(k) <> atp_peg_tab.reference_item_id(k) ) THEN
1664               x_fcst_data_tab.forecast_qty(l_fcst_cnt)      := NULL;
1665               x_fcst_data_tab.consumed_qty(l_fcst_cnt)      := NULL;
1666               x_fcst_data_tab.overconsumption_qty(l_fcst_cnt) := NULL;
1667            END IF;
1668            x_fcst_data_tab.bom_item_type(l_fcst_cnt)     := 1;
1669            x_fcst_data_tab.fixed_lt(l_fcst_cnt)          := 0;
1670            x_fcst_data_tab.variable_lt(l_fcst_cnt)       := 0;
1671            -- Bug 3701093
1672            x_fcst_data_tab.cons_config_mod_flag(l_fcst_cnt) := C_NO_FCST_CONSUMED;
1673            -- Bug 3701093 Model and Config forecast consumption does not happen
1674         END IF;
1675         -- Bug 3417410 Assign the default model data into the output record.
1676 
1677     END IF;
1678     -- End Bug 3362499
1679 
1680   /* Old code that links to the BOM DELETED
1681    */
1682 
1683 EXCEPTION
1684     WHEN OTHERS THEN
1685       IF PG_DEBUG in ('Y', 'C') THEN
1686         msc_util.msc_log ('Get_Forecast_Consumption. Error : ' || sqlerrm);
1687       END IF;
1688         x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
1689 
1690 END Get_Forecast_Consumption;
1691 
1692 -- This procedure transforms a flat combined supply/demand pegging into a two
1693 -- level pegging that contains supplies and demands separately.
1694 PROCEDURE Create_Simple_Pegging (atp_peg_det      IN            ATP_Detail_Peg_Typ,
1695                                  atp_peg_tab      IN OUT NoCopy ATP_Simple_Peg_Typ,
1696                                  x_return_status  OUT NOCOPY    VARCHAR2)
1697 IS
1698 n                  NUMBER;
1699 l_return_status    VARCHAR2(1);
1700 l_count            NUMBER := 0;
1701 BEGIN
1702 
1703   IF PG_DEBUG in ('Y', 'C') THEN
1704        msc_util.msc_log('***** Begin Create_Simple_Pegging Procedure *****');
1705   END IF;
1706 
1707   x_return_status := FND_API.G_RET_STS_SUCCESS;
1708 
1709   IF PG_DEBUG in ('Y', 'C') THEN
1710     msc_util.msc_log(' atp_peg_det.reference_item_id.COUNT ' ||
1711                                      atp_peg_det.reference_item_id.COUNT);
1712     msc_util.msc_log('atp_peg_tab.reference_item_id.COUNT ' ||
1713                                       atp_peg_tab.reference_item_id.COUNT);
1714   END IF;
1715 
1716   l_count := atp_peg_tab.reference_item_id.COUNT;
1717 
1718   FOR n in 1..atp_peg_det.inventory_item_id.COUNT LOOP
1719     -- First Call to extend the tables in atp_peg_tab.
1720     Extend_Atp_Peg (atp_peg_tab, l_return_status, 1);
1721 
1722    IF PG_DEBUG in ('Y', 'C') THEN
1723     msc_util.msc_log(' Item Id  ' || atp_peg_det.inventory_item_id(n));
1724     msc_util.msc_log(' atp_peg_tab.pegging_id ' ||
1725                                       atp_peg_det.pegging_id(n));
1726    END IF;
1727     l_count := l_count + 1;
1728 
1729     -- The detail data is divided into two simplified pegging records.
1730     -- one for demand and one for supply.
1731     -- Assign Common Data
1732 
1733     atp_peg_tab.reference_item_id(l_count) := atp_peg_det.reference_item_id(n);
1734     atp_peg_tab.base_item_id(l_count) := atp_peg_det.base_item_id(n);
1735     atp_peg_tab.inventory_item_id(l_count) := atp_peg_det.inventory_item_id(n);
1736     atp_peg_tab.plan_id(l_count) := atp_peg_det.plan_id(n);
1737     atp_peg_tab.sr_instance_id(l_count) := atp_peg_det.sr_instance_id(n);
1738     atp_peg_tab.organization_id(l_count) := atp_peg_det.organization_id(n);
1739     atp_peg_tab.bom_item_type(l_count) := atp_peg_det.bom_item_type(n);
1740     atp_peg_tab.fixed_lt(l_count) := atp_peg_det.fixed_lt(n);
1741     atp_peg_tab.variable_lt(l_count) := atp_peg_det.variable_lt(n);
1742     atp_peg_tab.sales_order_line_id(l_count) := atp_peg_det.sales_order_line_id(n);
1743     atp_peg_tab.demand_source_type(l_count) := atp_peg_det.demand_source_type(n);--cmro
1744     atp_peg_tab.end_pegging_id(l_count) := atp_peg_det.end_pegging_id(n);
1745     atp_peg_tab.pegging_id(l_count) := atp_peg_det.pegging_id(n);
1746     atp_peg_tab.prev_pegging_id(l_count) := atp_peg_det.prev_pegging_id(n);
1747     atp_peg_tab.sales_order_qty(l_count) := atp_peg_det.sales_order_qty(n);
1748     atp_peg_tab.tot_relief_qty(l_count) := atp_peg_det.tot_relief_qty(n);
1749     -- CTO_PF_PRJ changes.
1750     atp_peg_tab.end_demand_id(l_count) := atp_peg_det.end_demand_id(n);
1751     -- CTO-PF
1752     atp_peg_tab.atf_date(l_count) := atp_peg_det.atf_date(n);
1753     atp_peg_tab.product_family_id(l_count) := atp_peg_det.product_family_id(n);
1754 
1755     atp_peg_tab.demand_class(l_count) := atp_peg_det.demand_class(n);
1756     -- Bug 3805136 -- Add end_item_usage to handle no forecast consumption.
1757     atp_peg_tab.end_item_usage(l_count) := atp_peg_det.end_item_usage(n);
1758     -- Exclude flag helps in excluding supplies
1759     -- during relef data calculation.
1760     atp_peg_tab.exclude_flag(l_count) := atp_peg_det.exclude_flag(n);
1761     -- End Bug 3805136
1762 
1763     -- Assign Demand Data
1764     atp_peg_tab.transaction_date(l_count) := TRUNC(atp_peg_det.demand_date(n));
1765     atp_peg_tab.demand_id(l_count) := atp_peg_det.demand_id(n);
1766     atp_peg_tab.demand_quantity(l_count) := atp_peg_det.demand_quantity(n);
1767     atp_peg_tab.disposition_id(l_count) := atp_peg_det.disposition_id(n);
1768     atp_peg_tab.consumed_qty(l_count) := atp_peg_det.consumed_qty(n);
1769     atp_peg_tab.overconsumption_qty(l_count) := atp_peg_det.overconsumption_qty(n);
1770     atp_peg_tab.allocated_quantity(l_count) := atp_peg_det.allocated_quantity(n);
1771 
1772     -- Auxiliary Data for CTO_PF_PRJ_2, Track the supply data.
1773     atp_peg_tab.supply_id(l_count) := atp_peg_det.supply_id(n);
1774     atp_peg_tab.supply_quantity(l_count) := atp_peg_det.supply_quantity(n);
1775 
1776     -- Determine Relief Type
1777     IF atp_peg_det.demand_type(n) = 6 or atp_peg_det.demand_type(n) = 30 THEN
1778        atp_peg_tab.relief_type(l_count) := 1;   -- Relief Type is SO.
1779     ELSIF atp_peg_det.demand_type(n) = 1 THEN
1780        atp_peg_tab.relief_type(l_count) := 3;   -- Relief Type is POD.
1781     END IF;
1782 
1783 
1784     -- Now create the supply simplified pegging data.
1785     IF (atp_peg_det.base_item_id(n) IS NOT NULL AND
1786         atp_peg_det.supply_id(n) IS NOT NULL ) THEN
1787        Extend_Atp_Peg (atp_peg_tab, l_return_status, 1);
1788 
1789        l_count  := l_count + 1;
1790 
1791       -- Assign Common Data
1792       atp_peg_tab.reference_item_id(l_count) := atp_peg_det.reference_item_id(n);
1793       atp_peg_tab.base_item_id(l_count) := atp_peg_det.base_item_id(n);
1794       atp_peg_tab.inventory_item_id(l_count) := atp_peg_det.inventory_item_id(n);
1795       atp_peg_tab.plan_id(l_count) := atp_peg_det.plan_id(n);
1796       atp_peg_tab.sr_instance_id(l_count) := atp_peg_det.sr_instance_id(n);
1797       atp_peg_tab.organization_id(l_count) := atp_peg_det.organization_id(n);
1798       atp_peg_tab.bom_item_type(l_count) := atp_peg_det.bom_item_type(n);
1799       atp_peg_tab.fixed_lt(l_count) := atp_peg_det.fixed_lt(n);
1800       atp_peg_tab.variable_lt(l_count) := atp_peg_det.variable_lt(n);
1801       atp_peg_tab.sales_order_line_id(l_count) := atp_peg_det.sales_order_line_id(n);
1802       atp_peg_tab.demand_source_type(l_count) := atp_peg_det.demand_source_type(n);--cmro
1803       atp_peg_tab.end_pegging_id(l_count) := atp_peg_det.end_pegging_id(n);
1804       atp_peg_tab.pegging_id(l_count) := atp_peg_det.pegging_id(n);
1805       atp_peg_tab.prev_pegging_id(l_count) := atp_peg_det.prev_pegging_id(n);
1806       atp_peg_tab.sales_order_qty(l_count) := atp_peg_det.sales_order_qty(n);
1807       atp_peg_tab.tot_relief_qty(l_count) := atp_peg_det.tot_relief_qty(n);
1808       -- CTO_PF_PRJ changes.
1809       atp_peg_tab.end_demand_id(l_count) := atp_peg_det.end_demand_id(n);
1810       --CTO-PF
1811       atp_peg_tab.atf_date(l_count) := atp_peg_det.atf_date(n);
1812       atp_peg_tab.product_family_id(l_count) := atp_peg_det.product_family_id(n);
1813       -- Bug 3805136 -- Add end_item_usage to handle no forecast consumption.
1814       atp_peg_tab.end_item_usage(l_count) := atp_peg_det.end_item_usage(n);
1815       -- Exclude flag helps in excluding supplies
1816       -- during relef data calculation.
1817       atp_peg_tab.exclude_flag(l_count) := atp_peg_det.exclude_flag(n);
1818       -- End Bug 3805136
1819 
1820       -- Assign corresponding supply_data
1821       atp_peg_tab.transaction_date(l_count) := TRUNC(atp_peg_det.supply_date(n));
1822       atp_peg_tab.consumed_qty(l_count) := atp_peg_det.consumed_qty(n);
1823       atp_peg_tab.overconsumption_qty(l_count) := atp_peg_det.overconsumption_qty(n);
1824       atp_peg_tab.supply_id(l_count) := atp_peg_det.supply_id(n);
1825       atp_peg_tab.supply_quantity(l_count) := atp_peg_det.supply_quantity(n);
1826       atp_peg_tab.allocated_quantity(l_count) := atp_peg_det.allocated_quantity(n);
1827 
1828 
1829      IF PG_DEBUG in ('Y', 'C') THEN
1830       msc_util.msc_log(' atp_peg_tab.allocated_quantity ' ||
1831                                      atp_peg_det.allocated_quantity(n));
1832      END IF;
1833       -- Determine Relief Type
1834       -- For material supplies the relief type is POs
1835       atp_peg_tab.relief_type(l_count) := 2;   -- Relief Type is PO.
1836     END IF;
1837   END LOOP;
1838     msc_util.msc_log(' atp_peg_tab.reference_item_id.COUNT ' ||
1839                                      atp_peg_tab.reference_item_id.COUNT);
1840 EXCEPTION
1841     WHEN OTHERS THEN
1842      IF PG_DEBUG in ('Y', 'C') THEN
1843         msc_util.msc_log ('Create_Simple_Pegging. Error : ' || sqlerrm);
1844      END IF;
1845         x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
1846 
1847 END  Create_Simple_Pegging;
1848 
1849 -- Bug 3344102 Procedure begin
1850 -- This procedure creates the ATP simplified pegging for allocated ATP case
1851 -- and stores it into the msc_atp_pegging table after plan run.
1852 PROCEDURE Create_Pre_Allocation_Reliefs (p_plan_id         IN          NUMBER,
1853                                          p_insert_table    IN          VARCHAR2,
1854                                          p_user_id         IN          NUMBER,
1855                                          p_sysdate         IN          DATE,
1856                                          x_return_status   OUT NOCOPY  VARCHAR2
1857                                         )
1858 IS
1859 
1860 l_sql_stmt                      VARCHAR2(800);
1861 l_sql_stmt_1                    VARCHAR2(8000);
1862 l_relief_type                   NUMBER;
1863 
1864 -- Default Demand Class
1865 l_def_dmd_class                 VARCHAR2(3) := '-1';
1866 
1867 BEGIN
1868 
1869   IF PG_DEBUG in ('Y', 'C') THEN
1870      msc_util.msc_log('***** Begin Create_Pre_Allocation_Reliefs Procedure *****');
1871      msc_util.msc_log(' Plan Id : ' || p_plan_id );
1872      msc_util.msc_log(' Insert Table parameter : ' || p_insert_table );
1873      msc_util.msc_log(' User Id Paramenter : ' || p_user_id );
1874      msc_util.msc_log(' Date Parameter : ' || p_sysdate );
1875   END IF;
1876 
1877   x_return_status := FND_API.G_RET_STS_SUCCESS;
1878 
1879     -- Set the relief type for only demands with Allocated ATP on.
1880     l_relief_type := 5;
1881 
1882     IF PG_DEBUG in ('Y', 'C') THEN
1883        msc_util.msc_log(' Inserting Demands');
1884     END IF;
1885 
1886     l_sql_stmt_1 := 'INSERT INTO  ' || p_insert_table || -- actually the insert table parameter.
1887              ' (reference_item_id, inventory_item_id, plan_id,
1888              sr_instance_id, organization_id, sales_order_line_id,
1889              demand_source_type, end_demand_id, bom_item_type,
1890              sales_order_qty, transaction_date, demand_id,
1891              demand_quantity, disposition_id, demand_class,
1892              consumed_qty, overconsumption_qty, supply_id, supply_quantity,
1893              allocated_quantity,
1894              relief_type, relief_quantity,
1895              pegging_id, prev_pegging_id, end_pegging_id,
1896              created_by, creation_date, last_updated_by, last_update_date,
1897              customer_id, customer_site_id)
1898     SELECT   mapt.reference_item_id, mapt.inventory_item_id, mapt.plan_id,
1899              mapt.sr_instance_id, mapt.organization_id,
1900              mapt.sales_order_line_id, mapt.demand_source_type, mapt.end_demand_id,
1901              mapt.bom_item_type, mapt.sales_order_qty, mapt.transaction_date,
1902              mapt.demand_id , mapt.demand_quantity,
1903              mapt.disposition_id,
1904              NVL(mv.demand_class, :l_def_dmd_class) demand_class ,
1905              mapt.consumed_qty, mapt.overconsumption_qty,
1906              mapt.supply_id, mapt.supply_quantity,
1907              mapt.allocated_quantity ,  :l_relief_type,
1908              mapt.relief_quantity ,
1909              mapt.pegging_id, mapt.prev_pegging_id, mapt.end_pegging_id,
1910              :p_user_id, :p_sysdate, :p_user_id, :p_sysdate,
1911              mv.partner_id, mv.partner_site_id customer_site_id
1912     FROM    msc_atp_peg_temp mapt, msc_item_hierarchy_mv mv
1913     WHERE   mapt.plan_id = :p_plan_id
1914     AND     mapt.relief_type = 3
1915     AND     mapt.inventory_item_id = mv.inventory_item_id(+)
1916     AND     mapt.organization_id = mv.organization_id (+)
1917     AND     mapt.sr_instance_id = mv.sr_instance_id (+)
1918     AND     mapt.transaction_date >=  mv.effective_date (+)
1919     AND     mapt.transaction_date <=  mv.disable_date (+)
1920     AND     mapt.demand_class = mv.demand_class (+)
1921     AND     mv.level_id (+) = -1 '
1922     ;
1923 
1924     EXECUTE IMMEDIATE l_sql_stmt_1 USING
1925                         l_def_dmd_class, l_relief_type,
1926                         p_user_id, p_sysdate, p_user_id, p_sysdate, p_plan_id;
1927 
1928     IF PG_DEBUG in ('Y', 'C') THEN
1929         msc_util.msc_log('Create_Pre_Allocation_Reliefs:  Number of Demand rows inserted '||
1930                                SQL%ROWCOUNT);
1931     END IF;
1932 
1933     -- Set the relief type for only supplies with Allocated ATP on.
1934     l_relief_type := 6;
1935 
1936   IF PG_DEBUG in ('Y', 'C') THEN
1937      msc_util.msc_log(' Inserting Supplies');
1938   END IF;
1939 
1940     l_sql_stmt_1 := 'INSERT INTO  ' || p_insert_table || -- actually the insert table parameter.
1941              ' (reference_item_id, inventory_item_id, plan_id,
1942              sr_instance_id, organization_id, sales_order_line_id,
1943              demand_source_type, end_demand_id, bom_item_type,
1944              sales_order_qty, transaction_date, demand_id,
1945              demand_quantity, disposition_id, demand_class,
1946              consumed_qty, overconsumption_qty, supply_id, supply_quantity,
1947              allocated_quantity,
1948              relief_type, relief_quantity,
1949              pegging_id, prev_pegging_id, end_pegging_id,
1950              created_by, creation_date, last_updated_by, last_update_date,
1951              customer_id, customer_site_id)
1952     SELECT   mapt.reference_item_id, mapt.inventory_item_id, mapt.plan_id,
1953              mapt.sr_instance_id, mapt.organization_id,
1954              mapt.sales_order_line_id, mapt.demand_source_type, mapt.end_demand_id,
1955              mapt.bom_item_type, mapt.sales_order_qty, mapt.transaction_date,
1956              mapt.demand_id , mapt.demand_quantity,
1957              mapt.disposition_id,
1958              NVL(mv.demand_class, :l_def_dmd_class) demand_class ,
1959              mapt.consumed_qty, mapt.overconsumption_qty,
1960              mapt.supply_id, mapt.supply_quantity,
1961              mapt.allocated_quantity ,  :l_relief_type,
1962              mapt.relief_quantity ,
1963              mapt.pegging_id, mapt.prev_pegging_id, mapt.end_pegging_id,
1964              :p_user_id, :p_sysdate, :p_user_id, :p_sysdate,
1965              mv.partner_id, mv.partner_site_id customer_site_id
1966     FROM    msc_atp_peg_temp mapt, msc_item_hierarchy_mv mv
1967     WHERE   mapt.plan_id = :p_plan_id
1968     AND     mapt.relief_type = 2
1969     AND     mapt.inventory_item_id = mv.inventory_item_id(+)
1970     AND     mapt.organization_id = mv.organization_id (+)
1971     AND     mapt.sr_instance_id = mv.sr_instance_id (+)
1972     AND     mapt.transaction_date >=  mv.effective_date (+)
1973     AND     mapt.transaction_date <=  mv.disable_date (+)
1974     AND     mapt.demand_class = mv.demand_class (+)
1975     AND     mv.level_id (+) = -1 '
1976     ;
1977 
1978     EXECUTE IMMEDIATE l_sql_stmt_1 USING
1979                         l_def_dmd_class, l_relief_type,
1980                         p_user_id, p_sysdate, p_user_id, p_sysdate, p_plan_id;
1981 
1982     IF PG_DEBUG in ('Y', 'C') THEN
1983         msc_util.msc_log('Create_Pre_Allocation_Reliefs:  Number of Supply rows inserted '||
1984                                SQL%ROWCOUNT);
1985     END IF;
1986 
1987 EXCEPTION
1988     WHEN OTHERS THEN
1989       IF PG_DEBUG in ('Y', 'C') THEN
1990         msc_util.msc_log('Inside main exception of Create_Pre_Allocation_Reliefs');
1991         msc_util.msc_log ('Create_Pre_Allocation_Reliefs. Error : ' || sqlcode || ': '|| sqlerrm);
1992       END IF;
1993         x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
1994 
1995 END Create_Pre_Allocation_Reliefs;
1996 -- Bug 3344102 Procedure End
1997 
1998 -- Bug 3750638 Move all the pegging releated SQLs into this procedure.
1999 -- This procedure fetches pegging data for a Sales Order
2000 -- from MSC_FULL_PEGGING in a loop.
2001 PROCEDURE Get_Pegging_Data_Loop (p_plan_id       IN          NUMBER,
2002                                  c_items_rec     IN          ATP_End_Config_Dmd_Typ,
2003                                  x_return_status OUT  NoCopy VARCHAR2   )
2004 IS
2005 
2006 l_sql_stmt_1                    varchar2(8000);
2007 l_timestamp                     NUMBER;
2008 l_hash_size                     NUMBER := -1;
2009 l_sort_size                     NUMBER := -1;
2010 l_parallel_degree               NUMBER := 1;
2011 
2012 -- Fix for Multiple (N) Level of Config Items using Loop
2013 -- Define PL/SQL Variable of Record of Arrays Type to correspond to
2014 -- Config Item Supplies being processed in the Pegging Retrieval loop.
2015 L_Config_Sup                    ATP_Config_Sup_Typ;
2016 l_multi_config_count            NUMBER;
2017 n_idx                           NUMBER; -- Index for Items
2018 n_row_count                     NUMBER;
2019 l_config_level                  NUMBER;
2020 i                               NUMBER;
2021 
2022 BEGIN
2023     IF PG_DEBUG in ('Y', 'C') THEN
2024     msc_util.msc_log('***** Begin Get_Pegging_Data_Loop (Get_Pegging_Loop) *****');
2025     msc_util.msc_log('Get_Pegging_Loop : p_plan_id ' || p_plan_id);
2026   END IF;
2027 
2028   x_return_status := FND_API.G_RET_STS_SUCCESS;
2029 
2030   -- Initialize variables;
2031   -- First get the performance parameters.
2032 
2033   BEGIN
2034      SELECT      NVL(pre_alloc_hash_size, -1),
2035                  NVL(pre_alloc_sort_size, -1),
2036                  NVL(pre_alloc_parallel_degree, 1)
2037      INTO        l_hash_size,
2038                  l_sort_size,
2039                  l_parallel_degree
2040      FROM        msc_atp_parameters
2041      WHERE       rownum = 1;
2042      EXCEPTION
2043          WHEN others THEN
2044          msc_util.msc_log('Error getting performance param: ' || sqlcode || ': ' || sqlerrm);
2045          l_hash_size := -1;
2046          l_sort_size := -1;
2047          l_parallel_degree := 1;
2048   END;
2049 
2050   IF PG_DEBUG in ('Y', 'C') THEN
2051      msc_util.msc_log('Hash: ' || l_hash_size || ' Sort: ' || l_sort_size ||
2052                          ' Parallel: ' || l_parallel_degree);
2053   END IF;
2054 
2055   IF NVL(l_hash_size, -1) <> -1 THEN
2056         l_sql_stmt_1 := 'alter session set hash_area_size = ' || to_char(l_hash_size);
2057         msc_util.msc_log('l_sql_stmt : ' || l_sql_stmt_1);
2058         execute immediate l_sql_stmt_1;
2059   END IF;
2060 
2061   IF NVL(l_sort_size, -1) <> -1 THEN
2062          l_sql_stmt_1 := 'alter session set sort_area_size = ' || to_char(l_sort_size);
2063          msc_util.msc_log('l_sql_stmt : ' || l_sql_stmt_1);
2064          execute immediate l_sql_stmt_1;
2065   END IF;
2066 
2067   -- Now obtain the pegging data into Global Temporary Table in a Loop.
2068 
2069       -- Obtain the supplies info for the config item.
2070       INSERT INTO MSC_ATP_DETAIL_PEG_TEMP (
2071               reference_item_id, base_item_id,
2072               inventory_item_id,
2073               plan_id,
2074               sr_instance_id,
2075               organization_id,
2076               end_item_usage,
2077               bom_item_type, fixed_lt, variable_lt,
2078               sales_order_line_id,
2079               demand_source_type,--cmro
2080               -- CTO_PF_PRJ changes.
2081               end_demand_id,
2082               sales_order_qty,
2083               process_seq_id, supply_id,
2084               supply_date,
2085               supply_quantity,
2086               allocated_quantity, tot_relief_qty,
2087               supply_type,
2088               firm_planned_type,
2089               release_status,
2090               exclude_flag,    -- All other cases exclude
2091               end_pegging_id, pegging_id,  prev_pegging_id,
2092               fcst_organization_id, forecast_qty,
2093               consumed_qty, overconsumption_qty )
2094       SELECT  DISTINCT
2095               c_items_rec.inventory_item_id, msi.base_item_id,
2096               peg2.inventory_item_id,
2097               peg2.plan_id,
2098               peg2.sr_instance_id,
2099               peg2.organization_id,
2100               peg2.end_item_usage,
2101               msi.bom_item_type, msi.fixed_lead_time, msi.variable_lead_time,
2102               c_items_rec.sales_order_line_id,
2103               c_items_rec.demand_source_type, --cmro
2104               -- CTO_PF_PRJ changes.
2105               NVL(d1.original_demand_id, d1.demand_id),
2106               NULL sales_order_qty, -- will be used to factor sales_order_qty,
2107               SUP.process_seq_id, SUP.transaction_id supply_id,
2108               SUP.new_schedule_date supply_date,
2109               SUP.new_order_quantity supply_qty,
2110               peg2.allocated_quantity, NULL tot_relief_qty,
2111               SUP.order_type,
2112               SUP.firm_planned_type,
2113               SUP.release_status, -- 1 released
2114               DECODE (SUP.order_type, 5,
2115                      -- order type is 5 proceed with further checks
2116                         (DECODE(SUP.firm_planned_type, 1, 1, -- 1 firm, others not firm
2117                           -- order is not firmed proceed with further checks
2118                           -- Bug 3717618 Use "quantity_in_process"
2119                           -- instead of incorrect release_status
2120                             (DECODE(SIGN (NVL(SUP.implemented_quantity, 0) +
2121                                           NVL(SUP.quantity_in_process, 0) -
2122                                           NVL(SUP.firm_quantity,SUP.new_order_quantity)),
2123                              0, 1, -- equal then flag as released
2124                              1, 1, -- positive then flag as released
2125                              0)) -- 0 otherwise not released.
2126                           -- End Bug 3717618
2127                          )),
2128                       1) exclude_flag,    -- All other cases exclude
2129               peg2.end_pegging_id, peg2.pegging_id,  peg2.prev_pegging_id,
2130               NULL fcst_organization_id, NULL forecast_qty,
2131               NULL consumed_qty, NULL overconsumption_qty
2132       FROM
2133               msc_demands d1,
2134               msc_full_pegging peg1 ,
2135               msc_full_pegging peg2 ,
2136               msc_supplies SUP,
2137               msc_system_items msi
2138       WHERE   d1.plan_id = p_plan_id
2139       AND     d1.sr_instance_id = c_items_rec.sr_instance_id
2140       AND     d1.inventory_item_id = c_items_rec.inventory_item_id
2141       AND     d1.origination_type IN (6,30)
2142       AND     d1.sales_order_line_id = c_items_rec.sales_order_line_id
2143       AND     decode(d1.demand_source_type,100,d1.demand_source_type,-1)
2144               =decode(c_items_rec.demand_source_type,
2145                                                 100,
2146                                                 c_items_rec.demand_source_type,
2147                                                 -1) --cmro
2148       AND     peg1.plan_id = d1.plan_id
2149       AND     peg1.sr_instance_id = d1.sr_instance_id
2150       AND     peg1.organization_id = d1.organization_id
2151       AND     peg1.demand_id = d1.demand_id
2152       AND     peg2.plan_id = peg1.plan_id
2153       AND     peg2.end_pegging_id = peg1.pegging_id
2154       -- Bug 3344032 On further investigation the outer join will not be needed.
2155       -- since the sr_instance_id join can be commented out.
2156       --AND     peg2.sr_instance_id = peg1.sr_instance_id (+) -- outer join to get all instances
2157       --  Bug 3319810 Match the item_id as well.
2158       AND     peg2.inventory_item_id = peg1.inventory_item_id
2159               -- Get the supplies corresponding to pegging
2160       AND     SUP.transaction_id = peg2.transaction_id
2161       AND     SUP.plan_id = peg2.plan_id
2162       AND     SUP.sr_instance_id = peg2.sr_instance_id
2163       AND     SUP.organization_id = peg2.organization_id
2164               -- Join to msc_system_items to filter out items
2165               -- from the pegging.
2166       AND     msi.plan_id = SUP.plan_id
2167       AND     msi.sr_instance_id = SUP.sr_instance_id
2168       AND     msi.inventory_item_id = SUP.inventory_item_id
2169       AND     msi.organization_id  = SUP.organization_id
2170               -- Restrict supplies to items that are configuration items
2171       AND     msi.bom_item_type = 4
2172       AND     msi.base_item_id is not null
2173       AND     msi.replenish_to_order_flag = 'Y'
2174       -- Bug 3717618 Remove exclusion of firmed or released supplies here.
2175       -- This will be handled during creation of Offset Data.
2176       -- This data is needed for getting the pegging chain.
2177       -- AND     DECODE (SUP.order_type, 5,
2178                      -- order type is 5 proceed with further checks
2179       --                   (DECODE(SUP.firm_planned_type, 1, 1, -- 1 firm, others not firm
2180                           -- order is not firmed proceed with further checks
2181       --                       (DECODE(SIGN (NVL(SUP.implemented_quantity, 0) +
2182       --                                     NVL(SUP.quantity_in_process, 0) -
2183       --                                     NVL(SUP.firm_quantity,SUP.new_order_quantity)),
2184       --                        0, 1, -- equal then flag as released
2185       --                        1, 1, -- positive then flag as released
2186       --                        0)) -- 0 otherwise not released.
2187       --                    )),
2188       --                 1)  <> 1   -- Exclude un-necessary supplies.
2189       -- End Bug 3717618
2190       ;
2191 
2192       IF PG_DEBUG in ('Y', 'C') THEN
2193         msc_util.msc_log('Gen_Atp_Pegging : Stage 1 ' );
2194         msc_util.msc_log('Gen_Atp_Pegging : Rows Procesed ' || SQL%ROWCOUNT );
2195       END IF;
2196 
2197       -- Update Pegging data with End demand Id. Information
2198       -- CTO_PF_PRJ changes.
2199 
2200       UPDATE MSC_ATP_DETAIL_PEG_TEMP madpt -- outer table
2201        SET
2202        (end_demand_id
2203        ) =
2204        (  SELECT  end_demand_id
2205           FROM    msc_atp_detail_peg_temp madpti -- Inner table
2206           WHERE   madpti.plan_id = madpt.plan_id
2207           AND     madpti.sr_instance_id = madpt.sr_instance_id
2208           AND     madpti.reference_item_id =  madpt.inventory_item_id
2209           AND     madpti.sales_order_line_id = madpt.sales_order_line_id
2210           AND     madpti.demand_source_type = madpt.demand_source_type
2211           AND     madpti.pegging_id = madpt.end_pegging_id
2212           AND     madpti.prev_pegging_id IS NULL
2213        )
2214        WHERE   madpt.plan_id = p_plan_id
2215        AND     madpt.sr_instance_id = c_items_rec.sr_instance_id
2216        AND     madpt.reference_item_id =  c_items_rec.inventory_item_id
2217        AND     madpt.sales_order_line_id = c_items_rec.sales_order_line_id
2218        AND     madpt.demand_source_type
2219                =decode(c_items_rec.demand_source_type,
2220                                                 100,
2221                                                 c_items_rec.demand_source_type,
2222                                                 -1)  -- CMRO
2223       ;
2224 
2225       IF PG_DEBUG in ('Y', 'C') THEN
2226         msc_util.msc_log('Gen_Atp_Pegging : Rows Procesed ' || SQL%ROWCOUNT );
2227       END IF;
2228 
2229       -- Update Pegging data with demand Information
2230 
2231       UPDATE MSC_ATP_DETAIL_PEG_TEMP madpt
2232        SET
2233        (demand_id,
2234        demand_date,
2235        demand_quantity,
2236        disposition_id,
2237        demand_class,
2238        demand_type,
2239        original_demand_id,
2240        order_number
2241        ) =
2242        -- Bug 3550296 and 3574164. IMPLEMENT_DATE AND DMD_SATISFIED_DATE are changed to
2243        -- IMPLEMENT_SHIP_DATE and PLANNED_SHIP_DATE resp.
2244        (  SELECT d.demand_id,
2245           decode(MSC_ATP_PVT.G_HP_DEMAND_BUCKETING_PREF,
2246                  2, NVL(D.PLANNED_SHIP_DATE,D.USING_ASSEMBLY_DEMAND_DATE),
2247                     NVL(D.SCHEDULE_SHIP_DATE,D.USING_ASSEMBLY_DEMAND_DATE)) demand_date,
2248                     -- plan by request date
2249           decode(d.origination_type, 4, d.daily_demand_rate,
2250                               d.using_requirement_quantity) demand_quantity,
2251           -- Bug 3319810 Set the disposition_id for top level supply pegging.
2252           NVL(d.disposition_id, peg.transaction_id) disposition_id,
2253           NVL(d.demand_class, '-1') demand_class,
2254           d.origination_type,
2255           NVL(d.original_demand_id, d.demand_id) original_demand_id,
2256           decode(d.origination_type, 1,
2257                     to_char(d.disposition_id), d.order_number)
2258           FROM       --msc_atp_detail_peg_temp madpt,
2259               msc_full_pegging peg,
2260               msc_demands d
2261           WHERE   madpt.plan_id = p_plan_id
2262           AND     madpt.sr_instance_id = c_items_rec.sr_instance_id
2263           AND     madpt.reference_item_id =  c_items_rec.inventory_item_id
2264           AND     madpt.sales_order_line_id = c_items_rec.sales_order_line_id
2265           AND     decode(madpt.demand_source_type,100,madpt.demand_source_type,-1)
2266                   = decode(c_items_rec.demand_source_type,
2267                                                 100,
2268                                                 c_items_rec.demand_source_type,
2269                                                 -1) --CMRO
2270           AND     peg.plan_id = madpt.plan_id
2271           AND     peg.sr_instance_id = madpt.sr_instance_id
2272           AND     peg.organization_id = madpt.organization_id
2273           AND     peg.pegging_id = madpt.pegging_id
2274           AND     peg.end_pegging_id = madpt.end_pegging_id
2275           AND     peg.inventory_item_id = madpt.inventory_item_id
2276               -- Get the demands corresponding to pegging
2277           AND     d.plan_id = peg.plan_id
2278           AND     d.sr_instance_id = peg.sr_instance_id
2279           AND     d.organization_id = peg.organization_id
2280           AND     d.inventory_item_id = peg.inventory_item_id
2281           AND     d.demand_id = peg.demand_id)
2282        WHERE   madpt.plan_id = p_plan_id
2283        AND     madpt.sr_instance_id = c_items_rec.sr_instance_id
2284        AND     madpt.reference_item_id =  c_items_rec.inventory_item_id
2285        AND     madpt.sales_order_line_id = c_items_rec.sales_order_line_id
2286        AND     decode(madpt.demand_source_type,100,madpt.demand_source_type,-1)
2287                =decode(c_items_rec.demand_source_type,
2288                                                 100,
2289                                                 c_items_rec.demand_source_type,
2290                                                 -1)  -- CMRO
2291        -- Bug 3750638
2292        -- Collect Supplies into Supplies PL/SQL Array.
2293        RETURNING
2294                  inventory_item_id,
2295                  sr_instance_id,
2296                  base_item_id,
2297                  sales_order_line_id,
2298                  demand_source_type,
2299                  end_demand_id,
2300                  supply_id,
2301                  pegging_id,
2302                  end_pegging_id
2303        BULK COLLECT INTO
2304                  L_Config_Sup.INVENTORY_ITEM_ID,
2305                  L_Config_Sup.SR_INSTANCE_ID,
2306                  L_Config_Sup.BASE_ITEM_ID,
2307                  L_Config_Sup.SALES_ORDER_LINE_ID,
2308                  L_Config_Sup.DEMAND_SOURCE_TYPE,
2309                  L_Config_Sup.END_DEMAND_ID,
2310                  L_Config_Sup.SUPPLY_ID,
2311                  L_Config_Sup.PEGGING_ID,
2312                  L_Config_Sup.END_PEGGING_ID
2313        ;
2314        -- End Bug 3750638
2315        -- Bug 3362558 Fetch the original_demand_id
2316        -- CTO_PF_PRJ changes.
2317        -- RETURNING madpt.original_demand_id BULK COLLECT INTO l_original_demand_ids;
2318        -- Commented out, since with the introduction of end_demand_id field,
2319        -- fetch into l_original_demand_id is not necessary.
2320 
2321 
2322       IF PG_DEBUG in ('Y', 'C') THEN
2323         msc_util.msc_log('Gen_Atp_Pegging : Stage 2 ' );
2324         msc_util.msc_log('Gen_Atp_Pegging : Rows Procesed ' || SQL%ROWCOUNT );
2325       END IF;
2326 
2327 
2328       -- Bug 3750638 Initialize the Count of Items to be processed.
2329       l_multi_config_count := L_Config_Sup.INVENTORY_ITEM_ID.COUNT;
2330       l_config_level := 1;
2331 
2332       -- Bug 3750638 Place the next couple of SQLs in a LOOP for processing
2333       -- N levels of Configuration Items.
2334       WHILE l_multi_config_count > 0 LOOP
2335          -- Bug 3750638 Introduce FORALL loop for processing Config Items.
2336         IF PG_DEBUG in ('Y', 'C') THEN
2337           msc_util.msc_log('Gen_Atp_Pegging : Total Config Items ' ||
2338                         'l_multi_config_count ' || l_multi_config_count);
2339         END IF;
2340         FOR n_idx IN 1..l_multi_config_count LOOP
2341             IF PG_DEBUG in ('Y', 'C') THEN
2342                msc_util.msc_log('Gen_Atp_Pegging : Config Instance_Id ' ||
2343                                         L_Config_Sup.SR_INSTANCE_ID(n_idx) );
2344                msc_util.msc_log('Gen_Atp_Pegging : Config Item_Id ' ||
2345                                         L_Config_Sup.INVENTORY_ITEM_ID(n_idx) );
2346                msc_util.msc_log('Gen_Atp_Pegging : Config Supply_Id ' ||
2347                                         L_Config_Sup.SUPPLY_ID(n_idx) );
2348                msc_util.msc_log('Gen_Atp_Pegging : Config Base_Item_Id ' ||
2349                                         L_Config_Sup.BASE_ITEM_ID(n_idx) );
2350                msc_util.msc_log('Gen_Atp_Pegging : Config Pegging_Id ' ||
2351                                         L_Config_Sup.PEGGING_ID(n_idx) );
2352                msc_util.msc_log('Gen_Atp_Pegging : Config End_Pegging_Id ' ||
2353                                         L_Config_Sup.END_PEGGING_ID(n_idx) );
2354             END IF;
2355         END LOOP;
2356 
2357         -- First obtain transfers if any.
2358         FORALL n_idx IN 1..l_multi_config_count
2359            INSERT INTO MSC_ATP_DETAIL_PEG_TEMP (
2360                  reference_item_id, base_item_id,
2361                  inventory_item_id,
2362                  plan_id,
2363                  sr_instance_id,
2364                  organization_id,
2365                  end_item_usage,
2366                  bom_item_type, fixed_lt, variable_lt,
2367                  sales_order_line_id,
2368                  demand_source_type,--cmro
2369                  -- CTO_PF_PRJ changes.
2370                  end_demand_id,
2371                  -- CTO-PF
2372                  atf_date,
2373                  product_family_id,
2374                  sales_order_qty,
2375                  demand_id,
2376                  demand_date,
2377                  demand_quantity,
2378                  disposition_id,
2379                  demand_class,
2380                  demand_type,
2381                  original_demand_id,
2382                  process_seq_id, supply_id,
2383                  supply_date,
2384                  supply_quantity,
2385                  allocated_quantity, tot_relief_qty,
2386                  supply_type,
2387                  firm_planned_type,
2388                  release_status,
2389                  exclude_flag,    -- All other cases exclude
2390                  order_number,
2391                  end_pegging_id, pegging_id,  prev_pegging_id,
2392                  fcst_organization_id, forecast_qty,
2393                  consumed_qty, overconsumption_qty )
2394          SELECT
2395                  adpt.reference_item_id, msi.base_item_id,
2396                  peg1.inventory_item_id,
2397                  peg1.plan_id,
2398                  peg1.sr_instance_id,
2399                  peg1.organization_id,
2400                  peg1.end_item_usage,
2401                  msi.bom_item_type, msi.fixed_lead_time, msi.variable_lead_time,
2402                  adpt.sales_order_line_id,
2403                  adpt.demand_source_type,--cmro
2404                  -- CTO_PF_PRJ changes.
2405                  adpt.end_demand_id,
2406                  -- CTO-PF
2407                  msi.aggregate_time_fence_date,
2408                  msi.product_family_id,
2409                  NULL sales_order_qty, -- will be used to factor sales_order_qty,
2410                  d1.demand_id,
2411                  -- Bug 3550296 and 3574164. IMPLEMENT_DATE AND DMD_SATISFIED_DATE are changed to
2412                  -- IMPLEMENT_SHIP_DATE and PLANNED_SHIP_DATE resp.
2413                  DECODE(
2414                          d1.RECORD_SOURCE,
2415                          2,
2416              	         NVL(d1.SCHEDULE_SHIP_DATE,d1.USING_ASSEMBLY_DEMAND_DATE),
2417                	         DECODE(MSC_ATP_PVT.G_HP_DEMAND_BUCKETING_PREF,
2418               	         2,
2419               	         (NVL(d1.IMPLEMENT_SHIP_DATE,NVL(d1.FIRM_DATE,NVL(d1.PLANNED_SHIP_DATE,d1.USING_ASSEMBLY_DEMAND_DATE)))),
2420                          NVL(d1.SCHEDULE_SHIP_DATE,d1.USING_ASSEMBLY_DEMAND_DATE))), --plan by request Date, Promise Date Scheduled Date
2421                  decode(d1.origination_type, 4, d1.daily_demand_rate,
2422                                      d1.using_requirement_quantity) demand_quantity,
2423                  d1.disposition_id,
2424                  NVL(d1.demand_class, adpt.demand_class) demand_class,
2425                  d1.origination_type,
2426                  -- Bug 3362558 use pegging's original demand_id
2427                  NVL(d1.original_demand_id, adpt.original_demand_id) original_demand_id,
2428                  -- Begin Bug 3319810
2429                  -- Use pegging's supply data instead of msc_atp_detail_peg_temp.
2430                  adpt.process_seq_id,
2431                  --adpt.supply_id,
2432                  --adpt.supply_date,
2433                  --adpt.supply_quantity,
2434                  --adpt.allocated_quantity, NULL tot_relief_qty,
2435                  --adpt.supply_type,
2436                  peg1.transaction_id supply_id,
2437                  -- Bug 3750638 Keep the supply date NULL for configs.
2438                  DECODE(NVL(msi.base_item_id, -2353), -2353,  peg1.supply_date, NULL) supply_date,
2439                  peg1.supply_quantity,
2440                  peg1.allocated_quantity, NULL tot_relief_qty,
2441                  peg1.supply_type,
2442                  -- End Bug 3319810
2443                  adpt.firm_planned_type,
2444                  adpt.release_status, -- 1 released
2445                  0 exclude_flag,    -- Include the demands as a default.
2446                  decode(d1.origination_type, 1, to_char(d1.disposition_id), d1.order_number) order_number,
2447                  peg1.end_pegging_id, peg1.pegging_id,  peg1.prev_pegging_id,
2448                  NULL fcst_organization_id, NULL forecast_qty,
2449                  NULL consumed_qty, NULL overconsumption_qty
2450          FROM
2451                  msc_atp_detail_peg_temp adpt,
2452                  msc_full_pegging peg1 ,
2453                  msc_demands d1,
2454                  msc_system_items msi
2455          WHERE   adpt.plan_id = p_plan_id
2456          AND     adpt.reference_item_id = c_items_rec.inventory_item_id
2457          AND     adpt.sales_order_line_id = c_items_rec.sales_order_line_id
2458          AND     decode(adpt.demand_source_type,100,adpt.demand_source_type,-1)
2459                  =decode(c_items_rec.demand_source_type,
2460                                                    100,
2461                                                    c_items_rec.demand_source_type,
2462                                                    -1) --CMRO
2463          -- Bug 3750638 Apply Config Item Array Filters
2464          AND     adpt.sr_instance_id = L_Config_Sup.SR_INSTANCE_ID(n_idx) -- outer join to get all instances
2465          AND     adpt.inventory_item_id = L_Config_Sup.INVENTORY_ITEM_ID(n_idx)
2466          AND     adpt.supply_id = L_Config_Sup.SUPPLY_ID(n_idx)
2467          AND     adpt.end_demand_id = L_Config_Sup.END_DEMAND_ID(n_idx)
2468          AND     adpt.pegging_id = L_Config_Sup.PEGGING_ID(n_idx)
2469          AND     adpt.end_pegging_id = L_Config_Sup.END_PEGGING_ID(n_idx)
2470          AND     adpt.base_item_id = L_Config_Sup.BASE_ITEM_ID(n_idx)
2471          AND     adpt.inventory_item_id <> adpt.reference_item_id
2472          -- End Bug 3750638
2473                  -- Link up pegging with config_item info in msc_atp_detail_peg_temp.
2474          AND     peg1.plan_id = adpt.plan_id
2475          AND     peg1.sr_instance_id = adpt.sr_instance_id
2476          AND     peg1.end_pegging_id = adpt.end_pegging_id
2477          AND     peg1.prev_pegging_id = adpt.pegging_id
2478          AND     peg1.inventory_item_id = adpt.inventory_item_id
2479          -- End Bug 3750638 Supply filter
2480          -- AND     peg1.supply_type = 5
2481                  -- Further control if necessary for performance will be added later.
2482                  -- AND peg1.transaction_id = adpt.supply_id
2483                  -- Get the demands corresponding to pegging
2484          AND     d1.plan_id = peg1.plan_id
2485          AND     d1.sr_instance_id = peg1.sr_instance_id
2486          AND     d1.organization_id = peg1.organization_id
2487          AND     d1.demand_id = peg1.demand_id
2488          -- Bug 3750638 The lower level item could also be sourced from muliple orgs.
2489          -- AND     d1.inventory_item_id <> adpt.inventory_item_id
2490                  -- Get all the items which peg to the supply using the disposition_id.
2491          AND     d1.disposition_id = adpt.supply_id
2492          AND     d1.using_requirement_quantity > 0
2493                  -- Join to msc_system_items to get items data
2494          AND     msi.plan_id = d1.plan_id
2495          AND     msi.sr_instance_id = d1.sr_instance_id
2496          AND     msi.inventory_item_id = d1.inventory_item_id
2497          AND     msi.organization_id  = d1.organization_id
2498          ;
2499 
2500          n_row_count := SQL%ROWCOUNT;
2501          IF PG_DEBUG in ('Y', 'C') THEN
2502            msc_util.msc_log('Gen_Atp_Pegging : Transfer of config n_row_count ' || n_row_count);
2503          END IF;
2504            -- Obtain the data for the components of the lower level configuration item(s)
2505            -- in the sales order.
2506         FORALL n_idx IN 1..l_multi_config_count
2507            INSERT INTO MSC_ATP_DETAIL_PEG_TEMP (
2508                  reference_item_id, base_item_id,
2509                  inventory_item_id,
2510                  plan_id,
2511                  sr_instance_id,
2512                  organization_id,
2513                  end_item_usage,
2514                  bom_item_type, fixed_lt, variable_lt,
2515                  sales_order_line_id,
2516                  demand_source_type,--cmro
2517                  -- CTO_PF_PRJ changes.
2518                  end_demand_id,
2519                  -- CTO-PF
2520                  atf_date,
2521                  product_family_id,
2522                  sales_order_qty,
2523                  demand_id,
2524                  demand_date,
2525                  demand_quantity,
2526                  disposition_id,
2527                  demand_class,
2528                  demand_type,
2529                  original_demand_id,
2530                  process_seq_id, supply_id,
2531                  supply_date,
2532                  supply_quantity,
2533                  allocated_quantity, tot_relief_qty,
2534                  supply_type,
2535                  firm_planned_type,
2536                  release_status,
2537                  exclude_flag,    -- All other cases exclude
2538                  order_number,
2539                  end_pegging_id, pegging_id,  prev_pegging_id,
2540                  fcst_organization_id, forecast_qty,
2541                  consumed_qty, overconsumption_qty )
2542          SELECT
2543                  adpt.reference_item_id, msi.base_item_id,
2544                  peg1.inventory_item_id,
2545                  peg1.plan_id,
2546                  peg1.sr_instance_id,
2547                  peg1.organization_id,
2548                  peg1.end_item_usage,
2549                  msi.bom_item_type, msi.fixed_lead_time, msi.variable_lead_time,
2550                  adpt.sales_order_line_id,
2551                  adpt.demand_source_type,--cmro
2552                  -- CTO_PF_PRJ changes.
2553                  adpt.end_demand_id,
2554                  -- CTO-PF
2555                  msi.aggregate_time_fence_date,
2556                  msi.product_family_id,
2557                  NULL sales_order_qty, -- will be used to factor sales_order_qty,
2558                  d1.demand_id,
2559                  -- Bug 3550296 and 3574164. IMPLEMENT_DATE AND DMD_SATISFIED_DATE are changed to
2560                  -- IMPLEMENT_SHIP_DATE and PLANNED_SHIP_DATE resp.
2561                  DECODE(
2562                          d1.RECORD_SOURCE,
2563                          2,
2564              	         NVL(d1.SCHEDULE_SHIP_DATE,d1.USING_ASSEMBLY_DEMAND_DATE),
2565                	         DECODE(MSC_ATP_PVT.G_HP_DEMAND_BUCKETING_PREF,
2566               	         2,
2567               	         (NVL(d1.IMPLEMENT_SHIP_DATE,NVL(d1.FIRM_DATE,NVL(d1.PLANNED_SHIP_DATE,d1.USING_ASSEMBLY_DEMAND_DATE)))),
2568                          NVL(d1.SCHEDULE_SHIP_DATE,d1.USING_ASSEMBLY_DEMAND_DATE))), --plan by request Date, Promise Date Scheduled Date
2569                  decode(d1.origination_type, 4, d1.daily_demand_rate,
2570                                      d1.using_requirement_quantity) demand_quantity,
2571                  d1.disposition_id,
2572                  NVL(d1.demand_class, adpt.demand_class) demand_class,
2573                  d1.origination_type,
2574                  -- Bug 3362558 use pegging's original demand_id
2575                  NVL(d1.original_demand_id, adpt.original_demand_id) original_demand_id,
2576                  -- Begin Bug 3319810
2577                  -- Use pegging's supply data instead of msc_atp_detail_peg_temp.
2578                  adpt.process_seq_id,
2579                  --adpt.supply_id,
2580                  --adpt.supply_date,
2581                  --adpt.supply_quantity,
2582                  --adpt.allocated_quantity, NULL tot_relief_qty,
2583                  --adpt.supply_type,
2584                  peg1.transaction_id supply_id,
2585                  -- Bug 3750638 Keep the supply date NULL for configs.
2586                  DECODE(NVL(msi.base_item_id, -2353), -2353,  peg1.supply_date, NULL) supply_date,
2587                  peg1.supply_quantity,
2588                  peg1.allocated_quantity, NULL tot_relief_qty,
2589                  peg1.supply_type,
2590                  -- End Bug 3319810
2591                  adpt.firm_planned_type,
2592                  adpt.release_status, -- 1 released
2593                  0 exclude_flag,    -- Include the demands as a default.
2594                  decode(d1.origination_type, 1, to_char(d1.disposition_id), d1.order_number) order_number,
2595                  peg1.end_pegging_id, peg1.pegging_id,  peg1.prev_pegging_id,
2596                  NULL fcst_organization_id, NULL forecast_qty,
2597                  NULL consumed_qty, NULL overconsumption_qty
2598          FROM
2599                  msc_atp_detail_peg_temp adpt,
2600                  msc_full_pegging peg1 ,
2601                  msc_demands d1,
2602                  msc_system_items msi,
2603                  msc_process_effectivity proc,
2604                  msc_bom_components mbc
2605          WHERE   adpt.plan_id = p_plan_id
2606          AND     adpt.reference_item_id = c_items_rec.inventory_item_id
2607          AND     adpt.sales_order_line_id = c_items_rec.sales_order_line_id
2608          AND     decode(adpt.demand_source_type,100,adpt.demand_source_type,-1)
2609                  =decode(c_items_rec.demand_source_type,
2610                                                    100,
2611                                                    c_items_rec.demand_source_type,
2612                                                    -1) --CMRO
2613          -- Bug 3750638 Apply Config Item Array Filters
2614          AND     adpt.sr_instance_id = L_Config_Sup.SR_INSTANCE_ID(n_idx) -- outer join to get all instances
2615          AND     adpt.inventory_item_id = L_Config_Sup.INVENTORY_ITEM_ID(n_idx)
2616          AND     adpt.supply_id = L_Config_Sup.SUPPLY_ID(n_idx)
2617          AND     adpt.end_demand_id = L_Config_Sup.END_DEMAND_ID(n_idx)
2618          AND     adpt.pegging_id = L_Config_Sup.PEGGING_ID(n_idx)
2619          AND     adpt.end_pegging_id = L_Config_Sup.END_PEGGING_ID(n_idx)
2620          AND     adpt.base_item_id = L_Config_Sup.BASE_ITEM_ID(n_idx)
2621          AND     adpt.supply_date is not NULL
2622          -- End Bug 3750638
2623                  -- Link up pegging with config_item info in msc_atp_detail_peg_temp.
2624          AND     peg1.plan_id = adpt.plan_id
2625          AND     peg1.sr_instance_id = adpt.sr_instance_id
2626          AND     peg1.end_pegging_id = adpt.end_pegging_id
2627          AND     peg1.prev_pegging_id = adpt.pegging_id
2628          AND     peg1.inventory_item_id <> adpt.reference_item_id
2629          -- End Bug 3750638 Supply filter
2630          -- AND     peg1.supply_type = 5
2631                  -- Further control if necessary for performance will be added later.
2632                  -- AND peg1.transaction_id = adpt.supply_id
2633                  -- Get the demands corresponding to pegging
2634          AND     d1.plan_id = peg1.plan_id
2635          AND     d1.sr_instance_id = peg1.sr_instance_id
2636          AND     d1.organization_id = peg1.organization_id
2637          AND     d1.demand_id = peg1.demand_id
2638          -- Bug 3750638 The lower level item could also be sourced from muliple orgs.
2639          -- AND     d1.inventory_item_id <> adpt.inventory_item_id
2640                  -- Get all the items which peg to the supply using the disposition_id.
2641          AND     d1.disposition_id = adpt.supply_id
2642          AND     d1.using_requirement_quantity > 0
2643                  -- Join to msc_system_items to get items data
2644          AND     msi.plan_id = d1.plan_id
2645          AND     msi.sr_instance_id = d1.sr_instance_id
2646          AND     msi.inventory_item_id = d1.inventory_item_id
2647          AND     msi.organization_id  = d1.organization_id
2648          --   Join to msc_process_effectivity to get the bill sequence
2649          AND     proc.plan_id = adpt.plan_id
2650          AND     proc.process_sequence_id = adpt.process_seq_id
2651          --   Join to msc_bom_components to exclude any exploded items underneath phantoms
2652          AND     mbc.plan_id = msi.plan_id
2653          AND     mbc.sr_instance_id = msi.sr_instance_id
2654          AND     mbc.organization_id = msi.organization_id
2655          AND     mbc.bill_sequence_id = proc.bill_sequence_id
2656                      -- manufacture in same org.
2657          AND     mbc.inventory_item_id = msi.inventory_item_id
2658          AND     mbc.using_assembly_id = adpt.inventory_item_id
2659          AND     mbc.organization_id = adpt.organization_id
2660          ;
2661          -- End Bug 3750638 -- FORALL loop
2662 
2663        select hsecs
2664        into   l_timestamp
2665        from   v$timer;
2666 
2667          -- Bug 3750638 Get the total number of records.
2668          n_row_count := SQL%ROWCOUNT;
2669 
2670          IF PG_DEBUG in ('Y', 'C') THEN
2671            msc_util.msc_log('Gen_Atp_Pegging : Stage 3 ' );
2672            msc_util.msc_log('Gen_Atp_Pegging : Components of config n_row_count ' || n_row_count);
2673            msc_util.msc_log('Gen_Atp_Pegging : TIMESTAMP 2 ' || l_timestamp);
2674          END IF;
2675 
2676 
2677          -- update the supplies for the new demands
2678          UPDATE MSC_ATP_DETAIL_PEG_TEMP madpt
2679           SET
2680           ( process_seq_id, supply_id,
2681             supply_date,
2682             supply_quantity,
2683             allocated_quantity, tot_relief_qty,
2684             supply_type,
2685             firm_planned_type,
2686             release_status,
2687             exclude_flag
2688           ) =
2689           (  SELECT SUP.process_seq_id, SUP.transaction_id supply_id,
2690                     SUP.new_schedule_date supply_date,
2691                     SUP.new_order_quantity supply_qty,
2692                     peg.allocated_quantity, NULL tot_relief_qty,
2693                     SUP.order_type,
2694                     SUP.firm_planned_type,
2695                     SUP.release_status, -- 1 released
2696                     DECODE (SUP.order_type, 5,
2697                         -- order type is 5 proceed with further checks
2698                         (DECODE(SUP.firm_planned_type, 1, 1, -- 1 firm, others not firm
2699                         -- order is not firmed proceed with further checks
2700                              -- Bug 3717618 Use "quantity_in_process"
2701                              -- instead of incorrect release_status
2702                              (DECODE(SIGN (NVL(SUP.implemented_quantity, 0) +
2703                                            NVL(SUP.quantity_in_process, 0) -
2704                                            NVL(SUP.firm_quantity,SUP.new_order_quantity)),
2705                                 0, 1, -- equal then flag as released
2706                                 1, 1, -- positive then flag as released
2707                                 0)) -- 0 otherwise not released.
2708                              -- End Bug 3717618
2709                           )),
2710                         1) exclude_flag
2711              FROM       --msc_atp_detail_peg_temp madpt,
2712                  msc_full_pegging peg,
2713                  msc_supplies SUP
2714              WHERE   madpt.plan_id = p_plan_id
2715              AND     madpt.sr_instance_id = c_items_rec.sr_instance_id
2716              AND     madpt.reference_item_id =  c_items_rec.inventory_item_id
2717              AND     madpt.sales_order_line_id = c_items_rec.sales_order_line_id
2718              AND     decode(madpt.demand_source_type,100,madpt.demand_source_type,-1)
2719                      =decode(c_items_rec.demand_source_type,
2720                                                    100,
2721                                                    c_items_rec.demand_source_type,
2722                                                    -1) --CMRO
2723              AND     madpt.inventory_item_id <> madpt.reference_item_id
2724              -- Bug 3750638
2725              -- Date is used to filter out other records.
2726              AND     madpt.supply_date IS NULL
2727              AND     peg.plan_id = madpt.plan_id
2728              AND     peg.sr_instance_id = madpt.sr_instance_id
2729              AND     peg.organization_id = madpt.organization_id
2730              AND     peg.pegging_id = madpt.pegging_id
2731              AND     peg.end_pegging_id = madpt.end_pegging_id
2732              AND     peg.inventory_item_id = madpt.inventory_item_id
2733                      -- Bug 3750638 also filter on supply_id
2734              AND     peg.transaction_id = madpt.supply_id
2735                      -- Get the supplies corresponding to pegging
2736              AND     SUP.plan_id = peg.plan_id
2737              AND     SUP.sr_instance_id = peg.sr_instance_id
2738              AND     SUP.organization_id = peg.organization_id
2739              AND     SUP.inventory_item_id = peg.inventory_item_id
2740              AND     SUP.order_type = 5
2741              AND     SUP.transaction_id = peg.transaction_id )
2742           WHERE   madpt.plan_id = p_plan_id
2743           -- Bug 3750638 Comment out sr_instance_id to support multi-instance plans.
2744           AND     madpt.sr_instance_id = c_items_rec.sr_instance_id
2745           AND     madpt.reference_item_id =  c_items_rec.inventory_item_id
2746           AND     madpt.sales_order_line_id = c_items_rec.sales_order_line_id
2747           AND     decode(madpt.demand_source_type,100,madpt.demand_source_type,-1)
2748                   =decode(c_items_rec.demand_source_type,
2749                                                    100,
2750                                                    c_items_rec.demand_source_type,
2751                                                    -1) --CMRO;
2752           AND     madpt.inventory_item_id <> madpt.reference_item_id
2753           -- Bug 3750638
2754           -- Date is used to filter out other records.
2755           AND     madpt.supply_date IS NULL
2756           AND     madpt.supply_type = 5
2757           -- Other filtering conditions that may potentially be added include end_demand_id
2758           -- Collect Supplies into Supplies PL/SQL Array.
2759           RETURNING
2760                   inventory_item_id,
2761                   sr_instance_id,
2762                   base_item_id,
2763                   sales_order_line_id,
2764                   demand_source_type,
2765                   end_demand_id,
2766                   supply_id,
2767                   pegging_id,
2768                   end_pegging_id
2769           BULK COLLECT INTO
2770                   L_Config_Sup.INVENTORY_ITEM_ID,
2771                   L_Config_Sup.SR_INSTANCE_ID,
2772                   L_Config_Sup.BASE_ITEM_ID,
2773                   L_Config_Sup.SALES_ORDER_LINE_ID,
2774                   L_Config_Sup.DEMAND_SOURCE_TYPE,
2775                   L_Config_Sup.END_DEMAND_ID,
2776                   L_Config_Sup.SUPPLY_ID,
2777                   L_Config_Sup.PEGGING_ID,
2778                   L_Config_Sup.END_PEGGING_ID
2779           ;
2780           -- End Bug 3750638
2781 
2782           -- Bug 3750638 Re-set the Count of Items to be processed.
2783           l_multi_config_count := L_Config_Sup.INVENTORY_ITEM_ID.COUNT;
2784           l_config_level := l_config_level + 1;
2785 
2786           IF PG_DEBUG in ('Y', 'C') THEN
2787             msc_util.msc_log('Gen_Atp_Pegging : Stage 4 ' );
2788             msc_util.msc_log('Gen_Atp_Pegging : Rows Procesed ' || SQL%ROWCOUNT );
2789             -- Bug 3750638 Print Out value of variables.
2790             msc_util.msc_log('Gen_Atp_Pegging : l_multi_config_count ' || l_multi_config_count );
2791             msc_util.msc_log('Gen_Atp_Pegging : l_config_level ' || l_config_level );
2792           END IF;
2793 
2794       END LOOP;
2795       -- End Bug 3750638
2796 
2797 EXCEPTION
2798     WHEN OTHERS THEN
2799       IF PG_DEBUG in ('Y', 'C') THEN
2800         msc_util.msc_log ('Get_Pegging_Data_Loop. Error : ' || sqlcode || ': ' || sqlerrm);
2801       END IF;
2802       x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
2803 
2804 END Get_Pegging_Data_Loop;
2805 -- End Bug 3750638 Move all the pegging releated SQLs into this procedure.
2806 
2807 -- This procedure is the main procedure that creates the ATP simplified pegging
2808 -- and stores it into the msc_atp_pegging table after plan run.
2809 PROCEDURE Generate_Simplified_Pegging(p_plan_id         IN          NUMBER,
2810                                       p_share_partition IN          VARCHAR2,
2811                                       p_applsys_schema  IN          VARCHAR2,
2812                                       RETCODE           OUT  NoCopy NUMBER   )
2813 IS
2814 
2815 l_count                         number;
2816 l_row_count                     number;
2817 l_tot_count                     NUMBER;
2818 l_partition_name                varchar2(30);
2819 l_sql_stmt                      varchar2(800); -- Bug 3344012 expand size.
2820 l_sql_stmt_1                    varchar2(8000);
2821 l_sql_stmt_2                    varchar2(8000); --CTO-PF
2822 l_ret_code                      NUMBER;
2823 l_err_msg                       VARCHAR2(1000);
2824 l_ind_tbspace                   VARCHAR2(30);
2825 l_insert_stmt                   VARCHAR2(8000);
2826 l_msc_schema                    VARCHAR2(30);
2827 l_sysdate                       date;
2828 l_user_id                       number;
2829 l_table_name                    VARCHAR2(30);
2830 l_tbspace                       VARCHAR2(30);
2831 l_temp_table                    VARCHAR2(30);
2832 atp_simple_peg_tab              MRP_ATP_PUB.char30_arr := MRP_ATP_PUB.char30_arr(
2833                                                                 'ATP_PEGGING');
2834 l_share_partition               VARCHAR2(1);
2835 l_plan_id                       NUMBER;
2836 l_plan_name                     varchar2(10);
2837 
2838 /* Currently the ATP Pegging Record Types will be defined local to this package. */
2839 -- Records for carrying ATP Pegging information
2840 atp_peg_tab                     ATP_Simple_Peg_Typ;
2841 atp_peg_det                     ATP_Detail_Peg_Typ;
2842 fcst_data_tab                   ATP_Fcst_Cons_Typ;
2843 l_pegging_id                    NUMBER;
2844 
2845 -- Bug 3362558 Store the original_demand_id
2846 -- CTO_PF_PRJ. This array is not needed anymore.
2847 l_original_demand_ids            MRP_ATP_PUB.number_arr := MRP_ATP_PUB.number_arr();
2848 -- CTO-PF
2849 l_time_phased_atp               VARCHAR2(1) := 'N';
2850 -- This cursor fetches the list of configuration_items.
2851 CURSOR config_items IS
2852    SELECT distinct msi.item_name, msi.inventory_item_id, msi.sr_inventory_item_id,
2853           msi.sr_instance_id, msi.base_item_id, d.sales_order_line_id,
2854           decode(d.demand_source_type, 100,  -- cmro fix
2855                        d.demand_source_type, -1) demand_source_type, -- cmro fix
2856           d.demand_class, d.demand_id  -- Bug 3319810 Add the sales_order demand class
2857    FROM   msc_system_items msi, msc_demands d
2858    WHERE  msi.plan_id = p_plan_id
2859    AND    msi.bom_item_type = 4
2860    AND    msi.base_item_id is NOT NULL
2861    AND    msi.replenish_to_order_flag = 'Y'
2862    AND    d.plan_id = msi.plan_id
2863    AND    d.sr_instance_id = msi.sr_instance_id
2864    AND    d.inventory_item_id = msi.inventory_item_id
2865    AND    d.organization_id = msi.organization_id
2866    AND    d.using_requirement_quantity > 0
2867    AND    d.origination_type in (6, 30)
2868  ;
2869       -- conditions to filter out records to be added
2870       -- using replenish_to_order_flag and pick_components_flag
2871 -- Define a corresponding record.
2872 c_items_rec                     ATP_End_Config_Dmd_Typ;
2873 
2874 l_order_org_ratio               NUMBER;
2875 
2876 i                               NUMBER;
2877 j                               NUMBER;
2878 k                               NUMBER;
2879 n                               NUMBER;
2880 rows_processed                  NUMBER;
2881 l_hash_size                     NUMBER := -1;
2882 l_sort_size                     NUMBER := -1;
2883 l_parallel_degree               NUMBER := 1;
2884 l_total_relief_qty              NUMBER;
2885 l_return_status                 VARCHAR2(1);
2886 
2887 l_timestamp                     NUMBER;
2888 
2889 -- Bug 3344102 Use Global Temporary table to store intermediate data.
2890 l_global_temp_table               VARCHAR2(30);
2891 l_insert_temp_table               VARCHAR2(30);
2892 l_ins_sql_stmt                    VARCHAR2(8000);
2893   -- For use as a switch between tables.
2894 
2895 -- Bug 3701093 Flag to control creation of offsets/reliefs/adjustments
2896 -- Values 1 TRUE, otherwise FALSE
2897 G_ADJUST_FLAG                   NUMBER;
2898 -- A Sales Order could be pegged to multiple Plan Orders with
2899 -- multiple end pegging ids.
2900 -- This variable is introduced for better control of the Adjustment process.
2901 L_TOT_RELIEF_QTY                NUMBER;
2902 l_peg_relief_qty                NUMBER;
2903 --bug 3950208
2904 l_err_buf                      varchar2(4000);
2905 l_call_status boolean;
2906 
2907 l_phase            varchar2(80);
2908 l_status           varchar2(80);
2909 l_dev_phase        varchar2(80);
2910 l_dev_status       varchar2(80);
2911 l_message          varchar2(2048);
2912 l_request_id       number;
2913 i                  number;
2914 
2915 BEGIN
2916 
2917   IF PG_DEBUG in ('Y', 'C') THEN
2918     msc_util.msc_log('***** Begin Generate_Simplified_Pegging (Gen_Atp_Pegging) *****');
2919     msc_util.msc_log('Gen_Atp_Pegging : p_plan_id ' || p_plan_id);
2920     msc_util.msc_log('Gen_Atp_Pegging : p_share_partition ' || p_share_partition);
2921     msc_util.msc_log('Gen_Atp_Pegging : p_applsys_schema ' || p_applsys_schema);
2922   END IF;
2923 
2924   --RETCODE := G_SUCCESS;
2925 
2926   -- Initialize variables;
2927 
2928     SELECT  a.oracle_username,
2929             sysdate,
2930             FND_GLOBAL.USER_ID
2931     INTO    l_msc_schema,
2932             l_sysdate,
2933             l_user_id
2934     FROM    fnd_oracle_userid a,
2935             fnd_product_installations b
2936     WHERE   a.oracle_id = b.oracle_id
2937     AND     b.application_id = 724;
2938 
2939   -- First get the performance parameters.
2940 
2941   BEGIN
2942      SELECT      NVL(pre_alloc_hash_size, -1),
2943                  NVL(pre_alloc_sort_size, -1),
2944                  NVL(pre_alloc_parallel_degree, 1)
2945      INTO        l_hash_size,
2946                  l_sort_size,
2947                  l_parallel_degree
2948      FROM        msc_atp_parameters
2949      WHERE       rownum = 1;
2950      EXCEPTION
2951          WHEN others THEN
2952          msc_util.msc_log('Error getting performance param: ' || sqlcode || ': ' || sqlerrm);
2953          l_hash_size := -1;
2954          l_sort_size := -1;
2955          l_parallel_degree := 1;
2956   END;
2957 
2958   IF PG_DEBUG in ('Y', 'C') THEN
2959      msc_util.msc_log('Hash: ' || l_hash_size || ' Sort: ' || l_sort_size ||
2960                          ' Parallel: ' || l_parallel_degree);
2961   END IF;
2962 
2963   IF NVL(l_hash_size, -1) <> -1 THEN
2964         l_sql_stmt_1 := 'alter session set hash_area_size = ' || to_char(l_hash_size);
2965         msc_util.msc_log('l_sql_stmt : ' || l_sql_stmt_1);
2966         execute immediate l_sql_stmt_1;
2967   END IF;
2968 
2969   IF NVL(l_sort_size, -1) <> -1 THEN
2970          l_sql_stmt_1 := 'alter session set sort_area_size = ' || to_char(l_sort_size);
2971          msc_util.msc_log('l_sql_stmt : ' || l_sql_stmt_1);
2972          execute immediate l_sql_stmt_1;
2973   END IF;
2974 
2975   -- Second set the table names.
2976 
2977   -- Bug 3344102
2978   -- Set the Global temporary table name.
2979   l_global_temp_table   := 'MSC_ATP_PEG_TEMP';
2980   -- End Bug 3344102
2981 
2982   FOR i in 1..atp_simple_peg_tab.count LOOP
2983 
2984         l_table_name := 'MSC_' || atp_simple_peg_tab(i);
2985 
2986         IF (p_share_partition = 'Y') THEN
2987            l_plan_id := MAXVALUE;
2988         ELSE
2989            l_plan_id := p_plan_id;
2990         END IF;
2991 
2992         l_partition_name :=  atp_simple_peg_tab(i)|| '_' || l_plan_id;
2993         IF PG_DEBUG in ('Y', 'C') THEN
2994           msc_util.msc_log('l_partition_name := ' || l_partition_name);
2995         END IF;
2996 
2997         BEGIN
2998             SELECT count(*)
2999             INTO   l_count
3000             --bug 2495962: Change refrence from dba_xxx to all_xxx tables
3001             --FROM   dba_tab_partitions
3002             FROM   all_tab_partitions
3003             WHERE  table_name = l_table_name
3004             AND    partition_name = l_partition_name
3005             AND    table_owner = l_msc_schema;
3006         EXCEPTION
3007             WHEN OTHERS THEN
3008               IF PG_DEBUG in ('Y', 'C') THEN
3009                  msc_util.msc_log('Inside Exception');
3010               END IF;
3011                  l_count := 0;
3012         END;
3013 
3014 
3015         IF (l_count = 0) THEN
3016            /* --bug 3950208: Create partitions if partitons are missing in this table
3017            -- Bug 2516506
3018            FND_MESSAGE.SET_NAME('MSC', 'MSC_ATP_PLAN_PARTITION_MISSING');
3019            FND_MESSAGE.SET_TOKEN('PLAN_NAME', l_plan_name);
3020            FND_MESSAGE.SET_TOKEN('TABLE_NAME', 'MSC_' || atp_simple_peg_tab(i));
3021            IF PG_DEBUG in ('Y', 'C') THEN
3022               msc_util.msc_log(FND_MESSAGE.GET);
3023            END IF;
3024            msc_util.msc_log('MSC_ATP_PLAN_PARTITION_MISSING : Partition ' || l_partition_name || ' NOT FOUND');
3025            -- Find out presence of config items.
3026            SELECT 1
3027            INTO   l_count
3028            FROM   msc_system_items msi, msc_demands d
3029            WHERE  msi.plan_id = p_plan_id
3030            AND    msi.bom_item_type = 4
3031            AND    msi.base_item_id is NOT NULL
3032            AND    msi.replenish_to_order_flag = 'Y'
3033            AND    d.plan_id = msi.plan_id
3034            AND    d.sr_instance_id = msi.sr_instance_id
3035            AND    d.inventory_item_id = msi.inventory_item_id
3036            AND    d.organization_id = msi.organization_id
3037            AND    d.using_requirement_quantity > 0
3038            AND    d.origination_type in (6, 30)
3039            AND    ROWNUM = 1 ;
3040 
3041            IF l_count > 0 THEN
3042               msc_util.msc_log('Config Items are present, Partition needs to be created : ERROR.');
3043               RETCODE := G_ERROR;
3044            ELSE
3045               msc_util.msc_log('Config Items are absent, Partition not present flagged as WARNING.');
3046               RETCODE := G_WARNING;
3047            END IF;
3048            RETURN;
3049            */
3050            msc_util.msc_log('Partitions are not found in MSC_ATP_PEGGING. Launch request to create partitions');
3051            l_request_id := FND_REQUEST.SUBMIT_REQUEST(
3052                                         'MSC',
3053                                         'MSCSUPRT',
3054                                         NULL,   -- description
3055                                         NULL,   -- start time
3056                                         FALSE);  -- sub request
3057 
3058            msc_util.msc_log('Request to create partition is launched with request id := ' || l_request_id);
3059            commit;
3060 
3061            LOOP
3062                l_call_status:= FND_CONCURRENT.GET_REQUEST_STATUS
3063                                       ( l_request_id,
3064                                         NULL,
3065                                         NULL,
3066                                         l_phase,
3067                                         l_status,
3068                                         l_dev_phase,
3069                                         l_dev_status,
3070                                         l_message);
3071 
3072 
3073                IF (l_call_status=FALSE) THEN
3074                    msc_util.msc_log('Error in creating ATP partitions. Please run Create ATP Partitions program
3075                                      and then run ATP Post Plan Processing Again');
3076                    RETCODE := G_ERROR;
3077                    RETURN;
3078                END IF;
3079 
3080                msc_util.msc_log('l_dev_phase := ' || l_dev_phase);
3081 
3082                EXIT WHEN l_dev_phase = 'COMPLETE';
3083 
3084            END LOOP;
3085 
3086         END IF;
3087   END LOOP;
3088 
3089   IF p_share_partition = 'Y' THEN
3090 
3091     IF PG_DEBUG in ('Y', 'C') THEN
3092        msc_util.msc_log('before deleting old ATP pegging data');
3093     END IF;
3094 
3095     DELETE MSC_ATP_PEGGING where plan_id = p_plan_id;
3096 
3097     IF PG_DEBUG in ('Y', 'C') THEN
3098        msc_util.msc_log('After deleting old ATP pegging info');
3099     END IF;
3100 
3101   END IF;
3102 
3103   IF p_share_partition = 'Y' THEN
3104 
3105         l_temp_table := 'MSC_ATP_PEGGING';
3106   ELSE
3107 
3108     IF PG_DEBUG in ('Y', 'C') THEN
3109         msc_util.msc_log('not a shared plan partition, insert data into temp tables');
3110     END IF;
3111 
3112     l_temp_table := 'MSC_TEMP_ATP_PEGG_'|| to_char(l_plan_id);
3113 
3114     IF PG_DEBUG in ('Y', 'C') THEN
3115         msc_util.msc_log('temp table : ' || l_temp_table);
3116     END IF;
3117 
3118     SELECT  t.tablespace_name, NVL(i.def_tablespace_name, t.tablespace_name)
3119     INTO    l_tbspace, l_ind_tbspace
3120     FROM    all_tab_partitions t,
3121             all_part_indexes i
3122     WHERE   t.table_owner = l_msc_schema
3123     AND     t.table_name = 'MSC_ATP_PEGGING'
3124     AND     t.partition_name = l_partition_name
3125     AND     i.owner (+) = t.table_owner
3126     AND     i.table_name (+) = t.table_name
3127     AND     rownum = 1;
3128 
3129     IF PG_DEBUG in ('Y', 'C') THEN
3130         msc_util.msc_log('tb space : ' || l_tbspace);
3131         msc_util.msc_log('ind tbspace : ' || l_ind_tbspace);
3132     END IF;
3133 
3134 --6113544
3135      l_insert_stmt := 'CREATE TABLE ' || l_temp_table
3136            || ' TABLESPACE ' || l_tbspace
3137            || ' PCTFREE 0 STORAGE(INITIAL 40K NEXT 5M PCTINCREASE 0)'
3138            || ' as select * from MSC_ATP_PEGGING where 1=2 ';
3139 
3140 /*
3141     l_insert_stmt := 'CREATE TABLE ' || l_temp_table || '(
3142                          plan_id                 NUMBER          NOT NULL,
3143                          sr_instance_id          NUMBER          NOT NULL,
3144                          reference_item_id       NUMBER          NOT NULL,
3145                          inventory_item_id       NUMBER          NOT NULL,
3146                          organization_id         NUMBER          NOT NULL,
3147                          sales_order_line_id     NUMBER          NOT NULL,
3148                          bom_item_type           NUMBER,
3149                          sales_order_qty         NUMBER,
3150                          transaction_date        NUMBER,
3151                          demand_id               NUMBER,
3152                          demand_quantity         NUMBER,
3153                          disposition_id          NUMBER,
3154                          demand_class            VARCHAR2(34)    ,
3155                          consumed_qty            NUMBER,
3156                          overconsumption_qty     NUMBER,
3157                          supply_id               NUMBER,
3158                          supply_quantity         NUMBER,
3159                          allocated_quantity      NUMBER,
3160                          resource_id             NUMBER,
3161                          department_id           NUMBER,
3162                          resource_hours          NUMBER,
3163                          daily_resource_hours    NUMBER,
3164                          start_date              NUMBER,
3165                          end_date                NUMBER,
3166                          relief_type             NUMBER,
3167                          relief_quantity         NUMBER,
3168                          daily_relief_qty        NUMBER,
3169                          pegging_id              NUMBER,
3170                          prev_pegging_id         NUMBER,
3171                          end_pegging_id          NUMBER,
3172                          created_by              NUMBER          NOT NULL,
3173                          creation_date           DATE            NOT NULL,
3174                          last_updated_by         NUMBER          NOT NULL,
3175                          last_update_date        DATE            NOT NULL,
3176                          customer_id             NUMBER,
3177                          customer_site_id        NUMBER,
3178                          DEMAND_SOURCE_TYPE      NUMBER, --cmro
3179                          -- CTO_PF_PRJ changes.
3180                          end_demand_id           NUMBER
3181                          )
3182                             TABLESPACE ' || l_tbspace || '
3183            --NOLOGGING
3184           PCTFREE 0 STORAGE(INITIAL 40K NEXT 5M PCTINCREASE 0)';
3185 */
3186     IF PG_DEBUG in ('Y', 'C') THEN
3187         msc_util.msc_log('before creating table : ' || l_temp_table);
3188     END IF;
3189 
3190     BEGIN
3191          ad_ddl.do_ddl(APPLSYS_SCHEMA => p_applsys_schema,
3192               APPLICATION_SHORT_NAME => 'MSC',
3193               STATEMENT_TYPE => ad_ddl.create_table,
3194               STATEMENT => l_insert_stmt,
3195               OBJECT_NAME => l_temp_table);
3196       IF PG_DEBUG in ('Y', 'C') THEN
3197          msc_util.msc_log('after creating table : ' || l_temp_table);
3198       END IF;
3199 
3200     EXCEPTION
3201        WHEN others THEN
3202          IF PG_DEBUG in ('Y', 'C') THEN
3203             msc_util.msc_log(sqlcode || ': ' || sqlerrm);
3204             msc_util.msc_log('Exception of create table : ' || l_temp_table);
3205          END IF;
3206             ad_ddl.do_ddl(APPLSYS_SCHEMA => p_applsys_schema,
3207                    APPLICATION_SHORT_NAME => 'MSC',
3208                    STATEMENT_TYPE => ad_ddl.drop_table,
3209                    STATEMENT =>  'DROP TABLE ' || l_temp_table,
3210                    OBJECT_NAME => l_temp_table);
3211 
3212          IF PG_DEBUG in ('Y', 'C') THEN
3213             msc_util.msc_log('After Drop table : ' ||l_temp_table);
3214             msc_util.msc_log('Before exception create table : ' ||l_temp_table);
3215          END IF;
3216 
3217             ad_ddl.do_ddl(APPLSYS_SCHEMA => p_applsys_schema,
3218                    APPLICATION_SHORT_NAME => 'MSC',
3219                    STATEMENT_TYPE => ad_ddl.create_table,
3220                    STATEMENT => l_insert_stmt,
3221                    OBJECT_NAME => l_temp_table);
3222          IF PG_DEBUG in ('Y', 'C') THEN
3223             msc_util.msc_log('After exception create table : ' ||l_temp_table);
3224          END IF;
3225     END;
3226   END IF;  -- p_share_partition = 'Y'
3227 
3228     OPEN config_items;
3229 
3230     select hsecs
3231     into   l_timestamp
3232     from   v$timer;
3233 
3234     IF PG_DEBUG in ('Y', 'C') THEN
3235        msc_util.msc_log('Gen_Atp_Pegging : After opening config_items ');
3236        msc_util.msc_log('Gen_Atp_Pegging : TIMESTAMP 1 ' || l_timestamp);
3237     END IF;
3238 
3239     LOOP  -- Begin config_items loop
3240       IF PG_DEBUG in ('Y', 'C') THEN
3241           msc_util.msc_log('Gen_Atp_Pegging : Before fetch config_items Cursor');
3242       END IF;
3243       FETCH config_items INTO c_items_rec;
3244       EXIT WHEN config_items%NOTFOUND;
3245 
3246       IF PG_DEBUG in ('Y', 'C') THEN
3247           msc_util.msc_log('Gen_Atp_Pegging : After fetch config_items Cursor');
3248           msc_util.msc_log('Gen_Atp_Pegging : c_items_rec.item_name ' ||
3249                                                        c_items_rec.item_name);
3250           msc_util.msc_log('Gen_Atp_Pegging : c_items_rec.inventory_item_id ' ||
3251                                                        c_items_rec.inventory_item_id);
3252           msc_util.msc_log('Gen_Atp_Pegging : c_items_rec.sr_inventory_item_id ' ||
3253                                                        c_items_rec.sr_inventory_item_id);
3254           msc_util.msc_log('Gen_Atp_Pegging : c_items_rec.sr_instance_id ' ||
3255                                                        c_items_rec.sr_instance_id);
3256           msc_util.msc_log('Gen_Atp_Pegging : c_items_rec.base_item_id ' ||
3257                                                        c_items_rec.base_item_id);
3258           msc_util.msc_log('Gen_Atp_Pegging : c_items_rec.sales_order_line_id ' ||
3259                                                        c_items_rec.sales_order_line_id);
3260           msc_util.msc_log('Gen_Atp_Pegging : c_items_rec.demand_source_type' ||
3261                                                        c_items_rec.demand_source_type);--cmro
3262           msc_util.msc_log('Gen_Atp_Pegging : c_items_rec.demand_class' ||
3263                                            c_items_rec.demand_class); --Bug 3319180
3264           msc_util.msc_log('Gen_Atp_Pegging : c_items_rec.demand_id' ||
3265                                            c_items_rec.demand_id); --Bug 3750638
3266           msc_util.msc_log('Gen_Atp_Pegging : Plan Id ' || p_plan_id );
3267           msc_util.msc_log('Gen_Atp_Pegging : Stage 0 ' );
3268       END IF;
3269 
3270       -- Bug 3750638 Call the SQL statements now moved to a new procedure
3271       Get_Pegging_Data_Loop ( p_plan_id,
3272                               c_items_rec,
3273                               l_return_status);
3274 
3275       IF l_return_status <> FND_API.G_RET_STS_SUCCESS THEN
3276        IF PG_DEBUG in ('Y', 'C') THEN
3277            msc_util.msc_log('Gen_Atp_Pegging: ' ||
3278                'Error occured in procedure Get_Pegging_Data_Loop');
3279         END IF;
3280         RAISE FND_API.G_EXC_ERROR;
3281       END IF;
3282       -- End Bug 3750638 Call the SQL statements now moved to a new procedure
3283 
3284 
3285     select hsecs
3286     into   l_timestamp
3287     from   v$timer;
3288 
3289       IF PG_DEBUG in ('Y', 'C') THEN
3290         msc_util.msc_log('Gen_Atp_Pegging : Stage 5 ' );
3291         msc_util.msc_log('Gen_Atp_Pegging : TIMESTAMP 3 ' || l_timestamp);
3292       END IF;
3293 
3294       -- Fetch the data into PL/SQL record of tables.
3295       SELECT
3296               reference_item_id, base_item_id,
3297               inventory_item_id,
3298               plan_id,
3299               sr_instance_id,
3300               organization_id,
3301               end_item_usage,
3302               bom_item_type, fixed_lt, variable_lt,
3303               sales_order_line_id,
3304               demand_source_type,--cmro
3305               sales_order_qty,
3306               demand_id,
3307               demand_date,
3308               demand_quantity,
3309               disposition_id,
3310               demand_class,
3311               demand_type,
3312               original_demand_id,
3313               process_seq_id, supply_id,
3314               supply_date,
3315               supply_quantity,
3316               allocated_quantity, tot_relief_qty,
3317               supply_type,
3318               firm_planned_type,
3319               release_status,
3320               exclude_flag,    -- All other cases exclude
3321               order_number,
3322               end_pegging_id, pegging_id,  prev_pegging_id,
3323               fcst_organization_id, forecast_qty,
3324               consumed_qty, overconsumption_qty,
3325               -- CTO_PF_PRJ changes.
3326               end_demand_id,
3327               --CTO-PF
3328               atf_date,
3329               product_family_id
3330       BULK COLLECT INTO
3331               atp_peg_det.reference_item_id, atp_peg_det.base_item_id,
3332               atp_peg_det.inventory_item_id, atp_peg_det.plan_id, atp_peg_det.sr_instance_id,
3333               atp_peg_det.organization_id, atp_peg_det.end_item_usage, atp_peg_det.bom_item_type,
3334               atp_peg_det.fixed_lt, atp_peg_det.variable_lt,
3335               atp_peg_det.sales_order_line_id,atp_peg_det.demand_source_type,atp_peg_det.sales_order_qty, --cmro
3336               atp_peg_det.demand_id, atp_peg_det.demand_date,
3337               atp_peg_det.demand_quantity, atp_peg_det.disposition_id,
3338               atp_peg_det.demand_class, atp_peg_det.demand_type, atp_peg_det.original_demand_id,
3339               atp_peg_det.process_seq_id, atp_peg_det.supply_id, atp_peg_det.supply_date,
3340               atp_peg_det.supply_quantity, atp_peg_det.allocated_quantity,
3341               atp_peg_det.tot_relief_qty, atp_peg_det.supply_type,
3342               atp_peg_det.firm_planned_type, atp_peg_det.release_status,
3343               atp_peg_det.exclude_flag, atp_peg_det.order_number,
3344               atp_peg_det.end_pegging_id, atp_peg_det.pegging_id, atp_peg_det.prev_pegging_id,
3345               atp_peg_det.fcst_organization_id, atp_peg_det.forecast_qty,
3346               atp_peg_det.consumed_qty, atp_peg_det.overconsumption_qty,
3347               -- CTO_PF_PRJ changes.
3348               atp_peg_det.end_demand_id,
3349               -- CTO-PF
3350               atp_peg_det.atf_date,
3351               atp_peg_det.product_family_id
3352       FROM
3353               msc_atp_detail_peg_temp
3354       WHERE   plan_id = p_plan_id
3355       AND     sr_instance_id (+) = c_items_rec.sr_instance_id -- outer join to get all instances
3356       AND     reference_item_id = c_items_rec.inventory_item_id
3357       AND     sales_order_line_id = c_items_rec.sales_order_line_id
3358       AND     Decode(demand_source_type,100,demand_source_type,-1)
3359               =decode(c_items_rec.demand_source_type,
3360                                                 100,
3361                                                 c_items_rec.demand_source_type,
3362                                                 -1) --CMRO
3363       ORDER BY
3364                end_pegging_id, prev_pegging_id,
3365                demand_date, supply_date,
3366                pegging_id DESC     -- prev_pegging_id, pegging_id DESC ???
3367       ;
3368 
3369 
3370 
3371     select hsecs
3372     into   l_timestamp
3373     from   v$timer;
3374 
3375       IF PG_DEBUG in ('Y', 'C') THEN
3376         msc_util.msc_log('Gen_Atp_Pegging : Stage 6 ' );
3377         msc_util.msc_log('Gen_Atp_Pegging : Rows Procesed ' || SQL%ROWCOUNT );
3378         msc_util.msc_log('Gen_Atp_Pegging : TIMESTAMP 4 ' || l_timestamp);
3379       END IF;
3380 
3381 
3382       -- Obtain and Assign forecast consumption info.
3383       FOR i in 1..atp_peg_det.inventory_item_id.COUNT LOOP
3384          -- Obtain forecast consumption info only for config items.
3385          IF (atp_peg_det.bom_item_type(i) = 4 AND
3386              atp_peg_det.base_item_id(i) IS NOT NULL ) THEN
3387             -- Bug 3362558 Display the original_demand_id
3388             IF PG_DEBUG in ('Y', 'C') THEN
3389                msc_util.msc_log('Gen_Atp_Pegging : End Demand Id for Sales Order: ' ||
3390                   -- CTO_PF_PRJ changes. Use end_demand_id
3391                                   atp_peg_det.end_demand_id(i) );
3392                                   --l_original_demand_ids(1) );
3393             END IF;
3394             -- End Bug 3362558
3395             Get_Forecast_Consumption(atp_peg_det, i, fcst_data_tab, l_return_status);
3396             l_total_relief_qty  := 0;
3397           IF PG_DEBUG in ('Y', 'C') THEN
3398             msc_util.msc_log('Gen_Atp_Pegging : Stage 7 ' );
3399             msc_util.msc_log('Gen_Atp_Pegging : Status post Fcst Consumption.' ||
3400                                                            l_return_status );
3401             msc_util.msc_log('Gen_Atp_Pegging : Fcst Data Count.' ||
3402                                                fcst_data_tab.inventory_item_id.Count);
3403           END IF;
3404          END IF;
3405 
3406          -- Re-initialize org_ratio
3407 
3408          l_order_org_ratio := NULL;
3409          -- Bug 3701093
3410          -- Initialize G_ADJUST_FLAG to 1, Default is to generate offsets.
3411          G_ADJUST_FLAG := 1;
3412 
3413          -- Here in this loop, the total relief quantities will also be determined.
3414          FOR j in 1..fcst_data_tab.inventory_item_id.COUNT LOOP
3415            IF (atp_peg_det.inventory_item_id(i) = fcst_data_tab.inventory_item_id(j) AND
3416                atp_peg_det.plan_id(i) = fcst_data_tab.plan_id(j) AND
3417                atp_peg_det.sr_instance_id(i) = fcst_data_tab.sr_instance_id(j) AND
3418                (atp_peg_det.original_demand_id(i) = fcst_data_tab.sales_order_id(j) OR
3419                 -- Bug 3362558
3420                 -- Global forecasting situation, org_id is -1.
3421                 (fcst_data_tab.fcst_organization_id(j) = -1 AND
3422                   -- CTO_PF_PRJ changes. Use end_demand_id
3423                  fcst_data_tab.sales_order_id(j) = atp_peg_det.end_demand_id(i) ) OR
3424                 atp_peg_det.demand_id(i) = fcst_data_tab.sales_order_id(j)  ) ) THEN
3425 
3426                atp_peg_det.forecast_qty(i) := fcst_data_tab.forecast_qty(j);
3427                atp_peg_det.bom_item_type(i) := fcst_data_tab.bom_item_type(j);
3428 
3429                -- Set the distribution of order ratio
3430                -- The same order can be satisfied using multiple organizations.
3431                -- The ratio below factors that in.
3432 
3433                IF (atp_peg_det.allocated_quantity(i) < fcst_data_tab.consumed_qty(j)
3434                                                     + NVL(fcst_data_tab.overconsumption_qty(j),0) ) THEN
3435                    l_order_org_ratio := atp_peg_det.allocated_quantity(i) /
3436                                             (fcst_data_tab.consumed_qty(j) +
3437                                                 NVL(fcst_data_tab.overconsumption_qty(j), 0)
3438                                             );
3439                ELSE
3440                    l_order_org_ratio := 1;
3441                END IF;
3442 
3443                atp_peg_det.consumed_qty(i) := NVL(fcst_data_tab.consumed_qty(j), 0) *
3444                                                                  l_order_org_ratio;
3445                atp_peg_det.overconsumption_qty(i) := NVL(fcst_data_tab.overconsumption_qty(j), 0)
3446                                                          * l_order_org_ratio;
3447 
3448                -- Determine the Total relief quantity across all organizations.
3449                IF ((fcst_data_tab.consumed_qty(j) IS NOT NULL) AND
3450                    (fcst_data_tab.sales_order_qty(j) > fcst_data_tab.consumed_qty(j))) THEN
3451 
3452                   atp_peg_det.tot_relief_qty(i) := fcst_data_tab.consumed_qty(j) -
3453                                                    fcst_data_tab.sales_order_qty(j);
3454                ELSE
3455 
3456                   -- If the sales order is not greater than the consumption
3457                   -- nothing to relieve at the configuration item level.
3458                   atp_peg_det.tot_relief_qty(i) := 0;
3459                END IF;
3460 
3461                l_total_relief_qty := atp_peg_det.tot_relief_qty(i);
3462                IF PG_DEBUG in ('Y', 'C') THEN
3463                  msc_util.msc_log('Gen_Atp_Pegging :  Total Relief Qty' ||
3464                                                            l_total_relief_qty);
3465                  msc_util.msc_log('Gen_Atp_Pegging :  FC Consumtion Flag' ||
3466                                                    fcst_data_tab.cons_config_mod_flag(j));
3467                END IF;
3468 
3469                -- Bug 3701093
3470                IF (fcst_data_tab.cons_config_mod_flag(j) = C_CONFIG_FCST_CONSUMED) AND
3471                   (atp_peg_det.reference_item_id(i) = fcst_data_tab.inventory_item_id(j)) THEN
3472                   G_ADJUST_FLAG := 0;
3473                   -- No offset data generation generation necessary when TOP LEVEL
3474                   -- config item's forecast can completely satisfy the Sales Order.
3475 
3476                ELSE
3477                  FOR n in 1..atp_peg_det.inventory_item_id.COUNT LOOP
3478 
3479                    -- Set the total_relief_qty for components pegged to the configuration_item
3480                    IF (atp_peg_det.plan_id(n) = atp_peg_det.plan_id(i) AND
3481                      atp_peg_det.disposition_id(n) = atp_peg_det.supply_id(i) ) THEN
3482 
3483                       atp_peg_det.tot_relief_qty(n) := atp_peg_det.tot_relief_qty(i)
3484                                                    * atp_peg_det.end_item_usage(n) / atp_peg_det.end_item_usage(i);
3485 
3486                    END IF;
3487 
3488                  END LOOP;
3489                END IF;
3490            -- match with base model
3491            ELSIF
3492                (atp_peg_det.plan_id(i) = fcst_data_tab.plan_id(j) AND
3493                atp_peg_det.sr_instance_id(i) = fcst_data_tab.sr_instance_id(j) AND
3494                atp_peg_det.base_item_id(i) = fcst_data_tab.inventory_item_id(j)  AND
3495                atp_peg_det.organization_id(i) = fcst_data_tab.organization_id(j) AND
3496                -- Bug 3319810 For lower level model the demand type will not be
3497                -- Sales Order, hence commented out.
3498                -- atp_peg_det.demand_type(i) in (6, 30) AND
3499                (atp_peg_det.original_demand_id(i) = fcst_data_tab.sales_order_id(j) OR
3500                 -- Bug 3362558
3501                 -- Global forecasting situation, org_id is -1.
3502                 (fcst_data_tab.fcst_organization_id(j) = -1 AND
3503                   -- CTO_PF_PRJ changes. Use end_demand_id
3504                  fcst_data_tab.sales_order_id(j) = atp_peg_det.end_demand_id(i) ) OR
3505                 atp_peg_det.demand_id(i) = fcst_data_tab.sales_order_id(j) ) ) THEN
3506 
3507                -- Will the ratio determined using the model work as well?
3508                -- Set the ratio
3509                -- Set the distribution of order ratio
3510                -- The same order can be satisfied using multiple organizations.
3511                -- The ratio below factors that in.
3512                IF (l_order_org_ratio IS NULL AND
3513                    atp_peg_det.allocated_quantity(i) < fcst_data_tab.consumed_qty(j) +
3514                                                      NVL(fcst_data_tab.overconsumption_qty(j), 0) ) THEN
3515                    l_order_org_ratio := atp_peg_det.allocated_quantity(i) /
3516                                             (fcst_data_tab.consumed_qty(j) +
3517                                           NVL(fcst_data_tab.overconsumption_qty(j), 0));
3518                ELSE
3519                    l_order_org_ratio := 1;
3520                END IF;
3521                IF PG_DEBUG in ('Y', 'C') THEN
3522                  msc_util.msc_log('Gen_Atp_Pegging :  fcst_data_tab.inventory_item_id(j)' ||
3523                                                 fcst_data_tab.inventory_item_id(j));
3524                  msc_util.msc_log('Gen_Atp_Pegging :  fcst_data_tab.consumed_qty(j)' ||
3525                                                 fcst_data_tab.consumed_qty(j));
3526                  msc_util.msc_log('Gen_Atp_Pegging : fcst_data_tab.sales_order_id(j)' ||
3527                                                 fcst_data_tab.sales_order_id(j));
3528                  msc_util.msc_log('Gen_Atp_Pegging :  l_order_org_ratio' ||
3529                                                              l_order_org_ratio);
3530                  msc_util.msc_log('Gen_Atp_Pegging :  FC Consumtion Flag' ||
3531                                                    fcst_data_tab.cons_config_mod_flag(j));
3532                END IF;
3533                -- Bug 3701093 Model Forecast Has been consumed,
3534                -- Generate Offsets for  Model.
3535                IF fcst_data_tab.cons_config_mod_flag(j) = C_MODEL_FCST_CONSUMED THEN
3536                   Extend_Atp_Peg_Det (atp_peg_det, l_return_status, 1);
3537 
3538                   k := atp_peg_det.reference_item_id.Count;
3539 
3540                   atp_peg_det.reference_item_id(k) := atp_peg_det.reference_item_id(i);
3541                   atp_peg_det.base_item_id(k) := NULL;
3542                   atp_peg_det.inventory_item_id(k) := fcst_data_tab.inventory_item_id(j);
3543                   atp_peg_det.plan_id(k) := atp_peg_det.plan_id(i);
3544                   atp_peg_det.sr_instance_id(k) := atp_peg_det.sr_instance_id(i);
3545                   atp_peg_det.organization_id(k) := atp_peg_det.organization_id(i);
3546                   atp_peg_det.bom_item_type(k) := fcst_data_tab.bom_item_type(j);
3547                   -- Configuration Item's lead times are used.
3548                   atp_peg_det.fixed_lt(k) := atp_peg_det.fixed_lt(i);
3549                   atp_peg_det.variable_lt(k) := atp_peg_det.variable_lt(i);
3550                   atp_peg_det.sales_order_qty(k) := fcst_data_tab.sales_order_qty(j);
3551                   atp_peg_det.sales_order_line_id(k) := atp_peg_det.sales_order_line_id(i);
3552                   atp_peg_det.demand_source_type(k) := atp_peg_det.demand_source_type(i);--cmro
3553                   atp_peg_det.demand_id(k) := fcst_data_tab.fcst_demand_id(j);
3554                   atp_peg_det.demand_date(k) := atp_peg_det.demand_date(i);
3555                   -- Set the demand_date for the model to be that
3556                   -- of configuration item's date, No offsets for model .
3557                   -- For sub-components other than models offset is applied
3558                   -- during calculation of relief quantities.
3559                   atp_peg_det.demand_quantity(k) :=  NVL(atp_peg_det.demand_quantity(i), 0) -
3560                                            NVL(atp_peg_det.consumed_qty (i) , 0);
3561                   -- Set the demand_quantity to be that of the configuration item's demand
3562                   -- after factoring the consumption.
3563                   atp_peg_det.disposition_id(k) :=  atp_peg_det.supply_id(i);
3564 
3565                   atp_peg_det.demand_class(k) := atp_peg_det.demand_class(i);
3566                   atp_peg_det.demand_type(k) := 1;  -- Plan Order Demand
3567                   atp_peg_det.original_demand_id(k) := atp_peg_det.original_demand_id(i);
3568                   -- CTO_PF_PRJ changes. Set end_demand_id
3569                   atp_peg_det.end_demand_id(k) := atp_peg_det.end_demand_id(i);
3570 
3571                   atp_peg_det.fcst_organization_id(k) :=
3572                                           fcst_data_tab.fcst_organization_id(j);
3573                   atp_peg_det.forecast_qty(k) := fcst_data_tab.forecast_qty(j) ;
3574                   atp_peg_det.consumed_qty(k) := NVL(fcst_data_tab.consumed_qty(j), 0) *
3575                                                                  l_order_org_ratio;
3576                   atp_peg_det.overconsumption_qty(k) :=
3577                                      NVL(fcst_data_tab.overconsumption_qty(j), 0)
3578                                                          * l_order_org_ratio;
3579                   IF PG_DEBUG in ('Y', 'C') THEN
3580                      msc_util.msc_log('Gen_Atp_Pegging : atp_peg_det.consumed_qty(k)' ||
3581                                                        atp_peg_det.consumed_qty(k));
3582                      msc_util.msc_log('Gen_Atp_Pegging : atp_peg_det.overconsumption_qty(k)' ||
3583                                                 atp_peg_det.overconsumption_qty(k));
3584                   END IF;
3585                   -- For now the process_seq_id remains unassigned
3586                   -- atp_peg_det.process_seq_id(k) := atp_peg_det.process_seq_id(i) ;
3587                   -- What to do with the Supply for model and the components?
3588                   -- Currently everything is set to NULL.
3589                   atp_peg_det.supply_id(k) := NULL;
3590                   atp_peg_det.supply_date(k) := NULL;
3591                   atp_peg_det.supply_quantity(k) := NULL;
3592                   -- Bug 3805136 Set the allocated_quantity to Config's allocated_quantity
3593                   atp_peg_det.allocated_quantity(k) := atp_peg_det.allocated_quantity(i);
3594                   -- End Bug 3805136
3595                   atp_peg_det.supply_type(k) := NULL;
3596                   atp_peg_det.firm_planned_type(k) := NULL;
3597                   atp_peg_det.release_status(k) := NULL;
3598 
3599                   atp_peg_det.end_item_usage(k) := atp_peg_det.end_item_usage(i);
3600 
3601                   atp_peg_det.exclude_flag(k) := atp_peg_det.exclude_flag(i);
3602 
3603                   atp_peg_det.order_number(k) := atp_peg_det.order_number(i);
3604 
3605                   atp_peg_det.end_pegging_id(k) := atp_peg_det.end_pegging_id(i);
3606                   atp_peg_det.pegging_id(k) := NULL;
3607                   -- Note that the prev_pegging_id is linked to the Configuration Item's
3608                   -- Pegging Id.
3609                   atp_peg_det.prev_pegging_id(k) := atp_peg_det.pegging_id(i);
3610                END IF;
3611                -- End Bug 3701093
3612 
3613                -- Determine the Total relief quantity across all organizations.
3614                IF ((fcst_data_tab.consumed_qty(j) IS NOT NULL) OR
3615                    (fcst_data_tab.overconsumption_qty(j) IS NOT NULL) ) THEN
3616 
3617                   -- Config is relieved to the extent of consumption + overconsumption.
3618                   atp_peg_det.tot_relief_qty(i) := -1 * (fcst_data_tab.consumed_qty(j) +
3619                                                    fcst_data_tab.overconsumption_qty(j) );
3620                -- Bug 3805136 No forecast consumed, total_relief_qty remains NULL
3621                ELSIF (fcst_data_tab.cons_config_mod_flag(j) = C_NO_FCST_CONSUMED) THEN
3622                   atp_peg_det.tot_relief_qty(i) := NULL;  -- Remains NULL
3623                -- Bug 3805136
3624                ELSE
3625 
3626                   atp_peg_det.tot_relief_qty(i) := 0;
3627                END IF;
3628                -- Bug 3701093 Model Forecast Has been consumed,
3629                -- Generate Offsets for  Model.
3630                IF fcst_data_tab.cons_config_mod_flag(j) = C_MODEL_FCST_CONSUMED THEN
3631                   -- Set the Relief Qty for the model
3632                   atp_peg_det.tot_relief_qty(k) := atp_peg_det.tot_relief_qty(i);
3633                END IF;
3634                -- End Bug 3701093
3635 
3636                IF PG_DEBUG in ('Y', 'C') THEN
3637                  msc_util.msc_log('Gen_Atp_Pegging :  atp_peg_det.tot_relief_qty(i) ' ||
3638                                                              atp_peg_det.tot_relief_qty(i));
3639                  msc_util.msc_log('Gen_Atp_Pegging :  atp_peg_det.inventory_item_id(i) '
3640                                                      ||   atp_peg_det.inventory_item_id(i));
3641                END IF;
3642                FOR n in 1..atp_peg_det.inventory_item_id.COUNT LOOP
3643 
3644                  -- Set the total_relief_qty for components pegged to the configuration_item
3645                  IF (atp_peg_det.plan_id(n) = atp_peg_det.plan_id(i) AND
3646                      atp_peg_det.tot_relief_qty(n) IS NULL AND
3647                      -- Bug 3805136 Link up the pegging.
3648                      atp_peg_det.prev_pegging_id(n) = atp_peg_det.pegging_id(i) AND
3649                      -- and forecast consumption happens
3650                      atp_peg_det.tot_relief_qty(i) IS NOT NULL AND
3651                      --  End Bug 3805136
3652                      atp_peg_det.disposition_id(n) = atp_peg_det.supply_id(i) ) THEN
3653 
3654                       atp_peg_det.tot_relief_qty(n) := atp_peg_det.tot_relief_qty(i)
3655                                                    * atp_peg_det.end_item_usage(n) / atp_peg_det.end_item_usage(i);
3656 
3657                   IF PG_DEBUG in ('Y', 'C') THEN
3658                     msc_util.msc_log('Gen_Atp_Pegging :  atp_peg_det.tot_relief_qty(n) ' ||
3659                                                              atp_peg_det.tot_relief_qty(n));
3660                     msc_util.msc_log('Gen_Atp_Pegging :  atp_peg_det.inventory_item_id(n) '
3661                                                      ||   atp_peg_det.inventory_item_id(n));
3662                     msc_util.msc_log('Gen_Atp_Pegging :  atp_peg_det.pegging_id(n) '
3663                                                      ||   atp_peg_det.pegging_id(n));
3664                     msc_util.msc_log('Gen_Atp_Pegging :  ' ||
3665                      'atp_peg_det.allocated_quantity(n) '|| atp_peg_det.allocated_quantity(n));
3666                   END IF;
3667                  END IF;
3668 
3669                END LOOP;
3670            -- other phantom items
3671            -- other items only in the manufacturing organization.
3672            ELSIF (atp_peg_det.process_seq_id(i) is NOT NULL ) AND
3673                   atp_peg_det.plan_id(i) = fcst_data_tab.plan_id(j) AND
3674                   atp_peg_det.sr_instance_id(i) = fcst_data_tab.sr_instance_id(j) AND
3675                   atp_peg_det.inventory_item_id(i) = fcst_data_tab.parent_item_id(j) AND
3676                   -- Bug 3319810 For lower level model the demand type will not be
3677                   -- Sales Order, hence commented out.
3678                   -- atp_peg_det.demand_type(i) in (6, 30) AND
3679                   atp_peg_det.organization_id(i) = fcst_data_tab.organization_id(j) THEN
3680            -- or alternatively
3681            -- ELSIF (atp_peg_det.source_organization_id(i) IS NULL AND
3682            --   atp_peg_det.source_supplier_id(i) IS NULL)
3683 
3684              l_row_count :=  1 ;
3685              -- model has already been factored above.
3686              l_count :=   atp_peg_det.inventory_item_id.COUNT;
3687 
3688              -- Extend the array by the number of rows in Fcst array.
3689              Extend_Atp_Peg_Det (atp_peg_det, l_return_status, l_row_count);
3690 
3691              -- Update the total count.
3692              l_tot_count := l_count + l_row_count;
3693 
3694              IF PG_DEBUG in ('Y', 'C') THEN
3695                msc_util.msc_log('Gen_Atp_Pegging : ATP Inventory_item_id. ' ||
3696                                                    atp_peg_det.inventory_item_id(i) );
3697                msc_util.msc_log('Gen_Atp_Pegging : FCST Inventory_item_id. ' ||
3698                                                  fcst_data_tab.inventory_item_id(j) );
3699                msc_util.msc_log('Gen_Atp_Pegging : FCST Parent_Item_id. ' ||
3700                                                  fcst_data_tab.Parent_Item_id(j) );
3701                msc_util.msc_log('Gen_Atp_Pegging : l_row_count. ' ||
3702                                                            l_row_count );
3703                msc_util.msc_log('Gen_Atp_Pegging : l_count. ' ||
3704                                                            l_count );
3705                msc_util.msc_log('Gen_Atp_Pegging : l_tot_count. ' ||
3706                                                            l_tot_count  );
3707              END IF;
3708              l_count := l_count + 1;
3709              -- Append the forecast_data for each config item to
3710              -- the original array with the phantom items information
3711              --FOR k in l_count..l_tot_count LOOP
3712 
3713               k:= l_count;
3714               IF PG_DEBUG in ('Y', 'C') THEN
3715                 msc_util.msc_log('Gen_Atp_Pegging : Value of loop var k. ' || k  );
3716               END IF;
3717 
3718                atp_peg_det.reference_item_id(k) := atp_peg_det.reference_item_id(i);
3719                atp_peg_det.base_item_id(k) := NULL;
3720                atp_peg_det.inventory_item_id(k) := fcst_data_tab.inventory_item_id(j);
3721                atp_peg_det.plan_id(k) := atp_peg_det.plan_id(i);
3722                atp_peg_det.sr_instance_id(k) := atp_peg_det.sr_instance_id(i);
3723                atp_peg_det.organization_id(k) := atp_peg_det.organization_id(i);
3724                atp_peg_det.bom_item_type(k) := fcst_data_tab.bom_item_type(j);
3725                -- Individual Item's lead times are used.
3726                atp_peg_det.fixed_lt(k) := fcst_data_tab.fixed_lt(j);
3727                atp_peg_det.variable_lt(k) := fcst_data_tab.variable_lt(j);
3728                atp_peg_det.sales_order_qty(k) := fcst_data_tab.sales_order_qty(j);
3729                -- Note that the sales_order_qty gets factored in during forecast consumption
3730                atp_peg_det.sales_order_line_id(k) := atp_peg_det.sales_order_line_id(i);
3731                atp_peg_det.demand_source_type(k) := atp_peg_det.demand_source_type(i);--cmro
3732                atp_peg_det.demand_id(k) := fcst_data_tab.fcst_demand_id(j);
3733                -- Bug 3445664 The date will be NULL for phantom items.
3734                -- atp_peg_det.demand_date(k) := atp_peg_det.supply_date(i);
3735                       -- Set the demand_date for the component to be that
3736                       -- of configuration item's supply date for offsets later.
3737                -- End Bug 3445664 The date will be NULL for phantom items.
3738                       -- For sub-components other than models offset is applied
3739                       -- during calculation of relief quantities.
3740                atp_peg_det.demand_quantity(k) :=  fcst_data_tab.sales_order_qty(j)
3741                                                        * l_order_org_ratio ;
3742                -- Set the demand_quantity to be that of sales_order_quantity.
3743                -- after applying the organization ratio.
3744                atp_peg_det.disposition_id(k) :=  atp_peg_det.supply_id(i);
3745 
3746                atp_peg_det.demand_class(k) := atp_peg_det.demand_class(i);
3747                atp_peg_det.demand_type(k) := 1;  -- Plan Order Demand
3748                atp_peg_det.original_demand_id(k) := atp_peg_det.original_demand_id(i);
3749                -- CTO_PF_PRJ changes. Set end_demand_id
3750                atp_peg_det.end_demand_id(k) := atp_peg_det.end_demand_id(i);
3751 
3752                atp_peg_det.fcst_organization_id(k) := fcst_data_tab.fcst_organization_id(j);
3753                atp_peg_det.forecast_qty(k) := fcst_data_tab.forecast_qty(j) ;
3754                atp_peg_det.consumed_qty(k) := NVL(fcst_data_tab.consumed_qty(j), 0) *
3755                                                                  l_order_org_ratio;
3756                atp_peg_det.overconsumption_qty(k) := NVL(fcst_data_tab.overconsumption_qty(j), 0)
3757                                                          * l_order_org_ratio;
3758 
3759 
3760                -- For now the process_seq_id remains unassigned
3761                -- atp_peg_det.process_seq_id(k) := atp_peg_det.process_seq_id(i) ;
3762                -- What to do with the Supply for model and the components?
3763                -- Currently everything is set to NULL.
3764                atp_peg_det.supply_id(k) := NULL;
3765                atp_peg_det.supply_date(k) := NULL;
3766                atp_peg_det.supply_quantity(k) := NULL;
3767                atp_peg_det.allocated_quantity(k) := NULL;
3768                atp_peg_det.supply_type(k) := NULL;
3769                atp_peg_det.firm_planned_type(k) := NULL;
3770                atp_peg_det.release_status(k) := NULL;
3771 
3772                -- Bug 3805136
3773                -- Set to 1 currently as a default.
3774                -- Usage Quantity to estimate end_item_usage
3775                -- Not provided by MBP in msc_forecast_updates currently.
3776                atp_peg_det.end_item_usage(k) := 1;
3777                -- Bug 3805136
3778 
3779                atp_peg_det.exclude_flag(k) := atp_peg_det.exclude_flag(i);
3780 
3781                atp_peg_det.order_number(k) := atp_peg_det.order_number(i);
3782 
3783                atp_peg_det.end_pegging_id(k) := atp_peg_det.end_pegging_id(i);
3784                atp_peg_det.pegging_id(k) := NULL;
3785                -- Note that the prev_pegging_id is linked to the Configuration Item's
3786                -- Pegging Id.
3787                atp_peg_det.prev_pegging_id(k) := atp_peg_det.pegging_id(i);
3788 
3789                -- Determine the Total relief quantity across all organizations.
3790                IF ((fcst_data_tab.consumed_qty(j) IS NOT NULL) OR
3791                    (fcst_data_tab.overconsumption_qty(j) IS NOT NULL) ) THEN
3792 
3793                   -- All others also relieved to the extent of consumption + overconsumption.
3794                   atp_peg_det.tot_relief_qty(k) := -1 * (fcst_data_tab.consumed_qty(j) +
3795                                                    fcst_data_tab.overconsumption_qty(j) );
3796                ELSE
3797 
3798                   atp_peg_det.tot_relief_qty(k) := 0;
3799                END IF;
3800                -- Bug 3805136 Allocated quantity is positive
3801                atp_peg_det.allocated_quantity(k) :=  ABS(atp_peg_det.tot_relief_qty(k));
3802                IF PG_DEBUG in ('Y', 'C') THEN
3803                  msc_util.msc_log('Gen_Atp_Pegging :  atp_peg_det.tot_relief_qty(k) ' ||
3804                                                            atp_peg_det.tot_relief_qty(k));
3805                  msc_util.msc_log('Gen_Atp_Pegging :  atp_peg_det.inventory_item_id(k) '
3806                                                    ||   atp_peg_det.inventory_item_id(k));
3807                  msc_util.msc_log('Gen_Atp_Pegging :  atp_peg_det.prev_pegging_id(k) '
3808                                                    ||   atp_peg_det.prev_pegging_id(k));
3809                END IF;
3810              --END LOOP;
3811 
3812            END IF;
3813          END LOOP;  -- j loop for fcst_data_tab
3814       END LOOP;   -- i loop for atp_peg_det
3815 
3816       -- Initialize the Simplified Pegging PL/SQL array
3817 
3818       Init_Atp_Peg ( atp_peg_tab, l_return_status);
3819       IF PG_DEBUG in ('Y', 'C') THEN
3820         msc_util.msc_log('Gen_Atp_Pegging : Initialized Simple Pegging Array ' ||
3821                                                                     l_return_status);
3822       END IF;
3823 
3824       -- Bug 3701093
3825       -- Do the rest of the process only if offset data needs to be generated.
3826       IF G_ADJUST_FLAG = 1 THEN
3827          -- To Calculate_Relief_Quantities first
3828          -- Obtain Simplified Pegging Information
3829          Create_Simple_Pegging (atp_peg_det, atp_peg_tab, l_return_status);
3830          select hsecs
3831          into   l_timestamp
3832          from   v$timer;
3833 
3834          IF PG_DEBUG in ('Y', 'C') THEN
3835            msc_util.msc_log('Gen_Atp_Pegging : Stage 8 After obtaining Simple Pegging ');
3836            msc_util.msc_log('Gen_Atp_Pegging : TIMESTAMP 5 ' || l_timestamp);
3837          END IF;
3838 
3839          -- Calculate and Cascade Relief Quantities
3840          -- will be strictly chronological.
3841          -- Relief will be done by traversing the simplified pegging tree.
3842 
3843          -- Initialize the variables
3844          L_TOT_RELIEF_QTY := NULL;
3845          l_peg_relief_qty := NULL;
3846          FOR i in 1..atp_peg_tab.reference_item_id.COUNT LOOP
3847             -- First relieve the Sales Order
3848             IF (L_TOT_RELIEF_QTY IS NULL) AND
3849                (atp_peg_tab.bom_item_type(i) = 4 AND
3850                 atp_peg_tab.reference_item_id(i) = atp_peg_tab.inventory_item_id(i) AND
3851                 atp_peg_tab.relief_type(i) = 2 AND
3852                 atp_peg_tab.prev_pegging_id(i) IS NULL) THEN
3853                L_TOT_RELIEF_QTY := atp_peg_tab.tot_relief_qty(i);
3854             END IF;
3855             IF (atp_peg_tab.bom_item_type(i) = 4 AND
3856                 atp_peg_tab.reference_item_id(i) = atp_peg_tab.inventory_item_id(i) AND
3857                 atp_peg_tab.relief_type(i) = 1) THEN
3858 
3859              IF PG_DEBUG in ('Y', 'C') THEN
3860                msc_util.msc_log('Gen_Atp_Pegging : reference_item_id ' ||
3861                                              atp_peg_tab.reference_item_id(i) );
3862              END IF;
3863                atp_peg_tab.relief_quantity(i) := 0;
3864 
3865             ELSIF (atp_peg_tab.bom_item_type(i) = 4 AND
3866                 atp_peg_tab.reference_item_id(i) = atp_peg_tab.inventory_item_id(i) AND
3867                 atp_peg_tab.relief_type(i) = 2 AND
3868                 -- Bug 3805136 Do not process excluded supplies
3869                 NVL(atp_peg_tab.exclude_flag(i),0) <> 1 AND
3870                 -- Bug 3761805 Only process the top level pegging in supply chain
3871                 atp_peg_tab.prev_pegging_id(i) IS NULL) THEN
3872 
3873                IF (ABS (L_TOT_RELIEF_QTY ) > 0 ) THEN
3874                  -- Determine the Relief Quantity for this
3875                  -- specific pegging_id.
3876                  IF (ABS (L_TOT_RELIEF_QTY ) >= ABS(atp_peg_tab.allocated_quantity(i)) ) THEN
3877                      l_peg_relief_qty := -1 * ABS(atp_peg_tab.allocated_quantity(i));
3878                  ELSE
3879                      l_peg_relief_qty := L_TOT_RELIEF_QTY;
3880                  END IF;
3881                  -- Start with the planned order corresponding to the sales order
3882                  IF PG_DEBUG in ('Y', 'C') THEN
3883                    msc_util.msc_log('Gen_Atp_Pegging : reference_item_id ' ||
3884                                                 atp_peg_tab.reference_item_id(i) );
3885                    msc_util.msc_log('Gen_Atp_Pegging : Pegging Id ' ||
3886                                              atp_peg_tab.pegging_id(i) );
3887                    msc_util.msc_log('Gen_Atp_Pegging : Prev Pegging Id ' ||
3888                                              atp_peg_tab.prev_pegging_id(i) );
3889                    msc_util.msc_log('Gen_Atp_Pegging : '||
3890                                      'Total Relief Quantity TRACK L_TOT_RELIEF_QTY   ' ||
3891                                              L_TOT_RELIEF_QTY );
3892                    msc_util.msc_log('Gen_Atp_Pegging : '||
3893                                      'Total Relief Quantity for this Pegged Supply  ' ||
3894                                              l_peg_relief_qty );
3895                  END IF;
3896                  Calculate_Relief_Quantities(atp_peg_tab,
3897                           atp_peg_tab.pegging_id(i),
3898                           atp_peg_tab.fixed_lt(i),
3899                           atp_peg_tab.variable_lt(i),
3900                           -- Introduce local peg related relief and ratio.
3901                           atp_peg_tab.tot_relief_qty(i),
3902                           l_peg_relief_qty / atp_peg_tab.tot_relief_qty(i),
3903                           -- Bug 3805136 offset_qty to alloc_qty ratio
3904                           1,
3905                           l_peg_relief_qty,
3906                           atp_peg_tab.end_item_usage(i),
3907                           -- End Bug 3805136
3908                           --atp_peg_tab.tot_relief_qty(i),
3909                           -- Bug 3761805 Pass Config Item Id and END PEG as a parameter
3910                           atp_peg_tab.inventory_item_id(i),
3911                           atp_peg_tab.end_pegging_id(i),
3912                           atp_peg_tab.supply_id(i),
3913                           -- End Bug 3761805
3914                           atp_peg_tab.transaction_date(i),
3915                           l_return_status
3916                           );
3917 
3918                  L_TOT_RELIEF_QTY := L_TOT_RELIEF_QTY - l_peg_relief_qty;
3919                END IF; --  IF (ABS (L_TOT_RELIEF_QTY ) > 0 )
3920 
3921             END IF; -- IF (atp_peg_tab.bom_item_type(i)
3922          END LOOP; -- FOR i in 1..atp_peg_t
3923 
3924           select hsecs
3925           into   l_timestamp
3926           from   v$timer;
3927 
3928          IF PG_DEBUG in ('Y', 'C') THEN
3929            msc_util.msc_log('Gen_Atp_Pegging : Stage 9 After Calculating Reliefs ');
3930            msc_util.msc_log('Gen_Atp_Pegging : TIMESTAMP 6 ' || l_timestamp);
3931          END IF;
3932          -- Generate ATP Resource Pegging.
3933 
3934          Generate_Resource_Pegging (atp_peg_tab, l_return_status);
3935 
3936           select hsecs
3937           into   l_timestamp
3938           from   v$timer;
3939 
3940          IF PG_DEBUG in ('Y', 'C') THEN
3941            msc_util.msc_log('Gen_Atp_Pegging : Stage 10 After Resource Pegging ');
3942            msc_util.msc_log('Gen_Atp_Pegging : TIMESTAMP 7 ' || l_timestamp);
3943          END IF;
3944       END IF;
3945       -- End Bug 3701093
3946 
3947       -- After obtaining all the atp simplified pegging information.
3948 
3949       l_row_count := atp_peg_tab.reference_item_id.COUNT ;
3950       IF PG_DEBUG in ('Y', 'C') THEN
3951            msc_util.msc_log('ATP pegging data will be inserted into ' || l_temp_table);
3952            msc_util.msc_log('Total Records to be inserted ' || l_row_count);
3953       END IF;
3954 
3955       -- Bug 3344102 First insert the data into the global temporary table.
3956 
3957       l_sql_stmt_1 := ' (
3958                        plan_id,
3959                        sr_instance_id,
3960                        reference_item_id,
3961                        inventory_item_id,
3962                        organization_id,
3963                        sales_order_line_id,
3964                        demand_source_type,--cmro
3965                        -- CTO_PF_PRJ changes. use end_demand_id
3966                        end_demand_id,
3967                        bom_item_type,
3968                        sales_order_qty,
3969                        transaction_date,
3970                        demand_id,
3971                        demand_quantity,
3972                        disposition_id,
3973                        demand_class,
3974                        consumed_qty,
3975                        overconsumption_qty,
3976                        supply_id,
3977                        supply_quantity,
3978                        allocated_quantity,
3979                        resource_id,
3980                        department_id,
3981                        resource_hours,
3982                        daily_resource_hours,
3983                        start_date,
3984                        end_date,
3985                        relief_type,
3986                        relief_quantity,
3987                        daily_relief_qty,
3988                        pegging_id,
3989                        prev_pegging_id,
3990                        end_pegging_id,
3991                        created_by,
3992                        creation_date,
3993                        last_updated_by,
3994                        last_update_date )
3995                     VALUES (
3996                        :l_plan_id,
3997                        :l_sr_instance_id,
3998                        :l_reference_item_id,
3999                        :l_inventory_item_id,
4000                        :l_organization_id,
4001                        :l_sales_order_line_id,
4002                        :l_demand_source_type,--cmro
4003                        -- CTO_PF_PRJ changes. use end_demand_id
4004                        :l_end_demand_id,
4005                        :l_bom_item_type,
4006                        :l_ales_order_qty,
4007                        :l_transaction_date,
4008                        :l_demand_id,
4009                        :l_demand_quantity,
4010                        :l_disposition_id,
4011                        :l_demand_class,
4012                        :l_consumed_qty,
4013                        :l_overconsumption_qty,
4014                        :l_supply_id,
4015                        :l_supply_quantity,
4016                        :l_allocated_quantity,
4017                        :l_resource_id,
4018                        :l_department_id,
4019                        :l_resource_hours,
4020                        :l_daily_resource_hours,
4021                        :l_start_date,
4022                        :l_end_date,
4023                        :l_relief_type,
4024                        :l_relief_quantity,
4025                        :l_daily_relief_qty,
4026                        :l_pegging_id,
4027                        :l_prev_pegging_id,
4028                        :l_end_pegging_id,
4029                        :l_user_id,
4030                        :l_sysdate,
4031                        :l_user_id,
4032                        :l_sysdate )';
4033 
4034       l_sql_stmt_2 := ' (
4035                        plan_id,
4036                        sr_instance_id,
4037                        reference_item_id,
4038                        inventory_item_id,
4039                        organization_id,
4040                        sales_order_line_id,
4041                        demand_source_type,--cmro
4042                        -- CTO_PF_PRJ changes. use end_demand_id
4043                        end_demand_id,
4044                        -- CTO-PF
4045                        atf_date,
4046                        product_family_id,
4047                        bom_item_type,
4048                        sales_order_qty,
4049                        transaction_date,
4050                        demand_id,
4051                        demand_quantity,
4052                        disposition_id,
4053                        demand_class,
4054                        consumed_qty,
4055                        overconsumption_qty,
4056                        supply_id,
4057                        supply_quantity,
4058                        allocated_quantity,
4059                        resource_id,
4060                        department_id,
4061                        resource_hours,
4062                        daily_resource_hours,
4063                        start_date,
4064                        end_date,
4065                        relief_type,
4066                        relief_quantity,
4067                        daily_relief_qty,
4068                        pegging_id,
4069                        prev_pegging_id,
4070                        end_pegging_id,
4071                        created_by,
4072                        creation_date,
4073                        last_updated_by,
4074                        last_update_date )
4075                     VALUES (
4076                        :l_plan_id,
4077                        :l_sr_instance_id,
4078                        :l_reference_item_id,
4079                        :l_inventory_item_id,
4080                        :l_organization_id,
4081                        :l_sales_order_line_id,
4082                        :l_demand_source_type,--cmro
4083                        -- CTO_PF_PRJ changes. use end_demand_id
4084                        :l_end_demand_id,
4085                        -- CTO-PF
4086                        :l_atf_date,
4087                        :l_product_family_id,
4088                        :l_bom_item_type,
4089                        :l_ales_order_qty,
4090                        :l_transaction_date,
4091                        :l_demand_id,
4092                        :l_demand_quantity,
4093                        :l_disposition_id,
4094                        :l_demand_class,
4095                        :l_consumed_qty,
4096                        :l_overconsumption_qty,
4097                        :l_supply_id,
4098                        :l_supply_quantity,
4099                        :l_allocated_quantity,
4100                        :l_resource_id,
4101                        :l_department_id,
4102                        :l_resource_hours,
4103                        :l_daily_resource_hours,
4104                        :l_start_date,
4105                        :l_end_date,
4106                        :l_relief_type,
4107                        :l_relief_quantity,
4108                        :l_daily_relief_qty,
4109                        :l_pegging_id,
4110                        :l_prev_pegging_id,
4111                        :l_end_pegging_id,
4112                        :l_user_id,
4113                        :l_sysdate,
4114                        :l_user_id,
4115                        :l_sysdate )';
4116 
4117       FOR i in 1..l_row_count LOOP
4118          IF ( ((G_ALLOC_ATP = 'Y' AND G_CLASS_HRCHY = 1 AND G_ALLOC_METHOD = 1)
4119             -- CTO-PF
4120             OR atp_peg_tab.atf_date(i) is not null )
4121             -- Bug 3701093 Do not store records with relief_quantity 0
4122             -- for relief_types other than 1 i.e., SO.
4123             -- Bug 3761824
4124             AND ( ABS(NVL(atp_peg_tab.relief_quantity(i),0)) > C_ZERO_APPROXIMATOR )
4125             -- Use Zero_Approximator to exclude quantities below 6 levels of precision.
4126             -- End Bug 3761824
4127             AND
4128             atp_peg_tab.relief_type(i) in (2, 3) ) THEN
4129 
4130             l_insert_temp_table := l_global_temp_table;
4131             l_time_phased_atp := 'Y';
4132             l_ins_sql_stmt := 'INSERT INTO '|| l_insert_temp_table || l_sql_stmt_2;
4133 
4134             EXECUTE IMMEDIATE l_ins_sql_stmt USING
4135                    atp_peg_tab.plan_id(i),
4136                    atp_peg_tab.sr_instance_id(i),
4137                    atp_peg_tab.reference_item_id(i),
4138                    atp_peg_tab.inventory_item_id(i),
4139                    atp_peg_tab.organization_id(i),
4140                    atp_peg_tab.sales_order_line_id(i),
4141                    atp_peg_tab.demand_source_type(i),--cmro
4142                    -- CTO_PF_PRJ changes. use end_demand_id
4143                    atp_peg_tab.end_demand_id(i),
4144                    -- CTO-PF
4145                    atp_peg_tab.atf_date(i),
4146                    atp_peg_tab.product_family_id(i),
4147 
4148                    atp_peg_tab.bom_item_type(i),
4149                    atp_peg_tab.sales_order_qty(i),
4150                    atp_peg_tab.transaction_date(i),
4151                    atp_peg_tab.demand_id(i),
4152                    atp_peg_tab.demand_quantity(i),
4153                    atp_peg_tab.disposition_id(i),
4154                    atp_peg_tab.demand_class(i),
4155                    atp_peg_tab.consumed_qty(i),
4156                    atp_peg_tab.overconsumption_qty(i),
4157                    atp_peg_tab.supply_id(i),
4158                    atp_peg_tab.supply_quantity(i),
4159                    atp_peg_tab.allocated_quantity(i),
4160                    atp_peg_tab.resource_id(i),
4161                    atp_peg_tab.department_id(i),
4162                    atp_peg_tab.resource_hours(i),
4163                    atp_peg_tab.daily_resource_hours(i),
4164                    atp_peg_tab.start_date(i),
4165                    atp_peg_tab.end_date(i),
4166                    atp_peg_tab.relief_type(i),
4167                    atp_peg_tab.relief_quantity(i),
4168                    atp_peg_tab.daily_relief_qty(i),
4169                    atp_peg_tab.pegging_id(i),
4170                    atp_peg_tab.prev_pegging_id(i),
4171                    atp_peg_tab.end_pegging_id(i),
4172                    l_user_id,
4173                    l_sysdate,
4174                    l_user_id,
4175                    l_sysdate;
4176 
4177          ELSE
4178            l_insert_temp_table := l_temp_table;
4179            l_ins_sql_stmt := 'INSERT INTO '|| l_insert_temp_table || l_sql_stmt_1;
4180 
4181            -- Bug 3701093 Do not store records with relief_quantity 0
4182            -- for relief_types other than 1 i.e., SO.
4183            IF
4184             -- Bug 3761824
4185              ( ABS(NVL(atp_peg_tab.relief_quantity(i),0)) > C_ZERO_APPROXIMATOR  OR
4186             -- Use Zero_Approximator to exclude quantities below 6 levels of precision.
4187             -- End Bug 3761824
4188                             atp_peg_tab.relief_type(i) = 1) THEN
4189               EXECUTE IMMEDIATE l_ins_sql_stmt USING
4190                    atp_peg_tab.plan_id(i),
4191                    atp_peg_tab.sr_instance_id(i),
4192                    atp_peg_tab.reference_item_id(i),
4193                    atp_peg_tab.inventory_item_id(i),
4194                    atp_peg_tab.organization_id(i),
4195                    atp_peg_tab.sales_order_line_id(i),
4196                    atp_peg_tab.demand_source_type(i),--cmro
4197                    -- CTO_PF_PRJ changes. use end_demand_id
4198                    atp_peg_tab.end_demand_id(i),
4199                    atp_peg_tab.bom_item_type(i),
4200                    atp_peg_tab.sales_order_qty(i),
4201                    atp_peg_tab.transaction_date(i),
4202                    atp_peg_tab.demand_id(i),
4203                    atp_peg_tab.demand_quantity(i),
4204                    atp_peg_tab.disposition_id(i),
4205                    atp_peg_tab.demand_class(i),
4206                    atp_peg_tab.consumed_qty(i),
4207                    atp_peg_tab.overconsumption_qty(i),
4208                    atp_peg_tab.supply_id(i),
4209                    atp_peg_tab.supply_quantity(i),
4210                    atp_peg_tab.allocated_quantity(i),
4211                    atp_peg_tab.resource_id(i),
4212                    atp_peg_tab.department_id(i),
4213                    atp_peg_tab.resource_hours(i),
4214                    atp_peg_tab.daily_resource_hours(i),
4215                    atp_peg_tab.start_date(i),
4216                    atp_peg_tab.end_date(i),
4217                    atp_peg_tab.relief_type(i),
4218                    atp_peg_tab.relief_quantity(i),
4219                    atp_peg_tab.daily_relief_qty(i),
4220                    atp_peg_tab.pegging_id(i),
4221                    atp_peg_tab.prev_pegging_id(i),
4222                    atp_peg_tab.end_pegging_id(i),
4223                    l_user_id,
4224                    l_sysdate,
4225                    l_user_id,
4226                    l_sysdate;
4227            END IF;
4228            -- End Bug 3701093
4229          END IF;
4230          --CTO-PF
4231          IF PG_DEBUG in ('Y', 'C') THEN
4232             msc_util.msc_log('Gen_Atp_Pegging : atf_date ' || atp_peg_tab.atf_date(i));
4233             msc_util.msc_log('Gen_Atp_Pegging : product_family_id ' || atp_peg_tab.product_family_id(i));
4234             msc_util.msc_log('Gen_Atp_Pegging : reference_item_id ' || atp_peg_tab.reference_item_id(i));
4235             msc_util.msc_log('Gen_Atp_Pegging : inventory_item_id ' || atp_peg_tab.inventory_item_id(i));
4236             msc_util.msc_log('Gen_Atp_Pegging : l_time_phased_atp ' || l_time_phased_atp);
4237          END IF;
4238       END LOOP; -- Insert Loop
4239 
4240        IF PG_DEBUG in ('Y', 'C') THEN
4241           msc_util.msc_log('Gen_Atp_Pegging : Rows Procesed ' || SQL%ROWCOUNT );
4242           msc_util.msc_log('Gen_Atp_Pegging : TIMESTAMP 8 ' || l_timestamp);
4243        END IF;
4244       /* commented as a part of CTO-PF
4245       -- Bug 3344102 Second insert the data into the main table.
4246       l_sql_stmt_1 := 'INSERT INTO ' || l_temp_table || '(
4247                        plan_id,
4248                        sr_instance_id,
4249                        reference_item_id,
4250                        inventory_item_id,
4251                        organization_id,
4252                        sales_order_line_id,
4253                        demand_source_type,--cmro
4254                        -- CTO_PF_PRJ changes. use end_demand_id
4255                        end_demand_id,
4256                        bom_item_type,
4257                        sales_order_qty,
4258                        transaction_date,
4259                        demand_id,
4260                        demand_quantity,
4261                        disposition_id,
4262                        demand_class,
4263                        consumed_qty,
4264                        overconsumption_qty,
4265                        supply_id,
4266                        supply_quantity,
4267                        allocated_quantity,
4268                        resource_id,
4269                        department_id,
4270                        resource_hours,
4271                        daily_resource_hours,
4272                        start_date,
4273                        end_date,
4274                        relief_type,
4275                        relief_quantity,
4276                        daily_relief_qty,
4277                        pegging_id,
4278                        prev_pegging_id,
4279                        end_pegging_id,
4280                        created_by,
4281                        creation_date,
4282                        last_updated_by,
4283                        last_update_date )
4284                SELECT
4285                        plan_id,
4286                        sr_instance_id,
4287                        reference_item_id,
4288                        inventory_item_id,
4289                        organization_id,
4290                        sales_order_line_id,
4291                        demand_source_type,--cmro
4292                        -- CTO_PF_PRJ changes. use end_demand_id
4293                        end_demand_id,
4294                        bom_item_type,
4295                        sales_order_qty,
4296                        transaction_date,
4297                        demand_id,
4298                        demand_quantity,
4299                        disposition_id,
4300                        demand_class,
4301                        consumed_qty,
4302                        overconsumption_qty,
4303                        supply_id,
4304                        supply_quantity,
4305                        allocated_quantity,
4306                        resource_id,
4307                        department_id,
4308                        resource_hours,
4309                        daily_resource_hours,
4310                        start_date,
4311                        end_date,
4312                        relief_type,
4313                        relief_quantity,
4314                        daily_relief_qty,
4315                        pegging_id,
4316                        prev_pegging_id,
4317                        end_pegging_id,
4318                        created_by,
4319                        creation_date,
4320                        last_updated_by,
4321                        last_update_date
4322                FROM
4323                        msc_atp_peg_temp
4324                WHERE   plan_id =  :p_plan_id
4325                AND     end_demand_id  = :l_end_demand_id
4326                AND     relief_type in (2, 3)   ';
4327 
4328       IF PG_DEBUG in ('Y', 'C') THEN
4329         msc_util.msc_log('SQL statement to be executed ' || l_sql_stmt_1);
4330       END IF;
4331 
4332       IF l_row_count > 0 THEN
4333          EXECUTE IMMEDIATE l_sql_stmt_1 USING
4334                            p_plan_id,
4335                            atp_peg_tab.end_demand_id(1);
4336       END IF;
4337 
4338       IF PG_DEBUG in ('Y', 'C') THEN
4339           msc_util.msc_log('Gen_Atp_Pegging : Rows Procesed ' || SQL%ROWCOUNT );
4340           msc_util.msc_log('Gen_Atp_Pegging : TIMESTAMP 9 ' || l_timestamp);
4341       END IF;
4342 
4343       -- End Bug 3344102 Secod insert the data into the main table.
4344       */
4345 
4346     END LOOP; -- End config_items loop
4347     -- insert into MSC_ATP_PEG_TEMP_NEW select * from MSC_ATP_PEG_TEMP; --MSC_ATP_PEG_TEMP
4348     -- End Bug 3344102 Call Creation of ATP Pegging Data for Allocated ATP case.
4349     IF  ((G_ALLOC_ATP = 'Y' AND G_CLASS_HRCHY = 1 AND G_ALLOC_METHOD = 1)
4350           AND l_time_phased_atp = 'N') THEN
4351         Create_Pre_Allocation_Reliefs ( p_plan_id,
4352                                         l_temp_table,
4353                                         l_user_id,
4354                                         l_sysdate,
4355                                         l_return_status);
4356     -- CTO-PF start
4357     ELSIF (l_time_phased_atp = 'Y' AND
4358            (G_ALLOC_ATP = 'Y' AND G_CLASS_HRCHY = 1 AND G_ALLOC_METHOD = 1)) THEN
4359 
4360         MSC_ATP_PF.Create_PF_DP_Alloc_Reliefs ( p_plan_id,
4361                                                      l_temp_table,
4362                                                      l_user_id,
4363                                                      l_sysdate,
4364                                                      l_return_status);
4365 
4366     ELSIF (l_time_phased_atp = 'Y') THEN
4367 
4368         MSC_ATP_PF.Create_PF_Allocation_Reliefs ( p_plan_id,
4369                                                   l_temp_table,
4370                                                   l_user_id,
4371                                                   l_sysdate,
4372                                                   l_return_status);
4373 
4374     END IF;
4375     -- CTO-PF end
4376     IF l_return_status <> FND_API.G_RET_STS_SUCCESS THEN
4377        IF PG_DEBUG in ('Y', 'C') THEN
4378            msc_util.msc_log('Gen_Atp_Pegging: ' ||
4379                'Error occured in procedure Create_Pre_Allocation_Reliefs');
4380         END IF;
4381         RAISE FND_API.G_EXC_ERROR;
4382     END IF;
4383     -- End Bug 3344102 After Call to creation of Allocated ATP Pegging Data.
4384 
4385   IF p_share_partition = 'Y' THEN
4386 
4387       IF PG_DEBUG in ('Y', 'C') THEN
4388         msc_util.msc_log('Analyze Plan partition for MSC_ATP_PEGGING');
4389       END IF;
4390         fnd_stats.gather_table_stats(ownname=>'MSC',tabname=>'MSC_ATP_PEGGING',
4391                                    partname=>'ATP_PEGGING_999999',
4392                                    granularity=>'PARTITION',
4393                                    percent =>10);
4394 
4395   ELSE
4396 
4397       -- INDEX CREATION CODE COMES HERE.
4398 
4399       l_sql_stmt := 'CREATE INDEX ' || l_temp_table || '_N1 ON ' || l_temp_table ||
4400                     '(
4401                      Plan_id,
4402                      relief_type,
4403                      sr_instance_id,
4404                      organization_id,
4405                      inventory_item_id,
4406                      Reference_Item_Id,
4407                      -- CTO_PF_PRJ changes use end_demand_id.
4408                      end_demand_id,
4409                      demand_id,
4410                      supply_id,
4411                      resource_id
4412                     )
4413                     STORAGE(INITIAL 40K NEXT 2M PCTINCREASE 0)
4414                     LOCAL TABLESPACE ' || l_ind_tbspace;
4415 
4416       BEGIN
4417         IF PG_DEBUG in ('Y', 'C') THEN
4418            msc_util.msc_log('Before creating index ' || l_temp_table ||
4419                                                 '_N1 for table ');
4420         END IF;
4421            ad_ddl.do_ddl( applsys_schema => p_applsys_schema,
4422                  application_short_name => l_msc_schema,
4423                  statement_type => AD_DDL.CREATE_INDEX,
4424                  statement => l_sql_stmt,
4425                  object_name => l_temp_table );
4426       END ;
4427       l_sql_stmt := 'CREATE INDEX ' || l_temp_table || '_N2 ON ' || l_temp_table ||
4428                     '(
4429                      Plan_id,
4430                      relief_type,
4431                      sales_order_line_id,
4432                      demand_source_type,
4433                      inventory_item_id,
4434                      demand_id
4435                     )
4436                     STORAGE(INITIAL 40K NEXT 2M PCTINCREASE 0)
4437                     LOCAL TABLESPACE ' || l_ind_tbspace;
4438 
4439       BEGIN
4440         IF PG_DEBUG in ('Y', 'C') THEN
4441            msc_util.msc_log('Before creating index ' || l_temp_table ||
4442                                                 '_N2 for table ');
4443         END IF;
4444            ad_ddl.do_ddl( applsys_schema => p_applsys_schema,
4445                  application_short_name => l_msc_schema,
4446                  statement_type => AD_DDL.CREATE_INDEX,
4447                  statement => l_sql_stmt,
4448                  object_name => l_temp_table );
4449       END ;
4450       l_sql_stmt := 'CREATE INDEX ' || l_temp_table || '_N3 ON ' || l_temp_table ||
4451                     '(
4452                      Plan_id,
4453                      relief_type,
4454                      sales_order_line_id,
4455                      demand_source_type,
4456                      inventory_item_id,
4457                      supply_id,
4458                      resource_id
4459                     )
4460                     STORAGE(INITIAL 40K NEXT 2M PCTINCREASE 0)
4461                     LOCAL TABLESPACE ' || l_ind_tbspace;
4462 
4463       BEGIN
4464         IF PG_DEBUG in ('Y', 'C') THEN
4465            msc_util.msc_log('Before creating index ' || l_temp_table ||
4466                                                 '_N3 for table ');
4467         END IF;
4468            ad_ddl.do_ddl( applsys_schema => p_applsys_schema,
4469                  application_short_name => l_msc_schema,
4470                  statement_type => AD_DDL.CREATE_INDEX,
4471                  statement => l_sql_stmt,
4472                  object_name => l_temp_table );
4473       END ;
4474       -- Bug 3629191
4475       l_sql_stmt := 'CREATE INDEX ' || l_temp_table || '_N4 ON ' || l_temp_table ||
4476                     '(
4477                      Plan_id,
4478                      relief_type,
4479                      offset_supply_id,
4480                     )
4481                     STORAGE(INITIAL 40K NEXT 2M PCTINCREASE 0)
4482                     LOCAL TABLESPACE ' || l_ind_tbspace;
4483 
4484       BEGIN
4485         IF PG_DEBUG in ('Y', 'C') THEN
4486            msc_util.msc_log('Before creating index ' || l_temp_table ||
4487                                                 '_N4 for table ');
4488         END IF;
4489            ad_ddl.do_ddl( applsys_schema => p_applsys_schema,
4490                  application_short_name => l_msc_schema,
4491                  statement_type => AD_DDL.CREATE_INDEX,
4492                  statement => l_sql_stmt,
4493                  object_name => l_temp_table );
4494       END ;
4495       IF PG_DEBUG in ('Y', 'C') THEN
4496         msc_util.msc_log('Gather Table Stats for MSC_ATP_PEGGING');
4497       END IF;
4498 
4499       fnd_stats.gather_table_stats('MSC', 'ATP_PEGGING' || to_char(l_plan_id),
4500                 granularity => 'ALL');
4501 
4502       IF PG_DEBUG in ('Y', 'C') THEN
4503         msc_util.msc_log('swap partition ');
4504       END IF;
4505 
4506       l_sql_stmt := 'ALTER TABLE msc_atp_pegging EXCHANGE PARTITION ' ||
4507                           l_partition_name  ||
4508            ' with table MSC_TEMP_ATP_PEGG_'|| to_char(l_plan_id) ||
4509            ' including indexes without validation';
4510 
4511            BEGIN
4512                IF PG_DEBUG in ('Y', 'C') THEN
4513                    msc_util.msc_log('Before alter table msc_atp_pegging');
4514                END IF;
4515                    ad_ddl.do_ddl(APPLSYS_SCHEMA => p_applsys_schema,
4516                    APPLICATION_SHORT_NAME => 'MSC',
4517                    STATEMENT_TYPE => ad_ddl.alter_table,
4518                    STATEMENT => l_sql_stmt,
4519                    OBJECT_NAME => 'MSC_ATP_PEGGING');
4520            END;
4521 
4522   END IF;  -- p_share_partition = 'Y'
4523 
4524 EXCEPTION
4525     WHEN OTHERS THEN
4526       IF PG_DEBUG in ('Y', 'C') THEN
4527         msc_util.msc_log ('Generate_Simplified_Pegging. Error : ' || sqlcode || ': ' || sqlerrm);
4528       END IF;
4529       RETCODE := G_ERROR;
4530 
4531 END Generate_Simplified_Pegging;
4532 
4533 
4534 PROCEDURE post_plan_pegging(
4535         ERRBUF          OUT     NoCopy VARCHAR2,
4536         RETCODE         OUT     NoCopy NUMBER,
4537         p_plan_id       IN      NUMBER)
4538 IS
4539 
4540    l_share_partition               VARCHAR2(1);
4541    l_summary_flag                  NUMBER;
4542    l_plan_name                     VARCHAR2(10);
4543    l_retval                        BOOLEAN;
4544    l_applsys_schema                VARCHAR2(10);
4545    dummy1                          VARCHAR2(10);
4546    dummy2                          VARCHAR2(10);
4547    l_ret_code                      NUMBER;
4548 
4549    l_return_status                 VARCHAR2(40);
4550    l_session_id                    NUMBER;
4551    l_log_file                      VARCHAR2(255);
4552 
4553 BEGIN
4554 
4555     msc_util.msc_log('Begin procedure post_plan_pegging');
4556 
4557     RETCODE := G_SUCCESS;
4558 
4559 
4560     l_share_partition := fnd_profile.value('MSC_SHARE_PARTITIONS');
4561 
4562     msc_util.msc_log('l_share_partition := ' || l_share_partition);
4563 
4564     SELECT NVL(summary_flag,1), compile_designator
4565     INTO   l_summary_flag, l_plan_name
4566     FROM   msc_plans
4567     WHERE  plan_id = p_plan_id;
4568 
4569     IF NVL(l_summary_flag,1) NOT IN
4570             (MSC_POST_PRO.G_SF_SUMMARY_NOT_RUN,
4571              MSC_POST_PRO.G_SF_PREALLOC_COMPLETED,
4572              MSC_POST_PRO.G_SF_SYNC_SUCCESS,
4573              MSC_POST_PRO.G_SF_SUMMARY_COMPLETED,
4574              MSC_POST_PRO.G_SF_ATPPEG_COMPLETED) THEN
4575        msc_util.msc_log('Another session is running post-plan allocation program for this plan');
4576        RETCODE :=  G_ERROR;
4577        RETURN;
4578     END IF;
4579 
4580     -- Bug 3344102 Set Alloc Related Global Variables.
4581     G_ALLOC_ATP := NVL(FND_PROFILE.value('MSC_ALLOCATED_ATP'),'N');
4582     G_CLASS_HRCHY := NVL(FND_PROFILE.VALUE('MSC_CLASS_HIERARCHY'), 2);
4583     G_ALLOC_METHOD := NVL(FND_PROFILE.VALUE('MSC_ALLOCATION_METHOD'), 2);
4584 
4585     msc_util.msc_log('G_ALLOC_ATP    := ' || G_ALLOC_ATP);
4586     msc_util.msc_log('G_CLASS_HRCHY  := ' || G_CLASS_HRCHY);
4587     msc_util.msc_log('G_ALLOC_METHOD := ' || G_ALLOC_METHOD);
4588     -- End Bug 3344102
4589 
4590     msc_util.msc_log('Deleting Existing ATP Pegging data for plan : ' || p_plan_id);
4591 
4592     IF l_share_partition = 'Y' THEN
4593       DELETE from msc_atp_pegging
4594       where  plan_id = p_plan_id;
4595 
4596       IF PG_DEBUG in ('Y', 'C') THEN
4597         msc_util.msc_log ('Post_Plan_Pegging:  Number of rows deleted '|| SQL%ROWCOUNT);
4598       END IF;
4599     END IF;
4600 
4601     l_retval := FND_INSTALLATION.GET_APP_INFO('FND', dummy1, dummy2, l_applsys_schema);
4602 
4603     -- Update summary flag to signify begining of pegging generation
4604     Update_Summary_Flag (   p_plan_id,
4605                             MSC_POST_PRO.G_SF_ATPPEG_RUNNING,
4606                             l_return_status);
4607     IF l_return_status <> FND_API.G_RET_STS_SUCCESS THEN
4608        IF PG_DEBUG in ('Y', 'C') THEN
4609            msc_util.msc_log('Post_Plan_Pegging: ' ||
4610                'Error occured in procedure Update_Summary_Flag');
4611         END IF;
4612         RAISE FND_API.G_EXC_ERROR;
4613     END IF;
4614     BEGIN
4615        IF fnd_global.conc_request_id > 0  THEN
4616           select logfile_name
4617           into   l_log_file
4618           from   fnd_concurrent_requests
4619           where request_id = fnd_global.conc_request_id;
4620          msc_util.msc_log('LOG FILE is: ' || l_log_file);
4621        ELSE
4622          BEGIN
4623             SELECT mrp_atp_schedule_temp_s.currval
4624             INTO   l_session_id
4625             FROM   dual;
4626          EXCEPTION
4627             WHEN OTHERS THEN
4628               SELECT mrp_atp_schedule_temp_s.nextval
4629               INTO   l_session_id
4630               FROM   dual;
4631               order_sch_wb.debug_session_id := l_session_id;
4632          END;
4633 
4634          msc_util.msc_log('Setting ATP Session ID : ' || l_session_id);
4635          msc_util.msc_log('LOG FILE is: session-' || l_session_id);
4636        END IF;
4637 
4638        IF PG_DEBUG in ('Y', 'C') THEN
4639 
4640          msc_util.msc_log('Calling Generate_Simplified_Pegging ' );
4641        END IF;
4642 
4643        MSC_ATP_PEG.Generate_Simplified_Pegging(p_plan_id, l_share_partition,
4644                                                  l_applsys_schema, l_ret_code);
4645        IF PG_DEBUG in ('Y', 'C') THEN
4646          msc_util.msc_log('After Call to Generate_Simplified_Pegging ' );
4647          msc_util.msc_log('Return Code is := ' || l_ret_code);
4648        END IF;
4649        --IF l_ret_code = G_ERROR THEN
4650        --      RETCODE := G_WARNING;  -- For now we are treating this as a warning
4651        --END IF;
4652     EXCEPTION
4653         WHEN OTHERS THEN
4654 
4655           IF PG_DEBUG in ('Y', 'C') THEN
4656             msc_util.msc_log('ERROR IN  Generate_Simplified_Pegging ' );
4657             msc_util.msc_log('ERROR: ' || to_char(SQLCODE));
4658             msc_util.msc_log('ERROR: ' || sqlerrm);
4659           END IF;
4660           RETCODE := G_ERROR;
4661           ERRBUF  := sqlerrm;
4662     END;
4663     -- Update summary flag to signify end of pegging generation
4664     Update_Summary_Flag (   p_plan_id,
4665                             MSC_POST_PRO.G_SF_ATPPEG_COMPLETED,
4666                             l_return_status);
4667     IF l_return_status <> FND_API.G_RET_STS_SUCCESS THEN
4668        IF PG_DEBUG in ('Y', 'C') THEN
4669            msc_util.msc_log('Post_Plan_Pegging: ' ||
4670                'Error occured in procedure Update_Summary_Flag');
4671         END IF;
4672         RAISE FND_API.G_EXC_ERROR;
4673     END IF;
4674 EXCEPTION
4675     WHEN OTHERS THEN
4676       Update_Summary_Flag (   p_plan_id,
4677                             NVL(l_summary_flag, 1),
4678                             l_return_status);
4679 
4680       IF l_return_status <> FND_API.G_RET_STS_SUCCESS THEN
4681          IF PG_DEBUG in ('Y', 'C') THEN
4682              msc_util.msc_log('Post_Plan_Pegging: ' ||
4683                  'Error occured in procedure Update_Summary_Flag');
4684           END IF;
4685       END IF;
4686 
4687       IF PG_DEBUG in ('Y', 'C') THEN
4688         msc_util.msc_log ('post_plan_pegging. Error : ' || sqlerrm);
4689       END IF;
4690       ERRBUF := sqlerrm;
4691       RETCODE := G_ERROR;
4692 
4693 END post_plan_pegging;
4694 
4695 PROCEDURE Add_Offset_Demands (
4696                      p_identifier                      IN NUMBER,
4697                      p_config_line_id                  IN NUMBER,
4698                      p_plan_id                         IN NUMBER,
4699                      p_refresh_number                  IN NUMBER,
4700                      p_order_number                    IN NUMBER,
4701                      p_demand_source_type              IN NUMBER,--cmro
4702                      x_inv_item_id                     IN OUT NoCopy MRP_ATP_PUB.Number_Arr,
4703                      x_demand_id                       IN OUT NoCopy MRP_ATP_PUB.Number_Arr,
4704                      x_demand_instance_id              OUT NoCopy MRP_ATP_PUB.Number_Arr, --Bug 3629191
4705                      x_return_status                   IN OUT NoCopy VARCHAR2
4706                      )
4707 IS
4708     l_del_rows                  NUMBER;
4709     i                           PLS_INTEGER;
4710     my_sqlcode                  NUMBER;
4711 
4712     l_demand_id                 MRP_ATP_PUB.Number_Arr := MRP_ATP_PUB.Number_Arr();
4713     l_demand_qty                MRP_ATP_PUB.Number_Arr := MRP_ATP_PUB.Number_Arr();
4714     l_demand_date               MRP_ATP_PUB.date_arr := MRP_ATP_PUB.date_arr();
4715     l_reference_item_id         MRP_ATP_PUB.Number_Arr := MRP_ATP_PUB.Number_Arr();
4716     l_instance_id               MRP_ATP_PUB.Number_Arr := MRP_ATP_PUB.Number_Arr();
4717     l_organization_id           MRP_ATP_PUB.Number_Arr := MRP_ATP_PUB.Number_Arr();
4718     l_inventory_item_id         MRP_ATP_PUB.Number_Arr := MRP_ATP_PUB.Number_Arr();
4719     l_demand_class              MRP_ATP_PUB.char30_arr := MRP_ATP_PUB.char30_arr();
4720     l_customer_id               MRP_ATP_PUB.Number_Arr := MRP_ATP_PUB.Number_Arr();
4721     l_customer_site_id          MRP_ATP_PUB.Number_Arr := MRP_ATP_PUB.Number_Arr();
4722     l_ship_to_site_id           MRP_ATP_PUB.Number_Arr := MRP_ATP_PUB.Number_Arr();
4723     l_dmd_satisfied_date        MRP_ATP_PUB.date_arr := MRP_ATP_PUB.date_arr();
4724 
4725     l_offset_demand_id          MRP_ATP_PUB.Number_Arr := MRP_ATP_PUB.Number_Arr();
4726     -- Bug 3890723 Introduce a pegging_id array to track pegging
4727     -- For filtering out released/firmed supplies instead of disposition_id array.
4728     l_disposition_id            MRP_ATP_PUB.Number_Arr := MRP_ATP_PUB.Number_Arr(); -- Array retained as FYI for demand offsets.
4729     l_pegging_id                MRP_ATP_PUB.Number_Arr := MRP_ATP_PUB.Number_Arr();
4730     -- End Bug 3890723
4731 
4732     l_sysdate                   DATE;
4733     l_user_id                   number;
4734     l_so_line_ids               MRP_ATP_PUB.Number_Arr := MRP_ATP_PUB.Number_Arr();
4735 
4736     -- Bug 3344102 A variable/handle for processing reliefs/offsets.
4737     l_offset_type               NUMBER;
4738     -- CTO_PF_PRJ_2 Impacts
4739     l_supply_id                 MRP_ATP_PUB.Number_Arr := MRP_ATP_PUB.Number_Arr();
4740     l_original_item_id          MRP_ATP_PUB.Number_Arr := MRP_ATP_PUB.Number_Arr();
4741     l_original_demand_date      MRP_ATP_PUB.date_arr := MRP_ATP_PUB.date_arr();
4742     -- End CTO_PF_PRJ_2 Impacts
4743     -- Bug 3717618 Add supply offset type var. for limiting adjustment to demands
4744     -- that are pegged to supplies that can be relieved.
4745     l_sup_offset_type        NUMBER;
4746 BEGIN
4747 
4748   IF PG_DEBUG in ('Y', 'C') THEN
4749      msc_sch_wb.atp_debug('***** Begin Add_Offset_Demands *****');
4750   END IF;
4751 
4752   IF PG_DEBUG in ('Y', 'C') THEN
4753      msc_sch_wb.atp_debug('Add_Offset_Demands: ' ||
4754                           'Offsetting msc_demands for identifier = '
4755                           || p_identifier ||' : plan id = '||p_plan_id);
4756      msc_sch_wb.atp_debug('Add_Offset_Demands: ' || 'Config Line Id = ' || p_config_line_id );
4757   END IF;
4758 
4759   x_return_status := FND_API.G_RET_STS_SUCCESS;
4760 
4761   l_sysdate := sysdate;
4762   l_user_id := FND_GLOBAL.USER_ID;
4763 
4764   -- CTO_PF_PRJ_2 Impacts
4765   IF ((MSC_ATP_PVT.G_INV_CTP = 4) AND
4766       (MSC_ATP_PVT.G_ALLOCATED_ATP = 'Y') AND
4767       (MSC_ATP_PVT.G_HIERARCHY_PROFILE = 1) AND
4768       (MSC_ATP_PVT.G_ALLOCATION_METHOD = 1)) THEN
4769 
4770      l_offset_type := 5;
4771      -- Bug 3717618 Set value of supply relief type.
4772      l_sup_offset_type := 6;
4773   ELSE
4774      l_offset_type := 3;
4775      -- Bug 3717618 Set value of supply relief type.
4776      l_sup_offset_type := 2;
4777   END IF;
4778   -- CTO_PF_PRJ_2 Impacts
4779 
4780   IF PG_DEBUG in ('Y', 'C') THEN
4781       msc_sch_wb.atp_debug('Add_Offset_Demands: Dmd. Offset Type Set to '|| l_offset_type);
4782       -- Bug 3717618 Set value of supply relief type.
4783       msc_sch_wb.atp_debug('Add_Offset_Demands: Sup. Offset Type Set to '|| l_sup_offset_type);
4784   END IF;
4785 
4786   -- CTO_PF_PRJ_2 Impacts
4787   SELECT msc_demands_s.nextval ,
4788          map.relief_quantity   ,
4789          NVL(map.original_date, map.transaction_date) transaction_date ,
4790          -- End CTO_PF_PRJ_2 Impacts
4791          map.reference_item_id,
4792          map.sr_instance_id,
4793          map.organization_id,
4794          -- CTO_PF_PRJ_2 Impacts
4795          NVL(map.original_item_id, map.inventory_item_id) inventory_item_id,
4796          -- End CTO_PF_PRJ_2 Impacts
4797          map.demand_class,
4798          d.customer_id,
4799          d.customer_site_id,
4800          d.ship_to_site_id,
4801          d.dmd_satisfied_date,
4802          -- Bug 3890723 Introduce a pegging_id array to track pegging
4803          -- For filtering out released/firmed supplies instead of disposition_id array.
4804          map.disposition_id,
4805          map.prev_pegging_id,
4806          -- End Bug 3890723
4807          map.demand_id,
4808          map.sales_order_line_id,
4809          -- CTO_PF_PRJ Impacts
4810          NVL(map.supply_id, -1) supply_id,
4811          map.ORIGINAL_ITEM_ID,
4812          map.ORIGINAL_DATE
4813          -- End CTO_PF_PRJ Impacts
4814   BULK COLLECT
4815   INTO   x_demand_id,
4816          l_demand_qty,
4817          l_demand_date,
4818          l_reference_item_id,
4819          l_instance_id, -- Bug 3629191, Return it as out parameter
4820          l_organization_id,
4821          x_inv_item_id,
4822          l_demand_class,
4823          l_customer_id,
4824          l_customer_site_id,
4825          l_ship_to_site_id,
4826          l_dmd_satisfied_date,
4827          -- Bug 3890723 Introduce a pegging_id array to track pegging
4828          -- For filtering out released/firmed supplies instead of disposition_id array.
4829          l_disposition_id, -- Array retained as FYI for demand offsets.
4830          l_pegging_id,
4831          -- End Bug 3890723
4832          l_offset_demand_id,
4833          l_so_line_ids,
4834          -- CTO_PF_PRJ Impacts
4835          l_supply_id,
4836          l_original_item_id,
4837          l_original_demand_date
4838          -- End CTO_PF_PRJ Impacts
4839   FROM
4840          msc_atp_pegging map,
4841          msc_demands d
4842   WHERE  map.plan_id = p_plan_id
4843   --AND  map.sr_instance_id = p_instance_id  -- removed to support multiple instances in plan.
4844   AND    map.sales_order_line_id in (p_identifier, p_config_line_id)
4845          -- CTO_PF_PRJ_2 Impacts
4846   AND    map.relief_type in (l_offset_type, 7)  -- POD
4847          -- End CTO_PF_PRJ_2 Impacts
4848   -- Bug 3890723 Use only pegging_id as a filter
4849   -- ATP created transactions will not have disposition_id populated.
4850   -- Bug 3717618 Only offset demands pegged to supplies that are relieved
4851   -- using filter on disposition_id
4852   -- AND    (map.disposition_id, map.prev_pegging_id) IN
4853   AND    (map.prev_pegging_id) IN
4854          (SELECT map2.pegging_id
4855   -- End Bug 3890723
4856           FROM   msc_atp_pegging map2
4857           WHERE  map2.plan_id = p_plan_id
4858           AND    map2.sales_order_line_id in (p_identifier, p_config_line_id)
4859           AND    DECODE(map2.demand_source_type,100,map2.demand_source_type,-1)
4860                   =decode(p_demand_source_type,
4861                                            100,
4862                                             p_demand_source_type,
4863                                            -1) --CMRO
4864           AND    map2.offset_supply_id IS NOT NULL
4865           AND    map2.relief_type = l_sup_offset_type
4866          )
4867   -- End Bug 3717618
4868   AND    ABS(map.relief_quantity) > C_ZERO_APPROXIMATOR
4869   -- Bug 3761824 Use Precision figure while creating ofsets.
4870   AND    DECODE(d.demand_source_type,100,d.demand_source_type,-1)
4871                =decode(p_demand_source_type,
4872                                            100,
4873                                             p_demand_source_type,
4874                                            -1) --CMRO
4875   AND    d.plan_id (+) = map.plan_id
4876   AND    d.organization_id (+) = map.organization_id
4877   AND    d.demand_id (+) = map.demand_id
4878   AND    d.inventory_item_id (+) = map.inventory_item_id
4879   ;
4880   -- End CTO_PF_PRJ_2 Impacts
4881 
4882   x_demand_instance_id := l_instance_id; --Bug 3629191
4883 
4884   l_del_rows := x_demand_id.COUNT;
4885 
4886   FORALL i in 1..l_del_rows
4887      INSERT INTO msc_demands (
4888                  DEMAND_ID,
4889                  USING_REQUIREMENT_QUANTITY,
4890                  USING_ASSEMBLY_DEMAND_DATE,
4891                  DEMAND_TYPE,
4892                  ORIGINATION_TYPE,
4893                  USING_ASSEMBLY_ITEM_ID,
4894                  PLAN_ID,
4895                  ORGANIZATION_ID,
4896                  INVENTORY_ITEM_ID,
4897                  DEMAND_SOURCE_TYPE,--cmro
4898                  SALES_ORDER_LINE_ID,
4899                  SR_INSTANCE_ID,
4900                  LAST_UPDATE_DATE,
4901                  LAST_UPDATED_BY,
4902                  CREATION_DATE,
4903                  CREATED_BY,
4904                  DEMAND_CLASS,
4905                  REFRESH_NUMBER,
4906                  ORDER_NUMBER,
4907                  CUSTOMER_ID,
4908                  CUSTOMER_SITE_ID,
4909                  SHIP_TO_SITE_ID,
4910                  RECORD_SOURCE,  -- For plan order pegging
4911                  -- 24x7
4912                  ATP_SYNCHRONIZATION_FLAG,
4913                  DMD_SATISFIED_DATE,
4914                  DISPOSITION_ID
4915              --    ,OFFSET_DEMAND_ID
4916                  )
4917          VALUES (x_demand_id(i),
4918                  l_demand_qty(i),
4919                  --bug 3328421: Add at the end of the day
4920                  trunc(l_demand_date(i)) + MSC_ATP_PVT.G_END_OF_DAY ,
4921                  --l_demand_date(i),
4922                  1 ,   -- discrete demand
4923                  60,  -- offset demand
4924                  l_reference_item_id(i),  -- inventory_item_id
4925                  p_plan_id,
4926                  l_organization_id(i),
4927                  x_inv_item_id(i),
4928                  p_demand_source_type,--cmro
4929                  l_so_line_ids(i),
4930                  l_instance_id(i),
4931                  l_sysdate,
4932                  l_user_id,
4933                  l_sysdate,
4934                  l_user_id,
4935                  l_demand_class(i),
4936                  p_refresh_number,
4937                  p_order_number,
4938                  l_customer_id(i),
4939                  l_customer_site_id(i),
4940                  l_ship_to_site_id(i),
4941                  2,
4942                  0,
4943                  l_dmd_satisfied_date(i),
4944                  l_disposition_id(i)
4945                --  ,l_offset_demand_id(i)
4946                 );
4947 
4948       IF PG_DEBUG in ('Y', 'C') THEN
4949              msc_sch_wb.atp_debug('Add_Offset_Demands:  Number of rows inserted '||
4950                                SQL%ROWCOUNT);
4951       END IF;
4952 
4953       -- Allocated ATP Based on Planning Details
4954 
4955       IF ((MSC_ATP_PVT.G_INV_CTP = 4) AND
4956           (MSC_ATP_PVT.G_ALLOCATED_ATP = 'Y') AND
4957           (MSC_ATP_PVT.G_HIERARCHY_PROFILE = 1) AND
4958           (MSC_ATP_PVT.G_ALLOCATION_METHOD = 1)) THEN
4959 
4960          IF PG_DEBUG in ('Y', 'C') THEN
4961              msc_sch_wb.atp_debug('Add_Offset_Demands: before insert into'||
4962                                ' msc_alloc_demands');
4963          END IF;
4964 
4965          -- CTO_PF_PRJ2 relief_type already set above.
4966          -- Bug 3344102 First set offset type to 5  for alloc reliefs.
4967          -- l_offset_type := 5;
4968          -- CTO_PF_PRJ2
4969 
4970          -- Try to apply the offsets using alloc specific relief_type.
4971 
4972          FORALL i in 1..x_demand_id.COUNT
4973            INSERT INTO MSC_ALLOC_DEMANDS(
4974                        PLAN_ID,
4975                        INVENTORY_ITEM_ID,
4976                        ORGANIZATION_ID,
4977                        SR_INSTANCE_ID,
4978                        DEMAND_CLASS,
4979                        DEMAND_DATE,
4980                        PARENT_DEMAND_ID,
4981                        ALLOCATED_QUANTITY,
4982                        ORIGINATION_TYPE,
4983                        ORDER_NUMBER,
4984                        DEMAND_SOURCE_TYPE,--cmro
4985                        SALES_ORDER_LINE_ID,
4986                        CREATED_BY,
4987                        CREATION_DATE,
4988                        LAST_UPDATED_BY,
4989                        LAST_UPDATE_DATE,
4990                        refresh_number,
4991                        -- CTO_PF_PRJ_2 Impacts
4992                        ORIGINAL_ITEM_ID,
4993                        ORIGINAL_DEMAND_DATE,
4994                        ORIGINAL_ORIGINATION_TYPE,
4995                        PF_DISPLAY_FLAG
4996                        -- END CTO_PF_PRJ_2 Impacts
4997                        )
4998            SELECT
4999                    map.plan_id,
5000                    map.inventory_item_id,
5001                    map.organization_id,
5002                    map.sr_instance_id,
5003                    map.demand_class,
5004                    map.transaction_date,
5005                    x_demand_id(i),
5006                    NVL(map.relief_quantity, 0),
5007                    Decode(map.relief_type, 7, 51, 60),
5008                    --60,
5009                    p_order_number,
5010                    p_demand_source_type,--cmro
5011                    map.sales_order_line_id,
5012                    l_user_id,
5013                    l_sysdate,
5014                    l_user_id,
5015                    l_sysdate,
5016                    p_refresh_number,
5017                    -- CTO_PF_PRJ_2 Impacts
5018                    l_original_item_id(i),
5019                    l_original_demand_date(i),
5020                    Decode(map.relief_type, 7, 60, NULL),
5021                    --Decode(map.relief_type, 7, 51, 60),
5022                    Decode(map.relief_type, 7, 1, NULL)
5023                    -- pf_display_flag = 1 when offseting bucketed demand.
5024                    -- NULL will be the default value.
5025                    -- END CTO_PF_PRJ_2 Impacts
5026            FROM    msc_atp_pegging map
5027            WHERE   map.sr_instance_id = l_instance_id(i)
5028            AND     map.plan_id = p_plan_id
5029            AND     DECODE(map.demand_source_type,100,map.demand_source_type,-1)
5030                    =decode(p_demand_source_type,
5031                                                 100,
5032                                                 p_demand_source_type,
5033                                                 -1) --CMRO
5034            AND     map.sales_order_line_id in (p_identifier, p_config_line_id)
5035            AND     map.relief_type in (5,  7)  -- POD
5036            AND     NVL(map.original_item_id, map.inventory_item_id) =
5037                                NVL(l_original_item_id(i), x_inv_item_id(i))
5038            AND     map.relief_quantity = l_demand_qty(i)
5039            AND     NVL(map.original_date, l_sysdate) = NVL(l_original_demand_date(i), l_sysdate)
5040            -- FOR ATP created records only relieve PF, do not offset other demands
5041            -- as they are set to 0 already in Delete_Row.
5042            AND     NVL(map.supply_id,  100) = l_supply_id(i)
5043            --AND     NVL(map.supply_id, DECODE(map.relief_type, 7, -1, 100)) = l_supply_id(i)
5044            -- Bug 3890723 Use  pegging_id array to track pegging
5045            -- For filtering out released/firmed supplies instead of disposition_id array.
5046            -- Bug 3717618 Only offset demands pegged to supplies that are relieved
5047            -- using filter on disposition_id
5048            -- AND     map.disposition_id = l_disposition_id(i)
5049            AND     map.prev_pegging_id = l_pegging_id(i)
5050            -- End Bug 3890723
5051            AND     map.demand_id = l_offset_demand_id(i);
5052 
5053            FOR i in 1..x_demand_id.COUNT LOOP
5054               msc_sch_wb.atp_debug('Demand to be offset ' || l_offset_demand_id(i));
5055               msc_sch_wb.atp_debug('Original Item ' || l_original_item_id(i));
5056               msc_sch_wb.atp_debug('Actual Item ' || x_inv_item_id(i));
5057               msc_sch_wb.atp_debug('Original Date ' || l_original_demand_date(i));
5058               msc_sch_wb.atp_debug('Supply ID ' || l_supply_id(i));
5059               msc_sch_wb.atp_debug('New Demand ' || x_demand_id(i));
5060               msc_sch_wb.atp_debug('Add_Offset_Demands:  Number of Family rows inserted '||
5061                   'For Demand id '|| l_offset_demand_id(i) ||
5062                   ' with offset/relief_type 5 or 7 is ' || SQL%BULK_ROWCOUNT(i));
5063            END LOOP;
5064          IF PG_DEBUG in ('Y', 'C') THEN
5065                 msc_sch_wb.atp_debug('Add_Offset_Demands:  Number of Family and Alloc rows inserted '||
5066                       'with offset/relief_type = 7 or ' ||l_offset_type || 'is ' || SQL%ROWCOUNT);
5067          END IF;
5068 
5069          -- CTO_PF_PRJ_2
5070          -- Cascading SQLs no longer necessary
5071          --IF SQL%ROWCOUNT = 0 THEN
5072 
5073            -- Apply using standard demands relief_type
5074 
5075 
5076          -- END IF;
5077          -- End Bug 3344102
5078          -- END CTO_PF_PRJ_2
5079 
5080            IF PG_DEBUG in ('Y', 'C') THEN
5081                 msc_sch_wb.atp_debug('Add_Offset_Demands:  adjust stealing supplies');
5082                 msc_sch_wb.atp_debug(' Number of SO lines to be adjusted := ' || l_so_line_ids.count);
5083                 For i in 1..l_so_line_ids.count LOOP
5084                    msc_sch_wb.atp_debug('Line id # ' || i || ' := ' || l_so_line_ids(i));
5085                 END LOOP;
5086 
5087            END IF;
5088 
5089            ---update records due to supply/demand stealing
5090            IF l_so_line_ids.count > 0 THEN
5091               update msc_alloc_supplies
5092               set allocated_quantity = 0
5093               where plan_id = p_plan_id
5094               and   sr_instance_id = l_instance_id(1)
5095               and   ato_model_line_id  = p_identifier
5096               and     DECODE(demand_source_type,100,demand_source_type,-1)
5097                       =decode(p_demand_source_type,
5098                                                 100,
5099                                                 p_demand_source_type,
5100                                                 -1) --CMRO;
5101               and   order_type in (46, 47);
5102            END IF;
5103            IF PG_DEBUG in ('Y', 'C') THEN
5104                 msc_sch_wb.atp_debug('Add_Offset_Demands:  Number of stealing rows updated '||
5105                                SQL%ROWCOUNT);
5106            END IF;
5107 
5108       -- Offset Product Family Demands if any
5109       ELSE
5110          -- Try to apply the offsets using alloc specific relief_type.
5111 
5112          FORALL i in 1..x_demand_id.COUNT
5113            INSERT INTO MSC_ALLOC_DEMANDS(
5114                        PLAN_ID,
5115                        INVENTORY_ITEM_ID,
5116                        ORGANIZATION_ID,
5117                        SR_INSTANCE_ID,
5118                        DEMAND_CLASS,
5119                        DEMAND_DATE,
5120                        PARENT_DEMAND_ID,
5121                        ALLOCATED_QUANTITY,
5122                        ORIGINATION_TYPE,
5123                        ORDER_NUMBER,
5124                        DEMAND_SOURCE_TYPE,--cmro
5125                        SALES_ORDER_LINE_ID,
5126                        CREATED_BY,
5127                        CREATION_DATE,
5128                        LAST_UPDATED_BY,
5129                        LAST_UPDATE_DATE,
5130                        refresh_number,
5131                        -- CTO_PF_PRJ_2 Impacts
5132                        ORIGINAL_ITEM_ID,
5133                        ORIGINAL_DEMAND_DATE,
5134                        ORIGINAL_ORIGINATION_TYPE,
5135                        PF_DISPLAY_FLAG
5136                        -- END CTO_PF_PRJ_2 Impacts
5137                        )
5138            SELECT
5139                    map.plan_id,
5140                    map.inventory_item_id,
5141                    map.organization_id,
5142                    map.sr_instance_id,
5143                    map.demand_class,
5144                    map.transaction_date,
5145                    x_demand_id(i),
5146                    NVL(map.relief_quantity, 0),
5147                    Decode(map.relief_type, 7, 51, 60),
5148                    --60,
5149                    p_order_number,
5150                    p_demand_source_type,--cmro
5151                    map.sales_order_line_id,
5152                    l_user_id,
5153                    l_sysdate,
5154                    l_user_id,
5155                    l_sysdate,
5156                    p_refresh_number,
5157                    -- CTO_PF_PRJ_2 Impacts
5158                    l_original_item_id(i),
5159                    l_original_demand_date(i),
5160                    Decode(map.relief_type, 7, 60, NULL),
5161                    --Decode(map.relief_type, 7, 51, 60),
5162                    1  -- Always 1 for PF.
5163                    -- END CTO_PF_PRJ_2 Impacts
5164            FROM    msc_atp_pegging map
5165            WHERE   map.sr_instance_id = l_instance_id(i)
5166            AND     map.plan_id = p_plan_id
5167            AND     DECODE(map.demand_source_type,100,map.demand_source_type,-1)
5168                    =decode(p_demand_source_type,
5169                                                 100,
5170                                                 p_demand_source_type,
5171                                                 -1) --CMRO
5172            AND     map.sales_order_line_id in (p_identifier, p_config_line_id)
5173            AND     map.relief_type = 7   -- POD for family item.
5174            AND     NVL(map.original_item_id, map.inventory_item_id) =
5175                                NVL(l_original_item_id(i), x_inv_item_id(i))
5176            AND     map.relief_quantity = l_demand_qty(i)
5177            AND     NVL(map.original_date, l_sysdate) = NVL(l_original_demand_date(i), l_sysdate)
5178            AND     NVL(map.supply_id, -1) = l_supply_id(i)
5179            -- Bug 3890723 Use  pegging_id array to track pegging
5180            -- For filtering out released/firmed supplies instead of disposition_id array.
5181            -- Bug 3717618 Only offset demands pegged to supplies that are relieved
5182            -- using filter on disposition_id
5183            -- AND     map.disposition_id = l_disposition_id(i)
5184            AND     map.prev_pegging_id = l_pegging_id(i)
5185            -- End Bug 3890723
5186            AND     map.demand_id = l_offset_demand_id(i);
5187 
5188          IF PG_DEBUG in ('Y', 'C') THEN
5189            FOR i in 1..x_demand_id.COUNT LOOP
5190               msc_sch_wb.atp_debug('Demand to be offset ' || l_offset_demand_id(i));
5191               msc_sch_wb.atp_debug('Original Item ' || l_original_item_id(i));
5192               msc_sch_wb.atp_debug('Original Date ' || l_original_demand_date(i));
5193               msc_sch_wb.atp_debug('Supply ID ' || l_supply_id(i));
5194               msc_sch_wb.atp_debug('New Demand ' || x_demand_id(i));
5195               msc_sch_wb.atp_debug('Add_Offset_Demands:  Number of Family rows inserted '||
5196                   'For Demand id '|| l_offset_demand_id(i) ||
5197                   ' with offset/relief_type = 7 is ' || SQL%BULK_ROWCOUNT(i));
5198            END LOOP;
5199                 msc_sch_wb.atp_debug('Add_Offset_Demands:  Number of Family rows inserted '||
5200                       'with offset/relief_type = 7 is ' || SQL%ROWCOUNT);
5201          END IF;
5202       END IF; --IF ((MSC_ATP_PVT.G_INV_CTP = 4) AND  basically, IF ALLOC
5203 
5204   IF PG_DEBUG in ('Y', 'C') THEN
5205      msc_sch_wb.atp_debug('***** End Add_Offset_Demands *****');
5206   END IF;
5207 
5208 EXCEPTION
5209     WHEN OTHERS THEN
5210         my_sqlcode := SQLCODE;
5211         IF PG_DEBUG in ('Y', 'C') THEN
5212            msc_sch_wb.atp_debug('Add_Offset_Demands: ' ||
5213                 'error in insert row: sqlcode =  '|| to_char(my_sqlcode));
5214            msc_sch_wb.atp_debug('Add_Offset_Demands: ERROR- ' || sqlerrm );
5215         END IF;
5216 
5217         IF FND_MSG_PUB.Check_Msg_Level(FND_MSG_PUB.G_MSG_LVL_UNEXP_ERROR) THEN
5218             FND_MSG_PUB.Add_Exc_Msg(G_PKG_NAME , 'Add_Offset_Demands');
5219         END IF;
5220         x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
5221         -- Bug 3319810 Enable exception generation.
5222         RAISE FND_API.G_EXC_UNEXPECTED_ERROR;
5223 END Add_Offset_Demands;
5224 
5225 PROCEDURE Add_Offset_Supplies (
5226                      p_identifier                      IN NUMBER,
5227                      p_config_line_id                  IN NUMBER,
5228                      p_plan_id                         IN NUMBER,
5229                      p_refresh_number                  IN NUMBER,
5230                      p_order_number                    IN NUMBER,
5231                      p_demand_source_type              IN NUMBER,--cmro
5232                      x_inv_item_id                     IN OUT NoCopy MRP_ATP_PUB.Number_Arr,
5233                      x_supply_id                       IN OUT NoCopy MRP_ATP_PUB.Number_Arr,
5234                      x_supply_instance_id              OUT NoCopy MRP_ATP_PUB.Number_Arr, --Bug 3629191
5235                      x_return_status                   IN OUT NoCopy VARCHAR2
5236                      )
5237 IS
5238     l_del_rows                  NUMBER;
5239     i                           PLS_INTEGER;
5240     my_sqlcode                  NUMBER;
5241 
5242     l_supply_id                 MRP_ATP_PUB.Number_Arr := MRP_ATP_PUB.Number_Arr();
5243     l_instance_id               MRP_ATP_PUB.Number_Arr := MRP_ATP_PUB.Number_Arr();
5244     l_organization_id           MRP_ATP_PUB.Number_Arr := MRP_ATP_PUB.Number_Arr();
5245     l_inventory_item_id         MRP_ATP_PUB.Number_Arr := MRP_ATP_PUB.Number_Arr();
5246     l_supply_date               MRP_ATP_PUB.date_arr := MRP_ATP_PUB.date_arr();
5247     l_supply_qty                MRP_ATP_PUB.Number_Arr := MRP_ATP_PUB.Number_Arr();
5248     l_reference_item_id         MRP_ATP_PUB.Number_Arr := MRP_ATP_PUB.Number_Arr();
5249     l_demand_class              MRP_ATP_PUB.char30_arr := MRP_ATP_PUB.char30_arr();
5250     l_supplier_id               MRP_ATP_PUB.Number_Arr := MRP_ATP_PUB.Number_Arr();
5251     l_supplier_site_id          MRP_ATP_PUB.Number_Arr := MRP_ATP_PUB.Number_Arr();
5252     l_src_supplier_id           MRP_ATP_PUB.Number_Arr := MRP_ATP_PUB.Number_Arr();
5253     l_src_supplier_site_id      MRP_ATP_PUB.Number_Arr := MRP_ATP_PUB.Number_Arr();
5254     l_src_instance_id           MRP_ATP_PUB.Number_Arr := MRP_ATP_PUB.Number_Arr();
5255     l_src_org_id                MRP_ATP_PUB.Number_Arr := MRP_ATP_PUB.Number_Arr();
5256     l_process_seq_id            MRP_ATP_PUB.Number_Arr := MRP_ATP_PUB.Number_Arr();
5257     l_customer_id               MRP_ATP_PUB.Number_Arr := MRP_ATP_PUB.Number_Arr();
5258     l_ship_to_site_id           MRP_ATP_PUB.Number_Arr := MRP_ATP_PUB.Number_Arr();
5259     l_firm_planned_type         MRP_ATP_PUB.Number_Arr := MRP_ATP_PUB.Number_Arr();
5260 
5261     l_offset_supply_id          MRP_ATP_PUB.Number_Arr := MRP_ATP_PUB.Number_Arr();
5262     l_sysdate                   DATE;
5263     l_user_id                   number;
5264     l_dock_date                 MRP_ATP_PUB.date_arr := MRP_ATP_PUB.date_arr();
5265     l_ship_date                 MRP_ATP_PUB.date_arr := MRP_ATP_PUB.date_arr();
5266 
5267     -- Bug 3344102 A variable/handle for processing reliefs/offsets.
5268     l_offset_type               NUMBER := NULL;
5269 
5270     -- Bug 3381464 Array to track original supplies for updating msc_atp_pegging
5271     l_orig_supply_id            MRP_ATP_PUB.Number_Arr := MRP_ATP_PUB.Number_Arr();
5272     -- Bug 3717618 Introduce a pegging_id array to track pegging
5273     -- For filtering out released/firmed supplies and pegging both are needed.
5274     l_pegging_id                MRP_ATP_PUB.Number_Arr := MRP_ATP_PUB.Number_Arr();
5275 
5276 BEGIN
5277 
5278     IF PG_DEBUG in ('Y', 'C') THEN
5279         msc_sch_wb.atp_debug('***** Begin Add_Offset_Supplies *****');
5280     END IF;
5281     IF PG_DEBUG in ('Y', 'C') THEN
5282        msc_sch_wb.atp_debug('Add_Offset_Supplies: ' ||
5283                             'Offsetting msc_supplies for identifier = '
5284                             || p_identifier ||' : plan id = '||p_plan_id);
5285      msc_sch_wb.atp_debug('Add_Offset_Supplies: ' || 'Config Line Id = ' || p_config_line_id );
5286     END IF;
5287 
5288     x_return_status := FND_API.G_RET_STS_SUCCESS;
5289 
5290     l_sysdate := sysdate;
5291     l_user_id := FND_GLOBAL.USER_ID;
5292 
5293     -- CTO_PF_PRJ_2 Changes
5294     IF ((MSC_ATP_PVT.G_INV_CTP = 4) AND
5295       (MSC_ATP_PVT.G_ALLOCATED_ATP = 'Y') AND
5296       (MSC_ATP_PVT.G_HIERARCHY_PROFILE = 1) AND
5297       (MSC_ATP_PVT.G_ALLOCATION_METHOD = 1)) THEN
5298 
5299        l_offset_type := 6;
5300     ELSE
5301        l_offset_type := 2;
5302     END IF;
5303     -- End CTO_PF_PRJ_2 Changes
5304 
5305     IF PG_DEBUG in ('Y', 'C') THEN
5306        msc_sch_wb.atp_debug('Add_Offset_Supplies: Offset Type Set to '|| l_offset_type);
5307     END IF;
5308 
5309     -- Insert relief quantities as a Offsets in msc_supplies
5310 
5311     -- CTO_PF_PRJ_2 Changes
5312     SELECT   msc_supplies_s.nextval,
5313              map.sr_instance_id,
5314              map.organization_id,
5315              map.inventory_item_id,
5316              map.relief_quantity relief_quantity,
5317              map.transaction_date,
5318              -- Bug 3717618 Fetch pegging as well.
5319              map.pegging_id,
5320              -- Bug 3381464 Get original supply id
5321              s.transaction_id orig_supply_id,
5322              s.supplier_id,
5323              s.supplier_site_id,
5324              s.source_supplier_id,
5325              s.source_supplier_site_id,
5326              s.source_sr_instance_id,
5327              s.source_organization_id,
5328              s.process_seq_id,
5329              s.firm_planned_type,
5330              s.demand_class,
5331              s.customer_id,
5332              s.ship_to_site_id,
5333              s.transaction_id,
5334              s.new_ship_date,
5335              s.new_dock_date
5336     BULK COLLECT
5337     INTO     x_supply_id,
5338              l_instance_id,
5339              l_organization_id,
5340              x_inv_item_id,
5341              l_supply_qty,
5342              l_supply_date,
5343              -- Bug 3717618 Introduce a pegging_id array to track pegging
5344              -- For filtering out, released/firmed supplies and pegging both are needed.
5345              l_pegging_id,
5346              -- Bug 3381464 Get original supply id
5347              l_orig_supply_id,
5348              l_supplier_id,
5349              l_supplier_site_id,
5350              l_src_supplier_id,
5351              l_src_supplier_site_id,
5352              l_src_instance_id,
5353              l_src_org_id,
5354              l_process_seq_id,
5355              l_firm_planned_type,
5356              l_demand_class,
5357              l_customer_id,
5358              l_ship_to_site_id,
5359              l_offset_supply_id,
5360              l_ship_date,
5361              l_dock_date
5362     FROM
5363              msc_atp_pegging map,
5364              msc_supplies s
5365     WHERE    map.plan_id = p_plan_id
5366     --AND    map.sr_instance_id = p_instance_id  -- removed to support multiple instances in plan.
5367     AND      DECODE(map.demand_source_type,100,map.demand_source_type,-1)
5368                 =decode(p_demand_source_type,
5369                                         100,
5370                                         p_demand_source_type,
5371                                         -1) --CMRO;
5372     AND      map.sales_order_line_id in (p_identifier, p_config_line_id)
5373              -- CTO_PF_PRJ_2 Impacts Use the proper adjustment type.
5374     AND      map.relief_type = l_offset_type  -- PO
5375              -- End CTO_PF_PRJ_2 Impacts.
5376     -- Bug 3717618 Ensure that Firm or Released supplies are not included.
5377     AND      (map.supply_id, map.pegging_id) NOT IN
5378              (SELECT supply_id, pegging_id
5379               FROM   msc_atp_pegging mapeg1
5380               WHERE  plan_id = p_plan_id
5381               AND    DECODE(mapeg1.demand_source_type,100,mapeg1.demand_source_type,-1)
5382                      =decode(p_demand_source_type, 100,
5383                                      p_demand_source_type, -1) --CMRO
5384               AND    sales_order_line_id in (p_identifier, p_config_line_id)
5385               AND    relief_type in (1, l_offset_type)
5386               START WITH plan_id = p_plan_id
5387               AND    DECODE(mapeg1.demand_source_type,100,mapeg1.demand_source_type,-1)
5388                      =decode(p_demand_source_type, 100,
5389                                      p_demand_source_type, -1) --CMRO
5390               AND   sales_order_line_id in (p_identifier, p_config_line_id)
5391               AND   relief_type in (1, l_offset_type)
5392               AND   supply_id in
5393               (SELECT transaction_id
5394                FROM   msc_supplies S
5395                WHERE  S.plan_id = mapeg1.plan_id
5396                AND    S.sr_instance_id = mapeg1.sr_instance_id
5397                AND    S.transaction_id = mapeg1.supply_id
5398                AND    S.inventory_item_id = mapeg1.inventory_item_id
5399                AND    ((S.firm_planned_type = 1) -- firmed
5400                        OR -- released
5401                        NVL(S.implemented_quantity, 0) +
5402                        NVL(S.quantity_in_process, 0) >=
5403                        NVL(S.firm_quantity,S.new_order_quantity)
5404                       )
5405               )
5406               CONNECT BY prev_pegging_id = prior pegging_id
5407               AND   plan_id = p_plan_id
5408               AND   DECODE(mapeg1.demand_source_type,100,mapeg1.demand_source_type,-1)
5409                      =decode(p_demand_source_type, 100,
5410                                      p_demand_source_type, -1)
5411               AND   sales_order_line_id in (p_identifier, p_config_line_id)
5412               AND   relief_type in (1, l_offset_type)
5413               -- The Connect By clause sub_query traverses the pegging chain
5414               -- and helps in eliminating all supplies pegged to the firmed or released supply
5415              )
5416     -- End Bug 3717618
5417     AND      ABS(map.relief_quantity) > C_ZERO_APPROXIMATOR
5418     -- Bug 3761824 Use Precision figure while creating ofsets.
5419     AND      s.sr_instance_id = map.sr_instance_id
5420     AND      s.plan_id = map.plan_id
5421     AND      s.organization_id = map.organization_id
5422     AND      s.transaction_id = map.supply_id
5423     AND      s.inventory_item_id = map.inventory_item_id
5424     AND      s.order_type = 5
5425     ;
5426     -- End CTO_PF_PRJ_2 Impacts
5427 
5428     x_supply_instance_id := l_instance_id; --Bug 3629191
5429 
5430     l_del_rows := x_supply_id.COUNT;
5431 
5432     FORALL i in 1..l_del_rows
5433       INSERT into MSC_SUPPLIES (
5434                   plan_id,
5435                   transaction_id,
5436                   organization_id,
5437                   sr_instance_id,
5438                   inventory_item_id,
5439                   last_update_date,
5440                   last_updated_by,
5441                   creation_date,
5442                   created_by,
5443                   new_schedule_date,
5444                   disposition_status_type,
5445                   order_type,
5446                   new_order_quantity,
5447                   order_number,
5448                   supplier_id,
5449                   supplier_site_id,
5450                   source_supplier_id,
5451                   source_supplier_site_id,
5452                   source_sr_instance_id,
5453                   source_organization_id,
5454                   process_seq_id,
5455                   firm_planned_type,
5456                   demand_class,
5457                   customer_id,
5458                   ship_to_site_id,
5459                   record_source,
5460                   refresh_number,
5461                   new_ship_date,
5462                   new_dock_date
5463                  -- ,offset_supply_id
5464                   )
5465       VALUES      (p_plan_id,
5466                   x_supply_id(i),
5467                   l_organization_id(i),
5468                   l_instance_id(i),
5469                   x_inv_item_id(i),
5470                   l_sysdate,
5471                   l_user_id,
5472                   l_sysdate,
5473                   l_user_id,
5474                   --bug 3328421: Add at the end of the day
5475                   TRUNC(l_supply_date(i)) + MSC_ATP_PVT.G_END_OF_DAY,
5476                   --l_supply_date(i),
5477                   1,            -- 1512366: open status.
5478                   60,           -- offset sypply_type
5479                   l_supply_qty(i),
5480                   p_order_number,
5481                   l_supplier_id(i),
5482                   l_supplier_site_id(i),
5483                   l_src_supplier_id(i),
5484                   l_src_supplier_site_id(i),
5485                   l_src_instance_id(i),
5486                   l_src_org_id(i),
5487                   l_process_seq_id(i),
5488                   l_firm_planned_type(i),
5489                   l_demand_class(i),
5490                   l_customer_id(i),
5491                   l_ship_to_site_id(i),
5492                   2,            -- ATP created record
5493                   p_refresh_number,
5494                   l_ship_date(i),
5495                   l_dock_date(i)
5496                 --  ,l_offset_supply_id
5497                   );
5498 
5499            IF PG_DEBUG in ('Y', 'C') THEN
5500                 msc_sch_wb.atp_debug('Add_Offset_Supplies:  Number of rows inserted '||
5501                                SQL%ROWCOUNT);
5502            END IF;
5503 
5504     -- Bug 3381464 Update offset_supply_id in msc_atp_pegging.
5505     FORALL i in 1..l_del_rows
5506       UPDATE msc_atp_pegging map1
5507       SET    offset_supply_id = x_supply_id(i)
5508       WHERE  map1.plan_id = p_plan_id
5509       AND    DECODE(map1.demand_source_type,100,map1.demand_source_type,-1)
5510                 =decode(p_demand_source_type,
5511                                          100,
5512                                          p_demand_source_type,
5513                                          -1) --CMRO;
5514       AND    map1.sales_order_line_id in (p_identifier, p_config_line_id)
5515       AND    map1.relief_type = l_offset_type  -- PO, CTO_PF_PRJ_2
5516       AND    map1.inventory_item_id = x_inv_item_id(i)
5517              -- Bug 3717618 Use a pegging_id array to track pegging
5518              -- For filtering out, released/firmed supplies and pegging both are needed.
5519       AND    map1.pegging_id = l_pegging_id(i)
5520       AND    map1.supply_id = l_orig_supply_id(i);
5521 
5522       IF PG_DEBUG in ('Y', 'C') THEN
5523            msc_sch_wb.atp_debug('Add_Offset_Supplies:  Number of rows Updated '|| SQL%ROWCOUNT);
5524            FOR i in 1..l_del_rows LOOP
5525               msc_sch_wb.atp_debug('Add_Offset_Supplies:  Supply Id '|| l_orig_supply_id(i) ||
5526                                         ' Offset Supply Id ' || x_supply_id(i));
5527            END LOOP;
5528       END IF;
5529     -- End Bug 3381464.
5530 
5531 
5532       IF ((MSC_ATP_PVT.G_INV_CTP = 4) AND
5533           (MSC_ATP_PVT.G_ALLOCATED_ATP = 'Y') AND
5534           (MSC_ATP_PVT.G_HIERARCHY_PROFILE = 1) AND
5535           (MSC_ATP_PVT.G_ALLOCATION_METHOD = 1)) THEN
5536 
5537          IF PG_DEBUG in ('Y', 'C') THEN
5538               msc_sch_wb.atp_debug('Add_Offset_Supplies: ' ||
5539                   ' before insert into' || ' msc_alloc_supplies');
5540          END IF;
5541 
5542          -- CTO_PF_PRJ_2 relief_type already set above.
5543          -- Bug 3344102 First set offset type to 6 for supply alloc reliefs.
5544          -- l_offset_type := 6;
5545          -- End CTO_PF_PRJ_2
5546 
5547          -- Try to apply the offsets using alloc specific relief_type.
5548          FORALL i in 1..x_supply_id.COUNT
5549            INSERT INTO MSC_ALLOC_SUPPLIES(
5550                        PLAN_ID,
5551                        INVENTORY_ITEM_ID,
5552                        ORGANIZATION_ID,
5553                        SR_INSTANCE_ID,
5554                        DEMAND_CLASS,
5555                        SUPPLY_DATE,
5556                        PARENT_TRANSACTION_ID,
5557                        ALLOCATED_QUANTITY,
5558                        ORDER_TYPE,
5559                        SALES_ORDER_LINE_ID,
5560                        refresh_number,
5561                        CREATED_BY,
5562                        CREATION_DATE,
5563                        LAST_UPDATED_BY,
5564                        LAST_UPDATE_DATE
5565                        )
5566            SELECT
5567                    map.plan_id,
5568                    map.inventory_item_id,
5569                    map.organization_id,
5570                    map.sr_instance_id,
5571                    map.demand_class,
5572                    map.transaction_date,
5573                    x_supply_id(i),
5574                    NVL(map.relief_quantity, 0),
5575                    60,
5576                    map.sales_order_line_id,
5577                    p_refresh_number,
5578                    l_user_id,
5579                    l_sysdate,
5580                    l_user_id,
5581                    l_sysdate
5582            FROM    msc_atp_pegging map
5583            WHERE   map.sr_instance_id = l_instance_id(i)
5584            AND     map.plan_id = p_plan_id
5585            AND     DECODE(map.demand_source_type,100,map.demand_source_type,-1)
5586                    =decode(p_demand_source_type,
5587                                                 100,
5588                                                 p_demand_source_type,
5589                                                 -1) --CMRO;
5590 
5591            AND     map.sales_order_line_id in (p_identifier, p_config_line_id)
5592            AND     map.relief_type = l_offset_type --PO
5593                    -- Bug 3717618 Use a pegging_id array to track pegging
5594                    -- For filtering out released/firmed supplies both are needed.
5595            AND     map.pegging_id = l_pegging_id(i)
5596            AND     ABS(map.relief_quantity) > C_ZERO_APPROXIMATOR
5597            -- Bug 3761824 Use Precision figure while creating ofsets.
5598            AND     map.supply_id = l_offset_supply_id(i); -- Original Supply
5599 
5600          IF PG_DEBUG in ('Y', 'C') THEN
5601              FOR i in 1..x_supply_id.COUNT LOOP
5602                 msc_sch_wb.atp_debug('Supply to be offset ' || l_offset_supply_id(i));
5603                 msc_sch_wb.atp_debug('Actual Item ' || x_inv_item_id(i));
5604                 msc_sch_wb.atp_debug('Relief Qty' || l_supply_qty(i));
5605                 msc_sch_wb.atp_debug('New Supply ' || x_supply_id(i));
5606                 msc_sch_wb.atp_debug('Add_Offset_Demands:  Number of rows inserted '||
5607                   'For Supply id '|| l_offset_supply_id(i) ||
5608                   ' with offset/relief_type = 6 is ' || SQL%BULK_ROWCOUNT(i));
5609              END LOOP;
5610               msc_sch_wb.atp_debug('Add_Offset_Supplies:  Number of Alloc rows inserted '||
5611                  'with offset/relief_type = ' ||l_offset_type || 'is ' || SQL%ROWCOUNT);
5612          END IF;
5613 
5614          -- CTO_PF_PRJ_2
5615          -- Cascading SQLs no longer necessary
5616          -- IF SQL%ROWCOUNT = 0 THEN
5617 
5618            -- Apply using standard supplies relief_type
5619 
5620          -- END IF;
5621          -- End Bug 3344102
5622          -- END CTO_PF_PRJ_2
5623 
5624 
5625       END IF;
5626 
5627 
5628     IF PG_DEBUG in ('Y', 'C') THEN
5629        msc_sch_wb.atp_debug('***** End Add_Offset_Supplies *****');
5630     END IF;
5631 
5632 EXCEPTION
5633     WHEN OTHERS THEN
5634        BEGIN
5635          -- Bug 3381464 Update offset_supply_id in msc_atp_pegging.
5636          FORALL i in 1..l_del_rows
5637             UPDATE msc_atp_pegging map1
5638             SET    offset_supply_id = NULL
5639             WHERE  map1.plan_id = p_plan_id
5640             AND    DECODE(map1.demand_source_type,100,map1.demand_source_type,-1)
5641                     =decode(p_demand_source_type,
5642                                          100,
5643                                          p_demand_source_type,
5644                                          -1) --CMRO;
5645             AND    map1.sales_order_line_id in (p_identifier, p_config_line_id)
5646             AND    map1.relief_type = NVL(l_offset_type, 2)  -- PO
5647             AND    map1.inventory_item_id = x_inv_item_id(i)
5648             AND    map1.supply_id = l_orig_supply_id(i);
5649          IF PG_DEBUG in ('Y', 'C') THEN
5650            msc_sch_wb.atp_debug('Add_Offset_Supplies:  Number of rows Updated '||
5651                              SQL%ROWCOUNT);
5652          END IF;
5653 
5654        EXCEPTION
5655         WHEN OTHERS THEN
5656          IF PG_DEBUG in ('Y', 'C') THEN
5657            msc_sch_wb.atp_debug('Add_Offset_Supplies: ' ||
5658                 'error in updating offset supplies =  '|| sqlerrm );
5659          END IF;
5660        END;
5661        -- End Bug 3381464.
5662 
5663         my_sqlcode := SQLCODE;
5664         IF PG_DEBUG in ('Y', 'C') THEN
5665            msc_sch_wb.atp_debug('Add_Offset_Supplies: ' ||
5666                 'error in insert row: sqlcode =  '|| to_char(my_sqlcode));
5667            msc_sch_wb.atp_debug('Add_Offset_Supplies: ERROR- ' || sqlerrm );
5668         END IF;
5669 
5670         IF FND_MSG_PUB.Check_Msg_Level(FND_MSG_PUB.G_MSG_LVL_UNEXP_ERROR) THEN
5671             FND_MSG_PUB.Add_Exc_Msg(G_PKG_NAME , 'Add_Offset_Supplies');
5672         END IF;
5673         x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
5674         -- Bug 3319810 Enable exception generation.
5675         RAISE FND_API.G_EXC_UNEXPECTED_ERROR;
5676 
5677 END Add_Offset_Supplies;
5678 
5679 PROCEDURE Add_Offset_Resource_Reqs (
5680                      p_identifier                      IN NUMBER,
5681                      p_config_line_id                  IN NUMBER,
5682                      p_plan_id                         IN NUMBER,
5683                      p_refresh_number                  IN NUMBER,
5684                      p_order_number                    IN NUMBER,
5685                      p_demand_source_type              IN NUMBER,--cmro
5686                      x_inv_item_id                     IN OUT NoCopy MRP_ATP_PUB.Number_Arr,
5687                      x_res_transactions                IN OUT NoCopy MRP_ATP_PUB.Number_Arr,
5688                      x_res_instance_id                 OUT NoCopy MRP_ATP_PUB.Number_Arr, --Bug 3629191
5689                      x_return_status                   IN OUT NoCopy VARCHAR2
5690                      )
5691 IS
5692     l_del_rows                  NUMBER;
5693     i                           PLS_INTEGER;
5694     my_sqlcode                  NUMBER;
5695 
5696     l_supply_id                 MRP_ATP_PUB.Number_Arr := MRP_ATP_PUB.Number_Arr();
5697     l_instance_id               MRP_ATP_PUB.Number_Arr := MRP_ATP_PUB.Number_Arr();
5698     l_organization_id           MRP_ATP_PUB.Number_Arr := MRP_ATP_PUB.Number_Arr();
5699     l_resource_seq_num          MRP_ATP_PUB.Number_Arr := MRP_ATP_PUB.Number_Arr();
5700     l_resource_id               MRP_ATP_PUB.Number_Arr := MRP_ATP_PUB.Number_Arr();
5701     l_department_id             MRP_ATP_PUB.Number_Arr := MRP_ATP_PUB.Number_Arr();
5702     l_start_date                MRP_ATP_PUB.Date_Arr := MRP_ATP_PUB.Date_Arr();
5703     l_end_date                  MRP_ATP_PUB.Date_Arr := MRP_ATP_PUB.Date_Arr();
5704     l_resource_hours            MRP_ATP_PUB.Number_Arr := MRP_ATP_PUB.Number_Arr();
5705     l_daily_resource_hours      MRP_ATP_PUB.Number_Arr := MRP_ATP_PUB.Number_Arr();
5706     l_load_rate                 MRP_ATP_PUB.Number_Arr := MRP_ATP_PUB.Number_Arr();
5707     l_assigned_units            MRP_ATP_PUB.Number_Arr := MRP_ATP_PUB.Number_Arr();
5708     l_std_op_code               MRP_ATP_PUB.char10_arr;
5709 
5710     l_basis_type                MRP_ATP_PUB.Number_Arr := MRP_ATP_PUB.Number_Arr();
5711     l_op_seq_num                MRP_ATP_PUB.Number_Arr := MRP_ATP_PUB.Number_Arr();
5712     l_parent_id                 MRP_ATP_PUB.Number_Arr := MRP_ATP_PUB.Number_Arr();
5713 
5714     l_sysdate                   DATE;
5715     l_user_id                   number;
5716 
5717     -- CTO_PF_PRJ_2 Changes
5718     l_offset_type               NUMBER;
5719 BEGIN
5720 
5721      IF PG_DEBUG in ('Y', 'C') THEN
5722         msc_sch_wb.atp_debug('***** Begin Add_Offset_Resource_Reqs *****');
5723      END IF;
5724      IF PG_DEBUG in ('Y', 'C') THEN
5725         msc_sch_wb.atp_debug('Add_Offset_Resource_Reqs: ' ||
5726                           'Offsetting msc_resource_requirements for identifier = '
5727                       || p_identifier ||' : plan id = '||p_plan_id);
5728      msc_sch_wb.atp_debug('Add_Offset_Resource_Reqs: Config Line Id = ' || p_config_line_id );
5729      END IF ;
5730 
5731      x_return_status := FND_API.G_RET_STS_SUCCESS;
5732 
5733      -- CTO_PF_PRJ_2 Changes
5734      IF ((MSC_ATP_PVT.G_INV_CTP = 4) AND
5735         (MSC_ATP_PVT.G_ALLOCATED_ATP = 'Y') AND
5736         (MSC_ATP_PVT.G_HIERARCHY_PROFILE = 1) AND
5737         (MSC_ATP_PVT.G_ALLOCATION_METHOD = 1)) THEN
5738 
5739          l_offset_type := 6;
5740      ELSE
5741          l_offset_type := 2;
5742      END IF;
5743      -- End CTO_PF_PRJ_2 Changes
5744 
5745      l_sysdate := sysdate;
5746      l_user_id := FND_GLOBAL.USER_ID;
5747 
5748   -- Insert demand into msc_resource_requirements
5749      SELECT
5750                   supply_id,
5751                   sr_instance_id,
5752                   msc_resource_requirements_s.nextval,
5753                   organization_id,
5754                   inventory_item_id,
5755                   basis_type,
5756                   operation_seq_num,
5757                   parent_id,
5758                   resource_seq_num,
5759                   resource_id,
5760                   department_id,
5761                   start_date,
5762                   end_date,
5763                   relief_quantity,
5764                   daily_relief_qty,
5765                   load_rate,
5766                   assigned_units,    -- 0 originally.
5767                   std_op_code
5768      BULK COLLECT
5769      INTO
5770                   l_supply_id,
5771                   l_instance_id,
5772                   x_res_transactions,
5773                   l_organization_id,
5774                   x_inv_item_id,
5775                   l_basis_type,
5776                   l_op_seq_num,
5777                   l_parent_id,
5778                   l_resource_seq_num,
5779                   l_resource_id,
5780                   l_department_id,
5781                   l_start_date,
5782                   l_end_date,
5783                   l_resource_hours,
5784                   l_daily_resource_hours,
5785                   l_load_rate,
5786                   l_assigned_units,
5787                   l_std_op_code
5788     FROM
5789          (SELECT  DISTINCT
5790                   -- Bug 3381464 Obtain the Offset Suuply_ID
5791                   map2.offset_supply_id supply_id,
5792                   -- REQ.supply_id,
5793                   -- This ensures that offset resource requirements are pegged to offset supplies.
5794                   -- End Bug 3381464.
5795                   map.sr_instance_id,
5796                   REQ.transaction_id,
5797                   map.organization_id,
5798                   map.inventory_item_id,
5799                   REQ.basis_type,
5800                   REQ.operation_seq_num,
5801                   REQ.parent_id,
5802                   REQ.resource_seq_num,
5803                   map.resource_id,
5804                   map.department_id,
5805                   NVL(map.start_date, REQ.start_date) start_date,
5806                             -- Bug 3443056, 3348095 ATP now tracks end date.
5807                   map.end_date,
5808                   map.relief_quantity,
5809                   map.daily_relief_qty,
5810                   decode(map.resource_id,-1,map.relief_quantity,to_number(null)) load_rate,
5811                   REQ.assigned_units,    -- 0 originally.
5812                   REQ.std_op_code
5813           FROM       msc_atp_pegging map,
5814                      msc_resource_requirements REQ,
5815                      -- Bug 3381464 -- Join to Pegging to obtain offset supply ids.
5816                      msc_atp_pegging map2
5817           WHERE   map.plan_id = p_plan_id
5818           --AND      map.sr_instance_id = p_instance_id  -- removed to support multiple instances in plan.
5819           AND      DECODE(map.demand_source_type,100,map.demand_source_type,-1)
5820                    =decode(p_demand_source_type,
5821                                                 100,
5822                                                 p_demand_source_type,
5823                                                 -1) --CMRO;
5824 
5825           AND      map.sales_order_line_id in (p_identifier, p_config_line_id)
5826           AND      map.relief_type = 4  -- REQ
5827           AND      ABS(map.relief_quantity) > C_ZERO_APPROXIMATOR
5828           -- Bug 3761824 Use Precision figure while creating ofsets.
5829           AND      REQ.sr_instance_id = map.sr_instance_id
5830           AND      REQ.plan_id = map.plan_id
5831           AND      REQ.organization_id = map.organization_id
5832           --AND      REQ.supply_id = map.supply_id
5833           AND      REQ.transaction_id = map.supply_id   -- Here resource transaction ids.
5834           AND      REQ.resource_id = map.resource_id
5835           AND      REQ.department_id = map.department_id
5836           AND      REQ.assembly_item_id = map.inventory_item_id
5837           AND      ( (NVL(REQ.record_source, 1) = 1 AND
5838                            TRUNC(REQ.start_date) = TRUNC(map.start_date))
5839                     OR (REQ.record_source = 2 AND TRUNC(REQ.end_date) = TRUNC(map.end_date)) )
5840                             -- Bug 3443056, 3348095 ATP now tracks end date.
5841           -- Bug 3381464 Get Offset Supply Data.
5842           AND      map2.sr_instance_id = REQ.sr_instance_id
5843           AND      map2.plan_id = REQ.plan_id
5844           AND      map2.organization_id = REQ.organization_id
5845           AND      map2.inventory_item_id = REQ.assembly_item_id
5846           AND      map2.supply_id = REQ.supply_id
5847           -- Bug 3717618 Ensure that supply is relieved
5848           -- Only those corresponding resource reqs will be offset.
5849           AND      map2.offset_supply_id is NOT NULL
5850           -- End Bug 3717618
5851           AND      map2.relief_type = l_offset_type -- CTO_PF_PRJ_2
5852           AND      map2.sales_order_line_id = map.sales_order_line_id
5853           AND      DECODE(map2.demand_source_type,100,map2.demand_source_type,-1)
5854                    = DECODE(map.demand_source_type,100,map.demand_source_type,-1)
5855           -- End Bug 3381464
5856         )
5857      ;
5858 
5859      x_res_instance_id := l_instance_id; --Bug 3629191
5860 
5861      l_del_rows := x_res_transactions.COUNT;
5862 
5863      IF PG_DEBUG in ('Y', 'C') THEN
5864         msc_sch_wb.atp_debug('Add_Offset_Resource_Reqs: ' ||
5865                           'Total Rows to add = ' || l_del_rows );
5866      END IF;
5867      FORALL i in 1..l_del_rows
5868        INSERT into msc_resource_requirements
5869                  (plan_id,
5870                   supply_id,
5871                   transaction_id,
5872                   organization_id,
5873                   sr_instance_id,
5874                   assembly_item_id,
5875                   basis_type,
5876                   operation_seq_num,
5877                   parent_id,
5878                   record_source,
5879                   resource_seq_num,
5880                   resource_id,
5881                   department_id,
5882                   refresh_number,
5883                   start_date,
5884                   end_date,
5885                   resource_hours,
5886                   daily_resource_hours,
5887                   load_rate,
5888                   assigned_units,
5889                   supply_type, -- 1510686
5890                   std_op_code, --resource batching
5891                   last_update_date,
5892                   last_updated_by,
5893                   creation_date,
5894                   created_by)
5895        VALUES     (p_plan_id,
5896                    l_supply_id(i),
5897                    x_res_transactions(i),
5898                    l_organization_id(i),
5899                    l_instance_id(i),
5900                    x_inv_item_id(i),
5901                    l_basis_type(i),
5902                    l_op_seq_num(i),
5903                    l_parent_id(i),
5904                    2,                 -- ATP generated record.
5905                    l_resource_seq_num(i),
5906                    l_resource_id(i),
5907                    l_department_id(i),
5908                    p_refresh_number,
5909                    l_start_date(i),
5910                    l_end_date(i),
5911                    l_resource_hours(i),
5912                    l_daily_resource_hours(i),
5913                    l_load_rate(i),
5914                    l_assigned_units(i),   -- 0 originally.
5915                    60,                     -- for Resources offset supply type is applicable.
5916                    l_std_op_code(i),
5917                    l_sysdate,
5918                    l_user_id,
5919                    l_sysdate,
5920                    l_user_id ) ;
5921 
5922      IF PG_DEBUG in ('Y', 'C') THEN
5923           msc_sch_wb.atp_debug('Add_Offset_Resource_Reqs:  Number of rows inserted '||
5924                                SQL%ROWCOUNT);
5925      END IF;
5926 
5927 
5928     IF PG_DEBUG in ('Y', 'C') THEN
5929        msc_sch_wb.atp_debug('***** End Add_Offset_Resource_Reqs *****');
5930     END IF;
5931 EXCEPTION
5932     WHEN OTHERS THEN
5933         my_sqlcode := SQLCODE;
5934         IF PG_DEBUG in ('Y', 'C') THEN
5935            msc_sch_wb.atp_debug('Add_Offset_Resource_Reqs: ' ||
5936                 'error in processing: sqlcode =  '|| to_char(my_sqlcode));
5937            msc_sch_wb.atp_debug('Add_Offset_Resource_Reqs: ' ||
5938                 'error in processing: errmsg =  '|| sqlerrm );
5939         END IF;
5940 
5941         IF FND_MSG_PUB.Check_Msg_Level(FND_MSG_PUB.G_MSG_LVL_UNEXP_ERROR) THEN
5942             FND_MSG_PUB.Add_Exc_Msg(G_PKG_NAME , 'Add_Offset_Resource_Reqs');
5943         END IF;
5944         x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
5945         -- Bug 3319810 Enable exception generation.
5946         RAISE FND_API.G_EXC_UNEXPECTED_ERROR;
5947 
5948 END Add_Offset_Resource_Reqs;
5949 
5950 PROCEDURE Add_Offset_Data (
5951                     p_identifier       IN         NUMBER,
5952                     p_config_line_id   IN         NUMBER,
5953                     p_plan_id          IN         NUMBER,
5954                     p_refresh_number   IN         NUMBER,
5955                     p_order_number     IN         NUMBER,
5956                     p_demand_source_type IN       NUMBER,--cmro
5957                     x_inv_item_id      OUT NoCopy MRP_ATP_PUB.Number_Arr,
5958                     x_demand_id        OUT NoCopy MRP_ATP_PUB.Number_Arr,
5959                     x_supply_id        OUT NoCopy MRP_ATP_PUB.Number_Arr,
5960                     x_res_transactions OUT NoCopy MRP_ATP_PUB.Number_Arr,
5961                     x_demand_instance_id OUT NoCopy MRP_ATP_PUB.Number_Arr, --Bug 3629191
5962                     x_supply_instance_id OUT NoCopy MRP_ATP_PUB.Number_Arr, --Bug 3629191
5963                     x_res_instance_id    OUT NoCopy MRP_ATP_PUB.Number_Arr, --Bug 3629191
5964                     x_return_status    OUT NoCopy VARCHAR2
5965                     )
5966 IS
5967 
5968 l_inv_demand_items      MRP_ATP_PUB.Number_Arr := MRP_ATP_PUB.Number_Arr();
5969 l_inv_supply_items      MRP_ATP_PUB.Number_Arr := MRP_ATP_PUB.Number_Arr();
5970 j                       PLS_INTEGER;
5971 i                       PLS_INTEGER;
5972 match_found             NUMBER;
5973 l_supply_instance_id    MRP_ATP_PUB.Number_Arr := MRP_ATP_PUB.Number_Arr();
5974 BEGIN
5975 
5976     IF PG_DEBUG in ('Y', 'C')  THEN
5977         msc_sch_wb.atp_debug('**********Begin Add_Offset_Data Procedure************');
5978         msc_sch_wb.atp_debug('Add_Offset_Data p_identifier :' || p_identifier);
5979         msc_sch_wb.atp_debug('Add_Offset_Data p_config_line_id :' || p_config_line_id);
5980         msc_sch_wb.atp_debug('Add_Offset_Data p_plan_id :' || p_plan_id);
5981         msc_sch_wb.atp_debug('Add_Offset_Data p_refresh_number :' || p_refresh_number);
5982         msc_sch_wb.atp_debug('Add_Offset_Data p_order_number :' || p_order_number);
5983     END IF;
5984 
5985     x_return_status := FND_API.G_RET_STS_SUCCESS;
5986 
5987 
5988     -- Bug 3717618 Flip the order of calls to
5989     -- Add Offset records, First call Offset Supplies and
5990 
5991     Add_Offset_Supplies (p_identifier, p_config_line_id, p_plan_id,
5992                          p_refresh_number, p_order_number,p_demand_source_type,--cmro
5993                          l_inv_supply_items, x_supply_id, x_supply_instance_id, x_return_status); --Bug 3629191
5994 
5995     IF PG_DEBUG in ('Y', 'C')  THEN
5996         msc_sch_wb.atp_debug('Status After Call to Add_Offset_Supplies :' || x_return_status);
5997     END IF;
5998 
5999     -- and then call Offset Demands
6000     -- so that only those demands tied to offset supplies are relieved.
6001     Add_Offset_Demands (p_identifier, p_config_line_id, p_plan_id,
6002                         p_refresh_number, p_order_number,p_demand_source_type,--cmro
6003                         l_inv_demand_items, x_demand_id, x_demand_instance_id, x_return_status); --Bug 3629191
6004 
6005     IF PG_DEBUG in ('Y', 'C')  THEN
6006         msc_sch_wb.atp_debug('Status After Call to Add_Offset_Demands :' || x_return_status);
6007     END IF;
6008     -- End Bug 3717618 Flip the order of calls ...
6009 
6010     FOR j in 1..l_inv_supply_items.COUNT LOOP
6011 
6012       match_found := 2;  -- match found is set to false.
6013       FOR i in 1..l_inv_demand_items.COUNT LOOP
6014         IF (l_inv_demand_items(i) = l_inv_supply_items(j)) THEN
6015           -- match found exit loop
6016           match_found:= 1;
6017           EXIT;
6018         END IF;
6019       END LOOP;
6020 
6021       -- match not found, add to list of items.
6022       IF (match_found = 2) THEN
6023          l_inv_demand_items.EXTEND;
6024          l_inv_demand_items(l_inv_demand_items.COUNT) := l_inv_supply_items(j);
6025       END IF;
6026 
6027     END LOOP;
6028 
6029     Add_Offset_Resource_Reqs (p_identifier, p_config_line_id,  p_plan_id,
6030                               p_refresh_number, p_order_number,p_demand_source_type,--cmro
6031                               l_inv_supply_items, x_res_transactions, x_res_instance_id, x_return_status); --Bug 3629191
6032 
6033     IF PG_DEBUG in ('Y', 'C')  THEN
6034         msc_sch_wb.atp_debug('Status After Call to Add_Offset_Resource_Reqs :'
6035                                          || x_return_status);
6036     END IF;
6037 
6038 
6039     -- Finally assign to output list
6040     x_inv_item_id := l_inv_demand_items;
6041 
6042     IF PG_DEBUG in ('Y', 'C')  THEN
6043         msc_sch_wb.atp_debug('**********End Add_Offset_Data Procedure************');
6044     END IF;
6045 
6046 EXCEPTION
6047     WHEN OTHERS THEN
6048         IF FND_MSG_PUB.Check_Msg_Level(FND_MSG_PUB.G_MSG_LVL_UNEXP_ERROR) THEN
6049             FND_MSG_PUB.Add_Exc_Msg (G_PKG_NAME , 'Add_Offset_Data');
6050         END IF;
6051 
6052         IF PG_DEBUG in ('Y', 'C')  THEN
6053            msc_sch_wb.atp_debug('Add_Offset_Data: ERROR' || sqlerrm );
6054         END IF;
6055         x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
6056         -- Bug 3319810 Enable exception generation.
6057         RAISE FND_API.G_EXC_UNEXPECTED_ERROR;
6058 END Add_Offset_Data;
6059 
6060 PROCEDURE Remove_Offset_Demands (
6061              --p_identifiers      IN       MRP_ATP_PUB.Number_Arr,
6062              --p_plan_ids         IN       MRP_ATP_PUB.Number_Arr,
6063              p_atp_peg_demands_plan_ids  IN MRP_ATP_PUB.Number_Arr, --Bug 3629191
6064              p_inv_item_ids     IN       MRP_ATP_PUB.Number_Arr,
6065              p_del_demand_ids   IN       MRP_ATP_PUB.Number_Arr,
6066              p_demand_source_type IN     MRP_ATP_PUB.Number_Arr,--cmro
6067              x_return_status    IN OUT   NoCopy VARCHAR2
6068                                 )
6069 IS
6070 l_del_rows          NUMBER;
6071 i                   NUMBER;
6072 m                   PLS_INTEGER := 1;
6073 
6074 -- CTO_PF_PRJ_2 Impacts
6075 l_offset_type               NUMBER;
6076 -- End CTO_PF_PRJ_2 Impacts
6077 
6078 BEGIN
6079    IF PG_DEBUG in ('Y', 'C') THEN
6080         msc_sch_wb.atp_debug('**********Begin Remove_Offset_Demands Procedure************');
6081     END IF;
6082    IF PG_DEBUG in ('Y', 'C') THEN
6083        FOR i in 1..p_del_demand_ids.COUNT LOOP
6084             msc_sch_wb.atp_debug('Remove_Offset_Demands: ' ||
6085                              'p_del_demand_ids('||i||') = '|| p_del_demand_ids(i)||
6086                              --'p_inv_item_ids('||i||') = '|| p_inv_item_ids(i)||
6087                              'p_atp_peg_demands_plan_ids('||i||') = '|| p_atp_peg_demands_plan_ids(i)
6088                              --'p_plan_ids('||i||') = '|| p_plan_ids(i)||
6089                              --'p_identifiers('||i||') = '|| p_identifiers(i)
6090                              );
6091        END LOOP;
6092    END IF;
6093 
6094    x_return_status := FND_API.G_RET_STS_SUCCESS;
6095 
6096    -- CTO_PF_PRJ_2 Impacts
6097    IF ((MSC_ATP_PVT.G_INV_CTP = 4) AND
6098        (MSC_ATP_PVT.G_ALLOCATED_ATP = 'Y') AND
6099        (MSC_ATP_PVT.G_HIERARCHY_PROFILE = 1) AND
6100        (MSC_ATP_PVT.G_ALLOCATION_METHOD = 1)) THEN
6101 
6102       l_offset_type := 5;
6103    ELSE
6104       l_offset_type := 3;
6105    END IF;
6106    -- End CTO_PF_PRJ_2
6107 
6108    --Bug 3629191
6109    FORALL m IN 1..p_del_demand_ids.COUNT
6110       DELETE msc_demands
6111       WHERE
6112       -- Bug 3629191 :All where clause except plan_id and demand_id are commmented
6113       /* sr_instance_id  = p_instance_id
6114       (SELECT sr_instance_id
6115        FROM   msc_atp_pegging
6116        WHERE  plan_id = p_plan_ids(m)
6117        AND    sales_order_line_id = p_identifiers(m)
6118        AND     DECODE(demand_source_type,100,demand_source_type,-1)
6119                       =decode(p_demand_source_type(m),
6120                               100,
6121                               p_demand_source_type(m),
6122                               -1)  --CMRO;
6123        AND    inventory_item_id = p_inv_item_ids(m)
6124        -- CTO_PF_PRJ_2 Impacts
6125        AND    relief_type in (l_offset_type, 7)
6126        -- End CTO_PF_PRJ_2
6127       )
6128       AND */
6129              plan_id = p_atp_peg_demands_plan_ids(m)
6130       --AND  inventory_item_id = p_inv_item_ids(m) -- Bug 3629191
6131       AND    demand_id = p_del_demand_ids(m);
6132 
6133    -- Count how many rows were updated for each demand id
6134    IF PG_DEBUG in ('Y', 'C') THEN
6135         FOR m IN 1..p_del_demand_ids.COUNT LOOP
6136            msc_sch_wb.atp_debug('For Demand id '|| p_del_demand_ids(m)||': updated '||
6137                         SQL%BULK_ROWCOUNT(m)||' records');
6138         END LOOP;
6139    END IF;
6140 
6141    --    (MSC_ATP_PVT.G_ALLOCATION_METHOD = 1)) THEN
6142    -- Allocation Profiles check that was there before has been removed
6143    -- with the introduction of CTO_PF_PRJ_2 impacts.
6144    -- Relief_Type 7 can get created irrespective of allocation profiles.
6145 
6146       IF PG_DEBUG in ('Y', 'C') THEN
6147             msc_sch_wb.atp_debug('Remove_Offset_Demands: before delete from ' ||
6148                               ' msc_alloc_demands');
6149       END IF;
6150 
6151       --Bug 3629191
6152       FORALL m IN 1..p_del_demand_ids.COUNT
6153          DELETE msc_alloc_demands
6154          WHERE
6155          -- Bug 3629191 :All where clause except plan_id and parent_demand_id are commmented
6156          /*sr_instance_id IN
6157          (SELECT sr_instance_id
6158           FROM   msc_atp_pegging
6159           WHERE  plan_id = p_plan_ids(m)
6160           AND    sales_order_line_id = p_identifiers(m)
6161           AND    DECODE(demand_source_type,100,demand_source_type,-1)
6162                  =decode(p_demand_source_type(m),
6163                          100,
6164                          p_demand_source_type(m),
6165                          -1) --CMRO;
6166           AND    inventory_item_id = p_inv_item_ids(m)
6167           -- CTO_PF_PRJ_2 Impacts
6168           AND    relief_type in (l_offset_type, 7)
6169           -- End CTO_PF_PRJ_2
6170          )
6171          AND */
6172                 plan_id = p_atp_peg_demands_plan_ids(m)
6173          --AND  inventory_item_id = p_inv_item_ids(m) -- Bug 3629191
6174          AND    parent_demand_id = p_del_demand_ids(m)
6175 ;
6176 
6177          -- Count how many rows were updated for each demand id
6178       IF PG_DEBUG in ('Y', 'C') THEN
6179            FOR m IN 1..p_del_demand_ids.COUNT LOOP
6180               msc_sch_wb.atp_debug('For Demand id '|| p_del_demand_ids(m)||': updated '||
6181                       SQL%BULK_ROWCOUNT(m)||' records');
6182            END LOOP;
6183       END IF;
6184 
6185    IF PG_DEBUG in ('Y', 'C') THEN
6186         msc_sch_wb.atp_debug('**********End Remove_Offset_Demands Procedure************');
6187    END IF;
6188 
6189 EXCEPTION
6190     WHEN OTHERS THEN
6191         IF FND_MSG_PUB.Check_Msg_Level(FND_MSG_PUB.G_MSG_LVL_UNEXP_ERROR) THEN
6192             FND_MSG_PUB.Add_Exc_Msg (G_PKG_NAME , 'Remove_Offset_Demands');
6193         END IF;
6194 
6195         IF PG_DEBUG in ('Y', 'C')  THEN
6196            msc_sch_wb.atp_debug('Remove_Offset_Demands: ERROR' || sqlerrm );
6197         END IF;
6198         x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
6199         -- Bug 3319810 Enable exception generation.
6200         RAISE FND_API.G_EXC_UNEXPECTED_ERROR;
6201 
6202 END Remove_Offset_Demands;
6203 
6204 PROCEDURE Remove_Offset_Supplies (
6205              --p_identifiers      IN       MRP_ATP_PUB.Number_Arr,
6206              --p_plan_ids         IN       MRP_ATP_PUB.Number_Arr,
6207              p_atp_peg_supplies_plan_ids IN MRP_ATP_PUB.Number_Arr, --Bug 3629191
6208              p_inv_item_ids     IN       MRP_ATP_PUB.Number_Arr,
6209              p_del_supply_ids   IN       MRP_ATP_PUB.Number_Arr,
6210              p_demand_source_type IN     MRP_ATP_PUB.Number_Arr,--cmro
6211              x_return_status    IN OUT   NoCopy VARCHAR2
6212                                 )
6213 IS
6214 l_del_rows          NUMBER;
6215 i                   NUMBER;
6216 m                   PLS_INTEGER := 1;
6217 
6218 -- CTO_PF_PRJ_2 Impacts
6219 l_offset_type               NUMBER;
6220 -- End CTO_PF_PRJ_2 Impacts
6221 
6222 BEGIN
6223    IF PG_DEBUG in ('Y', 'C') THEN
6224         msc_sch_wb.atp_debug('**********Begin Remove_Offset_Supplies Procedure************');
6225     END IF;
6226    IF PG_DEBUG in ('Y', 'C') THEN
6227        FOR i in 1..p_del_supply_ids.COUNT LOOP
6228             msc_sch_wb.atp_debug('Remove_Offset_Supplies: ' ||
6229                              'p_del_supply_ids('||i||') = '|| p_del_supply_ids(i)||
6230                              --'p_inv_item_ids('||i||') = '|| p_inv_item_ids(i)||
6231                              --'p_plan_ids('||i||') = '|| p_plan_ids(i)||
6232                              'p_atp_peg_supplies_plan_ids('||i||') = '|| p_atp_peg_supplies_plan_ids(i)
6233                              --'p_identifiers('||i||') = '|| p_identifiers(i)
6234                              );
6235        END LOOP;
6236    END IF;
6237 
6238 
6239    x_return_status := FND_API.G_RET_STS_SUCCESS;
6240 
6241     -- CTO_PF_PRJ_2 Changes Set Relief Type
6242     IF ((MSC_ATP_PVT.G_INV_CTP = 4) AND
6243       (MSC_ATP_PVT.G_ALLOCATED_ATP = 'Y') AND
6244       (MSC_ATP_PVT.G_HIERARCHY_PROFILE = 1) AND
6245       (MSC_ATP_PVT.G_ALLOCATION_METHOD = 1)) THEN
6246 
6247        l_offset_type := 6;
6248     ELSE
6249        l_offset_type := 2;
6250     END IF;
6251     -- End CTO_PF_PRJ_2 Changes
6252 
6253    -- Bug 3381464 Update offset_supply_id in msc_atp_pegging.
6254    --Bug 3629191
6255    FORALL m in 1..p_del_supply_ids.COUNT
6256       UPDATE msc_atp_pegging map1
6257       SET    offset_supply_id = NULL
6258       WHERE  map1.plan_id = p_atp_peg_supplies_plan_ids(m)
6259       -- Bug 3629191: where clause on demand_source_type, sales_order_line_id
6260       -- and inventory_item_id are removed
6261       /*AND    DECODE(map1.demand_source_type,100,map1.demand_source_type,-1)
6262                       =decode(p_demand_source_type(m),
6263                               100,
6264                               p_demand_source_type(m),
6265                               -1) --CMRO;
6266       AND    map1.sales_order_line_id = p_identifiers(m) */
6267       AND    map1.relief_type = l_offset_type  -- PO
6268       --AND  map1.inventory_item_id = p_inv_item_ids(m) -- Bug 3629191
6269       AND    map1.offset_supply_id = p_del_supply_ids(m);
6270 
6271       IF PG_DEBUG in ('Y', 'C') THEN
6272          msc_sch_wb.atp_debug('Remove_Offset_Supplies:  Number of rows Updated '||
6273                              SQL%ROWCOUNT);
6274       END IF;
6275    -- End Bug 3381464.
6276 
6277    -- CTO_PF_PRJ_2 Changes Set Relief Type
6278     IF ((MSC_ATP_PVT.G_INV_CTP = 4) AND
6279       (MSC_ATP_PVT.G_ALLOCATED_ATP = 'Y') AND
6280       (MSC_ATP_PVT.G_HIERARCHY_PROFILE = 1) AND
6281       (MSC_ATP_PVT.G_ALLOCATION_METHOD = 1)) THEN
6282 
6283        l_offset_type := 6;
6284     ELSE
6285        l_offset_type := 2;
6286     END IF;
6287     -- End CTO_PF_PRJ_2 Changes
6288 
6289    --Bug 3629191
6290    FORALL m IN 1..p_del_supply_ids.COUNT
6291       DELETE msc_supplies
6292       WHERE
6293       -- Bug 3629191 :All where clause except and transaction_id are commmented
6294       /* sr_instance_id = p_instance_id
6295       (SELECT sr_instance_id
6296        FROM   msc_atp_pegging
6297        WHERE  plan_id = p_plan_ids(m)
6298        AND    sales_order_line_id = p_identifiers(m)
6299        AND     DECODE(demand_source_type,100,demand_source_type,-1)
6300                       =decode(p_demand_source_type(m),
6301                               100,
6302                               p_demand_source_type(m),
6303                               -1) --CMRO;
6304        -- CTO_PF_PRJ_2 Changes Use Relief Type
6305        AND    relief_type = l_offset_type
6306        -- End CTO_PF_PRJ_2 Changes
6307        AND    inventory_item_id = p_inv_item_ids(m)
6308       )
6309       AND */
6310              plan_id = p_atp_peg_supplies_plan_ids(m)
6311       --AND  inventory_item_id = p_inv_item_ids(m) --Bug 3629191
6312       AND    transaction_id = p_del_supply_ids(m);
6313 
6314    -- Count how many rows were updated for each supply id
6315    IF PG_DEBUG in ('Y', 'C') THEN
6316         FOR m IN 1..p_del_supply_ids.COUNT LOOP
6317            msc_sch_wb.atp_debug('For Supply id '|| p_del_supply_ids(m)||': updated '||
6318                         SQL%BULK_ROWCOUNT(m)||' records');
6319         END LOOP;
6320    END IF;
6321 
6322    IF ((MSC_ATP_PVT.G_INV_CTP = 4) AND
6323        (MSC_ATP_PVT.G_ALLOCATED_ATP = 'Y') AND
6324        (MSC_ATP_PVT.G_HIERARCHY_PROFILE = 1) AND
6325        (MSC_ATP_PVT.G_ALLOCATION_METHOD = 1)) THEN
6326 
6327       IF PG_DEBUG in ('Y', 'C') THEN
6328             msc_sch_wb.atp_debug('Remove_Offset_Supplies: before delete from ' ||
6329                               ' msc_alloc_supplies');
6330       END IF;
6331 
6332       --Bug 3629191
6333       FORALL m IN 1..p_del_supply_ids.COUNT
6334          DELETE msc_alloc_supplies
6335          WHERE
6336          -- Bug 3629191 :All where clause except and parent_transaction_id are commmented
6337          /* sr_instance_id = p_instance_id
6338          (SELECT sr_instance_id
6339           FROM   msc_atp_pegging
6340           WHERE  plan_id = p_plan_ids(m)
6341           -- CTO_PF_PRJ_2 Changes Use Relief Type
6342           AND    relief_type = l_offset_type
6343           -- End CTO_PF_PRJ_2 Changes
6344           AND    sales_order_line_id = p_identifiers(m)
6345           AND     DECODE(demand_source_type,100,demand_source_type,-1)
6346                          =decode(p_demand_source_type(m),
6347                                  100,
6348                                  p_demand_source_type(m),
6349                                  -1) --CMRO;
6350           AND    inventory_item_id = p_inv_item_ids(m)
6351          )
6352          AND */
6353                 plan_id = p_atp_peg_supplies_plan_ids(m)
6354          --AND  inventory_item_id = p_inv_item_ids(m) --Bug 3629191
6355          AND    parent_transaction_id = p_del_supply_ids(m)
6356          ;
6357 
6358          -- Count how many rows were updated for each supply id
6359       IF PG_DEBUG in ('Y', 'C') THEN
6360            FOR m IN 1..p_del_supply_ids.COUNT LOOP
6361               msc_sch_wb.atp_debug('For Supply id '|| p_del_supply_ids(m)||': updated '||
6362                       SQL%BULK_ROWCOUNT(m)||' records');
6363            END LOOP;
6364       END IF;
6365    END IF;
6366 
6367    IF PG_DEBUG in ('Y', 'C') THEN
6368         msc_sch_wb.atp_debug('**********End Remove_Offset_Supplies Procedure************');
6369    END IF;
6370 
6371 EXCEPTION
6372     WHEN OTHERS THEN
6373         IF FND_MSG_PUB.Check_Msg_Level(FND_MSG_PUB.G_MSG_LVL_UNEXP_ERROR) THEN
6374             FND_MSG_PUB.Add_Exc_Msg (G_PKG_NAME , 'Remove_Offset_Supplies');
6375         END IF;
6376 
6377         IF PG_DEBUG in ('Y', 'C')  THEN
6378            msc_sch_wb.atp_debug('Remove_Offset_Supplies: ERROR' || sqlerrm );
6379         END IF;
6380         x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
6381         -- Bug 3319810 Enable exception generation.
6382         RAISE FND_API.G_EXC_UNEXPECTED_ERROR;
6383 
6384 END Remove_Offset_Supplies;
6385 
6386 
6387 PROCEDURE Remove_Offset_Resource_Reqs (
6388              --p_identifiers      IN       MRP_ATP_PUB.Number_Arr,
6389              --p_plan_ids         IN       MRP_ATP_PUB.Number_Arr,
6390              p_atp_peg_res_reqs_plan_ids IN MRP_ATP_PUB.Number_Arr, --Bug 3629191
6391              p_inv_item_ids     IN       MRP_ATP_PUB.Number_Arr,
6392              p_del_resrc_reqs   IN       MRP_ATP_PUB.Number_Arr,
6393              p_demand_source_type IN     MRP_ATP_PUB.Number_Arr,--cmro
6394              x_return_status    IN OUT   NoCopy VARCHAR2
6395                                 )
6396 IS
6397 l_del_rows          NUMBER;
6398 i                   NUMBER;
6399 m                   PLS_INTEGER := 1;
6400 BEGIN
6401    IF PG_DEBUG in ('Y', 'C') THEN
6402         msc_sch_wb.atp_debug('**********Begin Remove_Offset_Resource_Reqs Procedure************');
6403     END IF;
6404    IF PG_DEBUG in ('Y', 'C') THEN
6405        FOR i in 1..p_del_resrc_reqs.COUNT LOOP
6406             msc_sch_wb.atp_debug('Remove_Offset_Resource_Reqs: ' ||
6407                              'p_del_resrc_reqs('||i||') = '|| p_del_resrc_reqs(i)||
6408                              --'p_inv_item_ids('||i||') = '|| p_inv_item_ids(i)||
6409                              --'p_plan_ids('||i||') = '|| p_plan_ids(i)||
6410                              --'p_identifiers('||i||') = '|| p_identifiers(i)
6411                              'p_atp_peg_res_reqs_plan_ids('||i||') = '|| p_atp_peg_res_reqs_plan_ids(i)
6412                              );
6413        END LOOP;
6414    END IF;
6415 
6416    x_return_status := FND_API.G_RET_STS_SUCCESS;
6417 
6418    --Bug 3629191
6419    FORALL m IN 1..p_del_resrc_reqs.COUNT
6420       DELETE msc_resource_requirements
6421       WHERE
6422       -- Bug 3629191 :All where clause except and transaction_id are commmented
6423       /*sr_instance_id = p_instance_id
6424       (SELECT sr_instance_id
6425        FROM   msc_atp_pegging
6426        WHERE  plan_id = p_plan_ids(m)
6427        AND    sales_order_line_id = p_identifiers(m)
6428        AND     DECODE(demand_source_type,100,demand_source_type,-1)
6429                       =decode(p_demand_source_type(m),
6430                               100,
6431                               p_demand_source_type(m),
6432                               -1) --CMRO;
6433        AND    inventory_item_id = p_inv_item_ids(m)
6434        AND    relief_type = 4
6435       )
6436       AND */
6437              plan_id = p_atp_peg_res_reqs_plan_ids(m) --Bug 3629191
6438       --AND  assembly_item_id = p_inv_item_ids(m)
6439       AND    transaction_id = p_del_resrc_reqs(m);
6440 
6441    -- Count how many rows were updated for each resource transaction id
6442    IF PG_DEBUG in ('Y', 'C') THEN
6443         FOR m IN 1..p_del_resrc_reqs.COUNT LOOP
6444            msc_sch_wb.atp_debug('For Transaction id '|| p_del_resrc_reqs(m)||': updated '||
6445                         SQL%BULK_ROWCOUNT(m)||' records');
6446         END LOOP;
6447    END IF;
6448 
6449    IF PG_DEBUG in ('Y', 'C') THEN
6450         msc_sch_wb.atp_debug('**********End Remove_Offset_Resource_Reqs Procedure************');
6451    END IF;
6452 
6453 EXCEPTION
6454     WHEN OTHERS THEN
6455         IF FND_MSG_PUB.Check_Msg_Level(FND_MSG_PUB.G_MSG_LVL_UNEXP_ERROR) THEN
6456             FND_MSG_PUB.Add_Exc_Msg (G_PKG_NAME , 'Remove_Offset_Resource_Reqs');
6457         END IF;
6458 
6459         IF PG_DEBUG in ('Y', 'C')  THEN
6460            msc_sch_wb.atp_debug('Remove_Offset_Supplies: ERROR' || sqlerrm );
6461         END IF;
6462         x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
6463         -- Bug 3319810 Enable exception generation.
6464         RAISE FND_API.G_EXC_UNEXPECTED_ERROR;
6465 
6466 END Remove_Offset_Resource_Reqs;
6467 
6468 PROCEDURE Remove_Offset_Data (
6469                     --p_identifiers      IN         MRP_ATP_PUB.Number_Arr, --Bug 3629191
6470                     --p_plan_ids         IN         MRP_ATP_PUB.Number_Arr, --Bug 3629191
6471                     p_inv_item_ids     IN         MRP_ATP_PUB.Number_Arr,
6472                     p_del_demand_ids   IN         MRP_ATP_PUB.Number_Arr,
6473                     p_del_supply_ids   IN         MRP_ATP_PUB.Number_Arr,
6474                     p_del_resrc_reqs   IN         MRP_ATP_PUB.Number_Arr,
6475                     p_demand_source_type IN       MRP_ATP_PUB.Number_Arr,--cmro
6476                     p_atp_peg_demands_plan_ids  IN MRP_ATP_PUB.Number_Arr, --Bug 3629191
6477                     p_atp_peg_supplies_plan_ids IN MRP_ATP_PUB.Number_Arr, --Bug 3629191
6478                     p_atp_peg_res_reqs_plan_ids IN MRP_ATP_PUB.Number_Arr, --Bug 3629191
6479                     x_return_status    OUT NoCopy VARCHAR2
6480                     )
6481 IS
6482 BEGIN
6483 
6484    IF PG_DEBUG in ('Y', 'C') THEN
6485         msc_sch_wb.atp_debug('**********Begin Remove_Offset_Data Procedure************');
6486     END IF;
6487 
6488     x_return_status := FND_API.G_RET_STS_SUCCESS;
6489 
6490     Remove_Offset_Demands ( --p_identifiers, p_plan_ids,
6491                            p_atp_peg_demands_plan_ids, --Bug 3629191
6492                            p_inv_item_ids, p_del_demand_ids,p_demand_source_type, x_return_status);--cmro
6493 
6494     IF PG_DEBUG in ('Y', 'C')  THEN
6495         msc_sch_wb.atp_debug('Status After Call to Remove_Offset_Demands :'
6496                                                         || x_return_status);
6497     END IF;
6498 
6499     Remove_Offset_Supplies ( --p_identifiers, p_plan_ids,
6500                             p_atp_peg_supplies_plan_ids, --Bug 3629191
6501                             p_inv_item_ids, p_del_supply_ids,p_demand_source_type,x_return_status);--cmro
6502 
6503     IF PG_DEBUG in ('Y', 'C')  THEN
6504         msc_sch_wb.atp_debug('Status After Call to Remove_Offset_Supplies :'
6505                                                         || x_return_status);
6506     END IF;
6507 
6508     Remove_Offset_Resource_Reqs ( --p_identifiers, p_plan_ids,
6509                            p_atp_peg_res_reqs_plan_ids, --Bug 3629191
6510                            p_inv_item_ids, p_del_resrc_reqs,p_demand_source_type,x_return_status);--cmro
6511 
6512     IF PG_DEBUG in ('Y', 'C')  THEN
6513         msc_sch_wb.atp_debug('Status After Call to Remove_Offset_Resource_Reqs :'
6514                                                         || x_return_status);
6515     END IF;
6516 
6517 EXCEPTION
6518     WHEN OTHERS THEN
6519         IF FND_MSG_PUB.Check_Msg_Level(FND_MSG_PUB.G_MSG_LVL_UNEXP_ERROR) THEN
6520             FND_MSG_PUB.Add_Exc_Msg (G_PKG_NAME , 'Remove_Offset_Data');
6521         END IF;
6522 
6523         IF PG_DEBUG in ('Y', 'C')  THEN
6524            msc_sch_wb.atp_debug('Remove_Offset_Data: ERROR' || sqlerrm );
6525         END IF;
6526         x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
6527         -- Bug 3319810 Enable exception generation.
6528         RAISE FND_API.G_EXC_UNEXPECTED_ERROR;
6529 END Remove_Offset_Data;
6530 
6531 -- Create Simplified pegging data for PF ATP Scenario.
6532 -- CTO_PF_PRJ_2 New procedure for CTO PF Cross Project Impacts.
6533 PROCEDURE Create_PF_Atp_Pegging(
6534   p_reference_item_id      IN         NUMBER,
6535   p_model_order_line_id    IN         NUMBER,
6536   p_config_order_line_id   IN         NUMBER,
6537   p_demand_source_type     IN         NUMBER,--cmro
6538   p_end_demand_id          IN         NUMBER,
6539   p_plan_id                IN         NUMBER,
6540   x_return_status          IN OUT     NoCopy VARCHAR2
6541 )
6542 IS
6543 
6544 my_sqlcode                NUMBER;
6545 l_dmd_offset_typ          NUMBER;
6546 
6547 BEGIN
6548 
6549   IF PG_DEBUG in ('Y', 'C') THEN
6550      msc_sch_wb.atp_debug('***** Begin Create_PF_Atp_Pegging Procedure *****');
6551      msc_sch_wb.atp_debug('Reference Item Id : ' || p_reference_item_id);
6552      msc_sch_wb.atp_debug('Model Line Id p_model_order_line_id : ' || p_model_order_line_id);
6553      msc_sch_wb.atp_debug('Config. Line Id p_config_order_line_id : ' || p_config_order_line_id);
6554      msc_sch_wb.atp_debug('Demand Source Type : ' || p_demand_source_type);
6555      msc_sch_wb.atp_debug('SO End Demand Id : ' || p_end_demand_id);
6556      msc_sch_wb.atp_debug('Plan Id : ' || p_plan_id);
6557   END IF;
6558 
6559   x_return_status := FND_API.G_RET_STS_SUCCESS;
6560 
6561   IF ((MSC_ATP_PVT.G_INV_CTP = 4) AND
6562       (MSC_ATP_PVT.G_ALLOCATED_ATP = 'Y') AND
6563       (MSC_ATP_PVT.G_HIERARCHY_PROFILE = 1) AND
6564       (MSC_ATP_PVT.G_ALLOCATION_METHOD = 1)) THEN
6565 
6566      l_dmd_offset_typ := 5;
6567    ELSE
6568      l_dmd_offset_typ := 3;
6569    END IF;
6570   -- First create the demand records for component members and component family items.
6571 
6572   INSERT INTO msc_atp_pegging
6573           (reference_item_id, inventory_item_id, plan_id, sr_instance_id,
6574            organization_id, sales_order_line_id, demand_source_type, bom_item_type, --cmro
6575            transaction_date, demand_id, demand_quantity,
6576            disposition_id, demand_class, supply_id, supply_quantity,
6577            allocated_quantity, relief_type, relief_quantity, daily_relief_qty,
6578            pegging_id, prev_pegging_id, end_pegging_id, end_demand_id,
6579            created_by, creation_date, last_updated_by, last_update_date,
6580            original_item_id, original_date,
6581            customer_id, customer_site_id)
6582   SELECT mapt.reference_item_id, alocd.inventory_item_id, alocd.plan_id,
6583          alocd.sr_instance_id, alocd.organization_id,
6584          mapt.sales_order_line_id, mapt.demand_source_type,
6585          msi.bom_item_type, alocd.demand_date transaction_date,
6586          alocd.parent_demand_id demand_id, alocd.demand_quantity, mapt.disposition_id,
6587          alocd.demand_class, mapt.supply_id,
6588          mapt.supply_quantity, alocd.allocated_quantity, 7 relief_type,
6589          LEAST(ABS(mapt.relief_quantity), alocd.allocated_quantity) * SIGN(mapt.relief_quantity) *
6590          alocd.allocated_quantity/NVL(mapt.allocated_quantity,alocd.allocated_quantity) relief_quantity,
6591          LEAST(ABS(mapt.daily_relief_qty), alocd.allocated_quantity) * SIGN(mapt.relief_quantity) *
6592          alocd.allocated_quantity/NVL(mapt.allocated_quantity,alocd.allocated_quantity) daily_relief_qty,
6593          mapt.pegging_id, mapt.prev_pegging_id, mapt.end_pegging_id, mapt.end_demand_id,
6594          mapt.created_by, mapt.creation_date, mapt.last_updated_by, mapt.last_update_date,
6595          mapt.inventory_item_id, mapt.transaction_date,
6596          alocd.customer_id, alocd.ship_to_site_id
6597   FROM   msc_atp_peg_temp mapt, msc_alloc_demands alocd,
6598          msc_system_items msi
6599   WHERE  mapt.reference_item_id = p_reference_item_id
6600   AND    mapt.plan_id = p_plan_id
6601   AND    mapt.sales_order_line_id = NVL(p_config_order_line_id, p_model_order_line_id)
6602   --AND    mapt.demand_source_type = p_demand_source_type
6603   AND    mapt.end_demand_id = p_end_demand_id
6604   AND    mapt.relief_type = l_dmd_offset_typ
6605   AND    alocd.plan_id = mapt.plan_id
6606   AND    alocd.sr_instance_id = mapt.sr_instance_id
6607   AND    alocd.organization_id = mapt.organization_id
6608   AND    alocd.original_item_id = mapt.inventory_item_id
6609   AND    alocd.parent_demand_id = mapt.demand_id
6610   AND    msi.plan_id = alocd.plan_id
6611   AND    msi.sr_instance_id = alocd.sr_instance_id
6612   AND    msi.organization_id = alocd.organization_id
6613   AND    msi.inventory_item_id = alocd.inventory_item_id;
6614 
6615   IF PG_DEBUG in ('Y', 'C') THEN
6616      msc_sch_wb.atp_debug('Create_PF_Atp_Pegging:  Number of rows inserted Stage-1 '||
6617                                SQL%ROWCOUNT);
6618   END IF;
6619 
6620   -- Now Create Rest of the Records.
6621   INSERT INTO msc_atp_pegging
6622           (reference_item_id, inventory_item_id, plan_id, sr_instance_id,
6623            organization_id, sales_order_line_id, demand_source_type, bom_item_type, --cmro
6624            transaction_date, demand_id, demand_quantity,
6625            disposition_id, demand_class, supply_id, supply_quantity,
6626            allocated_quantity,
6627            resource_id, department_id, resource_hours, end_date,
6628            relief_type, relief_quantity, daily_relief_qty,
6629            pegging_id, prev_pegging_id, end_pegging_id, end_demand_id,
6630            created_by, creation_date, last_updated_by, last_update_date,
6631            customer_id, customer_site_id)
6632   SELECT  reference_item_id, inventory_item_id, plan_id, sr_instance_id,
6633           organization_id, sales_order_line_id, demand_source_type, bom_item_type, --cmro
6634           transaction_date, demand_id, demand_quantity,
6635           disposition_id, demand_class, supply_id, supply_quantity,
6636           allocated_quantity,
6637           resource_id, department_id, resource_hours, end_date,
6638           relief_type, relief_quantity, daily_relief_qty,
6639           pegging_id, prev_pegging_id, end_pegging_id, end_demand_id,
6640           created_by, creation_date, last_updated_by, last_update_date,
6641           customer_id, customer_site_id
6642   FROM    msc_atp_peg_temp mapt
6643   WHERE   mapt.reference_item_id = p_reference_item_id
6644   AND     mapt.plan_id = p_plan_id
6645   AND     mapt.sales_order_line_id = NVL(p_config_order_line_id, p_model_order_line_id)
6646   --AND     mapt.demand_source_type = p_demand_source_type
6647   AND     mapt.end_demand_id = p_end_demand_id
6648           -- Process everything except PF member and family demands.
6649   AND     mapt.inventory_item_id NOT IN
6650           (SELECT NVL(original_item_id, inventory_item_id)
6651            FROM   msc_atp_pegging
6652            WHERE  reference_item_id = p_reference_item_id
6653            AND    plan_id = p_plan_id
6654            AND    sales_order_line_id = NVL(p_config_order_line_id, p_model_order_line_id)
6655            --AND    demand_source_type = p_demand_source_type
6656            AND    end_demand_id = p_end_demand_id
6657            AND    relief_type = 7
6658           );
6659 
6660   IF PG_DEBUG in ('Y', 'C') THEN
6661      msc_sch_wb.atp_debug('Create_PF_Atp_Pegging:  Number of rows inserted Stage-2 '||
6662                                SQL%ROWCOUNT);
6663   END IF;
6664 
6665   IF PG_DEBUG in ('Y', 'C') THEN
6666      msc_sch_wb.atp_debug('***** End Create_PF_Atp_Pegging Procedure *****');
6667   END IF;
6668 
6669 EXCEPTION
6670     WHEN OTHERS THEN
6671         my_sqlcode := SQLCODE;
6672         IF PG_DEBUG in ('Y', 'C') THEN
6673            msc_sch_wb.atp_debug('Create_PF_Atp_Pegging: ' || my_sqlcode ||
6674                 ' error encountered while creating ATP Pegging : ERROR =  '|| sqlerrm);
6675         END IF;
6676 
6677         IF FND_MSG_PUB.Check_Msg_Level(FND_MSG_PUB.G_MSG_LVL_UNEXP_ERROR) THEN
6678             FND_MSG_PUB.Add_Exc_Msg(G_PKG_NAME , 'Create_PF_Atp_Pegging');
6679         END IF;
6680         x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
6681         RAISE FND_API.G_EXC_UNEXPECTED_ERROR;
6682 
6683 END Create_PF_Atp_Pegging;
6684 -- End CTO_PF_PRJ_2
6685 
6686 -- Create Simplified pegging data using ATP Pegging information.
6687 PROCEDURE Create_Atp_Pegging(
6688   p_identifier             IN      NUMBER,
6689   p_instance_id            IN      NUMBER,
6690   p_old_plan_id            IN      NUMBER,
6691   p_model_order_line_id    IN      NUMBER,
6692   p_config_order_line_id   IN      NUMBER,
6693   p_demand_source_type     IN      NUMBER,--cmro
6694   x_return_status          OUT     NoCopy VARCHAR2
6695 )
6696 IS
6697 
6698 l_reference_item_id       NUMBER;
6699 i                         NUMBER;
6700 atp_peg_rec               msc_atp_pegging%ROWTYPE;
6701 my_sqlcode                NUMBER;
6702 -- Bug 3334643 Track the plan_id
6703 l_plan_id                 NUMBER;
6704 
6705 -- CTO_PF_PRJ Get End Demand Id
6706 l_end_demand_id                 NUMBER;
6707 -- CTO_PF_PRJ_2 Impacts
6708 l_session_id                    NUMBER;
6709 l_insert_temp_table             VARCHAR2(30);
6710 l_sql_stmt                      VARCHAR2(800);
6711 l_sql_stmt_1                    VARCHAR2(8000);
6712 l_sup_offset_typ                NUMBER;
6713 l_dmd_offset_typ                NUMBER;
6714 l_peg_type                      NUMBER;
6715 -- End CTO_PF_PRJ_2 Impacts
6716 
6717 BEGIN
6718 
6719   IF PG_DEBUG in ('Y', 'C') THEN
6720      msc_sch_wb.atp_debug('***** Begin Create_Atp_Pegging Procedure *****');
6721      msc_sch_wb.atp_debug('End Pegging Id p_identifier : ' || p_identifier);
6722      msc_sch_wb.atp_debug('Instance Id p_instance_id : ' || p_instance_id);
6723      msc_sch_wb.atp_debug('Old Plan Id : ' || p_old_plan_id);
6724      msc_sch_wb.atp_debug('Model Line Id p_model_order_line_id : ' || p_model_order_line_id);
6725      msc_sch_wb.atp_debug('Config. Line Id p_config_order_line_id : ' || p_config_order_line_id);
6726      msc_sch_wb.atp_debug('Demand. Source Type p_demand_source_type : ' || p_demand_source_type);
6727   END IF;
6728 
6729   x_return_status := FND_API.G_RET_STS_SUCCESS;
6730 
6731    -- CTO_PF_PRJ_2 Impacts
6732    IF (MSC_ATP_PVT.G_CTO_PF_ATP = 'Y') THEN
6733       l_insert_temp_table := 'MSC_ATP_PEG_TEMP';
6734    ELSE
6735       l_insert_temp_table := 'MSC_ATP_PEGGING';
6736    END IF;
6737 
6738    IF ((MSC_ATP_PVT.G_INV_CTP = 4) AND
6739       (MSC_ATP_PVT.G_ALLOCATED_ATP = 'Y') AND
6740       (MSC_ATP_PVT.G_HIERARCHY_PROFILE = 1) AND
6741       (MSC_ATP_PVT.G_ALLOCATION_METHOD = 1)) THEN
6742 
6743      l_sup_offset_typ := 6;
6744      l_dmd_offset_typ := 5;
6745    ELSE
6746      l_sup_offset_typ := 2;
6747      l_dmd_offset_typ := 3;
6748    END IF;
6749    -- CTO_PF_PRJ_2 Impacts
6750 
6751    -- First Delete old pegging data.
6752    BEGIN
6753 
6754          DELETE from msc_atp_pegging
6755          WHERE  plan_id = p_old_plan_id
6756          AND    relief_type > 0
6757          AND    sales_order_line_id in (NVL(p_config_order_line_id, -1), p_model_order_line_id)
6758          AND     decode(demand_source_type,100,demand_source_type,-1)
6759                 =decode(p_demand_source_type,
6760                                                 100,
6761                                                 p_demand_source_type,
6762                                                 -1); --CMRO
6763       IF PG_DEBUG in ('Y', 'C') THEN
6764              msc_sch_wb.atp_debug('Create_Atp_Pegging:  Number of rows deleted '||
6765                                SQL%ROWCOUNT);
6766       END IF;
6767    EXCEPTION
6768       WHEN OTHERS THEN
6769         IF PG_DEBUG in ('Y', 'C') THEN
6770            msc_sch_wb.atp_debug('Create_Atp_Pegging:  Error '|| sqlerrm);
6771         END IF;
6772 
6773    END;
6774 
6775    -- CTO_PF_PRJ_2 Impacts SQL are changed to Dynamic Ones
6776    --  first insert the sales order line to the ATP simplified pegging.
6777    l_sql_stmt_1 := 'INSERT INTO ' || l_insert_temp_table ||
6778                '(reference_item_id, inventory_item_id, plan_id, sr_instance_id,
6779                 organization_id, sales_order_line_id,demand_source_type, bom_item_type, --cmro
6780                 transaction_date, demand_id, demand_quantity,
6781                 disposition_id, demand_class, supply_id, supply_quantity,
6782                 allocated_quantity,
6783                 resource_id, department_id, resource_hours, end_date, -- start_date,
6784                             -- Bug 3443056, 3348095 ATP now tracks end date.
6785                 relief_type, relief_quantity, daily_relief_qty,
6786                 pegging_id, prev_pegging_id, end_pegging_id, end_demand_id,
6787                 created_by, creation_date, last_updated_by, last_update_date,
6788                 customer_id, customer_site_id)
6789          SELECT dest_inv_item_id , NVL(DEST_INV_ITEM_ID, INVENTORY_ITEM_ID),
6790                 identifier2 plan_id, identifier1 sr_instance_id,
6791                 NVL(RECEIVING_ORGANIZATION_ID, organization_id) ,
6792                 NVL(:p_config_order_line_id, :p_model_order_line_id) sales_order_line_id,
6793                 :p_demand_source_type,--cmro
6794                 --bug 3328421
6795                 --NULL bom_item_type, NVL(required_date, supply_demand_date) transaction_date,
6796                 NULL bom_item_type, NVL(actual_supply_demand_date, supply_demand_date) transaction_date,
6797                 -- identifier3 contains the demand_id
6798                 -- supply_demand_quantity contains the demand_quantity
6799                 DECODE (pegging_type, :l_peg_type1,
6800                          identifier3, NULL) demand_id,
6801                 DECODE (pegging_type, :l_peg_type2,
6802                          supply_demand_quantity, NULL) supply_demand_quantity,
6803                 NULL disposition_id, demand_class,
6804                 -- identifier3 contains the transaction_id
6805                 -- supply_demand_quantity contains the supply_quantitiy
6806                 -- For ATP created pegging the allocated_qty is the same as supply_qty
6807                 DECODE (pegging_type,
6808                          :l_peg_type3, identifier3,
6809                          :l_peg_type4, identifier3,
6810                          :l_peg_type5, identifier3,
6811                           NULL) supply_id,
6812                 DECODE (pegging_type,
6813                          :l_peg_type6, supply_demand_quantity,
6814                          :l_peg_type7, supply_demand_quantity,
6815                          :l_peg_type8, supply_demand_quantity,
6816                           NULL) supply_quantity,
6817                 DECODE (pegging_type,
6818                          :l_peg_type9, supply_demand_quantity,
6819                          :l_peg_type10, supply_demand_quantity,
6820                          :l_peg_type11, supply_demand_quantity,
6821                           NULL) allocated_quantity,
6822                 resource_id, department_id,
6823                 DECODE (pegging_type,
6824                          :l_peg_type12, supply_demand_quantity,
6825                          NULL) resource_hours,
6826                 --bug 3328421
6827                 --NVL(required_date, supply_demand_date) start_date,
6828                 NVL(actual_supply_demand_date, supply_demand_date) end_date, -- start_date,
6829                             -- Bug 3443056, 3348095 ATP now tracks end date.
6830                 DECODE (pegging_type,
6831                         :l_peg_type13,
6832                           decode(pegging_id, end_pegging_id, 1, :l_dmd_offset_typ),
6833                            -- pegging_id is same as end_pegging_id then SO
6834                            -- otherwise POD
6835                          :l_peg_type14, :l_sup_offset_typ,      -- PO
6836                          :l_peg_type15, :l_sup_offset_typ,  -- PO
6837                          :l_peg_type16, 4 , -- REQ
6838                          :l_peg_type17, :l_sup_offset_typ )
6839                           relief_type,
6840                 decode(pegging_id, end_pegging_id, 0,
6841                       -1 *  supply_demand_quantity ) relief_quantity,
6842                 NULL daily_relief_qty,
6843                 pegging_id, parent_pegging_id, end_pegging_id,
6844                 DECODE (pegging_type, :l_peg_type18,
6845                          identifier3, NULL) end_demand_id,
6846                 created_by, creation_date, last_updated_by, last_update_date,
6847                 customer_id, customer_site_id
6848          FROM   mrp_atp_details_temp
6849          WHERE  pegging_id = :p_identifier
6850          AND    identifier1 = :p_instance_id
6851          AND    record_type = 3
6852          and    session_id = :l_session_id
6853          and    model_sd_flag = 1' -- ensure that we only obtain pegging for things in the order.
6854          ;
6855 
6856   IF PG_DEBUG in ('Y', 'C') THEN
6857              msc_sch_wb.atp_debug('Create_Atp_Pegging:  Insert SQL Statement '||
6858                                l_sql_stmt_1);
6859   END IF;
6860 
6861     EXECUTE IMMEDIATE l_sql_stmt_1 USING
6862            p_config_order_line_id,
6863            p_model_order_line_id,
6864            p_demand_source_type,
6865            MSC_ATP_PVT.ORG_DEMAND,
6866            MSC_ATP_PVT.ORG_DEMAND,
6867            MSC_ATP_PVT.MAKE_SUPPLY,
6868            MSC_ATP_PVT.TRANSFER_SUPPLY,
6869            MSC_ATP_PVT.BUY_SUPPLY,
6870            MSC_ATP_PVT.MAKE_SUPPLY,
6871            MSC_ATP_PVT.TRANSFER_SUPPLY,
6872            MSC_ATP_PVT.BUY_SUPPLY,
6873            MSC_ATP_PVT.MAKE_SUPPLY,
6874            MSC_ATP_PVT.TRANSFER_SUPPLY,
6875            MSC_ATP_PVT.BUY_SUPPLY,
6876            MSC_ATP_PVT.RESOURCE_DEMAND,
6877            MSC_ATP_PVT.ORG_DEMAND,
6878            l_dmd_offset_typ,
6879            MSC_ATP_PVT.MAKE_SUPPLY,
6880            l_sup_offset_typ,
6881            MSC_ATP_PVT.TRANSFER_SUPPLY,
6882            l_sup_offset_typ,
6883            MSC_ATP_PVT.RESOURCE_DEMAND,
6884            MSC_ATP_PVT.BUY_SUPPLY,
6885            l_sup_offset_typ,
6886            MSC_ATP_PVT.ORG_DEMAND,
6887            p_identifier,
6888            p_instance_id,
6889            MSC_ATP_PVT.G_SESSION_ID;
6890    -- End CTO_PF_PRJ_2 Impacts SQL are changed to Dynamic Ones
6891 
6892   IF PG_DEBUG in ('Y', 'C') THEN
6893              msc_sch_wb.atp_debug('Create_Atp_Pegging:  Number of rows inserted-1 '||
6894                                SQL%ROWCOUNT);
6895   END IF;
6896 
6897    SELECT       DEST_INV_ITEM_ID, identifier2,
6898                 -- Bug 3334643 Track the plan_id
6899                 -- CTO_PF_PRJ Get End Demand Id
6900                 DECODE (pegging_type, MSC_ATP_PVT.ORG_DEMAND,
6901                          identifier3, NULL) end_demand_id
6902    INTO         l_reference_item_id, l_plan_id, l_end_demand_id
6903                 -- End CTO_PF_PRJ Get End Demand Id
6904                 -- Bug 3334643 Track the plan_id
6905    FROM         mrp_atp_details_temp
6906    WHERE        pegging_id = p_identifier
6907    AND          identifier1 = p_instance_id
6908    AND          record_type = 3
6909    AND          model_sd_flag = 1
6910    AND          session_id = MSC_ATP_PVT.G_SESSION_ID;
6911 
6912   IF PG_DEBUG in ('Y', 'C') THEN
6913      msc_sch_wb.atp_debug('Create_Atp_Pegging: l_reference_item_id ' ||
6914                                    l_reference_item_id);
6915                 -- Bug 3334643 Track the plan_id
6916      msc_sch_wb.atp_debug('Create_Atp_Pegging: l_plan_id ' ||
6917                                    l_plan_id);
6918                 -- CTO_PF_PRJ Get End Demand Id
6919      msc_sch_wb.atp_debug('Create_Atp_Pegging: End Demand Id ' ||
6920                                    l_end_demand_id);
6921                 -- End CTO_PF_PRJ Get End Demand Id
6922   END IF;
6923 
6924   -- ORG_DEMAND             CONSTANT NUMBER := 1; POD, SO
6925   -- SUPPLIER_DEMAND        CONSTANT NUMBER := 2;
6926   -- ATP_SUPPLY             CONSTANT NUMBER := 3;
6927   -- MAKE_SUPPLY            CONSTANT NUMBER := 4; PO
6928   -- BUY_SUPPLY             CONSTANT NUMBER := 5; PO
6929   -- TRANSFER_SUPPLY        CONSTANT NUMBER := 6; PO
6930   -- ATP_SUPPLIER           CONSTANT NUMBER := 7;
6931   -- RESOURCE_DEMAND        CONSTANT NUMBER := 8; RES REQ
6932   -- RESOURCE_SUPPLY        CONSTANT NUMBER := 9;
6933 
6934   -- CTO_PF_PRJ_2 Impacts SQL are changed to Dynamic Ones
6935   -- Then Add all other lines in the pegging.
6936   l_sql_stmt_1 := 'INSERT INTO ' || l_insert_temp_table ||
6937                '(reference_item_id, inventory_item_id, plan_id, sr_instance_id,
6938                 organization_id, sales_order_line_id,demand_source_type,bom_item_type, --cmro
6939                 transaction_date, demand_id, demand_quantity,
6940                 disposition_id, demand_class, supply_id, supply_quantity,
6941                 allocated_quantity,
6942                 resource_id, department_id, resource_hours, end_date, -- start_date,
6943                             -- Bug 3443056, 3348095 ATP now tracks end date.
6944                 relief_type, relief_quantity, daily_relief_qty,
6945                 pegging_id, prev_pegging_id, end_pegging_id, end_demand_id,
6946                 created_by, creation_date, last_updated_by, last_update_date,
6947                 customer_id, customer_site_id)
6948          SELECT :l_reference_item_id , NVL(DEST_INV_ITEM_ID, INVENTORY_ITEM_ID),
6949                 identifier2 plan_id, identifier1 sr_instance_id,
6950                 NVL(RECEIVING_ORGANIZATION_ID, organization_id),
6951                 NVL(:p_config_order_line_id, :p_model_order_line_id) sales_order_line_id,
6952                 :p_demand_source_type, --cmro
6953                 --3328421
6954                 --NULL bom_item_type, NVL(required_date, supply_demand_date) transaction_date,
6955                 NULL bom_item_type, NVL(actual_supply_demand_date, supply_demand_date) transaction_date,
6956                 -- identifier3 contains the demand_id
6957                 -- supply_demand_quantity contains the demand_quantity
6958                 DECODE (pegging_type, :l_peg_type1,
6959                          identifier3, NULL) demand_id,
6960                 DECODE (pegging_type, :l_peg_type2,
6961                          supply_demand_quantity, NULL) supply_demand_quantity,
6962                 NULL disposition_id, demand_class,
6963                 -- identifier3 contains the transaction_id
6964                 -- supply_demand_quantity contains the supply_quantitiy
6965                 -- For ATP created pegging the allocated_qty is the same as supply_qty
6966                 DECODE (pegging_type,
6967                          :l_peg_type3, identifier3,
6968                          :l_peg_type4, identifier3,
6969                          :l_peg_type5, identifier3,
6970                          :l_peg_type6, identifier3, -- REQ
6971                           NULL) supply_id,
6972                 DECODE (pegging_type,
6973                          :l_peg_type7, supply_demand_quantity,
6974                          :l_peg_type8, supply_demand_quantity,
6975                          :l_peg_type9, supply_demand_quantity,
6976                           NULL) supply_quantity,
6977                 DECODE (pegging_type,
6978                          :l_peg_type10, supply_demand_quantity,
6979                          :l_peg_type11, supply_demand_quantity,
6980                          :l_peg_type12, supply_demand_quantity,
6981                           NULL) allocated_quantity,
6982                 resource_id, department_id,
6983                 DECODE (pegging_type,
6984                          :l_peg_type13, supply_demand_quantity,
6985                          NULL) resource_hours,
6986                 --bug 3328421
6987                 --NVL(required_date, supply_demand_date) start_date,
6988                 NVL(actual_supply_demand_date, supply_demand_date) end_date, -- start_date,
6989                             -- Bug 3443056, 3348095 ATP now tracks end date.
6990                 DECODE (pegging_type,
6991                         :l_peg_type14,
6992                           decode(pegging_id, end_pegging_id, 1, :l_dmd_offset_typ),
6993                            -- pegging_id is same as end_pegging_id then SO
6994                            -- otherwise POD
6995                          :l_peg_type15, :l_sup_offset_typ,      -- PO
6996                          :l_peg_type16, :l_sup_offset_typ,  -- PO
6997                          :l_peg_type17, 4 , -- REQ
6998                          :l_peg_type18, :l_sup_offset_typ )
6999                           relief_type,
7000                 decode(pegging_id, end_pegging_id, 0,
7001                       -1 *  supply_demand_quantity ) relief_quantity,
7002                 NULL daily_relief_qty,
7003                 pegging_id, parent_pegging_id, end_pegging_id, :l_end_demand_id,
7004                 created_by, creation_date, last_updated_by, last_update_date,
7005                 customer_id, customer_site_id
7006          FROM   mrp_atp_details_temp
7007          WHERE  pegging_id <> :p_identifier
7008          AND    record_type in (3, 4)
7009          and    session_id = :l_session_id
7010          and    model_sd_flag = 1  -- ensure that we only obtain pegging for things in the order.
7011          -- Bug 3334643 Ensure that line is a PDS line.
7012          and    identifier2 > 0
7013          START  WITH pegging_id = :p_identifier
7014          AND    session_id = :l_session_id
7015          AND    record_type = 3
7016          CONNECT BY parent_pegging_id = prior pegging_id
7017          AND    session_id = prior session_id
7018          AND    record_type in (3,4)';
7019 
7020   IF PG_DEBUG in ('Y', 'C') THEN
7021              msc_sch_wb.atp_debug('Create_Atp_Pegging:  Insert SQL Statement '||
7022                                l_sql_stmt_1);
7023   END IF;
7024 
7025     EXECUTE IMMEDIATE l_sql_stmt_1 USING
7026            l_reference_item_id,
7027            p_config_order_line_id,
7028            p_model_order_line_id,
7029            p_demand_source_type,
7030            MSC_ATP_PVT.ORG_DEMAND,
7031            MSC_ATP_PVT.ORG_DEMAND,
7032            MSC_ATP_PVT.MAKE_SUPPLY,
7033            MSC_ATP_PVT.TRANSFER_SUPPLY,
7034            MSC_ATP_PVT.BUY_SUPPLY,
7035            MSC_ATP_PVT.RESOURCE_DEMAND,
7036            MSC_ATP_PVT.MAKE_SUPPLY,
7037            MSC_ATP_PVT.TRANSFER_SUPPLY,
7038            MSC_ATP_PVT.BUY_SUPPLY,
7039            MSC_ATP_PVT.MAKE_SUPPLY,
7040            MSC_ATP_PVT.TRANSFER_SUPPLY,
7041            MSC_ATP_PVT.BUY_SUPPLY,
7042            MSC_ATP_PVT.RESOURCE_DEMAND,
7043            MSC_ATP_PVT.ORG_DEMAND,
7044            l_dmd_offset_typ,
7045            MSC_ATP_PVT.MAKE_SUPPLY,
7046            l_sup_offset_typ,
7047            MSC_ATP_PVT.TRANSFER_SUPPLY,
7048            l_sup_offset_typ,
7049            MSC_ATP_PVT.RESOURCE_DEMAND,
7050            MSC_ATP_PVT.BUY_SUPPLY,
7051            l_sup_offset_typ,
7052            l_end_demand_id,
7053            p_identifier,
7054            MSC_ATP_PVT.G_SESSION_ID,
7055            p_identifier,
7056            MSC_ATP_PVT.G_SESSION_ID;
7057    -- End CTO_PF_PRJ_2 Impacts SQL are changed to Dynamic Ones
7058 
7059   IF PG_DEBUG in ('Y', 'C') THEN
7060              msc_sch_wb.atp_debug('Create_Atp_Pegging:  Number of rows inserted '||
7061                                SQL%ROWCOUNT);
7062   END IF;
7063 
7064   -- CTO_PF_PRJ Impacts
7065   IF (MSC_ATP_PVT.G_CTO_PF_ATP = 'Y') THEN
7066       -- Call Procedure to insert data from temp table to main table
7067       -- For PF items, PF related processing will be done.
7068       Create_PF_Atp_Pegging ( l_reference_item_id   ,
7069                               p_model_order_line_id ,
7070                               p_config_order_line_id,
7071                               p_demand_source_type  ,
7072                               l_end_demand_id       ,
7073                               l_plan_id             ,
7074                               x_return_status        );
7075   END IF;
7076   -- CTO_PF_PRJ Impacts
7077 
7078   IF PG_DEBUG in ('Y', 'C') THEN
7079      msc_sch_wb.atp_debug('***** End Create_Atp_Pegging Procedure *****');
7080   END IF;
7081 
7082 EXCEPTION
7083     WHEN OTHERS THEN
7084         my_sqlcode := SQLCODE;
7085         IF PG_DEBUG in ('Y', 'C') THEN
7086            msc_sch_wb.atp_debug('Create_Atp_Pegging: ' || my_sqlcode ||
7087                 ' error encountered while creating ATP Pegging : ERROR =  '|| sqlerrm);
7088         END IF;
7089 
7090         IF FND_MSG_PUB.Check_Msg_Level(FND_MSG_PUB.G_MSG_LVL_UNEXP_ERROR) THEN
7091             FND_MSG_PUB.Add_Exc_Msg(G_PKG_NAME , 'Create_Atp_Pegging');
7092         END IF;
7093         x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
7094         RAISE FND_API.G_EXC_UNEXPECTED_ERROR;
7095 
7096 END Create_Atp_Pegging;
7097 
7098 END MSC_ATP_PEG;