DBA Data[Home] [Help]

PACKAGE BODY: APPS.MSC_ATP_PEG

Source


1 PACKAGE BODY MSC_ATP_PEG AS
2 /* $Header: MSCAPEGB.pls 120.13 2011/12/06 09:45:39 vjuluri 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  --bug 9184226
1391 	 OR(msi.wip_supply_type = 6
1392 		 AND msi.bom_item_type <> 1
1393 		 AND (msi.bom_item_type <> 4 OR  (msi.bom_item_type = 4 AND msi.base_item_id IS NULL)) )
1394           )
1395        AND msi.inventory_item_id = fcst.inventory_item_id
1396        UNION ALL
1397        SELECT msi.plan_id,
1398          msi.sr_instance_id,
1399          fcst.inventory_item_id,
1400          fcst.parent_item_id,
1401          msi.organization_id,
1402          fcst.organization_id fcst_organization_id,
1403          -1 forecast_demand_id,
1404          fcst.sales_order_id,
1405          sales_order_qty,
1406          fcst.forecast_qty forecast_qty,
1407          fcst.consumed_qty consumed_qty,
1408          nvl(fcst.overconsumption_qty,    0) overconsumption_qty,
1409          msi.bom_item_type,
1410          msi.fixed_lead_time,
1411          msi.variable_lead_time,
1412          1,
1413          decode(fcst.inventory_item_id,    fcst.parent_item_id,    0,    atp_peg_tab.base_item_id(k),    1,    fcst.inventory_item_id)
1414        FROM msc_forecast_updates fcst,
1415          msc_system_items msi
1416        WHERE fcst.sr_instance_id = atp_peg_tab.sr_instance_id(k)
1417        AND fcst.plan_id = atp_peg_tab.plan_id(k)
1418        AND(fcst.organization_id = atp_peg_tab.organization_id(k) OR fcst.organization_id = -1)
1419        AND(fcst.sales_order_id = atp_peg_tab.original_demand_id(k) OR fcst.sales_order_id = atp_peg_tab.end_demand_id(k))
1420        AND fcst.parent_item_id = atp_peg_tab.inventory_item_id(k)
1421        AND msi.plan_id = fcst.plan_id
1422        AND msi.sr_instance_id = fcst.sr_instance_id
1423        AND msi.organization_id = atp_peg_tab.organization_id(k)
1424        AND msi.wip_supply_type = 6
1425        AND msi.bom_item_type = 4  --bug 9184226
1426        AND msi.base_item_id IS NOT NULL
1427        AND msi.inventory_item_id = fcst.parent_item_id) fcst1
1428     GROUP BY fcst1.plan_id,
1429       fcst1.sr_instance_id,
1430       fcst1.inventory_item_id,
1431       fcst1.parent_item_id,
1432       fcst1.organization_id,
1433       fcst1.fcst_organization_id,
1434       -1,
1435       fcst1.sales_order_id,
1436       sales_order_qty,
1437       fcst1.bom_item_type,
1438       fcst1.fixed_lead_time,
1439       fcst1.variable_lead_time,
1440       1,
1441       decode(fcst1.inventory_item_id,   fcst1.parent_item_id,   0,   atp_peg_tab.base_item_id(k),   1,   fcst1.inventory_item_id)
1442     ORDER BY decode(fcst1.inventory_item_id,   fcst1.parent_item_id,   0,   atp_peg_tab.base_item_id(k),   1,   fcst1.inventory_item_id);
1443     --End Modified SQL for Bug 6046524
1444     IF PG_DEBUG in ('Y', 'C') THEN
1445         msc_util.msc_log(' Count After Model Overconsumption Check : ' ||
1446                             x_fcst_data_tab.inventory_item_id.COUNT);
1447     END IF;
1448 
1449     -- Bug 3701093 pure Config Item consumption data only when Model overconsumption
1450     -- data is not found.
1451     IF x_fcst_data_tab.inventory_item_id.COUNT = 0 THEN
1452        SELECT msi.plan_id, msi.sr_instance_id,
1453               fcst.inventory_item_id, fcst.parent_item_id,
1454               msi.organization_id, fcst.organization_id fcst_organization_id,
1455               -1 forecast_demand_id, fcst.sales_order_id, sales_order_qty,
1456               SUM(fcst.forecast_qty) forecast_qty, SUM(fcst.consumed_qty) consumed_qty,
1457               SUM(NVL(fcst.overconsumption_qty,0)) overconsumption_qty,
1458               msi.bom_item_type, msi.fixed_lead_time, msi.variable_lead_time,
1459               2 -- only config item is consumed
1460        BULK COLLECT
1461        INTO   x_fcst_data_tab.plan_id, x_fcst_data_tab.sr_instance_id,
1462               x_fcst_data_tab.inventory_item_id, x_fcst_data_tab.parent_item_id,
1463               x_fcst_data_tab.organization_id, x_fcst_data_tab.fcst_organization_id,
1464               x_fcst_data_tab.fcst_demand_id, x_fcst_data_tab.sales_order_id,
1465               x_fcst_data_tab.sales_order_qty, x_fcst_data_tab.forecast_qty,
1466               x_fcst_data_tab.consumed_qty, x_fcst_data_tab.overconsumption_qty,
1467               x_fcst_data_tab.bom_item_type, x_fcst_data_tab.fixed_lt,
1468               x_fcst_data_tab.variable_lt, x_fcst_data_tab.cons_config_mod_flag
1469        FROM   msc_forecast_updates fcst, msc_system_items msi
1470        WHERE  fcst.sr_instance_id = atp_peg_tab.sr_instance_id(k)
1471        AND    fcst.plan_id = atp_peg_tab.plan_id(k)
1472        AND    (fcst.organization_id = atp_peg_tab.organization_id(k)
1473                  OR    fcst.organization_id = -1)
1474                 -- First check for local forecast
1475                 -- CTO_PF_PRJ changes. Use end_demand_id
1476        AND    (fcst.sales_order_id = atp_peg_tab.original_demand_id(k)
1477                  OR
1478                  fcst.sales_order_id = atp_peg_tab.end_demand_id(k)
1479                 )
1480                 -- CTO_PF_PRJ
1481        AND    fcst.inventory_item_id = atp_peg_tab.inventory_item_id(k)
1482        -- Only get records where config item's forecast is consumed
1483        AND    fcst.forecast_qty > 0
1484        AND    (fcst.consumed_qty + NVL(fcst.overconsumption_qty,0)) > 0
1485                                      -- Bug 3805136        atp_peg_tab.allocated_quantity(k)
1486        -- and there is no overconsumption of corresponding base model's forecast.
1487        AND    msi.plan_id = fcst.plan_id
1488        AND    msi.sr_instance_id = fcst.sr_instance_id
1489        AND    msi.organization_id = atp_peg_tab.organization_id(k)
1490        AND    msi.inventory_item_id =  fcst.inventory_item_id
1491        GROUP  BY msi.plan_id, msi.sr_instance_id,
1492                 fcst.inventory_item_id, fcst.parent_item_id,
1493                 msi.organization_id, fcst.organization_id ,
1494                 -1 , fcst.sales_order_id, sales_order_qty,
1495                 msi.bom_item_type, msi.fixed_lead_time, msi.variable_lead_time,
1496                 2 -- only config item is consumed
1497        -- Bug 3805136 (Uncomment HAVING clause)
1498        HAVING SUM(fcst.consumed_qty) + SUM(NVL(fcst.overconsumption_qty, 0))
1499                                                           >= fcst.sales_order_qty
1500        ;
1501 
1502        IF PG_DEBUG in ('Y', 'C') THEN
1503           msc_util.msc_log(' Count After Config Check : ' ||
1504                               x_fcst_data_tab.inventory_item_id.COUNT);
1505           msc_util.msc_log(' Allocated Quantity : ' || atp_peg_tab.allocated_quantity(k));
1506        END IF;
1507        -- End Bug 3701093
1508     END IF;
1509     -- End Bug 3701093
1510 
1511 
1512     -- Bug 3362558
1513     -- Global forecasting situation, org_id is -1.
1514     -- CTO_PF_PRJ Query present below removed. The use of
1515     -- end_demand_id obviates the need for SQL that joins with msc_atp_detail_peg_temp.
1516     -- Changes here in relation to Bug 3362558 not needed anymore.
1517     -- End Bug 3362558
1518 
1519         -- Bug 3362499
1520         -- No data in msc_forecast_updates.
1521     -- Bug 3417410 Determine if model line is present in data
1522     IF x_fcst_data_tab.inventory_item_id.COUNT = 0 THEN
1523        l_fcst_mod_flag := 0;
1524     ELSE
1525        FOR i in 1..x_fcst_data_tab.inventory_item_id.COUNT
1526        LOOP
1527           IF ( (x_fcst_data_tab.inventory_item_id(i) =
1528                                atp_peg_tab.base_item_id(k) ) OR
1529                (x_fcst_data_tab.inventory_item_id(i) =
1530                                atp_peg_tab.inventory_item_id(k) ) ) THEN
1531              -- The config item or model has been forecast
1532              l_fcst_mod_flag := 1;
1533              IF PG_DEBUG in ('Y', 'C') THEN
1534                 msc_util.msc_log('Get_Fcst_Cons: Model or Config in Forecast Data');
1535                 msc_util.msc_log('Get_Fcst_Cons: Forecast Inventory_Item_id : '||
1536                                                     x_fcst_data_tab.inventory_item_id(i));
1537              END IF;
1538           END IF;
1539        END LOOP;
1540     END IF;
1541     -- End Bug 3417410 Determine if model line is present in data
1542 
1543     IF l_fcst_mod_flag = 0 THEN -- Bug 3417410 If no model line is present in forecast
1544        IF PG_DEBUG in ('Y', 'C') THEN
1545           msc_util.msc_log('Get Data from msc_system_items for base_item_id');
1546           msc_util.msc_log('Provide default values for other forecast fields ');
1547        END IF;
1548         -- Get data from msc_system_items for the base_item_id
1549         -- and provide default values for other forecast related fields.
1550         -- Note Local forecast is assumed as a default.
1551         SELECT msi.plan_id, msi.sr_instance_id,
1552                msi.inventory_item_id, atp_peg_tab.inventory_item_id(k),
1553                msi.organization_id, msi.organization_id fcst_organization_id,
1554                -1 forecast_demand_id, atp_peg_tab.original_demand_id(k) sales_order_id,
1555                0 sales_order_qty, 0 forecast_qty, 0 consumed_qty,
1556                atp_peg_tab.allocated_quantity(k)  overconsumption_qty,
1557                msi.bom_item_type, msi.fixed_lead_time, msi.variable_lead_time,
1558                -- Bug 3701093
1559                0  -- No forecast Consumption Happens,
1560                                    -- Generating data based on allocated quantities.
1561         BULK COLLECT
1562              -- Bug 3417410 Collect into local record.
1563         INTO   l_fcst_data_tab.plan_id, l_fcst_data_tab.sr_instance_id,
1564                l_fcst_data_tab.inventory_item_id, l_fcst_data_tab.parent_item_id,
1565                l_fcst_data_tab.organization_id, l_fcst_data_tab.fcst_organization_id,
1566                l_fcst_data_tab.fcst_demand_id, l_fcst_data_tab.sales_order_id,
1567                l_fcst_data_tab.sales_order_qty, l_fcst_data_tab.forecast_qty,
1568                l_fcst_data_tab.consumed_qty, l_fcst_data_tab.overconsumption_qty,
1569                l_fcst_data_tab.bom_item_type, l_fcst_data_tab.fixed_lt,
1570                l_fcst_data_tab.variable_lt,
1571                -- Bug 3701093 Model overconsumption does not happen
1572                l_fcst_data_tab.cons_config_mod_flag
1573                -- Just get the data from msc_system_items
1574                -- and default the rest of the values.
1575              -- End Bug 3417410 Collect into local record.
1576         FROM   msc_system_items msi
1577         WHERE  msi.plan_id = atp_peg_tab.plan_id(k)
1578         AND    msi.sr_instance_id = atp_peg_tab.sr_instance_id(k)
1579         AND    msi.organization_id = atp_peg_tab.organization_id(k)
1580         AND    (msi.wip_supply_type = 6 or msi.bom_item_type = 1)
1581                -- only phantom model info is obtained
1582         AND    msi.inventory_item_id =  atp_peg_tab.base_item_id(k)
1583         ;
1584 
1585         -- Bug 3417410 Assign the default model data into the output record.
1586         x_fcst_data_tab.plan_id.EXTEND;
1587         x_fcst_data_tab.sr_instance_id.EXTEND;
1588         x_fcst_data_tab.inventory_item_id.EXTEND;
1589         x_fcst_data_tab.parent_item_id.EXTEND;
1590         x_fcst_data_tab.organization_id.EXTEND;
1591         x_fcst_data_tab.fcst_organization_id.EXTEND;
1592         x_fcst_data_tab.fcst_demand_id.EXTEND;
1593         x_fcst_data_tab.sales_order_id.EXTEND;
1594         x_fcst_data_tab.sales_order_qty.EXTEND;
1595         x_fcst_data_tab.forecast_qty.EXTEND;
1596         x_fcst_data_tab.consumed_qty.EXTEND;
1597         x_fcst_data_tab.overconsumption_qty.EXTEND;
1598         x_fcst_data_tab.bom_item_type.EXTEND;
1599         x_fcst_data_tab.fixed_lt.EXTEND;
1600         x_fcst_data_tab.variable_lt.EXTEND;
1601         -- Bug 3701093 Extend the new field.
1602         x_fcst_data_tab.cons_config_mod_flag.EXTEND;
1603 
1604         l_fcst_cnt :=  x_fcst_data_tab.inventory_item_id.COUNT;
1605 
1606         IF PG_DEBUG in ('Y', 'C') THEN
1607            msc_util.msc_log('Get_Fcst_Cons-Total Forecasted Items : '|| l_fcst_cnt);
1608         END IF;
1609 
1610         -- Bug 3701093 COUNT > 0 check only, changed from <>
1611         IF l_fcst_data_tab.inventory_item_id.COUNT > 0 THEN
1612            x_fcst_data_tab.plan_id(l_fcst_cnt)           := l_fcst_data_tab.plan_id(1);
1613            x_fcst_data_tab.sr_instance_id(l_fcst_cnt)    := l_fcst_data_tab.sr_instance_id(1);
1614            x_fcst_data_tab.inventory_item_id(l_fcst_cnt) := l_fcst_data_tab.inventory_item_id(1);
1615            x_fcst_data_tab.parent_item_id(l_fcst_cnt)    := l_fcst_data_tab.parent_item_id(1);
1616            x_fcst_data_tab.organization_id(l_fcst_cnt)   := l_fcst_data_tab.organization_id(1);
1617            x_fcst_data_tab.fcst_organization_id(l_fcst_cnt) :=
1618                                                       l_fcst_data_tab.fcst_organization_id(1);
1619            x_fcst_data_tab.fcst_demand_id(l_fcst_cnt)    := l_fcst_data_tab.fcst_demand_id(1);
1620            x_fcst_data_tab.sales_order_id(l_fcst_cnt)    := l_fcst_data_tab.sales_order_id(1);
1621            x_fcst_data_tab.sales_order_qty(l_fcst_cnt)   := l_fcst_data_tab.sales_order_qty(1);
1622            x_fcst_data_tab.forecast_qty(l_fcst_cnt)      := l_fcst_data_tab.forecast_qty(1);
1623            x_fcst_data_tab.consumed_qty(l_fcst_cnt)      := l_fcst_data_tab.consumed_qty(1);
1624            x_fcst_data_tab.overconsumption_qty(l_fcst_cnt) :=
1625                                                       l_fcst_data_tab.overconsumption_qty(1);
1626            -- Bug 3805136
1627            -- Lower Level Config No Forecast .
1628            IF (atp_peg_tab.inventory_item_id(k) <> atp_peg_tab.reference_item_id(k) ) THEN
1629               x_fcst_data_tab.forecast_qty(l_fcst_cnt)      := NULL;
1630               x_fcst_data_tab.consumed_qty(l_fcst_cnt)      := NULL;
1631               x_fcst_data_tab.overconsumption_qty(l_fcst_cnt) := NULL;
1632            END IF;
1633            -- End Bug 3805136
1634            x_fcst_data_tab.bom_item_type(l_fcst_cnt)     := l_fcst_data_tab.bom_item_type(1);
1635            x_fcst_data_tab.fixed_lt(l_fcst_cnt)          := l_fcst_data_tab.fixed_lt(1);
1636            x_fcst_data_tab.variable_lt(l_fcst_cnt)       := l_fcst_data_tab.variable_lt(1);
1637            -- Bug 3701093
1638            x_fcst_data_tab.cons_config_mod_flag(l_fcst_cnt) := C_NO_FCST_CONSUMED;
1639            -- Bug 3701093 Model and Config forecast consumption does not happen
1640         ELSE
1641            -- No data in msc_system_items for the base model
1642            -- Print out a Warning message.
1643            IF PG_DEBUG in ('Y', 'C') THEN
1644               msc_util.msc_log ( 'No plan data for Base Model ' ||
1645                                                         atp_peg_tab.base_item_id(k)  );
1646               msc_util.msc_log('Get_Fcst_Cons-No plan data for Base Model : '||
1647                                                         atp_peg_tab.base_item_id(k) );
1648            END IF;
1649            x_fcst_data_tab.plan_id(l_fcst_cnt)           := atp_peg_tab.plan_id(k);
1650            x_fcst_data_tab.sr_instance_id(l_fcst_cnt)    := atp_peg_tab.sr_instance_id(k);
1651            x_fcst_data_tab.inventory_item_id(l_fcst_cnt) := atp_peg_tab.base_item_id(k);
1652            x_fcst_data_tab.parent_item_id(l_fcst_cnt)    := atp_peg_tab.inventory_item_id(k);
1653            x_fcst_data_tab.organization_id(l_fcst_cnt)   := atp_peg_tab.organization_id(k);
1654            x_fcst_data_tab.fcst_organization_id(l_fcst_cnt) :=
1655                                                       atp_peg_tab.organization_id(k);
1656            x_fcst_data_tab.fcst_demand_id(l_fcst_cnt)    := -1;
1657            x_fcst_data_tab.sales_order_id(l_fcst_cnt)    := atp_peg_tab.original_demand_id(k);
1658            x_fcst_data_tab.sales_order_qty(l_fcst_cnt)   := 0;
1659            x_fcst_data_tab.forecast_qty(l_fcst_cnt)      := 0;
1660            x_fcst_data_tab.consumed_qty(l_fcst_cnt)      := 0;
1661            x_fcst_data_tab.overconsumption_qty(l_fcst_cnt) :=
1662                                                       atp_peg_tab.allocated_quantity(k);
1663            -- Bug 3805136
1664            -- Lower Level Config No Forecast .
1665            IF (atp_peg_tab.inventory_item_id(k) <> atp_peg_tab.reference_item_id(k) ) THEN
1666               x_fcst_data_tab.forecast_qty(l_fcst_cnt)      := NULL;
1667               x_fcst_data_tab.consumed_qty(l_fcst_cnt)      := NULL;
1668               x_fcst_data_tab.overconsumption_qty(l_fcst_cnt) := NULL;
1669            END IF;
1670            x_fcst_data_tab.bom_item_type(l_fcst_cnt)     := 1;
1671            x_fcst_data_tab.fixed_lt(l_fcst_cnt)          := 0;
1672            x_fcst_data_tab.variable_lt(l_fcst_cnt)       := 0;
1673            -- Bug 3701093
1674            x_fcst_data_tab.cons_config_mod_flag(l_fcst_cnt) := C_NO_FCST_CONSUMED;
1675            -- Bug 3701093 Model and Config forecast consumption does not happen
1676         END IF;
1677         -- Bug 3417410 Assign the default model data into the output record.
1678 
1679     END IF;
1680     -- End Bug 3362499
1681 
1682   /* Old code that links to the BOM DELETED
1683    */
1684 
1685 EXCEPTION
1686     WHEN OTHERS THEN
1687       IF PG_DEBUG in ('Y', 'C') THEN
1688         msc_util.msc_log ('Get_Forecast_Consumption. Error : ' || sqlerrm);
1689       END IF;
1690         x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
1691 
1692 END Get_Forecast_Consumption;
1693 
1694 -- This procedure transforms a flat combined supply/demand pegging into a two
1695 -- level pegging that contains supplies and demands separately.
1696 PROCEDURE Create_Simple_Pegging (atp_peg_det      IN            ATP_Detail_Peg_Typ,
1697                                  atp_peg_tab      IN OUT NoCopy ATP_Simple_Peg_Typ,
1698                                  x_return_status  OUT NOCOPY    VARCHAR2)
1699 IS
1700 n                  NUMBER;
1701 l_return_status    VARCHAR2(1);
1702 l_count            NUMBER := 0;
1703 BEGIN
1704 
1705   IF PG_DEBUG in ('Y', 'C') THEN
1706        msc_util.msc_log('***** Begin Create_Simple_Pegging Procedure *****');
1707   END IF;
1708 
1709   x_return_status := FND_API.G_RET_STS_SUCCESS;
1710 
1711   IF PG_DEBUG in ('Y', 'C') THEN
1712     msc_util.msc_log(' atp_peg_det.reference_item_id.COUNT ' ||
1713                                      atp_peg_det.reference_item_id.COUNT);
1714     msc_util.msc_log('atp_peg_tab.reference_item_id.COUNT ' ||
1715                                       atp_peg_tab.reference_item_id.COUNT);
1716   END IF;
1717 
1718   l_count := atp_peg_tab.reference_item_id.COUNT;
1719 
1720   FOR n in 1..atp_peg_det.inventory_item_id.COUNT LOOP
1721     -- First Call to extend the tables in atp_peg_tab.
1722     Extend_Atp_Peg (atp_peg_tab, l_return_status, 1);
1723 
1724    IF PG_DEBUG in ('Y', 'C') THEN
1725     msc_util.msc_log(' Item Id  ' || atp_peg_det.inventory_item_id(n));
1726     msc_util.msc_log(' atp_peg_tab.pegging_id ' ||
1727                                       atp_peg_det.pegging_id(n));
1728    END IF;
1729     l_count := l_count + 1;
1730 
1731     -- The detail data is divided into two simplified pegging records.
1732     -- one for demand and one for supply.
1733     -- Assign Common Data
1734 
1735     atp_peg_tab.reference_item_id(l_count) := atp_peg_det.reference_item_id(n);
1736     atp_peg_tab.base_item_id(l_count) := atp_peg_det.base_item_id(n);
1737     atp_peg_tab.inventory_item_id(l_count) := atp_peg_det.inventory_item_id(n);
1738     atp_peg_tab.plan_id(l_count) := atp_peg_det.plan_id(n);
1739     atp_peg_tab.sr_instance_id(l_count) := atp_peg_det.sr_instance_id(n);
1740     atp_peg_tab.organization_id(l_count) := atp_peg_det.organization_id(n);
1741     atp_peg_tab.bom_item_type(l_count) := atp_peg_det.bom_item_type(n);
1742     atp_peg_tab.fixed_lt(l_count) := atp_peg_det.fixed_lt(n);
1743     atp_peg_tab.variable_lt(l_count) := atp_peg_det.variable_lt(n);
1744     atp_peg_tab.sales_order_line_id(l_count) := atp_peg_det.sales_order_line_id(n);
1745     atp_peg_tab.demand_source_type(l_count) := atp_peg_det.demand_source_type(n);--cmro
1746     atp_peg_tab.end_pegging_id(l_count) := atp_peg_det.end_pegging_id(n);
1747     atp_peg_tab.pegging_id(l_count) := atp_peg_det.pegging_id(n);
1748     atp_peg_tab.prev_pegging_id(l_count) := atp_peg_det.prev_pegging_id(n);
1749     atp_peg_tab.sales_order_qty(l_count) := atp_peg_det.sales_order_qty(n);
1750     atp_peg_tab.tot_relief_qty(l_count) := atp_peg_det.tot_relief_qty(n);
1751     -- CTO_PF_PRJ changes.
1752     atp_peg_tab.end_demand_id(l_count) := atp_peg_det.end_demand_id(n);
1753     -- CTO-PF
1754     atp_peg_tab.atf_date(l_count) := atp_peg_det.atf_date(n);
1755     atp_peg_tab.product_family_id(l_count) := atp_peg_det.product_family_id(n);
1756 
1757     atp_peg_tab.demand_class(l_count) := atp_peg_det.demand_class(n);
1758     -- Bug 3805136 -- Add end_item_usage to handle no forecast consumption.
1759     atp_peg_tab.end_item_usage(l_count) := atp_peg_det.end_item_usage(n);
1760     -- Exclude flag helps in excluding supplies
1761     -- during relef data calculation.
1762     atp_peg_tab.exclude_flag(l_count) := atp_peg_det.exclude_flag(n);
1763     -- End Bug 3805136
1764 
1765     -- Assign Demand Data
1766     atp_peg_tab.transaction_date(l_count) := TRUNC(atp_peg_det.demand_date(n));
1767     atp_peg_tab.demand_id(l_count) := atp_peg_det.demand_id(n);
1768     atp_peg_tab.demand_quantity(l_count) := atp_peg_det.demand_quantity(n);
1769     atp_peg_tab.disposition_id(l_count) := atp_peg_det.disposition_id(n);
1770     atp_peg_tab.consumed_qty(l_count) := atp_peg_det.consumed_qty(n);
1771     atp_peg_tab.overconsumption_qty(l_count) := atp_peg_det.overconsumption_qty(n);
1772     atp_peg_tab.allocated_quantity(l_count) := atp_peg_det.allocated_quantity(n);
1773 
1774     -- Auxiliary Data for CTO_PF_PRJ_2, Track the supply data.
1775     atp_peg_tab.supply_id(l_count) := atp_peg_det.supply_id(n);
1776     atp_peg_tab.supply_quantity(l_count) := atp_peg_det.supply_quantity(n);
1777 
1778     -- Determine Relief Type
1779     IF atp_peg_det.demand_type(n) = 6 or atp_peg_det.demand_type(n) = 30 THEN
1780        atp_peg_tab.relief_type(l_count) := 1;   -- Relief Type is SO.
1781     ELSIF atp_peg_det.demand_type(n) = 1 THEN
1782        atp_peg_tab.relief_type(l_count) := 3;   -- Relief Type is POD.
1783     END IF;
1784 
1785 
1786     -- Now create the supply simplified pegging data.
1787     IF (atp_peg_det.base_item_id(n) IS NOT NULL AND
1788         atp_peg_det.supply_id(n) IS NOT NULL ) THEN
1789        Extend_Atp_Peg (atp_peg_tab, l_return_status, 1);
1790 
1791        l_count  := l_count + 1;
1792 
1793       -- Assign Common Data
1794       atp_peg_tab.reference_item_id(l_count) := atp_peg_det.reference_item_id(n);
1795       atp_peg_tab.base_item_id(l_count) := atp_peg_det.base_item_id(n);
1796       atp_peg_tab.inventory_item_id(l_count) := atp_peg_det.inventory_item_id(n);
1797       atp_peg_tab.plan_id(l_count) := atp_peg_det.plan_id(n);
1798       atp_peg_tab.sr_instance_id(l_count) := atp_peg_det.sr_instance_id(n);
1799       atp_peg_tab.organization_id(l_count) := atp_peg_det.organization_id(n);
1800       atp_peg_tab.bom_item_type(l_count) := atp_peg_det.bom_item_type(n);
1801       atp_peg_tab.fixed_lt(l_count) := atp_peg_det.fixed_lt(n);
1802       atp_peg_tab.variable_lt(l_count) := atp_peg_det.variable_lt(n);
1803       atp_peg_tab.sales_order_line_id(l_count) := atp_peg_det.sales_order_line_id(n);
1804       atp_peg_tab.demand_source_type(l_count) := atp_peg_det.demand_source_type(n);--cmro
1805       atp_peg_tab.end_pegging_id(l_count) := atp_peg_det.end_pegging_id(n);
1806       atp_peg_tab.pegging_id(l_count) := atp_peg_det.pegging_id(n);
1807       atp_peg_tab.prev_pegging_id(l_count) := atp_peg_det.prev_pegging_id(n);
1808       atp_peg_tab.sales_order_qty(l_count) := atp_peg_det.sales_order_qty(n);
1809       atp_peg_tab.tot_relief_qty(l_count) := atp_peg_det.tot_relief_qty(n);
1810       -- CTO_PF_PRJ changes.
1811       atp_peg_tab.end_demand_id(l_count) := atp_peg_det.end_demand_id(n);
1812       --CTO-PF
1813       atp_peg_tab.atf_date(l_count) := atp_peg_det.atf_date(n);
1814       atp_peg_tab.product_family_id(l_count) := atp_peg_det.product_family_id(n);
1815       -- Bug 3805136 -- Add end_item_usage to handle no forecast consumption.
1816       atp_peg_tab.end_item_usage(l_count) := atp_peg_det.end_item_usage(n);
1817       -- Exclude flag helps in excluding supplies
1818       -- during relef data calculation.
1819       atp_peg_tab.exclude_flag(l_count) := atp_peg_det.exclude_flag(n);
1820       -- End Bug 3805136
1821 
1822       -- Assign corresponding supply_data
1823       atp_peg_tab.transaction_date(l_count) := TRUNC(atp_peg_det.supply_date(n));
1824       atp_peg_tab.consumed_qty(l_count) := atp_peg_det.consumed_qty(n);
1825       atp_peg_tab.overconsumption_qty(l_count) := atp_peg_det.overconsumption_qty(n);
1826       atp_peg_tab.supply_id(l_count) := atp_peg_det.supply_id(n);
1827       atp_peg_tab.supply_quantity(l_count) := atp_peg_det.supply_quantity(n);
1828       atp_peg_tab.allocated_quantity(l_count) := atp_peg_det.allocated_quantity(n);
1829 
1830 
1831      IF PG_DEBUG in ('Y', 'C') THEN
1832       msc_util.msc_log(' atp_peg_tab.allocated_quantity ' ||
1833                                      atp_peg_det.allocated_quantity(n));
1834      END IF;
1835       -- Determine Relief Type
1836       -- For material supplies the relief type is POs
1837       atp_peg_tab.relief_type(l_count) := 2;   -- Relief Type is PO.
1838     END IF;
1839   END LOOP;
1840     msc_util.msc_log(' atp_peg_tab.reference_item_id.COUNT ' ||
1841                                      atp_peg_tab.reference_item_id.COUNT);
1842 EXCEPTION
1843     WHEN OTHERS THEN
1844      IF PG_DEBUG in ('Y', 'C') THEN
1845         msc_util.msc_log ('Create_Simple_Pegging. Error : ' || sqlerrm);
1846      END IF;
1847         x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
1848 
1849 END  Create_Simple_Pegging;
1850 
1851 -- Bug 3344102 Procedure begin
1852 -- This procedure creates the ATP simplified pegging for allocated ATP case
1853 -- and stores it into the msc_atp_pegging table after plan run.
1854 PROCEDURE Create_Pre_Allocation_Reliefs (p_plan_id         IN          NUMBER,
1855                                          p_insert_table    IN          VARCHAR2,
1856                                          p_user_id         IN          NUMBER,
1857                                          p_sysdate         IN          DATE,
1858                                          x_return_status   OUT NOCOPY  VARCHAR2
1859                                         )
1860 IS
1861 
1862 l_sql_stmt                      VARCHAR2(800);
1863 l_sql_stmt_1                    VARCHAR2(8000);
1864 l_relief_type                   NUMBER;
1865 
1866 -- Default Demand Class
1867 l_def_dmd_class                 VARCHAR2(3) := '-1';
1868 
1869 BEGIN
1870 
1871   IF PG_DEBUG in ('Y', 'C') THEN
1872      msc_util.msc_log('***** Begin Create_Pre_Allocation_Reliefs Procedure *****');
1873      msc_util.msc_log(' Plan Id : ' || p_plan_id );
1874      msc_util.msc_log(' Insert Table parameter : ' || p_insert_table );
1875      msc_util.msc_log(' User Id Paramenter : ' || p_user_id );
1876      msc_util.msc_log(' Date Parameter : ' || p_sysdate );
1877   END IF;
1878 
1879   x_return_status := FND_API.G_RET_STS_SUCCESS;
1880 
1881     -- Set the relief type for only demands with Allocated ATP on.
1882     l_relief_type := 5;
1883 
1884     IF PG_DEBUG in ('Y', 'C') THEN
1885        msc_util.msc_log(' Inserting Demands');
1886     END IF;
1887 
1888     l_sql_stmt_1 := 'INSERT INTO  ' || p_insert_table || -- actually the insert table parameter.
1889              ' (reference_item_id, inventory_item_id, plan_id,
1890              sr_instance_id, organization_id, sales_order_line_id,
1891              demand_source_type, end_demand_id, bom_item_type,
1892              sales_order_qty, transaction_date, demand_id,
1893              demand_quantity, disposition_id, demand_class,
1894              consumed_qty, overconsumption_qty, supply_id, supply_quantity,
1895              allocated_quantity,
1896              relief_type, relief_quantity,
1897              pegging_id, prev_pegging_id, end_pegging_id,
1898              created_by, creation_date, last_updated_by, last_update_date,
1899              customer_id, customer_site_id, offset_type)
1900     SELECT   mapt.reference_item_id, mapt.inventory_item_id, mapt.plan_id,
1901              mapt.sr_instance_id, mapt.organization_id,
1902              mapt.sales_order_line_id, mapt.demand_source_type, mapt.end_demand_id,
1903              mapt.bom_item_type, mapt.sales_order_qty, mapt.transaction_date,
1904              mapt.demand_id , mapt.demand_quantity,
1905              mapt.disposition_id,
1906              NVL(mv.demand_class, :l_def_dmd_class) demand_class ,
1907              mapt.consumed_qty, mapt.overconsumption_qty,
1908              mapt.supply_id, mapt.supply_quantity,
1909              mapt.allocated_quantity ,  :l_relief_type,
1910              mapt.relief_quantity ,
1911              mapt.pegging_id, mapt.prev_pegging_id, mapt.end_pegging_id,
1912              :p_user_id, :p_sysdate, :p_user_id, :p_sysdate,
1913              mv.partner_id, mv.partner_site_id customer_site_id,1
1914     FROM    msc_atp_peg_temp mapt, msc_item_hierarchy_mv mv
1915     WHERE   mapt.plan_id = :p_plan_id
1916     AND     mapt.relief_type = 3
1917     AND     mapt.inventory_item_id = mv.inventory_item_id(+)
1918     AND     mapt.organization_id = mv.organization_id (+)
1919     AND     mapt.sr_instance_id = mv.sr_instance_id (+)
1920     AND     mapt.transaction_date >=  mv.effective_date (+)
1921     AND     mapt.transaction_date <=  mv.disable_date (+)
1922     AND     mapt.demand_class = mv.demand_class (+)
1923     AND     mv.level_id (+) = -1 '
1924     ;
1925 
1926     EXECUTE IMMEDIATE l_sql_stmt_1 USING
1927                         l_def_dmd_class, l_relief_type,
1928                         p_user_id, p_sysdate, p_user_id, p_sysdate, p_plan_id;
1929 
1930     IF PG_DEBUG in ('Y', 'C') THEN
1931         msc_util.msc_log('Create_Pre_Allocation_Reliefs:  Number of Demand rows inserted '||
1932                                SQL%ROWCOUNT);
1933     END IF;
1934 
1935     -- Set the relief type for only supplies with Allocated ATP on.
1936     l_relief_type := 6;
1937 
1938   IF PG_DEBUG in ('Y', 'C') THEN
1939      msc_util.msc_log(' Inserting Supplies');
1940   END IF;
1941 
1942     l_sql_stmt_1 := 'INSERT INTO  ' || p_insert_table || -- actually the insert table parameter.
1943              ' (reference_item_id, inventory_item_id, plan_id,
1944              sr_instance_id, organization_id, sales_order_line_id,
1945              demand_source_type, end_demand_id, bom_item_type,
1946              sales_order_qty, transaction_date, demand_id,
1947              demand_quantity, disposition_id, demand_class,
1948              consumed_qty, overconsumption_qty, supply_id, supply_quantity,
1949              allocated_quantity,
1950              relief_type, relief_quantity,
1951              pegging_id, prev_pegging_id, end_pegging_id,
1952              created_by, creation_date, last_updated_by, last_update_date,
1953              customer_id, customer_site_id, offset_type)
1954     SELECT   mapt.reference_item_id, mapt.inventory_item_id, mapt.plan_id,
1955              mapt.sr_instance_id, mapt.organization_id,
1956              mapt.sales_order_line_id, mapt.demand_source_type, mapt.end_demand_id,
1957              mapt.bom_item_type, mapt.sales_order_qty, mapt.transaction_date,
1958              mapt.demand_id , mapt.demand_quantity,
1959              mapt.disposition_id,
1960              NVL(mv.demand_class, :l_def_dmd_class) demand_class ,
1961              mapt.consumed_qty, mapt.overconsumption_qty,
1962              mapt.supply_id, mapt.supply_quantity,
1963              mapt.allocated_quantity ,  :l_relief_type,
1964              mapt.relief_quantity ,
1965              mapt.pegging_id, mapt.prev_pegging_id, mapt.end_pegging_id,
1966              :p_user_id, :p_sysdate, :p_user_id, :p_sysdate,
1967              mv.partner_id, mv.partner_site_id customer_site_id,1
1968     FROM    msc_atp_peg_temp mapt, msc_item_hierarchy_mv mv
1969     WHERE   mapt.plan_id = :p_plan_id
1970     AND     mapt.relief_type = 2
1971     AND     mapt.inventory_item_id = mv.inventory_item_id(+)
1972     AND     mapt.organization_id = mv.organization_id (+)
1973     AND     mapt.sr_instance_id = mv.sr_instance_id (+)
1974     AND     mapt.transaction_date >=  mv.effective_date (+)
1975     AND     mapt.transaction_date <=  mv.disable_date (+)
1976     AND     mapt.demand_class = mv.demand_class (+)
1977     AND     mv.level_id (+) = -1 '
1978     ;
1979 
1980     EXECUTE IMMEDIATE l_sql_stmt_1 USING
1981                         l_def_dmd_class, l_relief_type,
1982                         p_user_id, p_sysdate, p_user_id, p_sysdate, p_plan_id;
1983 
1984     IF PG_DEBUG in ('Y', 'C') THEN
1985         msc_util.msc_log('Create_Pre_Allocation_Reliefs:  Number of Supply rows inserted '||
1986                                SQL%ROWCOUNT);
1987     END IF;
1988 
1989 EXCEPTION
1990     WHEN OTHERS THEN
1991       IF PG_DEBUG in ('Y', 'C') THEN
1992         msc_util.msc_log('Inside main exception of Create_Pre_Allocation_Reliefs');
1993         msc_util.msc_log ('Create_Pre_Allocation_Reliefs. Error : ' || sqlcode || ': '|| sqlerrm);
1994       END IF;
1995         x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
1996 
1997 END Create_Pre_Allocation_Reliefs;
1998 -- Bug 3344102 Procedure End
1999 
2000 -- Bug 3750638 Move all the pegging releated SQLs into this procedure.
2001 -- This procedure fetches pegging data for a Sales Order
2002 -- from MSC_FULL_PEGGING in a loop.
2003 PROCEDURE Get_Pegging_Data_Loop (p_plan_id       IN          NUMBER,
2004                                  c_items_rec     IN          ATP_End_Config_Dmd_Typ,
2005                                  x_return_status OUT  NoCopy VARCHAR2   )
2006 IS
2007 
2008 l_sql_stmt_1                    varchar2(8000);
2009 l_timestamp                     NUMBER;
2010 l_hash_size                     NUMBER := -1;
2011 l_sort_size                     NUMBER := -1;
2012 l_parallel_degree               NUMBER := 1;
2013 
2014 -- Fix for Multiple (N) Level of Config Items using Loop
2015 -- Define PL/SQL Variable of Record of Arrays Type to correspond to
2016 -- Config Item Supplies being processed in the Pegging Retrieval loop.
2017 L_Config_Sup                    ATP_Config_Sup_Typ;
2018 l_multi_config_count            NUMBER;
2019 n_idx                           NUMBER; -- Index for Items
2020 n_row_count                     NUMBER;
2021 l_config_level                  NUMBER;
2022 i                               NUMBER;
2023 
2024 BEGIN
2025     IF PG_DEBUG in ('Y', 'C') THEN
2026     msc_util.msc_log('***** Begin Get_Pegging_Data_Loop (Get_Pegging_Loop) *****');
2027     msc_util.msc_log('Get_Pegging_Loop : p_plan_id ' || p_plan_id);
2028   END IF;
2029 
2030   x_return_status := FND_API.G_RET_STS_SUCCESS;
2031 
2032   -- Initialize variables;
2033   -- First get the performance parameters.
2034 
2035   BEGIN
2036      SELECT      NVL(pre_alloc_hash_size, -1),
2037                  NVL(pre_alloc_sort_size, -1),
2038                  NVL(pre_alloc_parallel_degree, 1)
2039      INTO        l_hash_size,
2040                  l_sort_size,
2041                  l_parallel_degree
2042      FROM        msc_atp_parameters
2043      WHERE       rownum = 1;
2044      EXCEPTION
2045          WHEN others THEN
2046          msc_util.msc_log('Error getting performance param: ' || sqlcode || ': ' || sqlerrm);
2047          l_hash_size := -1;
2048          l_sort_size := -1;
2049          l_parallel_degree := 1;
2050   END;
2051 
2052   IF PG_DEBUG in ('Y', 'C') THEN
2053      msc_util.msc_log('Hash: ' || l_hash_size || ' Sort: ' || l_sort_size ||
2054                          ' Parallel: ' || l_parallel_degree);
2055   END IF;
2056 
2057   IF NVL(l_hash_size, -1) <> -1 THEN
2058         l_sql_stmt_1 := 'alter session set hash_area_size = ' || to_char(l_hash_size);
2059         msc_util.msc_log('l_sql_stmt : ' || l_sql_stmt_1);
2060         execute immediate l_sql_stmt_1;
2061   END IF;
2062 
2063   IF NVL(l_sort_size, -1) <> -1 THEN
2064          l_sql_stmt_1 := 'alter session set sort_area_size = ' || to_char(l_sort_size);
2065          msc_util.msc_log('l_sql_stmt : ' || l_sql_stmt_1);
2066          execute immediate l_sql_stmt_1;
2067   END IF;
2068 
2069   -- Now obtain the pegging data into Global Temporary Table in a Loop.
2070 
2071       -- Obtain the supplies info for the config item.
2072       INSERT INTO MSC_ATP_DETAIL_PEG_TEMP (
2073               reference_item_id, base_item_id,
2074               inventory_item_id,
2075               plan_id,
2076               sr_instance_id,
2077               organization_id,
2078               end_item_usage,
2079               bom_item_type, fixed_lt, variable_lt,
2080               sales_order_line_id,
2081               demand_source_type,--cmro
2082               -- CTO_PF_PRJ changes.
2083               end_demand_id,
2084               sales_order_qty,
2085               process_seq_id, supply_id,
2086               supply_date,
2087               supply_quantity,
2088               allocated_quantity, tot_relief_qty,
2089               supply_type,
2090               firm_planned_type,
2091               release_status,
2092               exclude_flag,    -- All other cases exclude
2093               end_pegging_id, pegging_id,  prev_pegging_id,
2094               fcst_organization_id, forecast_qty,
2095               consumed_qty, overconsumption_qty )
2096       SELECT  DISTINCT
2097               c_items_rec.inventory_item_id, msi.base_item_id,
2098               peg2.inventory_item_id,
2099               peg2.plan_id,
2100               peg2.sr_instance_id,
2101               peg2.organization_id,
2102               peg2.end_item_usage,
2103               msi.bom_item_type, msi.fixed_lead_time, msi.variable_lead_time,
2104               c_items_rec.sales_order_line_id,
2105               c_items_rec.demand_source_type, --cmro
2106               -- CTO_PF_PRJ changes.
2107               NVL(d1.original_demand_id, d1.demand_id),
2108               NULL sales_order_qty, -- will be used to factor sales_order_qty,
2109               SUP.process_seq_id, SUP.transaction_id supply_id,
2110               SUP.new_schedule_date supply_date,
2111               SUP.new_order_quantity supply_qty,
2112               peg2.allocated_quantity, NULL tot_relief_qty,
2113               SUP.order_type,
2114               SUP.firm_planned_type,
2115               SUP.release_status, -- 1 released
2116               DECODE (SUP.order_type, 5,
2117                      -- order type is 5 proceed with further checks
2118                         (DECODE(SUP.firm_planned_type, 1, 1, -- 1 firm, others not firm
2119                           -- order is not firmed proceed with further checks
2120                           -- Bug 3717618 Use "quantity_in_process"
2121                           -- instead of incorrect release_status
2122                             (DECODE(SIGN (NVL(SUP.implemented_quantity, 0) +
2123                                           NVL(SUP.quantity_in_process, 0) -
2124                                           NVL(SUP.firm_quantity,SUP.new_order_quantity)),
2125                              0, 1, -- equal then flag as released
2126                              1, 1, -- positive then flag as released
2127                              0)) -- 0 otherwise not released.
2128                           -- End Bug 3717618
2129                          )),
2130                       1) exclude_flag,    -- All other cases exclude
2131               peg2.end_pegging_id, peg2.pegging_id,  peg2.prev_pegging_id,
2132               NULL fcst_organization_id, NULL forecast_qty,
2133               NULL consumed_qty, NULL overconsumption_qty
2134       FROM
2135               msc_demands d1,
2136               msc_full_pegging peg1 ,
2137               msc_full_pegging peg2 ,
2138               msc_supplies SUP,
2139               msc_system_items msi
2140       WHERE   d1.plan_id = p_plan_id
2141       AND     d1.sr_instance_id = c_items_rec.sr_instance_id
2142       AND     d1.inventory_item_id = c_items_rec.inventory_item_id
2143       AND     d1.origination_type IN (6,30)
2144       AND     d1.sales_order_line_id = c_items_rec.sales_order_line_id
2145       AND     decode(d1.demand_source_type,100,d1.demand_source_type,-1)
2146               =decode(c_items_rec.demand_source_type,
2147                                                 100,
2148                                                 c_items_rec.demand_source_type,
2149                                                 -1) --cmro
2150       AND     peg1.plan_id = d1.plan_id
2151       AND     peg1.sr_instance_id = d1.sr_instance_id
2152       AND     peg1.organization_id = d1.organization_id
2153       AND     peg1.demand_id = d1.demand_id
2154       AND     peg2.plan_id = peg1.plan_id
2155       AND     peg2.end_pegging_id = peg1.pegging_id
2156       -- Bug 3344032 On further investigation the outer join will not be needed.
2157       -- since the sr_instance_id join can be commented out.
2158       --AND     peg2.sr_instance_id = peg1.sr_instance_id (+) -- outer join to get all instances
2159       --  Bug 3319810 Match the item_id as well.
2160       AND     peg2.inventory_item_id = peg1.inventory_item_id
2161               -- Get the supplies corresponding to pegging
2162       AND     SUP.transaction_id = peg2.transaction_id
2163       AND     SUP.plan_id = peg2.plan_id
2164       AND     SUP.sr_instance_id = peg2.sr_instance_id
2165       AND     SUP.organization_id = peg2.organization_id
2166               -- Join to msc_system_items to filter out items
2167               -- from the pegging.
2168       AND     msi.plan_id = SUP.plan_id
2169       AND     msi.sr_instance_id = SUP.sr_instance_id
2170       AND     msi.inventory_item_id = SUP.inventory_item_id
2171       AND     msi.organization_id  = SUP.organization_id
2172               -- Restrict supplies to items that are configuration items
2173       AND     msi.bom_item_type = 4
2174       AND     msi.base_item_id is not null
2175       AND     msi.replenish_to_order_flag = 'Y'
2176       -- Bug 3717618 Remove exclusion of firmed or released supplies here.
2177       -- This will be handled during creation of Offset Data.
2178       -- This data is needed for getting the pegging chain.
2179       -- AND     DECODE (SUP.order_type, 5,
2180                      -- order type is 5 proceed with further checks
2181       --                   (DECODE(SUP.firm_planned_type, 1, 1, -- 1 firm, others not firm
2182                           -- order is not firmed proceed with further checks
2183       --                       (DECODE(SIGN (NVL(SUP.implemented_quantity, 0) +
2184       --                                     NVL(SUP.quantity_in_process, 0) -
2185       --                                     NVL(SUP.firm_quantity,SUP.new_order_quantity)),
2186       --                        0, 1, -- equal then flag as released
2187       --                        1, 1, -- positive then flag as released
2188       --                        0)) -- 0 otherwise not released.
2189       --                    )),
2190       --                 1)  <> 1   -- Exclude un-necessary supplies.
2191       -- End Bug 3717618
2192       ;
2193 
2194       IF PG_DEBUG in ('Y', 'C') THEN
2195         msc_util.msc_log('Gen_Atp_Pegging : Stage 1 ' );
2196         msc_util.msc_log('Gen_Atp_Pegging : Rows Procesed ' || SQL%ROWCOUNT );
2197       END IF;
2198 
2199       -- Update Pegging data with End demand Id. Information
2200       -- CTO_PF_PRJ changes.
2201 
2202       UPDATE MSC_ATP_DETAIL_PEG_TEMP madpt -- outer table
2203        SET
2204        (end_demand_id
2205        ) =
2206        (  SELECT  end_demand_id
2207           FROM    msc_atp_detail_peg_temp madpti -- Inner table
2208           WHERE   madpti.plan_id = madpt.plan_id
2209           AND     madpti.sr_instance_id = madpt.sr_instance_id
2210           AND     madpti.reference_item_id =  madpt.inventory_item_id
2211           AND     madpti.sales_order_line_id = madpt.sales_order_line_id
2212           AND     madpti.demand_source_type = madpt.demand_source_type
2213           AND     madpti.pegging_id = madpt.end_pegging_id
2214           AND     madpti.prev_pegging_id IS NULL
2215        )
2216        WHERE   madpt.plan_id = p_plan_id
2217        AND     madpt.sr_instance_id = c_items_rec.sr_instance_id
2218        AND     madpt.reference_item_id =  c_items_rec.inventory_item_id
2219        AND     madpt.sales_order_line_id = c_items_rec.sales_order_line_id
2220        AND     madpt.demand_source_type
2221                =decode(c_items_rec.demand_source_type,
2222                                                 100,
2223                                                 c_items_rec.demand_source_type,
2224                                                 -1)  -- CMRO
2225       ;
2226 
2227       IF PG_DEBUG in ('Y', 'C') THEN
2228         msc_util.msc_log('Gen_Atp_Pegging : Rows Procesed ' || SQL%ROWCOUNT );
2229       END IF;
2230 
2231       -- Update Pegging data with demand Information
2232 
2233       UPDATE MSC_ATP_DETAIL_PEG_TEMP madpt
2234        SET
2235        (demand_id,
2236        demand_date,
2237        demand_quantity,
2238        disposition_id,
2239        demand_class,
2240        demand_type,
2241        original_demand_id,
2242        order_number
2243        ) =
2244        -- Bug 3550296 and 3574164. IMPLEMENT_DATE AND DMD_SATISFIED_DATE are changed to
2245        -- IMPLEMENT_SHIP_DATE and PLANNED_SHIP_DATE resp.
2246        (  SELECT d.demand_id,
2247           decode(MSC_ATP_PVT.G_HP_DEMAND_BUCKETING_PREF,
2248                  2, NVL(D.PLANNED_SHIP_DATE,D.USING_ASSEMBLY_DEMAND_DATE),
2249                     NVL(D.SCHEDULE_SHIP_DATE,D.USING_ASSEMBLY_DEMAND_DATE)) demand_date,
2250                     -- plan by request date
2251           decode(d.origination_type, 4, d.daily_demand_rate,
2252                               d.using_requirement_quantity) demand_quantity,
2253           -- Bug 3319810 Set the disposition_id for top level supply pegging.
2254           NVL(d.disposition_id, peg.transaction_id) disposition_id,
2255           NVL(d.demand_class, '-1') demand_class,
2256           d.origination_type,
2257           NVL(d.original_demand_id, d.demand_id) original_demand_id,
2258           decode(d.origination_type, 1,
2259                     to_char(d.disposition_id), d.order_number)
2260           FROM       --msc_atp_detail_peg_temp madpt,
2261               msc_full_pegging peg,
2262               msc_demands d
2263           WHERE   madpt.plan_id = p_plan_id
2264           AND     madpt.sr_instance_id = c_items_rec.sr_instance_id
2265           AND     madpt.reference_item_id =  c_items_rec.inventory_item_id
2266           AND     madpt.sales_order_line_id = c_items_rec.sales_order_line_id
2267           AND     decode(madpt.demand_source_type,100,madpt.demand_source_type,-1)
2268                   = decode(c_items_rec.demand_source_type,
2269                                                 100,
2270                                                 c_items_rec.demand_source_type,
2271                                                 -1) --CMRO
2272           AND     peg.plan_id = madpt.plan_id
2273           AND     peg.sr_instance_id = madpt.sr_instance_id
2274           AND     peg.organization_id = madpt.organization_id
2275           AND     peg.pegging_id = madpt.pegging_id
2276           AND     peg.end_pegging_id = madpt.end_pegging_id
2277           AND     peg.inventory_item_id = madpt.inventory_item_id
2278               -- Get the demands corresponding to pegging
2279           AND     d.plan_id = peg.plan_id
2280           AND     d.sr_instance_id = peg.sr_instance_id
2281           AND     d.organization_id = peg.organization_id
2282           AND     d.inventory_item_id = peg.inventory_item_id
2283           AND     d.demand_id = peg.demand_id)
2284        WHERE   madpt.plan_id = p_plan_id
2285        AND     madpt.sr_instance_id = c_items_rec.sr_instance_id
2286        AND     madpt.reference_item_id =  c_items_rec.inventory_item_id
2287        AND     madpt.sales_order_line_id = c_items_rec.sales_order_line_id
2288        AND     decode(madpt.demand_source_type,100,madpt.demand_source_type,-1)
2289                =decode(c_items_rec.demand_source_type,
2290                                                 100,
2291                                                 c_items_rec.demand_source_type,
2292                                                 -1)  -- CMRO
2293        -- Bug 3750638
2294        -- Collect Supplies into Supplies PL/SQL Array.
2295        RETURNING
2296                  inventory_item_id,
2297                  sr_instance_id,
2298                  base_item_id,
2299                  sales_order_line_id,
2300                  demand_source_type,
2301                  end_demand_id,
2302                  supply_id,
2303                  pegging_id,
2304                  end_pegging_id
2305        BULK COLLECT INTO
2306                  L_Config_Sup.INVENTORY_ITEM_ID,
2307                  L_Config_Sup.SR_INSTANCE_ID,
2308                  L_Config_Sup.BASE_ITEM_ID,
2309                  L_Config_Sup.SALES_ORDER_LINE_ID,
2310                  L_Config_Sup.DEMAND_SOURCE_TYPE,
2311                  L_Config_Sup.END_DEMAND_ID,
2312                  L_Config_Sup.SUPPLY_ID,
2313                  L_Config_Sup.PEGGING_ID,
2314                  L_Config_Sup.END_PEGGING_ID
2315        ;
2316        -- End Bug 3750638
2317        -- Bug 3362558 Fetch the original_demand_id
2318        -- CTO_PF_PRJ changes.
2319        -- RETURNING madpt.original_demand_id BULK COLLECT INTO l_original_demand_ids;
2320        -- Commented out, since with the introduction of end_demand_id field,
2321        -- fetch into l_original_demand_id is not necessary.
2322 
2323 
2324       IF PG_DEBUG in ('Y', 'C') THEN
2325         msc_util.msc_log('Gen_Atp_Pegging : Stage 2 ' );
2326         msc_util.msc_log('Gen_Atp_Pegging : Rows Procesed ' || SQL%ROWCOUNT );
2327       END IF;
2328 
2329 
2330       -- Bug 3750638 Initialize the Count of Items to be processed.
2331       l_multi_config_count := L_Config_Sup.INVENTORY_ITEM_ID.COUNT;
2332       l_config_level := 1;
2333 
2334       -- Bug 3750638 Place the next couple of SQLs in a LOOP for processing
2335       -- N levels of Configuration Items.
2336       WHILE l_multi_config_count > 0 LOOP
2337          -- Bug 3750638 Introduce FORALL loop for processing Config Items.
2338         IF PG_DEBUG in ('Y', 'C') THEN
2339           msc_util.msc_log('Gen_Atp_Pegging : Total Config Items ' ||
2340                         'l_multi_config_count ' || l_multi_config_count);
2341         END IF;
2342         FOR n_idx IN 1..l_multi_config_count LOOP
2343             IF PG_DEBUG in ('Y', 'C') THEN
2344                msc_util.msc_log('Gen_Atp_Pegging : Config Instance_Id ' ||
2345                                         L_Config_Sup.SR_INSTANCE_ID(n_idx) );
2346                msc_util.msc_log('Gen_Atp_Pegging : Config Item_Id ' ||
2347                                         L_Config_Sup.INVENTORY_ITEM_ID(n_idx) );
2348                msc_util.msc_log('Gen_Atp_Pegging : Config Supply_Id ' ||
2349                                         L_Config_Sup.SUPPLY_ID(n_idx) );
2350                msc_util.msc_log('Gen_Atp_Pegging : Config Base_Item_Id ' ||
2351                                         L_Config_Sup.BASE_ITEM_ID(n_idx) );
2352                msc_util.msc_log('Gen_Atp_Pegging : Config Pegging_Id ' ||
2353                                         L_Config_Sup.PEGGING_ID(n_idx) );
2354                msc_util.msc_log('Gen_Atp_Pegging : Config End_Pegging_Id ' ||
2355                                         L_Config_Sup.END_PEGGING_ID(n_idx) );
2356             END IF;
2357         END LOOP;
2358 
2359         -- First obtain transfers if any.
2360         FORALL n_idx IN 1..l_multi_config_count
2361            INSERT INTO MSC_ATP_DETAIL_PEG_TEMP (
2362                  reference_item_id, base_item_id,
2363                  inventory_item_id,
2364                  plan_id,
2365                  sr_instance_id,
2366                  organization_id,
2367                  end_item_usage,
2368                  bom_item_type, fixed_lt, variable_lt,
2369                  sales_order_line_id,
2370                  demand_source_type,--cmro
2371                  -- CTO_PF_PRJ changes.
2372                  end_demand_id,
2373                  -- CTO-PF
2374                  atf_date,
2375                  product_family_id,
2376                  sales_order_qty,
2377                  demand_id,
2378                  demand_date,
2379                  demand_quantity,
2380                  disposition_id,
2381                  demand_class,
2382                  demand_type,
2383                  original_demand_id,
2384                  process_seq_id, supply_id,
2385                  supply_date,
2386                  supply_quantity,
2387                  allocated_quantity, tot_relief_qty,
2388                  supply_type,
2389                  firm_planned_type,
2390                  release_status,
2391                  exclude_flag,    -- All other cases exclude
2392                  order_number,
2393                  end_pegging_id, pegging_id,  prev_pegging_id,
2394                  fcst_organization_id, forecast_qty,
2395                  consumed_qty, overconsumption_qty )
2396          SELECT
2397                  adpt.reference_item_id, msi.base_item_id,
2398                  peg1.inventory_item_id,
2399                  peg1.plan_id,
2400                  peg1.sr_instance_id,
2401                  peg1.organization_id,
2402                  peg1.end_item_usage,
2403                  msi.bom_item_type, msi.fixed_lead_time, msi.variable_lead_time,
2404                  adpt.sales_order_line_id,
2405                  adpt.demand_source_type,--cmro
2406                  -- CTO_PF_PRJ changes.
2407                  adpt.end_demand_id,
2408                  -- CTO-PF
2409                  msi.aggregate_time_fence_date,
2410                  msi.product_family_id,
2411                  NULL sales_order_qty, -- will be used to factor sales_order_qty,
2412                  d1.demand_id,
2413                  -- Bug 3550296 and 3574164. IMPLEMENT_DATE AND DMD_SATISFIED_DATE are changed to
2414                  -- IMPLEMENT_SHIP_DATE and PLANNED_SHIP_DATE resp.
2415                  DECODE(
2416                          d1.RECORD_SOURCE,
2417                          2,
2418              	         NVL(d1.SCHEDULE_SHIP_DATE,d1.USING_ASSEMBLY_DEMAND_DATE),
2419                	         DECODE(MSC_ATP_PVT.G_HP_DEMAND_BUCKETING_PREF,
2420               	         2,
2421               	         (NVL(d1.IMPLEMENT_SHIP_DATE,NVL(d1.FIRM_DATE,NVL(d1.PLANNED_SHIP_DATE,d1.USING_ASSEMBLY_DEMAND_DATE)))),
2422                          NVL(d1.SCHEDULE_SHIP_DATE,d1.USING_ASSEMBLY_DEMAND_DATE))), --plan by request Date, Promise Date Scheduled Date
2423                  decode(d1.origination_type, 4, d1.daily_demand_rate,
2424                                      d1.using_requirement_quantity) demand_quantity,
2425                  d1.disposition_id,
2426                  NVL(d1.demand_class, adpt.demand_class) demand_class,
2427                  d1.origination_type,
2428                  -- Bug 3362558 use pegging's original demand_id
2429                  NVL(d1.original_demand_id, adpt.original_demand_id) original_demand_id,
2430                  -- Begin Bug 3319810
2431                  -- Use pegging's supply data instead of msc_atp_detail_peg_temp.
2432                  adpt.process_seq_id,
2433                  --adpt.supply_id,
2434                  --adpt.supply_date,
2435                  --adpt.supply_quantity,
2436                  --adpt.allocated_quantity, NULL tot_relief_qty,
2437                  --adpt.supply_type,
2438                  peg1.transaction_id supply_id,
2439                  -- Bug 3750638 Keep the supply date NULL for configs.
2440                  DECODE(NVL(msi.base_item_id, -2353), -2353,  peg1.supply_date, NULL) supply_date,
2441                  peg1.supply_quantity,
2442                  peg1.allocated_quantity, NULL tot_relief_qty,
2443                  peg1.supply_type,
2444                  -- End Bug 3319810
2445                  adpt.firm_planned_type,
2446                  adpt.release_status, -- 1 released
2447                  0 exclude_flag,    -- Include the demands as a default.
2448                  decode(d1.origination_type, 1, to_char(d1.disposition_id), d1.order_number) order_number,
2449                  peg1.end_pegging_id, peg1.pegging_id,  peg1.prev_pegging_id,
2450                  NULL fcst_organization_id, NULL forecast_qty,
2451                  NULL consumed_qty, NULL overconsumption_qty
2452          FROM
2453                  msc_atp_detail_peg_temp adpt,
2454                  msc_full_pegging peg1 ,
2455                  msc_demands d1,
2456                  msc_system_items msi
2457          WHERE   adpt.plan_id = p_plan_id
2458          AND     adpt.reference_item_id = c_items_rec.inventory_item_id
2459          AND     adpt.sales_order_line_id = c_items_rec.sales_order_line_id
2460          AND     decode(adpt.demand_source_type,100,adpt.demand_source_type,-1)
2461                  =decode(c_items_rec.demand_source_type,
2462                                                    100,
2463                                                    c_items_rec.demand_source_type,
2464                                                    -1) --CMRO
2465          -- Bug 3750638 Apply Config Item Array Filters
2466          AND     adpt.sr_instance_id = L_Config_Sup.SR_INSTANCE_ID(n_idx) -- outer join to get all instances
2467          AND     adpt.inventory_item_id = L_Config_Sup.INVENTORY_ITEM_ID(n_idx)
2468          AND     adpt.supply_id = L_Config_Sup.SUPPLY_ID(n_idx)
2469          AND     adpt.end_demand_id = L_Config_Sup.END_DEMAND_ID(n_idx)
2470          AND     adpt.pegging_id = L_Config_Sup.PEGGING_ID(n_idx)
2471          AND     adpt.end_pegging_id = L_Config_Sup.END_PEGGING_ID(n_idx)
2472          AND     adpt.base_item_id = L_Config_Sup.BASE_ITEM_ID(n_idx)
2473          AND     adpt.inventory_item_id <> adpt.reference_item_id
2474          -- End Bug 3750638
2475                  -- Link up pegging with config_item info in msc_atp_detail_peg_temp.
2476          AND     peg1.plan_id = adpt.plan_id
2477          AND     peg1.sr_instance_id = adpt.sr_instance_id
2478          AND     peg1.end_pegging_id = adpt.end_pegging_id
2479          AND     peg1.prev_pegging_id = adpt.pegging_id
2480          AND     peg1.inventory_item_id = adpt.inventory_item_id
2481          -- End Bug 3750638 Supply filter
2482          -- AND     peg1.supply_type = 5
2483                  -- Further control if necessary for performance will be added later.
2484                  -- AND peg1.transaction_id = adpt.supply_id
2485                  -- Get the demands corresponding to pegging
2486          AND     d1.plan_id = peg1.plan_id
2487          AND     d1.sr_instance_id = peg1.sr_instance_id
2488          AND     d1.organization_id = peg1.organization_id
2489          AND     d1.demand_id = peg1.demand_id
2490          -- Bug 3750638 The lower level item could also be sourced from muliple orgs.
2491          -- AND     d1.inventory_item_id <> adpt.inventory_item_id
2492                  -- Get all the items which peg to the supply using the disposition_id.
2493          AND     d1.disposition_id = adpt.supply_id
2494          AND     d1.using_requirement_quantity > 0
2495                  -- Join to msc_system_items to get items data
2496          AND     msi.plan_id = d1.plan_id
2497          AND     msi.sr_instance_id = d1.sr_instance_id
2498          AND     msi.inventory_item_id = d1.inventory_item_id
2499          AND     msi.organization_id  = d1.organization_id
2500          ;
2501 
2502          n_row_count := SQL%ROWCOUNT;
2503          IF PG_DEBUG in ('Y', 'C') THEN
2504            msc_util.msc_log('Gen_Atp_Pegging : Transfer of config n_row_count ' || n_row_count);
2505          END IF;
2506            -- Obtain the data for the components of the lower level configuration item(s)
2507            -- in the sales order.
2508         FORALL n_idx IN 1..l_multi_config_count
2509            INSERT INTO MSC_ATP_DETAIL_PEG_TEMP (
2510                  reference_item_id, base_item_id,
2511                  inventory_item_id,
2512                  plan_id,
2513                  sr_instance_id,
2514                  organization_id,
2515                  end_item_usage,
2516                  bom_item_type, fixed_lt, variable_lt,
2517                  sales_order_line_id,
2518                  demand_source_type,--cmro
2519                  -- CTO_PF_PRJ changes.
2520                  end_demand_id,
2521                  -- CTO-PF
2522                  atf_date,
2523                  product_family_id,
2524                  sales_order_qty,
2525                  demand_id,
2526                  demand_date,
2527                  demand_quantity,
2528                  disposition_id,
2529                  demand_class,
2530                  demand_type,
2531                  original_demand_id,
2532                  process_seq_id, supply_id,
2533                  supply_date,
2534                  supply_quantity,
2535                  allocated_quantity, tot_relief_qty,
2536                  supply_type,
2537                  firm_planned_type,
2538                  release_status,
2539                  exclude_flag,    -- All other cases exclude
2540                  order_number,
2541                  end_pegging_id, pegging_id,  prev_pegging_id,
2542                  fcst_organization_id, forecast_qty,
2543                  consumed_qty, overconsumption_qty )
2544          SELECT
2545                  adpt.reference_item_id, msi.base_item_id,
2546                  peg1.inventory_item_id,
2547                  peg1.plan_id,
2548                  peg1.sr_instance_id,
2549                  peg1.organization_id,
2550                  peg1.end_item_usage,
2551                  msi.bom_item_type, msi.fixed_lead_time, msi.variable_lead_time,
2552                  adpt.sales_order_line_id,
2553                  adpt.demand_source_type,--cmro
2554                  -- CTO_PF_PRJ changes.
2555                  adpt.end_demand_id,
2556                  -- CTO-PF
2557                  msi.aggregate_time_fence_date,
2558                  msi.product_family_id,
2559                  NULL sales_order_qty, -- will be used to factor sales_order_qty,
2560                  d1.demand_id,
2561                  -- Bug 3550296 and 3574164. IMPLEMENT_DATE AND DMD_SATISFIED_DATE are changed to
2562                  -- IMPLEMENT_SHIP_DATE and PLANNED_SHIP_DATE resp.
2563                  DECODE(
2564                          d1.RECORD_SOURCE,
2565                          2,
2566              	         NVL(d1.SCHEDULE_SHIP_DATE,d1.USING_ASSEMBLY_DEMAND_DATE),
2567                	         DECODE(MSC_ATP_PVT.G_HP_DEMAND_BUCKETING_PREF,
2568               	         2,
2569               	         (NVL(d1.IMPLEMENT_SHIP_DATE,NVL(d1.FIRM_DATE,NVL(d1.PLANNED_SHIP_DATE,d1.USING_ASSEMBLY_DEMAND_DATE)))),
2570                          NVL(d1.SCHEDULE_SHIP_DATE,d1.USING_ASSEMBLY_DEMAND_DATE))), --plan by request Date, Promise Date Scheduled Date
2571                  decode(d1.origination_type, 4, d1.daily_demand_rate,
2572                                      d1.using_requirement_quantity) demand_quantity,
2573                  d1.disposition_id,
2574                  NVL(d1.demand_class, adpt.demand_class) demand_class,
2575                  d1.origination_type,
2576                  -- Bug 3362558 use pegging's original demand_id
2577                  NVL(d1.original_demand_id, adpt.original_demand_id) original_demand_id,
2578                  -- Begin Bug 3319810
2579                  -- Use pegging's supply data instead of msc_atp_detail_peg_temp.
2580                  adpt.process_seq_id,
2581                  --adpt.supply_id,
2582                  --adpt.supply_date,
2583                  --adpt.supply_quantity,
2584                  --adpt.allocated_quantity, NULL tot_relief_qty,
2585                  --adpt.supply_type,
2586                  peg1.transaction_id supply_id,
2587                  -- Bug 3750638 Keep the supply date NULL for configs.
2588                  DECODE(NVL(msi.base_item_id, -2353), -2353,  peg1.supply_date, NULL) supply_date,
2589                  peg1.supply_quantity,
2590                  peg1.allocated_quantity, NULL tot_relief_qty,
2591                  peg1.supply_type,
2592                  -- End Bug 3319810
2593                  adpt.firm_planned_type,
2594                  adpt.release_status, -- 1 released
2595                  0 exclude_flag,    -- Include the demands as a default.
2596                  decode(d1.origination_type, 1, to_char(d1.disposition_id), d1.order_number) order_number,
2597                  peg1.end_pegging_id, peg1.pegging_id,  peg1.prev_pegging_id,
2598                  NULL fcst_organization_id, NULL forecast_qty,
2599                  NULL consumed_qty, NULL overconsumption_qty
2600          FROM
2601                  msc_atp_detail_peg_temp adpt,
2602                  msc_full_pegging peg1 ,
2603                  msc_demands d1,
2604                  msc_system_items msi,
2605                  msc_process_effectivity proc,
2606                  msc_bom_components mbc
2607          WHERE   adpt.plan_id = p_plan_id
2608          AND     adpt.reference_item_id = c_items_rec.inventory_item_id
2609          AND     adpt.sales_order_line_id = c_items_rec.sales_order_line_id
2610          AND     decode(adpt.demand_source_type,100,adpt.demand_source_type,-1)
2611                  =decode(c_items_rec.demand_source_type,
2612                                                    100,
2613                                                    c_items_rec.demand_source_type,
2614                                                    -1) --CMRO
2615          -- Bug 3750638 Apply Config Item Array Filters
2616          AND     adpt.sr_instance_id = L_Config_Sup.SR_INSTANCE_ID(n_idx) -- outer join to get all instances
2617          AND     adpt.inventory_item_id = L_Config_Sup.INVENTORY_ITEM_ID(n_idx)
2618          AND     adpt.supply_id = L_Config_Sup.SUPPLY_ID(n_idx)
2619          AND     adpt.end_demand_id = L_Config_Sup.END_DEMAND_ID(n_idx)
2620          AND     adpt.pegging_id = L_Config_Sup.PEGGING_ID(n_idx)
2621          AND     adpt.end_pegging_id = L_Config_Sup.END_PEGGING_ID(n_idx)
2622          AND     adpt.base_item_id = L_Config_Sup.BASE_ITEM_ID(n_idx)
2623          AND     adpt.supply_date is not NULL
2624          -- End Bug 3750638
2625                  -- Link up pegging with config_item info in msc_atp_detail_peg_temp.
2626          AND     peg1.plan_id = adpt.plan_id
2627          AND     peg1.sr_instance_id = adpt.sr_instance_id
2628          AND     peg1.end_pegging_id = adpt.end_pegging_id
2629          AND     peg1.prev_pegging_id = adpt.pegging_id
2630          AND     peg1.inventory_item_id <> adpt.reference_item_id
2631          -- End Bug 3750638 Supply filter
2632          -- AND     peg1.supply_type = 5
2633                  -- Further control if necessary for performance will be added later.
2634                  -- AND peg1.transaction_id = adpt.supply_id
2635                  -- Get the demands corresponding to pegging
2636          AND     d1.plan_id = peg1.plan_id
2637          AND     d1.sr_instance_id = peg1.sr_instance_id
2638          AND     d1.organization_id = peg1.organization_id
2639          AND     d1.demand_id = peg1.demand_id
2640          -- Bug 3750638 The lower level item could also be sourced from muliple orgs.
2641          -- AND     d1.inventory_item_id <> adpt.inventory_item_id
2642                  -- Get all the items which peg to the supply using the disposition_id.
2643          AND     d1.disposition_id = adpt.supply_id
2644          AND     d1.using_requirement_quantity > 0
2645                  -- Join to msc_system_items to get items data
2646          AND     msi.plan_id = d1.plan_id
2647          AND     msi.sr_instance_id = d1.sr_instance_id
2648          AND     msi.inventory_item_id = d1.inventory_item_id
2649          AND     msi.organization_id  = d1.organization_id
2650          --   Join to msc_process_effectivity to get the bill sequence
2651          AND     proc.plan_id = adpt.plan_id
2652          AND     proc.process_sequence_id = adpt.process_seq_id
2653          --   Join to msc_bom_components to exclude any exploded items underneath phantoms
2654          AND     mbc.plan_id = msi.plan_id
2655          AND     mbc.sr_instance_id = msi.sr_instance_id
2656          AND     mbc.organization_id = msi.organization_id
2657          AND     mbc.bill_sequence_id = proc.bill_sequence_id
2658                      -- manufacture in same org.
2659          AND     mbc.inventory_item_id = msi.inventory_item_id
2660          AND     mbc.using_assembly_id = adpt.inventory_item_id
2661          AND     mbc.organization_id = adpt.organization_id
2662          ;
2663          -- End Bug 3750638 -- FORALL loop
2664 
2665        select hsecs
2666        into   l_timestamp
2667        from   v$timer;
2668 
2669          -- Bug 3750638 Get the total number of records.
2670          n_row_count := SQL%ROWCOUNT;
2671 
2672          IF PG_DEBUG in ('Y', 'C') THEN
2673            msc_util.msc_log('Gen_Atp_Pegging : Stage 3 ' );
2674            msc_util.msc_log('Gen_Atp_Pegging : Components of config n_row_count ' || n_row_count);
2675            msc_util.msc_log('Gen_Atp_Pegging : TIMESTAMP 2 ' || l_timestamp);
2676          END IF;
2677 
2678 
2679          -- update the supplies for the new demands
2680          UPDATE MSC_ATP_DETAIL_PEG_TEMP madpt
2681           SET
2682           ( process_seq_id, supply_id,
2683             supply_date,
2684             supply_quantity,
2685             allocated_quantity, tot_relief_qty,
2686             supply_type,
2687             firm_planned_type,
2688             release_status,
2689             exclude_flag
2690           ) =
2691           (  SELECT SUP.process_seq_id, SUP.transaction_id supply_id,
2692                     SUP.new_schedule_date supply_date,
2693                     SUP.new_order_quantity supply_qty,
2694                     peg.allocated_quantity, NULL tot_relief_qty,
2695                     SUP.order_type,
2696                     SUP.firm_planned_type,
2697                     SUP.release_status, -- 1 released
2698                     DECODE (SUP.order_type, 5,
2699                         -- order type is 5 proceed with further checks
2700                         (DECODE(SUP.firm_planned_type, 1, 1, -- 1 firm, others not firm
2701                         -- order is not firmed proceed with further checks
2702                              -- Bug 3717618 Use "quantity_in_process"
2703                              -- instead of incorrect release_status
2704                              (DECODE(SIGN (NVL(SUP.implemented_quantity, 0) +
2705                                            NVL(SUP.quantity_in_process, 0) -
2706                                            NVL(SUP.firm_quantity,SUP.new_order_quantity)),
2707                                 0, 1, -- equal then flag as released
2708                                 1, 1, -- positive then flag as released
2709                                 0)) -- 0 otherwise not released.
2710                              -- End Bug 3717618
2711                           )),
2712                         1) exclude_flag
2713              FROM       --msc_atp_detail_peg_temp madpt,
2714                  msc_full_pegging peg,
2715                  msc_supplies SUP
2716              WHERE   madpt.plan_id = p_plan_id
2717              AND     madpt.sr_instance_id = c_items_rec.sr_instance_id
2718              AND     madpt.reference_item_id =  c_items_rec.inventory_item_id
2719              AND     madpt.sales_order_line_id = c_items_rec.sales_order_line_id
2720              AND     decode(madpt.demand_source_type,100,madpt.demand_source_type,-1)
2721                      =decode(c_items_rec.demand_source_type,
2722                                                    100,
2723                                                    c_items_rec.demand_source_type,
2724                                                    -1) --CMRO
2725              AND     madpt.inventory_item_id <> madpt.reference_item_id
2726              -- Bug 3750638
2727              -- Date is used to filter out other records.
2728              AND     madpt.supply_date IS NULL
2729              AND     peg.plan_id = madpt.plan_id
2730              AND     peg.sr_instance_id = madpt.sr_instance_id
2731              AND     peg.organization_id = madpt.organization_id
2732              AND     peg.pegging_id = madpt.pegging_id
2733              AND     peg.end_pegging_id = madpt.end_pegging_id
2734              AND     peg.inventory_item_id = madpt.inventory_item_id
2735                      -- Bug 3750638 also filter on supply_id
2736              AND     peg.transaction_id = madpt.supply_id
2737                      -- Get the supplies corresponding to pegging
2738              AND     SUP.plan_id = peg.plan_id
2739              AND     SUP.sr_instance_id = peg.sr_instance_id
2740              AND     SUP.organization_id = peg.organization_id
2741              AND     SUP.inventory_item_id = peg.inventory_item_id
2742              AND     SUP.order_type = 5
2743              AND     SUP.transaction_id = peg.transaction_id )
2744           WHERE   madpt.plan_id = p_plan_id
2745           -- Bug 3750638 Comment out sr_instance_id to support multi-instance plans.
2746           AND     madpt.sr_instance_id = c_items_rec.sr_instance_id
2747           AND     madpt.reference_item_id =  c_items_rec.inventory_item_id
2748           AND     madpt.sales_order_line_id = c_items_rec.sales_order_line_id
2749           AND     decode(madpt.demand_source_type,100,madpt.demand_source_type,-1)
2750                   =decode(c_items_rec.demand_source_type,
2751                                                    100,
2752                                                    c_items_rec.demand_source_type,
2753                                                    -1) --CMRO;
2754           AND     madpt.inventory_item_id <> madpt.reference_item_id
2755           -- Bug 3750638
2756           -- Date is used to filter out other records.
2757           AND     madpt.supply_date IS NULL
2758           AND     madpt.supply_type = 5
2759           -- Other filtering conditions that may potentially be added include end_demand_id
2760           -- Collect Supplies into Supplies PL/SQL Array.
2761           RETURNING
2762                   inventory_item_id,
2763                   sr_instance_id,
2764                   base_item_id,
2765                   sales_order_line_id,
2766                   demand_source_type,
2767                   end_demand_id,
2768                   supply_id,
2769                   pegging_id,
2770                   end_pegging_id
2771           BULK COLLECT INTO
2772                   L_Config_Sup.INVENTORY_ITEM_ID,
2773                   L_Config_Sup.SR_INSTANCE_ID,
2774                   L_Config_Sup.BASE_ITEM_ID,
2775                   L_Config_Sup.SALES_ORDER_LINE_ID,
2776                   L_Config_Sup.DEMAND_SOURCE_TYPE,
2777                   L_Config_Sup.END_DEMAND_ID,
2778                   L_Config_Sup.SUPPLY_ID,
2779                   L_Config_Sup.PEGGING_ID,
2780                   L_Config_Sup.END_PEGGING_ID
2781           ;
2782           -- End Bug 3750638
2783 
2784           -- Bug 3750638 Re-set the Count of Items to be processed.
2785           l_multi_config_count := L_Config_Sup.INVENTORY_ITEM_ID.COUNT;
2786           l_config_level := l_config_level + 1;
2787 
2788           IF PG_DEBUG in ('Y', 'C') THEN
2789             msc_util.msc_log('Gen_Atp_Pegging : Stage 4 ' );
2790             msc_util.msc_log('Gen_Atp_Pegging : Rows Procesed ' || SQL%ROWCOUNT );
2791             -- Bug 3750638 Print Out value of variables.
2792             msc_util.msc_log('Gen_Atp_Pegging : l_multi_config_count ' || l_multi_config_count );
2793             msc_util.msc_log('Gen_Atp_Pegging : l_config_level ' || l_config_level );
2794           END IF;
2795 
2796       END LOOP;
2797       -- End Bug 3750638
2798 
2799 EXCEPTION
2800     WHEN OTHERS THEN
2801       IF PG_DEBUG in ('Y', 'C') THEN
2802         msc_util.msc_log ('Get_Pegging_Data_Loop. Error : ' || sqlcode || ': ' || sqlerrm);
2803       END IF;
2804       x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
2805 
2806 END Get_Pegging_Data_Loop;
2807 -- End Bug 3750638 Move all the pegging releated SQLs into this procedure.
2808 
2809 -- This procedure is the main procedure that creates the ATP simplified pegging
2810 -- and stores it into the msc_atp_pegging table after plan run.
2811 PROCEDURE Generate_Simplified_Pegging(p_plan_id         IN          NUMBER,
2812                                       p_share_partition IN          VARCHAR2,
2813                                       p_applsys_schema  IN          VARCHAR2,
2814                                       RETCODE           OUT  NoCopy NUMBER   )
2815 IS
2816 
2817 l_count                         number;
2818 l_row_count                     number;
2819 l_tot_count                     NUMBER;
2820 l_partition_name                varchar2(30);
2821 l_sql_stmt                      varchar2(800); -- Bug 3344012 expand size.
2822 l_sql_stmt_1                    varchar2(8000);
2823 l_sql_stmt_2                    varchar2(8000); --CTO-PF
2824 l_ret_code                      NUMBER;
2825 l_err_msg                       VARCHAR2(1000);
2826 l_ind_tbspace                   VARCHAR2(30);
2827 l_insert_stmt                   VARCHAR2(8000);
2828 l_msc_schema                    VARCHAR2(30);
2829 l_sysdate                       date;
2830 l_user_id                       number;
2831 l_table_name                    VARCHAR2(30);
2832 l_tbspace                       VARCHAR2(30);
2833 l_temp_table                    VARCHAR2(30);
2834 atp_simple_peg_tab              MRP_ATP_PUB.char30_arr := MRP_ATP_PUB.char30_arr(
2835                                                                 'ATP_PEGGING');
2836 l_share_partition               VARCHAR2(1);
2837 l_plan_id                       NUMBER;
2838 l_plan_name                     varchar2(10);
2839 
2840 /* Currently the ATP Pegging Record Types will be defined local to this package. */
2841 -- Records for carrying ATP Pegging information
2842 atp_peg_tab                     ATP_Simple_Peg_Typ;
2843 atp_peg_det                     ATP_Detail_Peg_Typ;
2844 fcst_data_tab                   ATP_Fcst_Cons_Typ;
2845 l_pegging_id                    NUMBER;
2846 
2847 -- Bug 3362558 Store the original_demand_id
2848 -- CTO_PF_PRJ. This array is not needed anymore.
2849 l_original_demand_ids            MRP_ATP_PUB.number_arr := MRP_ATP_PUB.number_arr();
2850 -- CTO-PF
2851 l_time_phased_atp               VARCHAR2(1) := 'N';
2852 -- This cursor fetches the list of configuration_items.
2853 CURSOR config_items IS
2854    SELECT distinct msi.item_name, msi.inventory_item_id, msi.sr_inventory_item_id,
2855           msi.sr_instance_id, msi.base_item_id, d.sales_order_line_id,
2856           decode(d.demand_source_type, 100,  -- cmro fix
2857                        d.demand_source_type, -1) demand_source_type, -- cmro fix
2858           d.demand_class, d.demand_id  -- Bug 3319810 Add the sales_order demand class
2859    FROM   msc_system_items msi, msc_demands d
2860    WHERE  msi.plan_id = p_plan_id
2861    AND    msi.bom_item_type = 4
2862    AND    msi.base_item_id is NOT NULL
2863    AND    msi.replenish_to_order_flag = 'Y'
2864    AND    d.plan_id = msi.plan_id
2865    AND    d.sr_instance_id = msi.sr_instance_id
2866    AND    d.inventory_item_id = msi.inventory_item_id
2867    AND    d.organization_id = msi.organization_id
2868    AND    d.using_requirement_quantity > 0
2869    AND    d.origination_type in (6, 30)
2870  ;
2871       -- conditions to filter out records to be added
2872       -- using replenish_to_order_flag and pick_components_flag
2873 -- Define a corresponding record.
2874 c_items_rec                     ATP_End_Config_Dmd_Typ;
2875 
2876 l_order_org_ratio               NUMBER;
2877 
2878 i                               NUMBER;
2879 j                               NUMBER;
2880 k                               NUMBER;
2881 n                               NUMBER;
2882 rows_processed                  NUMBER;
2883 l_hash_size                     NUMBER := -1;
2884 l_sort_size                     NUMBER := -1;
2885 l_parallel_degree               NUMBER := 1;
2886 l_total_relief_qty              NUMBER;
2887 l_return_status                 VARCHAR2(1);
2888 
2889 l_timestamp                     NUMBER;
2890 
2891 -- Bug 3344102 Use Global Temporary table to store intermediate data.
2892 l_global_temp_table               VARCHAR2(30);
2893 l_insert_temp_table               VARCHAR2(30);
2894 l_ins_sql_stmt                    VARCHAR2(8000);
2895   -- For use as a switch between tables.
2896 
2897 -- Bug 3701093 Flag to control creation of offsets/reliefs/adjustments
2898 -- Values 1 TRUE, otherwise FALSE
2899 G_ADJUST_FLAG                   NUMBER;
2900 -- A Sales Order could be pegged to multiple Plan Orders with
2901 -- multiple end pegging ids.
2902 -- This variable is introduced for better control of the Adjustment process.
2903 L_TOT_RELIEF_QTY                NUMBER;
2904 l_peg_relief_qty                NUMBER;
2905 --bug 3950208
2906 l_err_buf                      varchar2(4000);
2907 l_call_status boolean;
2908 
2909 l_phase            varchar2(80);
2910 l_status           varchar2(80);
2911 l_dev_phase        varchar2(80);
2912 l_dev_status       varchar2(80);
2913 l_message          varchar2(2048);
2914 l_request_id       number;
2915 i                  number;
2916 
2917 BEGIN
2918 
2919   IF PG_DEBUG in ('Y', 'C') THEN
2920     msc_util.msc_log('***** Begin Generate_Simplified_Pegging (Gen_Atp_Pegging) *****');
2921     msc_util.msc_log('Gen_Atp_Pegging : p_plan_id ' || p_plan_id);
2922     msc_util.msc_log('Gen_Atp_Pegging : p_share_partition ' || p_share_partition);
2923     msc_util.msc_log('Gen_Atp_Pegging : p_applsys_schema ' || p_applsys_schema);
2924   END IF;
2925 
2926   --RETCODE := G_SUCCESS;
2927 
2928   -- Initialize variables;
2929 
2930     SELECT  a.oracle_username,
2931             sysdate,
2932             FND_GLOBAL.USER_ID
2933     INTO    l_msc_schema,
2934             l_sysdate,
2935             l_user_id
2936     FROM    fnd_oracle_userid a,
2937             fnd_product_installations b
2938     WHERE   a.oracle_id = b.oracle_id
2939     AND     b.application_id = 724;
2940 
2941   -- First get the performance parameters.
2942 
2943   BEGIN
2944      SELECT      NVL(pre_alloc_hash_size, -1),
2945                  NVL(pre_alloc_sort_size, -1),
2946                  NVL(pre_alloc_parallel_degree, 1)
2947      INTO        l_hash_size,
2948                  l_sort_size,
2949                  l_parallel_degree
2950      FROM        msc_atp_parameters
2951      WHERE       rownum = 1;
2952      EXCEPTION
2953          WHEN others THEN
2954          msc_util.msc_log('Error getting performance param: ' || sqlcode || ': ' || sqlerrm);
2955          l_hash_size := -1;
2956          l_sort_size := -1;
2957          l_parallel_degree := 1;
2958   END;
2959 
2960   IF PG_DEBUG in ('Y', 'C') THEN
2961      msc_util.msc_log('Hash: ' || l_hash_size || ' Sort: ' || l_sort_size ||
2962                          ' Parallel: ' || l_parallel_degree);
2963   END IF;
2964 
2965   IF NVL(l_hash_size, -1) <> -1 THEN
2966         l_sql_stmt_1 := 'alter session set hash_area_size = ' || to_char(l_hash_size);
2967         msc_util.msc_log('l_sql_stmt : ' || l_sql_stmt_1);
2968         execute immediate l_sql_stmt_1;
2969   END IF;
2970 
2971   IF NVL(l_sort_size, -1) <> -1 THEN
2972          l_sql_stmt_1 := 'alter session set sort_area_size = ' || to_char(l_sort_size);
2973          msc_util.msc_log('l_sql_stmt : ' || l_sql_stmt_1);
2974          execute immediate l_sql_stmt_1;
2975   END IF;
2976 
2977   -- Second set the table names.
2978 
2979   -- Bug 3344102
2980   -- Set the Global temporary table name.
2981   l_global_temp_table   := 'MSC_ATP_PEG_TEMP';
2982   -- End Bug 3344102
2983 
2984   FOR i in 1..atp_simple_peg_tab.count LOOP
2985 
2986         l_table_name := 'MSC_' || atp_simple_peg_tab(i);
2987 
2988         IF (p_share_partition = 'Y') THEN
2989            l_plan_id := MAXVALUE;
2990         ELSE
2991            l_plan_id := p_plan_id;
2992         END IF;
2993 
2994         l_partition_name :=  atp_simple_peg_tab(i)|| '_' || l_plan_id;
2995         IF PG_DEBUG in ('Y', 'C') THEN
2996           msc_util.msc_log('l_partition_name := ' || l_partition_name);
2997         END IF;
2998 
2999         BEGIN
3000             SELECT count(*)
3001             INTO   l_count
3002             --bug 2495962: Change refrence from dba_xxx to all_xxx tables
3003             --FROM   dba_tab_partitions
3004             FROM   all_tab_partitions
3005             WHERE  table_name = l_table_name
3006             AND    partition_name = l_partition_name
3007             AND    table_owner = l_msc_schema;
3008         EXCEPTION
3009             WHEN OTHERS THEN
3010               IF PG_DEBUG in ('Y', 'C') THEN
3011                  msc_util.msc_log('Inside Exception');
3012               END IF;
3013                  l_count := 0;
3014         END;
3015 
3016 
3017         IF (l_count = 0) THEN
3018            /* --bug 3950208: Create partitions if partitons are missing in this table
3019            -- Bug 2516506
3020            FND_MESSAGE.SET_NAME('MSC', 'MSC_ATP_PLAN_PARTITION_MISSING');
3021            FND_MESSAGE.SET_TOKEN('PLAN_NAME', l_plan_name);
3022            FND_MESSAGE.SET_TOKEN('TABLE_NAME', 'MSC_' || atp_simple_peg_tab(i));
3023            IF PG_DEBUG in ('Y', 'C') THEN
3024               msc_util.msc_log(FND_MESSAGE.GET);
3025            END IF;
3026            msc_util.msc_log('MSC_ATP_PLAN_PARTITION_MISSING : Partition ' || l_partition_name || ' NOT FOUND');
3027            -- Find out presence of config items.
3028            SELECT 1
3029            INTO   l_count
3030            FROM   msc_system_items msi, msc_demands d
3031            WHERE  msi.plan_id = p_plan_id
3032            AND    msi.bom_item_type = 4
3033            AND    msi.base_item_id is NOT NULL
3034            AND    msi.replenish_to_order_flag = 'Y'
3035            AND    d.plan_id = msi.plan_id
3036            AND    d.sr_instance_id = msi.sr_instance_id
3037            AND    d.inventory_item_id = msi.inventory_item_id
3038            AND    d.organization_id = msi.organization_id
3039            AND    d.using_requirement_quantity > 0
3040            AND    d.origination_type in (6, 30)
3041            AND    ROWNUM = 1 ;
3042 
3043            IF l_count > 0 THEN
3044               msc_util.msc_log('Config Items are present, Partition needs to be created : ERROR.');
3045               RETCODE := G_ERROR;
3046            ELSE
3047               msc_util.msc_log('Config Items are absent, Partition not present flagged as WARNING.');
3048               RETCODE := G_WARNING;
3049            END IF;
3050            RETURN;
3051            */
3052            msc_util.msc_log('Partitions are not found in MSC_ATP_PEGGING. Launch request to create partitions');
3053            l_request_id := FND_REQUEST.SUBMIT_REQUEST(
3054                                         'MSC',
3055                                         'MSCSUPRT',
3056                                         NULL,   -- description
3057                                         NULL,   -- start time
3058                                         FALSE);  -- sub request
3059 
3060            msc_util.msc_log('Request to create partition is launched with request id := ' || l_request_id);
3061            commit;
3062 
3063            LOOP
3064                l_call_status:= FND_CONCURRENT.GET_REQUEST_STATUS
3065                                       ( l_request_id,
3066                                         NULL,
3067                                         NULL,
3068                                         l_phase,
3069                                         l_status,
3070                                         l_dev_phase,
3071                                         l_dev_status,
3072                                         l_message);
3073 
3074 
3075                IF (l_call_status=FALSE) THEN
3076                    msc_util.msc_log('Error in creating ATP partitions. Please run Create ATP Partitions program
3077                                      and then run ATP Post Plan Processing Again');
3078                    RETCODE := G_ERROR;
3079                    RETURN;
3080                END IF;
3081 
3082                msc_util.msc_log('l_dev_phase := ' || l_dev_phase);
3083 
3084                EXIT WHEN l_dev_phase = 'COMPLETE';
3085 
3086            END LOOP;
3087 
3088         END IF;
3089   END LOOP;
3090 
3091   IF p_share_partition = 'Y' THEN
3092 
3093     IF PG_DEBUG in ('Y', 'C') THEN
3094        msc_util.msc_log('before deleting old ATP pegging data');
3095     END IF;
3096 
3097     DELETE MSC_ATP_PEGGING where plan_id = p_plan_id;
3098 
3099     IF PG_DEBUG in ('Y', 'C') THEN
3100        msc_util.msc_log('After deleting old ATP pegging info');
3101     END IF;
3102 
3103   END IF;
3104 
3105   IF p_share_partition = 'Y' THEN
3106 
3107         l_temp_table := 'MSC_ATP_PEGGING';
3108   ELSE
3109 
3110     IF PG_DEBUG in ('Y', 'C') THEN
3111         msc_util.msc_log('not a shared plan partition, insert data into temp tables');
3112     END IF;
3113 
3114     l_temp_table := 'MSC_TEMP_ATP_PEGG_'|| to_char(l_plan_id);
3115 
3116     IF PG_DEBUG in ('Y', 'C') THEN
3117         msc_util.msc_log('temp table : ' || l_temp_table);
3118     END IF;
3119 
3120     SELECT  t.tablespace_name, NVL(i.def_tablespace_name, t.tablespace_name)
3121     INTO    l_tbspace, l_ind_tbspace
3122     FROM    all_tab_partitions t,
3123             all_part_indexes i
3124     WHERE   t.table_owner = l_msc_schema
3125     AND     t.table_name = 'MSC_ATP_PEGGING'
3126     AND     t.partition_name = l_partition_name
3127     AND     i.owner (+) = t.table_owner
3128     AND     i.table_name (+) = t.table_name
3129     AND     rownum = 1;
3130 
3131     IF PG_DEBUG in ('Y', 'C') THEN
3132         msc_util.msc_log('tb space : ' || l_tbspace);
3133         msc_util.msc_log('ind tbspace : ' || l_ind_tbspace);
3134     END IF;
3135 
3136 --6113544
3137      l_insert_stmt := 'CREATE TABLE ' || l_temp_table
3138            || ' TABLESPACE ' || l_tbspace
3139            || ' PCTFREE 0 STORAGE(INITIAL 40K NEXT 5M PCTINCREASE 0)'
3140            || ' as select * from MSC_ATP_PEGGING where 1=2 ';
3141 
3142 /*
3143     l_insert_stmt := 'CREATE TABLE ' || l_temp_table || '(
3144                          plan_id                 NUMBER          NOT NULL,
3145                          sr_instance_id          NUMBER          NOT NULL,
3146                          reference_item_id       NUMBER          NOT NULL,
3147                          inventory_item_id       NUMBER          NOT NULL,
3148                          organization_id         NUMBER          NOT NULL,
3149                          sales_order_line_id     NUMBER          NOT NULL,
3150                          bom_item_type           NUMBER,
3151                          sales_order_qty         NUMBER,
3152                          transaction_date        NUMBER,
3153                          demand_id               NUMBER,
3154                          demand_quantity         NUMBER,
3155                          disposition_id          NUMBER,
3156                          demand_class            VARCHAR2(34)    ,
3157                          consumed_qty            NUMBER,
3158                          overconsumption_qty     NUMBER,
3159                          supply_id               NUMBER,
3160                          supply_quantity         NUMBER,
3161                          allocated_quantity      NUMBER,
3162                          resource_id             NUMBER,
3163                          department_id           NUMBER,
3164                          resource_hours          NUMBER,
3165                          daily_resource_hours    NUMBER,
3166                          start_date              NUMBER,
3167                          end_date                NUMBER,
3168                          relief_type             NUMBER,
3169                          relief_quantity         NUMBER,
3170                          daily_relief_qty        NUMBER,
3171                          pegging_id              NUMBER,
3172                          prev_pegging_id         NUMBER,
3173                          end_pegging_id          NUMBER,
3174                          created_by              NUMBER          NOT NULL,
3175                          creation_date           DATE            NOT NULL,
3176                          last_updated_by         NUMBER          NOT NULL,
3177                          last_update_date        DATE            NOT NULL,
3178                          customer_id             NUMBER,
3179                          customer_site_id        NUMBER,
3180                          DEMAND_SOURCE_TYPE      NUMBER, --cmro
3181                          -- CTO_PF_PRJ changes.
3182                          end_demand_id           NUMBER
3183                          )
3184                             TABLESPACE ' || l_tbspace || '
3185            --NOLOGGING
3186           PCTFREE 0 STORAGE(INITIAL 40K NEXT 5M PCTINCREASE 0)';
3187 */
3188     IF PG_DEBUG in ('Y', 'C') THEN
3189         msc_util.msc_log('before creating table : ' || l_temp_table);
3190     END IF;
3191 
3192     BEGIN
3193          ad_ddl.do_ddl(APPLSYS_SCHEMA => p_applsys_schema,
3194               APPLICATION_SHORT_NAME => 'MSC',
3195               STATEMENT_TYPE => ad_ddl.create_table,
3196               STATEMENT => l_insert_stmt,
3197               OBJECT_NAME => l_temp_table);
3198       IF PG_DEBUG in ('Y', 'C') THEN
3199          msc_util.msc_log('after creating table : ' || l_temp_table);
3200       END IF;
3201 
3202     EXCEPTION
3203        WHEN others THEN
3204          IF PG_DEBUG in ('Y', 'C') THEN
3205             msc_util.msc_log(sqlcode || ': ' || sqlerrm);
3206             msc_util.msc_log('Exception of create table : ' || l_temp_table);
3207          END IF;
3208             ad_ddl.do_ddl(APPLSYS_SCHEMA => p_applsys_schema,
3209                    APPLICATION_SHORT_NAME => 'MSC',
3210                    STATEMENT_TYPE => ad_ddl.drop_table,
3211                    STATEMENT =>  'DROP TABLE ' || l_temp_table,
3212                    OBJECT_NAME => l_temp_table);
3213 
3214          IF PG_DEBUG in ('Y', 'C') THEN
3215             msc_util.msc_log('After Drop table : ' ||l_temp_table);
3216             msc_util.msc_log('Before exception create table : ' ||l_temp_table);
3217          END IF;
3218 
3219             ad_ddl.do_ddl(APPLSYS_SCHEMA => p_applsys_schema,
3220                    APPLICATION_SHORT_NAME => 'MSC',
3221                    STATEMENT_TYPE => ad_ddl.create_table,
3222                    STATEMENT => l_insert_stmt,
3223                    OBJECT_NAME => l_temp_table);
3224          IF PG_DEBUG in ('Y', 'C') THEN
3225             msc_util.msc_log('After exception create table : ' ||l_temp_table);
3226          END IF;
3227     END;
3228   END IF;  -- p_share_partition = 'Y'
3229 
3230     OPEN config_items;
3231 
3232     select hsecs
3233     into   l_timestamp
3234     from   v$timer;
3235 
3236     IF PG_DEBUG in ('Y', 'C') THEN
3237        msc_util.msc_log('Gen_Atp_Pegging : After opening config_items ');
3238        msc_util.msc_log('Gen_Atp_Pegging : TIMESTAMP 1 ' || l_timestamp);
3239     END IF;
3240 
3241     LOOP  -- Begin config_items loop
3242       IF PG_DEBUG in ('Y', 'C') THEN
3243           msc_util.msc_log('Gen_Atp_Pegging : Before fetch config_items Cursor');
3244       END IF;
3245       FETCH config_items INTO c_items_rec;
3246       EXIT WHEN config_items%NOTFOUND;
3247 
3248       IF PG_DEBUG in ('Y', 'C') THEN
3249           msc_util.msc_log('Gen_Atp_Pegging : After fetch config_items Cursor');
3250           msc_util.msc_log('Gen_Atp_Pegging : c_items_rec.item_name ' ||
3251                                                        c_items_rec.item_name);
3252           msc_util.msc_log('Gen_Atp_Pegging : c_items_rec.inventory_item_id ' ||
3253                                                        c_items_rec.inventory_item_id);
3254           msc_util.msc_log('Gen_Atp_Pegging : c_items_rec.sr_inventory_item_id ' ||
3255                                                        c_items_rec.sr_inventory_item_id);
3256           msc_util.msc_log('Gen_Atp_Pegging : c_items_rec.sr_instance_id ' ||
3257                                                        c_items_rec.sr_instance_id);
3258           msc_util.msc_log('Gen_Atp_Pegging : c_items_rec.base_item_id ' ||
3259                                                        c_items_rec.base_item_id);
3260           msc_util.msc_log('Gen_Atp_Pegging : c_items_rec.sales_order_line_id ' ||
3261                                                        c_items_rec.sales_order_line_id);
3262           msc_util.msc_log('Gen_Atp_Pegging : c_items_rec.demand_source_type' ||
3263                                                        c_items_rec.demand_source_type);--cmro
3264           msc_util.msc_log('Gen_Atp_Pegging : c_items_rec.demand_class' ||
3265                                            c_items_rec.demand_class); --Bug 3319180
3266           msc_util.msc_log('Gen_Atp_Pegging : c_items_rec.demand_id' ||
3267                                            c_items_rec.demand_id); --Bug 3750638
3268           msc_util.msc_log('Gen_Atp_Pegging : Plan Id ' || p_plan_id );
3269           msc_util.msc_log('Gen_Atp_Pegging : Stage 0 ' );
3270       END IF;
3271 
3272       -- Bug 3750638 Call the SQL statements now moved to a new procedure
3273       Get_Pegging_Data_Loop ( p_plan_id,
3274                               c_items_rec,
3275                               l_return_status);
3276 
3277       IF l_return_status <> FND_API.G_RET_STS_SUCCESS THEN
3278        IF PG_DEBUG in ('Y', 'C') THEN
3279            msc_util.msc_log('Gen_Atp_Pegging: ' ||
3280                'Error occured in procedure Get_Pegging_Data_Loop');
3281         END IF;
3282         RAISE FND_API.G_EXC_ERROR;
3283       END IF;
3284       -- End Bug 3750638 Call the SQL statements now moved to a new procedure
3285 
3286 
3287     select hsecs
3288     into   l_timestamp
3289     from   v$timer;
3290 
3291       IF PG_DEBUG in ('Y', 'C') THEN
3292         msc_util.msc_log('Gen_Atp_Pegging : Stage 5 ' );
3293         msc_util.msc_log('Gen_Atp_Pegging : TIMESTAMP 3 ' || l_timestamp);
3294       END IF;
3295 
3296       -- Fetch the data into PL/SQL record of tables.
3297       SELECT
3298               reference_item_id, base_item_id,
3299               inventory_item_id,
3300               plan_id,
3301               sr_instance_id,
3302               organization_id,
3303               end_item_usage,
3304               bom_item_type, fixed_lt, variable_lt,
3305               sales_order_line_id,
3306               demand_source_type,--cmro
3307               sales_order_qty,
3308               demand_id,
3309               demand_date,
3310               demand_quantity,
3311               disposition_id,
3312               demand_class,
3313               demand_type,
3314               original_demand_id,
3315               process_seq_id, supply_id,
3316               supply_date,
3317               supply_quantity,
3318               allocated_quantity, tot_relief_qty,
3319               supply_type,
3320               firm_planned_type,
3321               release_status,
3322               exclude_flag,    -- All other cases exclude
3323               order_number,
3324               end_pegging_id, pegging_id,  prev_pegging_id,
3325               fcst_organization_id, forecast_qty,
3326               consumed_qty, overconsumption_qty,
3327               -- CTO_PF_PRJ changes.
3328               end_demand_id,
3329               --CTO-PF
3330               atf_date,
3331               product_family_id
3332       BULK COLLECT INTO
3333               atp_peg_det.reference_item_id, atp_peg_det.base_item_id,
3334               atp_peg_det.inventory_item_id, atp_peg_det.plan_id, atp_peg_det.sr_instance_id,
3335               atp_peg_det.organization_id, atp_peg_det.end_item_usage, atp_peg_det.bom_item_type,
3336               atp_peg_det.fixed_lt, atp_peg_det.variable_lt,
3337               atp_peg_det.sales_order_line_id,atp_peg_det.demand_source_type,atp_peg_det.sales_order_qty, --cmro
3338               atp_peg_det.demand_id, atp_peg_det.demand_date,
3339               atp_peg_det.demand_quantity, atp_peg_det.disposition_id,
3340               atp_peg_det.demand_class, atp_peg_det.demand_type, atp_peg_det.original_demand_id,
3341               atp_peg_det.process_seq_id, atp_peg_det.supply_id, atp_peg_det.supply_date,
3342               atp_peg_det.supply_quantity, atp_peg_det.allocated_quantity,
3343               atp_peg_det.tot_relief_qty, atp_peg_det.supply_type,
3344               atp_peg_det.firm_planned_type, atp_peg_det.release_status,
3345               atp_peg_det.exclude_flag, atp_peg_det.order_number,
3346               atp_peg_det.end_pegging_id, atp_peg_det.pegging_id, atp_peg_det.prev_pegging_id,
3347               atp_peg_det.fcst_organization_id, atp_peg_det.forecast_qty,
3348               atp_peg_det.consumed_qty, atp_peg_det.overconsumption_qty,
3349               -- CTO_PF_PRJ changes.
3350               atp_peg_det.end_demand_id,
3351               -- CTO-PF
3352               atp_peg_det.atf_date,
3353               atp_peg_det.product_family_id
3354       FROM
3355               msc_atp_detail_peg_temp
3356       WHERE   plan_id = p_plan_id
3357       AND     sr_instance_id (+) = c_items_rec.sr_instance_id -- outer join to get all instances
3358       AND     reference_item_id = c_items_rec.inventory_item_id
3359       AND     sales_order_line_id = c_items_rec.sales_order_line_id
3360       AND     Decode(demand_source_type,100,demand_source_type,-1)
3361               =decode(c_items_rec.demand_source_type,
3362                                                 100,
3363                                                 c_items_rec.demand_source_type,
3364                                                 -1) --CMRO
3365       ORDER BY
3366                end_pegging_id, prev_pegging_id,
3367                demand_date, supply_date,
3368                pegging_id DESC     -- prev_pegging_id, pegging_id DESC ???
3369       ;
3370 
3371 
3372 
3373     select hsecs
3374     into   l_timestamp
3375     from   v$timer;
3376 
3377       IF PG_DEBUG in ('Y', 'C') THEN
3378         msc_util.msc_log('Gen_Atp_Pegging : Stage 6 ' );
3379         msc_util.msc_log('Gen_Atp_Pegging : Rows Procesed ' || SQL%ROWCOUNT );
3380         msc_util.msc_log('Gen_Atp_Pegging : TIMESTAMP 4 ' || l_timestamp);
3381       END IF;
3382 
3383 
3384       -- Obtain and Assign forecast consumption info.
3385       FOR i in 1..atp_peg_det.inventory_item_id.COUNT LOOP
3386          -- Obtain forecast consumption info only for config items.
3387          IF (atp_peg_det.bom_item_type(i) = 4 AND
3388              atp_peg_det.base_item_id(i) IS NOT NULL ) THEN
3389             -- Bug 3362558 Display the original_demand_id
3390             IF PG_DEBUG in ('Y', 'C') THEN
3391                msc_util.msc_log('Gen_Atp_Pegging : End Demand Id for Sales Order: ' ||
3392                   -- CTO_PF_PRJ changes. Use end_demand_id
3393                                   atp_peg_det.end_demand_id(i) );
3394                                   --l_original_demand_ids(1) );
3395             END IF;
3396             -- End Bug 3362558
3397             Get_Forecast_Consumption(atp_peg_det, i, fcst_data_tab, l_return_status);
3398             l_total_relief_qty  := 0;
3399           IF PG_DEBUG in ('Y', 'C') THEN
3400             msc_util.msc_log('Gen_Atp_Pegging : Stage 7 ' );
3401             msc_util.msc_log('Gen_Atp_Pegging : Status post Fcst Consumption.' ||
3402                                                            l_return_status );
3403             msc_util.msc_log('Gen_Atp_Pegging : Fcst Data Count.' ||
3404                                                fcst_data_tab.inventory_item_id.Count);
3405           END IF;
3406          END IF;
3407 
3408          -- Re-initialize org_ratio
3409 
3410          l_order_org_ratio := NULL;
3411          -- Bug 3701093
3412          -- Initialize G_ADJUST_FLAG to 1, Default is to generate offsets.
3413          G_ADJUST_FLAG := 1;
3414 
3415          -- Here in this loop, the total relief quantities will also be determined.
3416          FOR j in 1..fcst_data_tab.inventory_item_id.COUNT LOOP
3417            IF (atp_peg_det.inventory_item_id(i) = fcst_data_tab.inventory_item_id(j) AND
3418                atp_peg_det.plan_id(i) = fcst_data_tab.plan_id(j) AND
3419                atp_peg_det.sr_instance_id(i) = fcst_data_tab.sr_instance_id(j) AND
3420                (atp_peg_det.original_demand_id(i) = fcst_data_tab.sales_order_id(j) OR
3421                 -- Bug 3362558
3422                 -- Global forecasting situation, org_id is -1.
3423                 (fcst_data_tab.fcst_organization_id(j) = -1 AND
3424                   -- CTO_PF_PRJ changes. Use end_demand_id
3425                  fcst_data_tab.sales_order_id(j) = atp_peg_det.end_demand_id(i) ) OR
3426                 atp_peg_det.demand_id(i) = fcst_data_tab.sales_order_id(j)  ) ) THEN
3427 
3428                atp_peg_det.forecast_qty(i) := fcst_data_tab.forecast_qty(j);
3429                atp_peg_det.bom_item_type(i) := fcst_data_tab.bom_item_type(j);
3430 
3431                -- Set the distribution of order ratio
3432                -- The same order can be satisfied using multiple organizations.
3433                -- The ratio below factors that in.
3434 
3435                IF (atp_peg_det.allocated_quantity(i) < fcst_data_tab.consumed_qty(j)
3436                                                     + NVL(fcst_data_tab.overconsumption_qty(j),0) ) THEN
3437                    l_order_org_ratio := atp_peg_det.allocated_quantity(i) /
3438                                             (fcst_data_tab.consumed_qty(j) +
3439                                                 NVL(fcst_data_tab.overconsumption_qty(j), 0)
3440                                             );
3441                ELSE
3442                    l_order_org_ratio := 1;
3443                END IF;
3444 
3445                atp_peg_det.consumed_qty(i) := NVL(fcst_data_tab.consumed_qty(j), 0) *
3446                                                                  l_order_org_ratio;
3447                atp_peg_det.overconsumption_qty(i) := NVL(fcst_data_tab.overconsumption_qty(j), 0)
3448                                                          * l_order_org_ratio;
3449 
3450                -- Determine the Total relief quantity across all organizations.
3451                IF ((fcst_data_tab.consumed_qty(j) IS NOT NULL) AND
3452                    (fcst_data_tab.sales_order_qty(j) > fcst_data_tab.consumed_qty(j))) THEN
3453 
3454                   atp_peg_det.tot_relief_qty(i) := fcst_data_tab.consumed_qty(j) -
3455                                                    fcst_data_tab.sales_order_qty(j);
3456                ELSE
3457 
3458                   -- If the sales order is not greater than the consumption
3459                   -- nothing to relieve at the configuration item level.
3460                   atp_peg_det.tot_relief_qty(i) := 0;
3461                END IF;
3462 
3463                l_total_relief_qty := atp_peg_det.tot_relief_qty(i);
3464                IF PG_DEBUG in ('Y', 'C') THEN
3465                  msc_util.msc_log('Gen_Atp_Pegging :  Total Relief Qty' ||
3466                                                            l_total_relief_qty);
3467                  msc_util.msc_log('Gen_Atp_Pegging :  FC Consumtion Flag' ||
3468                                                    fcst_data_tab.cons_config_mod_flag(j));
3469                END IF;
3470 
3471                -- Bug 3701093
3472                IF (fcst_data_tab.cons_config_mod_flag(j) = C_CONFIG_FCST_CONSUMED) AND
3473                   (atp_peg_det.reference_item_id(i) = fcst_data_tab.inventory_item_id(j)) THEN
3474                   G_ADJUST_FLAG := 0;
3475                   -- No offset data generation generation necessary when TOP LEVEL
3476                   -- config item's forecast can completely satisfy the Sales Order.
3477 
3478                ELSE
3479                  FOR n in 1..atp_peg_det.inventory_item_id.COUNT LOOP
3480 
3481                    -- Set the total_relief_qty for components pegged to the configuration_item
3482                    IF (atp_peg_det.plan_id(n) = atp_peg_det.plan_id(i) AND
3483                      atp_peg_det.disposition_id(n) = atp_peg_det.supply_id(i) ) THEN
3484 
3485                       atp_peg_det.tot_relief_qty(n) := atp_peg_det.tot_relief_qty(i)
3486                                                    * atp_peg_det.end_item_usage(n) / atp_peg_det.end_item_usage(i);
3487 
3488                    END IF;
3489 
3490                  END LOOP;
3491                END IF;
3492            -- match with base model
3493            ELSIF
3494                (atp_peg_det.plan_id(i) = fcst_data_tab.plan_id(j) AND
3495                atp_peg_det.sr_instance_id(i) = fcst_data_tab.sr_instance_id(j) AND
3496                atp_peg_det.base_item_id(i) = fcst_data_tab.inventory_item_id(j)  AND
3497                atp_peg_det.organization_id(i) = fcst_data_tab.organization_id(j) AND
3498                -- Bug 3319810 For lower level model the demand type will not be
3499                -- Sales Order, hence commented out.
3500                -- atp_peg_det.demand_type(i) in (6, 30) AND
3501                (atp_peg_det.original_demand_id(i) = fcst_data_tab.sales_order_id(j) OR
3502                 -- Bug 3362558
3503                 -- Global forecasting situation, org_id is -1.
3504                 (fcst_data_tab.fcst_organization_id(j) = -1 AND
3505                   -- CTO_PF_PRJ changes. Use end_demand_id
3506                  fcst_data_tab.sales_order_id(j) = atp_peg_det.end_demand_id(i) ) OR
3507                 atp_peg_det.demand_id(i) = fcst_data_tab.sales_order_id(j) ) ) THEN
3508 
3509                -- Will the ratio determined using the model work as well?
3510                -- Set the ratio
3511                -- Set the distribution of order ratio
3512                -- The same order can be satisfied using multiple organizations.
3513                -- The ratio below factors that in.
3514                IF (l_order_org_ratio IS NULL AND
3515                    atp_peg_det.allocated_quantity(i) < fcst_data_tab.consumed_qty(j) +
3516                                                      NVL(fcst_data_tab.overconsumption_qty(j), 0) ) THEN
3517                    l_order_org_ratio := atp_peg_det.allocated_quantity(i) /
3518                                             (fcst_data_tab.consumed_qty(j) +
3519                                           NVL(fcst_data_tab.overconsumption_qty(j), 0));
3520                ELSE
3521                    l_order_org_ratio := 1;
3522                END IF;
3523                IF PG_DEBUG in ('Y', 'C') THEN
3524                  msc_util.msc_log('Gen_Atp_Pegging :  fcst_data_tab.inventory_item_id(j)' ||
3525                                                 fcst_data_tab.inventory_item_id(j));
3526                  msc_util.msc_log('Gen_Atp_Pegging :  fcst_data_tab.consumed_qty(j)' ||
3527                                                 fcst_data_tab.consumed_qty(j));
3528                  msc_util.msc_log('Gen_Atp_Pegging : fcst_data_tab.sales_order_id(j)' ||
3529                                                 fcst_data_tab.sales_order_id(j));
3530                  msc_util.msc_log('Gen_Atp_Pegging :  l_order_org_ratio' ||
3531                                                              l_order_org_ratio);
3532                  msc_util.msc_log('Gen_Atp_Pegging :  FC Consumtion Flag' ||
3533                                                    fcst_data_tab.cons_config_mod_flag(j));
3534                END IF;
3535                -- Bug 3701093 Model Forecast Has been consumed,
3536                -- Generate Offsets for  Model.
3537                IF fcst_data_tab.cons_config_mod_flag(j) = C_MODEL_FCST_CONSUMED THEN
3538                   Extend_Atp_Peg_Det (atp_peg_det, l_return_status, 1);
3539 
3540                   k := atp_peg_det.reference_item_id.Count;
3541 
3542                   atp_peg_det.reference_item_id(k) := atp_peg_det.reference_item_id(i);
3543                   atp_peg_det.base_item_id(k) := NULL;
3544                   atp_peg_det.inventory_item_id(k) := fcst_data_tab.inventory_item_id(j);
3545                   atp_peg_det.plan_id(k) := atp_peg_det.plan_id(i);
3546                   atp_peg_det.sr_instance_id(k) := atp_peg_det.sr_instance_id(i);
3547                   atp_peg_det.organization_id(k) := atp_peg_det.organization_id(i);
3548                   atp_peg_det.bom_item_type(k) := fcst_data_tab.bom_item_type(j);
3549                   -- Configuration Item's lead times are used.
3550                   atp_peg_det.fixed_lt(k) := atp_peg_det.fixed_lt(i);
3551                   atp_peg_det.variable_lt(k) := atp_peg_det.variable_lt(i);
3552                   atp_peg_det.sales_order_qty(k) := fcst_data_tab.sales_order_qty(j);
3553                   atp_peg_det.sales_order_line_id(k) := atp_peg_det.sales_order_line_id(i);
3554                   atp_peg_det.demand_source_type(k) := atp_peg_det.demand_source_type(i);--cmro
3555                   atp_peg_det.demand_id(k) := fcst_data_tab.fcst_demand_id(j);
3556                   atp_peg_det.demand_date(k) := atp_peg_det.demand_date(i);
3557                   -- Set the demand_date for the model to be that
3558                   -- of configuration item's date, No offsets for model .
3559                   -- For sub-components other than models offset is applied
3560                   -- during calculation of relief quantities.
3561                   atp_peg_det.demand_quantity(k) :=  NVL(atp_peg_det.demand_quantity(i), 0) -
3562                                            NVL(atp_peg_det.consumed_qty (i) , 0);
3563                   -- Set the demand_quantity to be that of the configuration item's demand
3564                   -- after factoring the consumption.
3565                   atp_peg_det.disposition_id(k) :=  atp_peg_det.supply_id(i);
3566 
3567                   atp_peg_det.demand_class(k) := atp_peg_det.demand_class(i);
3568                   atp_peg_det.demand_type(k) := 1;  -- Plan Order Demand
3569                   atp_peg_det.original_demand_id(k) := atp_peg_det.original_demand_id(i);
3570                   -- CTO_PF_PRJ changes. Set end_demand_id
3571                   atp_peg_det.end_demand_id(k) := atp_peg_det.end_demand_id(i);
3572 
3573                   atp_peg_det.fcst_organization_id(k) :=
3574                                           fcst_data_tab.fcst_organization_id(j);
3575                   atp_peg_det.forecast_qty(k) := fcst_data_tab.forecast_qty(j) ;
3576                   atp_peg_det.consumed_qty(k) := NVL(fcst_data_tab.consumed_qty(j), 0) *
3577                                                                  l_order_org_ratio;
3578                   atp_peg_det.overconsumption_qty(k) :=
3579                                      NVL(fcst_data_tab.overconsumption_qty(j), 0)
3580                                                          * l_order_org_ratio;
3581                   IF PG_DEBUG in ('Y', 'C') THEN
3582                      msc_util.msc_log('Gen_Atp_Pegging : atp_peg_det.consumed_qty(k)' ||
3583                                                        atp_peg_det.consumed_qty(k));
3584                      msc_util.msc_log('Gen_Atp_Pegging : atp_peg_det.overconsumption_qty(k)' ||
3585                                                 atp_peg_det.overconsumption_qty(k));
3586                   END IF;
3587                   -- For now the process_seq_id remains unassigned
3588                   -- atp_peg_det.process_seq_id(k) := atp_peg_det.process_seq_id(i) ;
3589                   -- What to do with the Supply for model and the components?
3590                   -- Currently everything is set to NULL.
3591                   atp_peg_det.supply_id(k) := NULL;
3592                   atp_peg_det.supply_date(k) := NULL;
3593                   atp_peg_det.supply_quantity(k) := NULL;
3594                   -- Bug 3805136 Set the allocated_quantity to Config's allocated_quantity
3595                   atp_peg_det.allocated_quantity(k) := atp_peg_det.allocated_quantity(i);
3596                   -- End Bug 3805136
3597                   atp_peg_det.supply_type(k) := NULL;
3598                   atp_peg_det.firm_planned_type(k) := NULL;
3599                   atp_peg_det.release_status(k) := NULL;
3600 
3601                   atp_peg_det.end_item_usage(k) := atp_peg_det.end_item_usage(i);
3602 
3603                   atp_peg_det.exclude_flag(k) := atp_peg_det.exclude_flag(i);
3604 
3605                   atp_peg_det.order_number(k) := atp_peg_det.order_number(i);
3606 
3607                   atp_peg_det.end_pegging_id(k) := atp_peg_det.end_pegging_id(i);
3608                   atp_peg_det.pegging_id(k) := NULL;
3609                   -- Note that the prev_pegging_id is linked to the Configuration Item's
3610                   -- Pegging Id.
3611                   atp_peg_det.prev_pegging_id(k) := atp_peg_det.pegging_id(i);
3612                END IF;
3613                -- End Bug 3701093
3614 
3615                -- Determine the Total relief quantity across all organizations.
3616                IF ((fcst_data_tab.consumed_qty(j) IS NOT NULL) OR
3617                    (fcst_data_tab.overconsumption_qty(j) IS NOT NULL) ) THEN
3618 
3619                   -- Config is relieved to the extent of consumption + overconsumption.
3620                   atp_peg_det.tot_relief_qty(i) := -1 * (fcst_data_tab.consumed_qty(j) +
3621                                                    fcst_data_tab.overconsumption_qty(j) );
3622                -- Bug 3805136 No forecast consumed, total_relief_qty remains NULL
3623                ELSIF (fcst_data_tab.cons_config_mod_flag(j) = C_NO_FCST_CONSUMED) THEN
3624                   atp_peg_det.tot_relief_qty(i) := NULL;  -- Remains NULL
3625                -- Bug 3805136
3626                ELSE
3627 
3628                   atp_peg_det.tot_relief_qty(i) := 0;
3629                END IF;
3630                -- Bug 3701093 Model Forecast Has been consumed,
3631                -- Generate Offsets for  Model.
3632                IF fcst_data_tab.cons_config_mod_flag(j) = C_MODEL_FCST_CONSUMED THEN
3633                   -- Set the Relief Qty for the model
3634                   atp_peg_det.tot_relief_qty(k) := atp_peg_det.tot_relief_qty(i);
3635                END IF;
3636                -- End Bug 3701093
3637 
3638                IF PG_DEBUG in ('Y', 'C') THEN
3639                  msc_util.msc_log('Gen_Atp_Pegging :  atp_peg_det.tot_relief_qty(i) ' ||
3640                                                              atp_peg_det.tot_relief_qty(i));
3641                  msc_util.msc_log('Gen_Atp_Pegging :  atp_peg_det.inventory_item_id(i) '
3642                                                      ||   atp_peg_det.inventory_item_id(i));
3643                END IF;
3644                FOR n in 1..atp_peg_det.inventory_item_id.COUNT LOOP
3645 
3646                  -- Set the total_relief_qty for components pegged to the configuration_item
3647                  IF (atp_peg_det.plan_id(n) = atp_peg_det.plan_id(i) AND
3648                      atp_peg_det.tot_relief_qty(n) IS NULL AND
3649                      -- Bug 3805136 Link up the pegging.
3650                      atp_peg_det.prev_pegging_id(n) = atp_peg_det.pegging_id(i) AND
3651                      -- and forecast consumption happens
3652                      atp_peg_det.tot_relief_qty(i) IS NOT NULL AND
3653                      --  End Bug 3805136
3654                      atp_peg_det.disposition_id(n) = atp_peg_det.supply_id(i) ) THEN
3655 
3656                       atp_peg_det.tot_relief_qty(n) := atp_peg_det.tot_relief_qty(i)
3657                                                    * atp_peg_det.end_item_usage(n) / atp_peg_det.end_item_usage(i);
3658 
3659                   IF PG_DEBUG in ('Y', 'C') THEN
3660                     msc_util.msc_log('Gen_Atp_Pegging :  atp_peg_det.tot_relief_qty(n) ' ||
3661                                                              atp_peg_det.tot_relief_qty(n));
3662                     msc_util.msc_log('Gen_Atp_Pegging :  atp_peg_det.inventory_item_id(n) '
3663                                                      ||   atp_peg_det.inventory_item_id(n));
3664                     msc_util.msc_log('Gen_Atp_Pegging :  atp_peg_det.pegging_id(n) '
3665                                                      ||   atp_peg_det.pegging_id(n));
3666                     msc_util.msc_log('Gen_Atp_Pegging :  ' ||
3667                      'atp_peg_det.allocated_quantity(n) '|| atp_peg_det.allocated_quantity(n));
3668                   END IF;
3669                  END IF;
3670 
3671                END LOOP;
3672            -- other phantom items
3673            -- other items only in the manufacturing organization.
3674            ELSIF (atp_peg_det.process_seq_id(i) is NOT NULL ) AND
3675                   atp_peg_det.plan_id(i) = fcst_data_tab.plan_id(j) AND
3676                   atp_peg_det.sr_instance_id(i) = fcst_data_tab.sr_instance_id(j) AND
3677                   atp_peg_det.inventory_item_id(i) = fcst_data_tab.parent_item_id(j) AND
3678                   -- Bug 3319810 For lower level model the demand type will not be
3679                   -- Sales Order, hence commented out.
3680                   -- atp_peg_det.demand_type(i) in (6, 30) AND
3681                   atp_peg_det.organization_id(i) = fcst_data_tab.organization_id(j) THEN
3682            -- or alternatively
3683            -- ELSIF (atp_peg_det.source_organization_id(i) IS NULL AND
3684            --   atp_peg_det.source_supplier_id(i) IS NULL)
3685 
3686              l_row_count :=  1 ;
3687              -- model has already been factored above.
3688              l_count :=   atp_peg_det.inventory_item_id.COUNT;
3689 
3690              -- Extend the array by the number of rows in Fcst array.
3691              Extend_Atp_Peg_Det (atp_peg_det, l_return_status, l_row_count);
3692 
3693              -- Update the total count.
3694              l_tot_count := l_count + l_row_count;
3695 
3696              IF PG_DEBUG in ('Y', 'C') THEN
3697                msc_util.msc_log('Gen_Atp_Pegging : ATP Inventory_item_id. ' ||
3698                                                    atp_peg_det.inventory_item_id(i) );
3699                msc_util.msc_log('Gen_Atp_Pegging : FCST Inventory_item_id. ' ||
3700                                                  fcst_data_tab.inventory_item_id(j) );
3701                msc_util.msc_log('Gen_Atp_Pegging : FCST Parent_Item_id. ' ||
3702                                                  fcst_data_tab.Parent_Item_id(j) );
3703                msc_util.msc_log('Gen_Atp_Pegging : l_row_count. ' ||
3704                                                            l_row_count );
3705                msc_util.msc_log('Gen_Atp_Pegging : l_count. ' ||
3706                                                            l_count );
3707                msc_util.msc_log('Gen_Atp_Pegging : l_tot_count. ' ||
3708                                                            l_tot_count  );
3709              END IF;
3710              l_count := l_count + 1;
3711              -- Append the forecast_data for each config item to
3712              -- the original array with the phantom items information
3713              --FOR k in l_count..l_tot_count LOOP
3714 
3715               k:= l_count;
3716               IF PG_DEBUG in ('Y', 'C') THEN
3717                 msc_util.msc_log('Gen_Atp_Pegging : Value of loop var k. ' || k  );
3718               END IF;
3719 
3720                atp_peg_det.reference_item_id(k) := atp_peg_det.reference_item_id(i);
3721                atp_peg_det.base_item_id(k) := NULL;
3722                atp_peg_det.inventory_item_id(k) := fcst_data_tab.inventory_item_id(j);
3723                atp_peg_det.plan_id(k) := atp_peg_det.plan_id(i);
3724                atp_peg_det.sr_instance_id(k) := atp_peg_det.sr_instance_id(i);
3725                atp_peg_det.organization_id(k) := atp_peg_det.organization_id(i);
3726                atp_peg_det.bom_item_type(k) := fcst_data_tab.bom_item_type(j);
3727                -- Individual Item's lead times are used.
3728                atp_peg_det.fixed_lt(k) := fcst_data_tab.fixed_lt(j);
3729                atp_peg_det.variable_lt(k) := fcst_data_tab.variable_lt(j);
3730                atp_peg_det.sales_order_qty(k) := fcst_data_tab.sales_order_qty(j);
3731                -- Note that the sales_order_qty gets factored in during forecast consumption
3732                atp_peg_det.sales_order_line_id(k) := atp_peg_det.sales_order_line_id(i);
3733                atp_peg_det.demand_source_type(k) := atp_peg_det.demand_source_type(i);--cmro
3734                atp_peg_det.demand_id(k) := fcst_data_tab.fcst_demand_id(j);
3735                -- Bug 3445664 The date will be NULL for phantom items.
3736                -- atp_peg_det.demand_date(k) := atp_peg_det.supply_date(i);
3737                       -- Set the demand_date for the component to be that
3738                       -- of configuration item's supply date for offsets later.
3739                -- End Bug 3445664 The date will be NULL for phantom items.
3740                       -- For sub-components other than models offset is applied
3741                       -- during calculation of relief quantities.
3742                atp_peg_det.demand_quantity(k) :=  fcst_data_tab.sales_order_qty(j)
3743                                                        * l_order_org_ratio ;
3744                -- Set the demand_quantity to be that of sales_order_quantity.
3745                -- after applying the organization ratio.
3746                atp_peg_det.disposition_id(k) :=  atp_peg_det.supply_id(i);
3747 
3748                atp_peg_det.demand_class(k) := atp_peg_det.demand_class(i);
3749                atp_peg_det.demand_type(k) := 1;  -- Plan Order Demand
3750                atp_peg_det.original_demand_id(k) := atp_peg_det.original_demand_id(i);
3751                -- CTO_PF_PRJ changes. Set end_demand_id
3752                atp_peg_det.end_demand_id(k) := atp_peg_det.end_demand_id(i);
3753 
3754                atp_peg_det.fcst_organization_id(k) := fcst_data_tab.fcst_organization_id(j);
3755                atp_peg_det.forecast_qty(k) := fcst_data_tab.forecast_qty(j) ;
3756                atp_peg_det.consumed_qty(k) := NVL(fcst_data_tab.consumed_qty(j), 0) *
3757                                                                  l_order_org_ratio;
3758                atp_peg_det.overconsumption_qty(k) := NVL(fcst_data_tab.overconsumption_qty(j), 0)
3759                                                          * l_order_org_ratio;
3760 
3761 
3762                -- For now the process_seq_id remains unassigned
3763                -- atp_peg_det.process_seq_id(k) := atp_peg_det.process_seq_id(i) ;
3764                -- What to do with the Supply for model and the components?
3765                -- Currently everything is set to NULL.
3766                atp_peg_det.supply_id(k) := NULL;
3767                atp_peg_det.supply_date(k) := NULL;
3768                atp_peg_det.supply_quantity(k) := NULL;
3769                atp_peg_det.allocated_quantity(k) := NULL;
3770                atp_peg_det.supply_type(k) := NULL;
3771                atp_peg_det.firm_planned_type(k) := NULL;
3772                atp_peg_det.release_status(k) := NULL;
3773 
3774                -- Bug 3805136
3775                -- Set to 1 currently as a default.
3776                -- Usage Quantity to estimate end_item_usage
3777                -- Not provided by MBP in msc_forecast_updates currently.
3778                atp_peg_det.end_item_usage(k) := 1;
3779                -- Bug 3805136
3780 
3781                atp_peg_det.exclude_flag(k) := atp_peg_det.exclude_flag(i);
3782 
3783                atp_peg_det.order_number(k) := atp_peg_det.order_number(i);
3784 
3785                atp_peg_det.end_pegging_id(k) := atp_peg_det.end_pegging_id(i);
3786                atp_peg_det.pegging_id(k) := NULL;
3787                -- Note that the prev_pegging_id is linked to the Configuration Item's
3788                -- Pegging Id.
3789                atp_peg_det.prev_pegging_id(k) := atp_peg_det.pegging_id(i);
3790 
3791                -- Determine the Total relief quantity across all organizations.
3792                IF ((fcst_data_tab.consumed_qty(j) IS NOT NULL) OR
3793                    (fcst_data_tab.overconsumption_qty(j) IS NOT NULL) ) THEN
3794 
3795                   -- All others also relieved to the extent of consumption + overconsumption.
3796                   atp_peg_det.tot_relief_qty(k) := -1 * (fcst_data_tab.consumed_qty(j) +
3797                                                    fcst_data_tab.overconsumption_qty(j) );
3798                ELSE
3799 
3800                   atp_peg_det.tot_relief_qty(k) := 0;
3801                END IF;
3802                -- Bug 3805136 Allocated quantity is positive
3803                atp_peg_det.allocated_quantity(k) :=  ABS(atp_peg_det.tot_relief_qty(k));
3804                IF PG_DEBUG in ('Y', 'C') THEN
3805                  msc_util.msc_log('Gen_Atp_Pegging :  atp_peg_det.tot_relief_qty(k) ' ||
3806                                                            atp_peg_det.tot_relief_qty(k));
3807                  msc_util.msc_log('Gen_Atp_Pegging :  atp_peg_det.inventory_item_id(k) '
3808                                                    ||   atp_peg_det.inventory_item_id(k));
3809                  msc_util.msc_log('Gen_Atp_Pegging :  atp_peg_det.prev_pegging_id(k) '
3810                                                    ||   atp_peg_det.prev_pegging_id(k));
3811                END IF;
3812              --END LOOP;
3813 
3814            END IF;
3815          END LOOP;  -- j loop for fcst_data_tab
3816       END LOOP;   -- i loop for atp_peg_det
3817 
3818       -- Initialize the Simplified Pegging PL/SQL array
3819 
3820       Init_Atp_Peg ( atp_peg_tab, l_return_status);
3821       IF PG_DEBUG in ('Y', 'C') THEN
3822         msc_util.msc_log('Gen_Atp_Pegging : Initialized Simple Pegging Array ' ||
3823                                                                     l_return_status);
3824       END IF;
3825 
3826       -- Bug 3701093
3827       -- Do the rest of the process only if offset data needs to be generated.
3828       IF G_ADJUST_FLAG = 1 THEN
3829          -- To Calculate_Relief_Quantities first
3830          -- Obtain Simplified Pegging Information
3831          Create_Simple_Pegging (atp_peg_det, atp_peg_tab, l_return_status);
3832          select hsecs
3833          into   l_timestamp
3834          from   v$timer;
3835 
3836          IF PG_DEBUG in ('Y', 'C') THEN
3837            msc_util.msc_log('Gen_Atp_Pegging : Stage 8 After obtaining Simple Pegging ');
3838            msc_util.msc_log('Gen_Atp_Pegging : TIMESTAMP 5 ' || l_timestamp);
3839          END IF;
3840 
3841          -- Calculate and Cascade Relief Quantities
3842          -- will be strictly chronological.
3843          -- Relief will be done by traversing the simplified pegging tree.
3844 
3845          -- Initialize the variables
3846          L_TOT_RELIEF_QTY := NULL;
3847          l_peg_relief_qty := NULL;
3848          FOR i in 1..atp_peg_tab.reference_item_id.COUNT LOOP
3849             -- First relieve the Sales Order
3850             IF (L_TOT_RELIEF_QTY IS NULL) AND
3851                (atp_peg_tab.bom_item_type(i) = 4 AND
3852                 atp_peg_tab.reference_item_id(i) = atp_peg_tab.inventory_item_id(i) AND
3853                 atp_peg_tab.relief_type(i) = 2 AND
3854                 atp_peg_tab.prev_pegging_id(i) IS NULL) THEN
3855                L_TOT_RELIEF_QTY := atp_peg_tab.tot_relief_qty(i);
3856             END IF;
3857             IF (atp_peg_tab.bom_item_type(i) = 4 AND
3858                 atp_peg_tab.reference_item_id(i) = atp_peg_tab.inventory_item_id(i) AND
3859                 atp_peg_tab.relief_type(i) = 1) THEN
3860 
3861              IF PG_DEBUG in ('Y', 'C') THEN
3862                msc_util.msc_log('Gen_Atp_Pegging : reference_item_id ' ||
3863                                              atp_peg_tab.reference_item_id(i) );
3864              END IF;
3865                atp_peg_tab.relief_quantity(i) := 0;
3866 
3867             ELSIF (atp_peg_tab.bom_item_type(i) = 4 AND
3868                 atp_peg_tab.reference_item_id(i) = atp_peg_tab.inventory_item_id(i) AND
3869                 atp_peg_tab.relief_type(i) = 2 AND
3870                 -- Bug 3805136 Do not process excluded supplies
3871                 NVL(atp_peg_tab.exclude_flag(i),0) <> 1 AND
3872                 -- Bug 3761805 Only process the top level pegging in supply chain
3873                 atp_peg_tab.prev_pegging_id(i) IS NULL) THEN
3874 
3875                IF (ABS (L_TOT_RELIEF_QTY ) > 0 ) THEN
3876                  -- Determine the Relief Quantity for this
3877                  -- specific pegging_id.
3878                  IF (ABS (L_TOT_RELIEF_QTY ) >= ABS(atp_peg_tab.allocated_quantity(i)) ) THEN
3879                      l_peg_relief_qty := -1 * ABS(atp_peg_tab.allocated_quantity(i));
3880                  ELSE
3881                      l_peg_relief_qty := L_TOT_RELIEF_QTY;
3882                  END IF;
3883                  -- Start with the planned order corresponding to the sales order
3884                  IF PG_DEBUG in ('Y', 'C') THEN
3885                    msc_util.msc_log('Gen_Atp_Pegging : reference_item_id ' ||
3886                                                 atp_peg_tab.reference_item_id(i) );
3887                    msc_util.msc_log('Gen_Atp_Pegging : Pegging Id ' ||
3888                                              atp_peg_tab.pegging_id(i) );
3889                    msc_util.msc_log('Gen_Atp_Pegging : Prev Pegging Id ' ||
3890                                              atp_peg_tab.prev_pegging_id(i) );
3891                    msc_util.msc_log('Gen_Atp_Pegging : '||
3892                                      'Total Relief Quantity TRACK L_TOT_RELIEF_QTY   ' ||
3893                                              L_TOT_RELIEF_QTY );
3894                    msc_util.msc_log('Gen_Atp_Pegging : '||
3895                                      'Total Relief Quantity for this Pegged Supply  ' ||
3896                                              l_peg_relief_qty );
3897                  END IF;
3898                  Calculate_Relief_Quantities(atp_peg_tab,
3899                           atp_peg_tab.pegging_id(i),
3900                           atp_peg_tab.fixed_lt(i),
3901                           atp_peg_tab.variable_lt(i),
3902                           -- Introduce local peg related relief and ratio.
3903                           atp_peg_tab.tot_relief_qty(i),
3904                           l_peg_relief_qty / atp_peg_tab.tot_relief_qty(i),
3905                           -- Bug 3805136 offset_qty to alloc_qty ratio
3906                           1,
3907                           l_peg_relief_qty,
3908                           atp_peg_tab.end_item_usage(i),
3909                           -- End Bug 3805136
3910                           --atp_peg_tab.tot_relief_qty(i),
3911                           -- Bug 3761805 Pass Config Item Id and END PEG as a parameter
3912                           atp_peg_tab.inventory_item_id(i),
3913                           atp_peg_tab.end_pegging_id(i),
3914                           atp_peg_tab.supply_id(i),
3915                           -- End Bug 3761805
3916                           atp_peg_tab.transaction_date(i),
3917                           l_return_status
3918                           );
3919 
3920                  L_TOT_RELIEF_QTY := L_TOT_RELIEF_QTY - l_peg_relief_qty;
3921                END IF; --  IF (ABS (L_TOT_RELIEF_QTY ) > 0 )
3922 
3923             END IF; -- IF (atp_peg_tab.bom_item_type(i)
3924          END LOOP; -- FOR i in 1..atp_peg_t
3925 
3926           select hsecs
3927           into   l_timestamp
3928           from   v$timer;
3929 
3930          IF PG_DEBUG in ('Y', 'C') THEN
3931            msc_util.msc_log('Gen_Atp_Pegging : Stage 9 After Calculating Reliefs ');
3932            msc_util.msc_log('Gen_Atp_Pegging : TIMESTAMP 6 ' || l_timestamp);
3933          END IF;
3934          -- Generate ATP Resource Pegging.
3935 
3936          Generate_Resource_Pegging (atp_peg_tab, l_return_status);
3937 
3938           select hsecs
3939           into   l_timestamp
3940           from   v$timer;
3941 
3942          IF PG_DEBUG in ('Y', 'C') THEN
3943            msc_util.msc_log('Gen_Atp_Pegging : Stage 10 After Resource Pegging ');
3944            msc_util.msc_log('Gen_Atp_Pegging : TIMESTAMP 7 ' || l_timestamp);
3945          END IF;
3946       END IF;
3947       -- End Bug 3701093
3948 
3949       -- After obtaining all the atp simplified pegging information.
3950 
3951       l_row_count := atp_peg_tab.reference_item_id.COUNT ;
3952       IF PG_DEBUG in ('Y', 'C') THEN
3953            msc_util.msc_log('ATP pegging data will be inserted into ' || l_temp_table);
3954            msc_util.msc_log('Total Records to be inserted ' || l_row_count);
3955       END IF;
3956 
3957       -- Bug 3344102 First insert the data into the global temporary table.
3958 
3959       l_sql_stmt_1 := ' (
3960                        plan_id,
3961                        sr_instance_id,
3962                        reference_item_id,
3963                        inventory_item_id,
3964                        organization_id,
3965                        sales_order_line_id,
3966                        demand_source_type,--cmro
3967                        -- CTO_PF_PRJ changes. use end_demand_id
3968                        end_demand_id,
3969                        bom_item_type,
3970                        sales_order_qty,
3971                        transaction_date,
3972                        demand_id,
3973                        demand_quantity,
3974                        disposition_id,
3975                        demand_class,
3976                        consumed_qty,
3977                        overconsumption_qty,
3978                        supply_id,
3979                        supply_quantity,
3980                        allocated_quantity,
3981                        resource_id,
3982                        department_id,
3983                        resource_hours,
3984                        daily_resource_hours,
3985                        start_date,
3986                        end_date,
3987                        relief_type,
3988                        relief_quantity,
3989                        daily_relief_qty,
3990                        pegging_id,
3991                        prev_pegging_id,
3992                        end_pegging_id,
3993                        created_by,
3994                        creation_date,
3995                        last_updated_by,
3996                        last_update_date )
3997                     VALUES (
3998                        :l_plan_id,
3999                        :l_sr_instance_id,
4000                        :l_reference_item_id,
4001                        :l_inventory_item_id,
4002                        :l_organization_id,
4003                        :l_sales_order_line_id,
4004                        :l_demand_source_type,--cmro
4005                        -- CTO_PF_PRJ changes. use end_demand_id
4006                        :l_end_demand_id,
4007                        :l_bom_item_type,
4008                        :l_ales_order_qty,
4009                        :l_transaction_date,
4010                        :l_demand_id,
4011                        :l_demand_quantity,
4012                        :l_disposition_id,
4013                        :l_demand_class,
4014                        :l_consumed_qty,
4015                        :l_overconsumption_qty,
4016                        :l_supply_id,
4017                        :l_supply_quantity,
4018                        :l_allocated_quantity,
4019                        :l_resource_id,
4020                        :l_department_id,
4021                        :l_resource_hours,
4022                        :l_daily_resource_hours,
4023                        :l_start_date,
4024                        :l_end_date,
4025                        :l_relief_type,
4026                        :l_relief_quantity,
4027                        :l_daily_relief_qty,
4028                        :l_pegging_id,
4029                        :l_prev_pegging_id,
4030                        :l_end_pegging_id,
4031                        :l_user_id,
4032                        :l_sysdate,
4033                        :l_user_id,
4034                        :l_sysdate )';
4035 
4036       l_sql_stmt_2 := ' (
4037                        plan_id,
4038                        sr_instance_id,
4039                        reference_item_id,
4040                        inventory_item_id,
4041                        organization_id,
4042                        sales_order_line_id,
4043                        demand_source_type,--cmro
4044                        -- CTO_PF_PRJ changes. use end_demand_id
4045                        end_demand_id,
4046                        -- CTO-PF
4047                        atf_date,
4048                        product_family_id,
4049                        bom_item_type,
4050                        sales_order_qty,
4051                        transaction_date,
4052                        demand_id,
4053                        demand_quantity,
4054                        disposition_id,
4055                        demand_class,
4056                        consumed_qty,
4057                        overconsumption_qty,
4058                        supply_id,
4059                        supply_quantity,
4060                        allocated_quantity,
4061                        resource_id,
4062                        department_id,
4063                        resource_hours,
4064                        daily_resource_hours,
4065                        start_date,
4066                        end_date,
4067                        relief_type,
4068                        relief_quantity,
4069                        daily_relief_qty,
4070                        pegging_id,
4071                        prev_pegging_id,
4072                        end_pegging_id,
4073                        created_by,
4074                        creation_date,
4075                        last_updated_by,
4076                        last_update_date )
4077                     VALUES (
4078                        :l_plan_id,
4079                        :l_sr_instance_id,
4080                        :l_reference_item_id,
4081                        :l_inventory_item_id,
4082                        :l_organization_id,
4083                        :l_sales_order_line_id,
4084                        :l_demand_source_type,--cmro
4085                        -- CTO_PF_PRJ changes. use end_demand_id
4086                        :l_end_demand_id,
4087                        -- CTO-PF
4088                        :l_atf_date,
4089                        :l_product_family_id,
4090                        :l_bom_item_type,
4091                        :l_ales_order_qty,
4092                        :l_transaction_date,
4093                        :l_demand_id,
4094                        :l_demand_quantity,
4095                        :l_disposition_id,
4096                        :l_demand_class,
4097                        :l_consumed_qty,
4098                        :l_overconsumption_qty,
4099                        :l_supply_id,
4100                        :l_supply_quantity,
4101                        :l_allocated_quantity,
4102                        :l_resource_id,
4103                        :l_department_id,
4104                        :l_resource_hours,
4105                        :l_daily_resource_hours,
4106                        :l_start_date,
4107                        :l_end_date,
4108                        :l_relief_type,
4109                        :l_relief_quantity,
4110                        :l_daily_relief_qty,
4111                        :l_pegging_id,
4112                        :l_prev_pegging_id,
4113                        :l_end_pegging_id,
4114                        :l_user_id,
4115                        :l_sysdate,
4116                        :l_user_id,
4117                        :l_sysdate )';
4118 
4119       FOR i in 1..l_row_count LOOP
4120          IF ( ((G_ALLOC_ATP = 'Y' AND G_CLASS_HRCHY = 1 AND G_ALLOC_METHOD = 1)
4121             -- CTO-PF
4122             OR atp_peg_tab.atf_date(i) is not null )
4123             -- Bug 3701093 Do not store records with relief_quantity 0
4124             -- for relief_types other than 1 i.e., SO.
4125             -- Bug 3761824
4126             AND ( ABS(NVL(atp_peg_tab.relief_quantity(i),0)) > C_ZERO_APPROXIMATOR )
4127             -- Use Zero_Approximator to exclude quantities below 6 levels of precision.
4128             -- End Bug 3761824
4129             AND
4130             atp_peg_tab.relief_type(i) in (2, 3) ) THEN
4131 
4132             l_insert_temp_table := l_global_temp_table;
4133             l_time_phased_atp := 'Y';
4134             l_ins_sql_stmt := 'INSERT INTO '|| l_insert_temp_table || l_sql_stmt_2;
4135 
4136             EXECUTE IMMEDIATE l_ins_sql_stmt USING
4137                    atp_peg_tab.plan_id(i),
4138                    atp_peg_tab.sr_instance_id(i),
4139                    atp_peg_tab.reference_item_id(i),
4140                    atp_peg_tab.inventory_item_id(i),
4141                    atp_peg_tab.organization_id(i),
4142                    atp_peg_tab.sales_order_line_id(i),
4143                    atp_peg_tab.demand_source_type(i),--cmro
4144                    -- CTO_PF_PRJ changes. use end_demand_id
4145                    atp_peg_tab.end_demand_id(i),
4146                    -- CTO-PF
4147                    atp_peg_tab.atf_date(i),
4148                    atp_peg_tab.product_family_id(i),
4149 
4150                    atp_peg_tab.bom_item_type(i),
4151                    atp_peg_tab.sales_order_qty(i),
4152                    atp_peg_tab.transaction_date(i),
4153                    atp_peg_tab.demand_id(i),
4154                    atp_peg_tab.demand_quantity(i),
4155                    atp_peg_tab.disposition_id(i),
4156                    atp_peg_tab.demand_class(i),
4157                    atp_peg_tab.consumed_qty(i),
4158                    atp_peg_tab.overconsumption_qty(i),
4159                    atp_peg_tab.supply_id(i),
4160                    atp_peg_tab.supply_quantity(i),
4161                    atp_peg_tab.allocated_quantity(i),
4162                    atp_peg_tab.resource_id(i),
4163                    atp_peg_tab.department_id(i),
4164                    atp_peg_tab.resource_hours(i),
4165                    atp_peg_tab.daily_resource_hours(i),
4166                    atp_peg_tab.start_date(i),
4167                    atp_peg_tab.end_date(i),
4168                    atp_peg_tab.relief_type(i),
4169                    atp_peg_tab.relief_quantity(i),
4170                    atp_peg_tab.daily_relief_qty(i),
4171                    atp_peg_tab.pegging_id(i),
4172                    atp_peg_tab.prev_pegging_id(i),
4173                    atp_peg_tab.end_pegging_id(i),
4174                    l_user_id,
4175                    l_sysdate,
4176                    l_user_id,
4177                    l_sysdate;
4178 
4179          ELSE
4180            l_insert_temp_table := l_temp_table;
4181            l_ins_sql_stmt := 'INSERT INTO '|| l_insert_temp_table || l_sql_stmt_1;
4182 
4183            -- Bug 3701093 Do not store records with relief_quantity 0
4184            -- for relief_types other than 1 i.e., SO.
4185            IF
4186             -- Bug 3761824
4187              ( ABS(NVL(atp_peg_tab.relief_quantity(i),0)) > C_ZERO_APPROXIMATOR  OR
4188             -- Use Zero_Approximator to exclude quantities below 6 levels of precision.
4189             -- End Bug 3761824
4190                             atp_peg_tab.relief_type(i) = 1) THEN
4191               EXECUTE IMMEDIATE l_ins_sql_stmt USING
4192                    atp_peg_tab.plan_id(i),
4193                    atp_peg_tab.sr_instance_id(i),
4194                    atp_peg_tab.reference_item_id(i),
4195                    atp_peg_tab.inventory_item_id(i),
4196                    atp_peg_tab.organization_id(i),
4197                    atp_peg_tab.sales_order_line_id(i),
4198                    atp_peg_tab.demand_source_type(i),--cmro
4199                    -- CTO_PF_PRJ changes. use end_demand_id
4200                    atp_peg_tab.end_demand_id(i),
4201                    atp_peg_tab.bom_item_type(i),
4202                    atp_peg_tab.sales_order_qty(i),
4203                    atp_peg_tab.transaction_date(i),
4204                    atp_peg_tab.demand_id(i),
4205                    atp_peg_tab.demand_quantity(i),
4206                    atp_peg_tab.disposition_id(i),
4207                    atp_peg_tab.demand_class(i),
4208                    atp_peg_tab.consumed_qty(i),
4209                    atp_peg_tab.overconsumption_qty(i),
4210                    atp_peg_tab.supply_id(i),
4211                    atp_peg_tab.supply_quantity(i),
4212                    atp_peg_tab.allocated_quantity(i),
4213                    atp_peg_tab.resource_id(i),
4214                    atp_peg_tab.department_id(i),
4215                    atp_peg_tab.resource_hours(i),
4216                    atp_peg_tab.daily_resource_hours(i),
4217                    atp_peg_tab.start_date(i),
4218                    atp_peg_tab.end_date(i),
4219                    atp_peg_tab.relief_type(i),
4220                    atp_peg_tab.relief_quantity(i),
4221                    atp_peg_tab.daily_relief_qty(i),
4222                    atp_peg_tab.pegging_id(i),
4223                    atp_peg_tab.prev_pegging_id(i),
4224                    atp_peg_tab.end_pegging_id(i),
4225                    l_user_id,
4226                    l_sysdate,
4227                    l_user_id,
4228                    l_sysdate;
4229            END IF;
4230            -- End Bug 3701093
4231          END IF;
4232          --CTO-PF
4233          IF PG_DEBUG in ('Y', 'C') THEN
4234             msc_util.msc_log('Gen_Atp_Pegging : atf_date ' || atp_peg_tab.atf_date(i));
4235             msc_util.msc_log('Gen_Atp_Pegging : product_family_id ' || atp_peg_tab.product_family_id(i));
4236             msc_util.msc_log('Gen_Atp_Pegging : reference_item_id ' || atp_peg_tab.reference_item_id(i));
4237             msc_util.msc_log('Gen_Atp_Pegging : inventory_item_id ' || atp_peg_tab.inventory_item_id(i));
4238             msc_util.msc_log('Gen_Atp_Pegging : l_time_phased_atp ' || l_time_phased_atp);
4239          END IF;
4240       END LOOP; -- Insert Loop
4241 
4242        IF PG_DEBUG in ('Y', 'C') THEN
4243           msc_util.msc_log('Gen_Atp_Pegging : Rows Procesed ' || SQL%ROWCOUNT );
4244           msc_util.msc_log('Gen_Atp_Pegging : TIMESTAMP 8 ' || l_timestamp);
4245        END IF;
4246       /* commented as a part of CTO-PF
4247       -- Bug 3344102 Second insert the data into the main table.
4248       l_sql_stmt_1 := 'INSERT INTO ' || l_temp_table || '(
4249                        plan_id,
4250                        sr_instance_id,
4251                        reference_item_id,
4252                        inventory_item_id,
4253                        organization_id,
4254                        sales_order_line_id,
4255                        demand_source_type,--cmro
4256                        -- CTO_PF_PRJ changes. use end_demand_id
4257                        end_demand_id,
4258                        bom_item_type,
4259                        sales_order_qty,
4260                        transaction_date,
4261                        demand_id,
4262                        demand_quantity,
4263                        disposition_id,
4264                        demand_class,
4265                        consumed_qty,
4266                        overconsumption_qty,
4267                        supply_id,
4268                        supply_quantity,
4269                        allocated_quantity,
4270                        resource_id,
4271                        department_id,
4272                        resource_hours,
4273                        daily_resource_hours,
4274                        start_date,
4275                        end_date,
4276                        relief_type,
4277                        relief_quantity,
4278                        daily_relief_qty,
4279                        pegging_id,
4280                        prev_pegging_id,
4281                        end_pegging_id,
4282                        created_by,
4283                        creation_date,
4284                        last_updated_by,
4285                        last_update_date )
4286                SELECT
4287                        plan_id,
4288                        sr_instance_id,
4289                        reference_item_id,
4290                        inventory_item_id,
4291                        organization_id,
4292                        sales_order_line_id,
4293                        demand_source_type,--cmro
4294                        -- CTO_PF_PRJ changes. use end_demand_id
4295                        end_demand_id,
4296                        bom_item_type,
4297                        sales_order_qty,
4298                        transaction_date,
4299                        demand_id,
4300                        demand_quantity,
4301                        disposition_id,
4302                        demand_class,
4303                        consumed_qty,
4304                        overconsumption_qty,
4305                        supply_id,
4306                        supply_quantity,
4307                        allocated_quantity,
4308                        resource_id,
4309                        department_id,
4310                        resource_hours,
4311                        daily_resource_hours,
4312                        start_date,
4313                        end_date,
4314                        relief_type,
4315                        relief_quantity,
4316                        daily_relief_qty,
4317                        pegging_id,
4318                        prev_pegging_id,
4319                        end_pegging_id,
4320                        created_by,
4321                        creation_date,
4322                        last_updated_by,
4323                        last_update_date
4324                FROM
4325                        msc_atp_peg_temp
4326                WHERE   plan_id =  :p_plan_id
4327                AND     end_demand_id  = :l_end_demand_id
4328                AND     relief_type in (2, 3)   ';
4329 
4330       IF PG_DEBUG in ('Y', 'C') THEN
4331         msc_util.msc_log('SQL statement to be executed ' || l_sql_stmt_1);
4332       END IF;
4333 
4334       IF l_row_count > 0 THEN
4335          EXECUTE IMMEDIATE l_sql_stmt_1 USING
4336                            p_plan_id,
4337                            atp_peg_tab.end_demand_id(1);
4338       END IF;
4339 
4340       IF PG_DEBUG in ('Y', 'C') THEN
4341           msc_util.msc_log('Gen_Atp_Pegging : Rows Procesed ' || SQL%ROWCOUNT );
4342           msc_util.msc_log('Gen_Atp_Pegging : TIMESTAMP 9 ' || l_timestamp);
4343       END IF;
4344 
4345       -- End Bug 3344102 Secod insert the data into the main table.
4346       */
4347 
4348     END LOOP; -- End config_items loop
4349     -- insert into MSC_ATP_PEG_TEMP_NEW select * from MSC_ATP_PEG_TEMP; --MSC_ATP_PEG_TEMP
4350     -- End Bug 3344102 Call Creation of ATP Pegging Data for Allocated ATP case.
4351     IF  ((G_ALLOC_ATP = 'Y' AND G_CLASS_HRCHY = 1 AND G_ALLOC_METHOD = 1)
4352           AND l_time_phased_atp = 'N') THEN
4353         Create_Pre_Allocation_Reliefs ( p_plan_id,
4354                                         l_temp_table,
4355                                         l_user_id,
4356                                         l_sysdate,
4357                                         l_return_status);
4358     -- CTO-PF start
4359     ELSIF (l_time_phased_atp = 'Y' AND
4360            (G_ALLOC_ATP = 'Y' AND G_CLASS_HRCHY = 1 AND G_ALLOC_METHOD = 1)) THEN
4361 
4362         MSC_ATP_PF.Create_PF_DP_Alloc_Reliefs ( p_plan_id,
4363                                                      l_temp_table,
4364                                                      l_user_id,
4365                                                      l_sysdate,
4366                                                      l_return_status);
4367 
4368     ELSIF (l_time_phased_atp = 'Y') THEN
4369 
4370         MSC_ATP_PF.Create_PF_Allocation_Reliefs ( p_plan_id,
4371                                                   l_temp_table,
4372                                                   l_user_id,
4373                                                   l_sysdate,
4374                                                   l_return_status);
4375 
4376     END IF;
4377     -- CTO-PF end
4378     IF l_return_status <> FND_API.G_RET_STS_SUCCESS THEN
4379        IF PG_DEBUG in ('Y', 'C') THEN
4380            msc_util.msc_log('Gen_Atp_Pegging: ' ||
4381                'Error occured in procedure Create_Pre_Allocation_Reliefs');
4382         END IF;
4383         RAISE FND_API.G_EXC_ERROR;
4384     END IF;
4385     -- End Bug 3344102 After Call to creation of Allocated ATP Pegging Data.
4386 
4387   IF p_share_partition = 'Y' THEN
4388 
4389       IF PG_DEBUG in ('Y', 'C') THEN
4390         msc_util.msc_log('Analyze Plan partition for MSC_ATP_PEGGING');
4391       END IF;
4392         fnd_stats.gather_table_stats(ownname=>l_msc_schema,tabname=>'MSC_ATP_PEGGING',
4393                                    partname=>'ATP_PEGGING_999999',
4394                                    granularity=>'PARTITION',
4395                                    percent =>10);
4396 
4397   ELSE
4398 
4399       -- INDEX CREATION CODE COMES HERE.
4400 
4401       l_sql_stmt := 'CREATE INDEX ' || l_temp_table || '_N1 ON ' || l_temp_table ||
4402                     '(
4403                      Plan_id,
4404                      relief_type,
4405                      sr_instance_id,
4406                      organization_id,
4407                      inventory_item_id,
4408                      Reference_Item_Id,
4409                      -- CTO_PF_PRJ changes use end_demand_id.
4410                      end_demand_id,
4411                      demand_id,
4412                      supply_id,
4413                      resource_id
4414                     )
4415                     STORAGE(INITIAL 40K NEXT 2M PCTINCREASE 0)
4416                      TABLESPACE ' || l_ind_tbspace; --13021736 removed local keyword
4417 
4418       BEGIN
4419         IF PG_DEBUG in ('Y', 'C') THEN
4420            msc_util.msc_log('Before creating index ' || l_temp_table ||
4421                                                 '_N1 for table ');
4422         END IF;
4423            ad_ddl.do_ddl( applsys_schema => p_applsys_schema,
4424                  application_short_name => 'MSC',
4425                  statement_type => AD_DDL.CREATE_INDEX,
4426                  statement => l_sql_stmt,
4427                  object_name => l_temp_table );
4428       END ;
4429       l_sql_stmt := 'CREATE INDEX ' || l_temp_table || '_N2 ON ' || l_temp_table ||
4430                     '(
4431                      Plan_id,
4432                      relief_type,
4433                      sales_order_line_id,
4434                      demand_source_type,
4435                      inventory_item_id,
4436                      demand_id
4437                     )
4438                     STORAGE(INITIAL 40K NEXT 2M PCTINCREASE 0)
4439                      TABLESPACE ' || l_ind_tbspace; --13021736 removed local keyword
4440 
4441       BEGIN
4442         IF PG_DEBUG in ('Y', 'C') THEN
4443            msc_util.msc_log('Before creating index ' || l_temp_table ||
4444                                                 '_N2 for table ');
4445         END IF;
4446            ad_ddl.do_ddl( applsys_schema => p_applsys_schema,
4447                  application_short_name => 'MSC',
4448                  statement_type => AD_DDL.CREATE_INDEX,
4449                  statement => l_sql_stmt,
4450                  object_name => l_temp_table );
4451       END ;
4452       l_sql_stmt := 'CREATE INDEX ' || l_temp_table || '_N3 ON ' || l_temp_table ||
4453                     '(
4454                      Plan_id,
4455                      relief_type,
4456                      sales_order_line_id,
4457                      demand_source_type,
4458                      inventory_item_id,
4459                      supply_id,
4460                      resource_id
4461                     )
4462                     STORAGE(INITIAL 40K NEXT 2M PCTINCREASE 0)
4463                      TABLESPACE ' || l_ind_tbspace; --13021736 removed local keyword
4464 
4465       BEGIN
4466         IF PG_DEBUG in ('Y', 'C') THEN
4467            msc_util.msc_log('Before creating index ' || l_temp_table ||
4468                                                 '_N3 for table ');
4469         END IF;
4470            ad_ddl.do_ddl( applsys_schema => p_applsys_schema,
4471                  application_short_name => 'MSC',
4472                  statement_type => AD_DDL.CREATE_INDEX,
4473                  statement => l_sql_stmt,
4474                  object_name => l_temp_table );
4475       END ;
4476       -- Bug 3629191
4477       l_sql_stmt := 'CREATE INDEX ' || l_temp_table || '_N4 ON ' || l_temp_table ||
4478                     '(
4479                      Plan_id,
4480                      relief_type,
4481                      offset_supply_id
4482                     )
4483                     STORAGE(INITIAL 40K NEXT 2M PCTINCREASE 0)
4484                      TABLESPACE ' || l_ind_tbspace; --13021736 removed local keyword/extra comma
4485 
4486       BEGIN
4487         IF PG_DEBUG in ('Y', 'C') THEN
4488            msc_util.msc_log('Before creating index ' || l_temp_table ||
4489                                                 '_N4 for table ');
4490         END IF;
4491            ad_ddl.do_ddl( applsys_schema => p_applsys_schema,
4492                  application_short_name => 'MSC',
4493                  statement_type => AD_DDL.CREATE_INDEX,
4494                  statement => l_sql_stmt,
4495                  object_name => l_temp_table );
4496       END ;
4497       IF PG_DEBUG in ('Y', 'C') THEN
4498         msc_util.msc_log('Gather Table Stats for MSC_ATP_PEGGING');
4499       END IF;
4500       --13021736 corrected the syntax.
4501 	  fnd_stats.gather_table_stats(ownname     => l_msc_schema,
4502                                    tabname     => 'MSC_ATP_PEGGING',
4503                                    partname    => 'ATP_PEGGING_' || to_char(l_plan_id),
4504                                    granularity => 'ALL'
4505                                    );
4506 
4507 
4508       IF PG_DEBUG in ('Y', 'C') THEN
4509         msc_util.msc_log('swap partition ');
4510       END IF;
4511 
4512       l_sql_stmt := 'ALTER TABLE msc_atp_pegging EXCHANGE PARTITION ' ||
4513                           l_partition_name  ||
4514            ' with table MSC_TEMP_ATP_PEGG_'|| to_char(l_plan_id) ||
4515            ' including indexes without validation';
4516 
4517            BEGIN
4518                IF PG_DEBUG in ('Y', 'C') THEN
4519                    msc_util.msc_log('Before alter table msc_atp_pegging');
4520                END IF;
4521                    ad_ddl.do_ddl(APPLSYS_SCHEMA => p_applsys_schema,
4522                    APPLICATION_SHORT_NAME => 'MSC',
4523                    STATEMENT_TYPE => ad_ddl.alter_table,
4524                    STATEMENT => l_sql_stmt,
4525                    OBJECT_NAME => 'MSC_ATP_PEGGING');
4526            END;
4527 
4528   END IF;  -- p_share_partition = 'Y'
4529 
4530 EXCEPTION
4531     WHEN OTHERS THEN
4532       IF PG_DEBUG in ('Y', 'C') THEN
4533         msc_util.msc_log ('Generate_Simplified_Pegging. Error : ' || sqlcode || ': ' || sqlerrm);
4534       END IF;
4535       RETCODE := G_ERROR;
4536 
4537 END Generate_Simplified_Pegging;
4538 
4539 
4540 PROCEDURE post_plan_pegging(
4541         ERRBUF          OUT     NoCopy VARCHAR2,
4542         RETCODE         OUT     NoCopy NUMBER,
4543         p_plan_id       IN      NUMBER)
4544 IS
4545 
4546    l_share_partition               VARCHAR2(1);
4547    l_summary_flag                  NUMBER;
4548    l_plan_name                     VARCHAR2(10);
4549    l_retval                        BOOLEAN;
4550    l_applsys_schema                VARCHAR2(10);
4551    dummy1                          VARCHAR2(10);
4552    dummy2                          VARCHAR2(10);
4553    l_ret_code                      NUMBER;
4554 
4555    l_return_status                 VARCHAR2(40);
4556    l_session_id                    NUMBER;
4557    l_log_file                      VARCHAR2(255);
4558 
4559 BEGIN
4560 
4561     msc_util.msc_log('Begin procedure post_plan_pegging');
4562 
4563     RETCODE := G_SUCCESS;
4564 
4565 
4566     l_share_partition := fnd_profile.value('MSC_SHARE_PARTITIONS');
4567 
4568     msc_util.msc_log('l_share_partition := ' || l_share_partition);
4569 
4570     SELECT NVL(summary_flag,1), compile_designator
4571     INTO   l_summary_flag, l_plan_name
4572     FROM   msc_plans
4573     WHERE  plan_id = p_plan_id;
4574 
4575     IF NVL(l_summary_flag,1) NOT IN
4576             (MSC_POST_PRO.G_SF_SUMMARY_NOT_RUN,
4577              MSC_POST_PRO.G_SF_PREALLOC_COMPLETED,
4578              MSC_POST_PRO.G_SF_SYNC_SUCCESS,
4579              MSC_POST_PRO.G_SF_SUMMARY_COMPLETED,
4580              MSC_POST_PRO.G_SF_ATPPEG_COMPLETED) THEN
4581        msc_util.msc_log('Another session is running post-plan allocation program for this plan');
4582        RETCODE :=  G_ERROR;
4583        RETURN;
4584     END IF;
4585 
4586     -- Bug 3344102 Set Alloc Related Global Variables.
4587     G_ALLOC_ATP := NVL(FND_PROFILE.value('MSC_ALLOCATED_ATP'),'N');
4588     G_CLASS_HRCHY := NVL(FND_PROFILE.VALUE('MSC_CLASS_HIERARCHY'), 2);
4589     G_ALLOC_METHOD := NVL(FND_PROFILE.VALUE('MSC_ALLOCATION_METHOD'), 2);
4590 
4591     msc_util.msc_log('G_ALLOC_ATP    := ' || G_ALLOC_ATP);
4592     msc_util.msc_log('G_CLASS_HRCHY  := ' || G_CLASS_HRCHY);
4593     msc_util.msc_log('G_ALLOC_METHOD := ' || G_ALLOC_METHOD);
4594     -- End Bug 3344102
4595 
4596     msc_util.msc_log('Deleting Existing ATP Pegging data for plan : ' || p_plan_id);
4597 
4598     IF l_share_partition = 'Y' THEN
4599       DELETE from msc_atp_pegging
4600       where  plan_id = p_plan_id;
4601 
4602       IF PG_DEBUG in ('Y', 'C') THEN
4603         msc_util.msc_log ('Post_Plan_Pegging:  Number of rows deleted '|| SQL%ROWCOUNT);
4604       END IF;
4605     END IF;
4606 
4607     l_retval := FND_INSTALLATION.GET_APP_INFO('FND', dummy1, dummy2, l_applsys_schema);
4608 
4609     -- Update summary flag to signify begining of pegging generation
4610     Update_Summary_Flag (   p_plan_id,
4611                             MSC_POST_PRO.G_SF_ATPPEG_RUNNING,
4612                             l_return_status);
4613     IF l_return_status <> FND_API.G_RET_STS_SUCCESS THEN
4614        IF PG_DEBUG in ('Y', 'C') THEN
4615            msc_util.msc_log('Post_Plan_Pegging: ' ||
4616                'Error occured in procedure Update_Summary_Flag');
4617         END IF;
4618         RAISE FND_API.G_EXC_ERROR;
4619     END IF;
4620     BEGIN
4621        IF fnd_global.conc_request_id > 0  THEN
4622           select logfile_name
4623           into   l_log_file
4624           from   fnd_concurrent_requests
4625           where request_id = fnd_global.conc_request_id;
4626          msc_util.msc_log('LOG FILE is: ' || l_log_file);
4627        ELSE
4628          BEGIN
4629             SELECT mrp_atp_schedule_temp_s.currval
4630             INTO   l_session_id
4631             FROM   dual;
4632          EXCEPTION
4633             WHEN OTHERS THEN
4634               SELECT mrp_atp_schedule_temp_s.nextval
4635               INTO   l_session_id
4636               FROM   dual;
4637               order_sch_wb.debug_session_id := l_session_id;
4638          END;
4639 
4640          msc_util.msc_log('Setting ATP Session ID : ' || l_session_id);
4641          msc_util.msc_log('LOG FILE is: session-' || l_session_id);
4642        END IF;
4643 
4644        IF PG_DEBUG in ('Y', 'C') THEN
4645 
4646          msc_util.msc_log('Calling Generate_Simplified_Pegging ' );
4647        END IF;
4648 
4649        MSC_ATP_PEG.Generate_Simplified_Pegging(p_plan_id, l_share_partition,
4650                                                  l_applsys_schema, l_ret_code);
4651        IF PG_DEBUG in ('Y', 'C') THEN
4652          msc_util.msc_log('After Call to Generate_Simplified_Pegging ' );
4653          msc_util.msc_log('Return Code is := ' || l_ret_code);
4654        END IF;
4655        --IF l_ret_code = G_ERROR THEN
4656        --      RETCODE := G_WARNING;  -- For now we are treating this as a warning
4657        --END IF;
4658        --13021736 start Since procedure Generate_Simplified_Pegging is having exception block
4659        -- of when others so if error comes from this procedure we need to set the
4660        --RETCODE as we will not go inside this exception.
4661        IF l_ret_code = G_ERROR THEN
4662           RETCODE := G_ERROR;
4663        END IF;
4664        --13021736 end
4665 
4666     EXCEPTION
4667         WHEN OTHERS THEN
4668 
4669           IF PG_DEBUG in ('Y', 'C') THEN
4670             msc_util.msc_log('ERROR IN  Generate_Simplified_Pegging ' );
4671             msc_util.msc_log('ERROR: ' || to_char(SQLCODE));
4672             msc_util.msc_log('ERROR: ' || sqlerrm);
4673           END IF;
4674           RETCODE := G_ERROR;
4675           ERRBUF  := sqlerrm;
4676     END;
4677     -- Update summary flag to signify end of pegging generation
4678     Update_Summary_Flag (   p_plan_id,
4679                             MSC_POST_PRO.G_SF_ATPPEG_COMPLETED,
4680                             l_return_status);
4681     IF l_return_status <> FND_API.G_RET_STS_SUCCESS THEN
4682        IF PG_DEBUG in ('Y', 'C') THEN
4683            msc_util.msc_log('Post_Plan_Pegging: ' ||
4684                'Error occured in procedure Update_Summary_Flag');
4685         END IF;
4686         RAISE FND_API.G_EXC_ERROR;
4687     END IF;
4688 EXCEPTION
4689     WHEN OTHERS THEN
4690       Update_Summary_Flag (   p_plan_id,
4691                             NVL(l_summary_flag, 1),
4692                             l_return_status);
4693 
4694       IF l_return_status <> FND_API.G_RET_STS_SUCCESS THEN
4695          IF PG_DEBUG in ('Y', 'C') THEN
4696              msc_util.msc_log('Post_Plan_Pegging: ' ||
4697                  'Error occured in procedure Update_Summary_Flag');
4698           END IF;
4699       END IF;
4700 
4701       IF PG_DEBUG in ('Y', 'C') THEN
4702         msc_util.msc_log ('post_plan_pegging. Error : ' || sqlerrm);
4703       END IF;
4704       ERRBUF := sqlerrm;
4705       RETCODE := G_ERROR;
4706 
4707 END post_plan_pegging;
4708 
4709 PROCEDURE Add_Offset_Demands (
4710                      p_identifier                      IN NUMBER,
4711                      p_config_line_id                  IN NUMBER,
4712                      p_plan_id                         IN NUMBER,
4713                      p_refresh_number                  IN NUMBER,
4714                      p_order_number                    IN NUMBER,
4715                      p_demand_source_type              IN NUMBER,--cmro
4716                      x_inv_item_id                     IN OUT NoCopy MRP_ATP_PUB.Number_Arr,
4717                      x_demand_id                       IN OUT NoCopy MRP_ATP_PUB.Number_Arr,
4718                      x_demand_instance_id              OUT NoCopy MRP_ATP_PUB.Number_Arr, --Bug 3629191
4719                      x_return_status                   IN OUT NoCopy VARCHAR2
4720                      )
4721 IS
4722     l_del_rows                  NUMBER;
4723     i                           PLS_INTEGER;
4724     my_sqlcode                  NUMBER;
4725 
4726     l_demand_id                 MRP_ATP_PUB.Number_Arr := MRP_ATP_PUB.Number_Arr();
4727     l_demand_qty                MRP_ATP_PUB.Number_Arr := MRP_ATP_PUB.Number_Arr();
4728     l_demand_date               MRP_ATP_PUB.date_arr := MRP_ATP_PUB.date_arr();
4729     l_reference_item_id         MRP_ATP_PUB.Number_Arr := MRP_ATP_PUB.Number_Arr();
4730     l_instance_id               MRP_ATP_PUB.Number_Arr := MRP_ATP_PUB.Number_Arr();
4731     l_organization_id           MRP_ATP_PUB.Number_Arr := MRP_ATP_PUB.Number_Arr();
4732     l_inventory_item_id         MRP_ATP_PUB.Number_Arr := MRP_ATP_PUB.Number_Arr();
4733     l_demand_class              MRP_ATP_PUB.char30_arr := MRP_ATP_PUB.char30_arr();
4734     l_customer_id               MRP_ATP_PUB.Number_Arr := MRP_ATP_PUB.Number_Arr();
4735     l_customer_site_id          MRP_ATP_PUB.Number_Arr := MRP_ATP_PUB.Number_Arr();
4736     l_ship_to_site_id           MRP_ATP_PUB.Number_Arr := MRP_ATP_PUB.Number_Arr();
4737     l_dmd_satisfied_date        MRP_ATP_PUB.date_arr := MRP_ATP_PUB.date_arr();
4738 
4739     l_offset_demand_id          MRP_ATP_PUB.Number_Arr := MRP_ATP_PUB.Number_Arr();
4740     -- Bug 3890723 Introduce a pegging_id array to track pegging
4741     -- For filtering out released/firmed supplies instead of disposition_id array.
4742     l_disposition_id            MRP_ATP_PUB.Number_Arr := MRP_ATP_PUB.Number_Arr(); -- Array retained as FYI for demand offsets.
4743     l_pegging_id                MRP_ATP_PUB.Number_Arr := MRP_ATP_PUB.Number_Arr();
4744     -- End Bug 3890723
4745 
4746     l_sysdate                   DATE;
4747     l_user_id                   number;
4748     l_so_line_ids               MRP_ATP_PUB.Number_Arr := MRP_ATP_PUB.Number_Arr();
4749 
4750     -- Bug 3344102 A variable/handle for processing reliefs/offsets.
4751     l_offset_type               NUMBER;
4752     -- CTO_PF_PRJ_2 Impacts
4753     l_supply_id                 MRP_ATP_PUB.Number_Arr := MRP_ATP_PUB.Number_Arr();
4754     l_original_item_id          MRP_ATP_PUB.Number_Arr := MRP_ATP_PUB.Number_Arr();
4755     l_original_demand_date      MRP_ATP_PUB.date_arr := MRP_ATP_PUB.date_arr();
4756     -- End CTO_PF_PRJ_2 Impacts
4757     -- Bug 3717618 Add supply offset type var. for limiting adjustment to demands
4758     -- that are pegged to supplies that can be relieved.
4759     l_sup_offset_type        NUMBER;
4760 BEGIN
4761 
4762   IF PG_DEBUG in ('Y', 'C') THEN
4763      msc_sch_wb.atp_debug('***** Begin Add_Offset_Demands *****');
4764   END IF;
4765 
4766   IF PG_DEBUG in ('Y', 'C') THEN
4767      msc_sch_wb.atp_debug('Add_Offset_Demands: ' ||
4768                           'Offsetting msc_demands for identifier = '
4769                           || p_identifier ||' : plan id = '||p_plan_id);
4770      msc_sch_wb.atp_debug('Add_Offset_Demands: ' || 'Config Line Id = ' || p_config_line_id );
4771   END IF;
4772 
4773   x_return_status := FND_API.G_RET_STS_SUCCESS;
4774 
4775   l_sysdate := sysdate;
4776   l_user_id := FND_GLOBAL.USER_ID;
4777 
4778   -- CTO_PF_PRJ_2 Impacts
4779   IF ((MSC_ATP_PVT.G_INV_CTP = 4) AND
4780       (MSC_ATP_PVT.G_ALLOCATED_ATP = 'Y') AND
4781       (MSC_ATP_PVT.G_HIERARCHY_PROFILE = 1) AND
4782       (MSC_ATP_PVT.G_ALLOCATION_METHOD = 1)) THEN
4783 
4784      l_offset_type := 5;
4785      -- Bug 3717618 Set value of supply relief type.
4786      l_sup_offset_type := 6;
4787   ELSE
4788      l_offset_type := 3;
4789      -- Bug 3717618 Set value of supply relief type.
4790      l_sup_offset_type := 2;
4791   END IF;
4792   -- CTO_PF_PRJ_2 Impacts
4793 
4794   IF PG_DEBUG in ('Y', 'C') THEN
4795       msc_sch_wb.atp_debug('Add_Offset_Demands: Dmd. Offset Type Set to '|| l_offset_type);
4796       -- Bug 3717618 Set value of supply relief type.
4797       msc_sch_wb.atp_debug('Add_Offset_Demands: Sup. Offset Type Set to '|| l_sup_offset_type);
4798   END IF;
4799 
4800   -- CTO_PF_PRJ_2 Impacts
4801   SELECT msc_demands_s.nextval ,
4802          map.relief_quantity   ,
4803          NVL(map.original_date, map.transaction_date) transaction_date ,
4804          -- End CTO_PF_PRJ_2 Impacts
4805          map.reference_item_id,
4806          map.sr_instance_id,
4807          map.organization_id,
4808          -- CTO_PF_PRJ_2 Impacts
4809          NVL(map.original_item_id, map.inventory_item_id) inventory_item_id,
4810          -- End CTO_PF_PRJ_2 Impacts
4811          map.demand_class,
4812          d.customer_id,
4813          d.customer_site_id,
4814          d.ship_to_site_id,
4815          d.dmd_satisfied_date,
4816          -- Bug 3890723 Introduce a pegging_id array to track pegging
4817          -- For filtering out released/firmed supplies instead of disposition_id array.
4818          map.disposition_id,
4819          map.prev_pegging_id,
4820          -- End Bug 3890723
4821          map.demand_id,
4822          map.sales_order_line_id,
4823          -- CTO_PF_PRJ Impacts
4824          NVL(map.supply_id, -1) supply_id,
4825          map.ORIGINAL_ITEM_ID,
4826          map.ORIGINAL_DATE
4827          -- End CTO_PF_PRJ Impacts
4828   BULK COLLECT
4829   INTO   x_demand_id,
4830          l_demand_qty,
4831          l_demand_date,
4832          l_reference_item_id,
4833          l_instance_id, -- Bug 3629191, Return it as out parameter
4834          l_organization_id,
4835          x_inv_item_id,
4836          l_demand_class,
4837          l_customer_id,
4838          l_customer_site_id,
4839          l_ship_to_site_id,
4840          l_dmd_satisfied_date,
4841          -- Bug 3890723 Introduce a pegging_id array to track pegging
4842          -- For filtering out released/firmed supplies instead of disposition_id array.
4843          l_disposition_id, -- Array retained as FYI for demand offsets.
4844          l_pegging_id,
4845          -- End Bug 3890723
4846          l_offset_demand_id,
4847          l_so_line_ids,
4848          -- CTO_PF_PRJ Impacts
4849          l_supply_id,
4850          l_original_item_id,
4851          l_original_demand_date
4852          -- End CTO_PF_PRJ Impacts
4853   FROM
4854          msc_atp_pegging map,
4855          msc_demands d
4856   WHERE  map.plan_id = p_plan_id
4857   --AND  map.sr_instance_id = p_instance_id  -- removed to support multiple instances in plan.
4858   AND    map.sales_order_line_id in (p_identifier, p_config_line_id)
4859          -- CTO_PF_PRJ_2 Impacts
4860   AND    map.relief_type in (decode(map.offset_type,1,5,3), 7)  --l_offset_type POD
4861          -- End CTO_PF_PRJ_2 Impacts
4862   -- Bug 3890723 Use only pegging_id as a filter
4863   -- ATP created transactions will not have disposition_id populated.
4864   -- Bug 3717618 Only offset demands pegged to supplies that are relieved
4865   -- using filter on disposition_id
4866   -- AND    (map.disposition_id, map.prev_pegging_id) IN
4867   AND    (map.prev_pegging_id) IN
4868          (SELECT map2.pegging_id
4869   -- End Bug 3890723
4870           FROM   msc_atp_pegging map2
4871           WHERE  map2.plan_id = p_plan_id
4872           AND    map2.sales_order_line_id in (p_identifier, p_config_line_id)
4873           AND    DECODE(map2.demand_source_type,100,map2.demand_source_type,-1)
4874                   =decode(p_demand_source_type,
4875                                            100,
4876                                             p_demand_source_type,
4877                                            -1) --CMRO
4878           AND    map2.offset_supply_id IS NOT NULL
4879           AND    map2.relief_type = decode(map2.offset_type,1,6,2) --l_sup_offset_type
4880          )
4881   -- End Bug 3717618
4882   AND    ABS(map.relief_quantity) > C_ZERO_APPROXIMATOR
4883   -- Bug 3761824 Use Precision figure while creating ofsets.
4884   AND    DECODE(d.demand_source_type,100,d.demand_source_type,-1)
4885                =decode(p_demand_source_type,
4886                                            100,
4887                                             p_demand_source_type,
4888                                            -1) --CMRO
4889   AND    d.plan_id (+) = map.plan_id
4890   AND    d.organization_id (+) = map.organization_id
4891   AND    d.demand_id (+) = map.demand_id
4892   AND    d.inventory_item_id (+) = map.inventory_item_id
4893   ;
4894   -- End CTO_PF_PRJ_2 Impacts
4895 
4896   x_demand_instance_id := l_instance_id; --Bug 3629191
4897 
4898   l_del_rows := x_demand_id.COUNT;
4899 
4900   FORALL i in 1..l_del_rows
4901      INSERT INTO msc_demands (
4902                  DEMAND_ID,
4903                  USING_REQUIREMENT_QUANTITY,
4904                  USING_ASSEMBLY_DEMAND_DATE,
4905                  DEMAND_TYPE,
4906                  ORIGINATION_TYPE,
4907                  USING_ASSEMBLY_ITEM_ID,
4908                  PLAN_ID,
4909                  ORGANIZATION_ID,
4910                  INVENTORY_ITEM_ID,
4911                  DEMAND_SOURCE_TYPE,--cmro
4912                  SALES_ORDER_LINE_ID,
4913                  SR_INSTANCE_ID,
4914                  LAST_UPDATE_DATE,
4915                  LAST_UPDATED_BY,
4916                  CREATION_DATE,
4917                  CREATED_BY,
4918                  DEMAND_CLASS,
4919                  REFRESH_NUMBER,
4920                  ORDER_NUMBER,
4921                  CUSTOMER_ID,
4922                  CUSTOMER_SITE_ID,
4923                  SHIP_TO_SITE_ID,
4924                  RECORD_SOURCE,  -- For plan order pegging
4925                  -- 24x7
4926                  ATP_SYNCHRONIZATION_FLAG,
4927                  DMD_SATISFIED_DATE,
4928                  DISPOSITION_ID
4929              --    ,OFFSET_DEMAND_ID
4930                  )
4931          VALUES (x_demand_id(i),
4932                  l_demand_qty(i),
4933                  --bug 3328421: Add at the end of the day
4934                  trunc(l_demand_date(i)) + MSC_ATP_PVT.G_END_OF_DAY ,
4935                  --l_demand_date(i),
4936                  1 ,   -- discrete demand
4937                  60,  -- offset demand
4938                  l_reference_item_id(i),  -- inventory_item_id
4939                  p_plan_id,
4940                  l_organization_id(i),
4941                  x_inv_item_id(i),
4942                  p_demand_source_type,--cmro
4943                  l_so_line_ids(i),
4944                  l_instance_id(i),
4945                  l_sysdate,
4946                  l_user_id,
4947                  l_sysdate,
4948                  l_user_id,
4949                  l_demand_class(i),
4950                  p_refresh_number,
4951                  p_order_number,
4952                  l_customer_id(i),
4953                  l_customer_site_id(i),
4954                  l_ship_to_site_id(i),
4955                  2,
4956                  0,
4957                  l_dmd_satisfied_date(i),
4958                  l_disposition_id(i)
4959                --  ,l_offset_demand_id(i)
4960                 );
4961 
4962       IF PG_DEBUG in ('Y', 'C') THEN
4963              msc_sch_wb.atp_debug('Add_Offset_Demands:  Number of rows inserted '||
4964                                SQL%ROWCOUNT);
4965       END IF;
4966 
4967       -- Allocated ATP Based on Planning Details
4968 
4969       IF ((MSC_ATP_PVT.G_INV_CTP = 4) AND
4970           (MSC_ATP_PVT.G_ALLOCATED_ATP = 'Y') AND
4971           (MSC_ATP_PVT.G_HIERARCHY_PROFILE = 1) AND
4972           (MSC_ATP_PVT.G_ALLOCATION_METHOD = 1)) THEN
4973 
4974          IF PG_DEBUG in ('Y', 'C') THEN
4975              msc_sch_wb.atp_debug('Add_Offset_Demands: before insert into'||
4976                                ' msc_alloc_demands');
4977          END IF;
4978 
4979          -- CTO_PF_PRJ2 relief_type already set above.
4980          -- Bug 3344102 First set offset type to 5  for alloc reliefs.
4981          -- l_offset_type := 5;
4982          -- CTO_PF_PRJ2
4983 
4984          -- Try to apply the offsets using alloc specific relief_type.
4985 
4986          FORALL i in 1..x_demand_id.COUNT
4987            INSERT INTO MSC_ALLOC_DEMANDS(
4988                        PLAN_ID,
4989                        INVENTORY_ITEM_ID,
4990                        ORGANIZATION_ID,
4991                        SR_INSTANCE_ID,
4992                        DEMAND_CLASS,
4993                        DEMAND_DATE,
4994                        PARENT_DEMAND_ID,
4995                        ALLOCATED_QUANTITY,
4996                        ORIGINATION_TYPE,
4997                        ORDER_NUMBER,
4998                        DEMAND_SOURCE_TYPE,--cmro
4999                        SALES_ORDER_LINE_ID,
5000                        CREATED_BY,
5001                        CREATION_DATE,
5002                        LAST_UPDATED_BY,
5003                        LAST_UPDATE_DATE,
5004                        refresh_number,
5005                        -- CTO_PF_PRJ_2 Impacts
5006                        ORIGINAL_ITEM_ID,
5007                        ORIGINAL_DEMAND_DATE,
5008                        ORIGINAL_ORIGINATION_TYPE,
5009                        PF_DISPLAY_FLAG
5010                        -- END CTO_PF_PRJ_2 Impacts
5011                        )
5012            SELECT
5013                    map.plan_id,
5014                    map.inventory_item_id,
5015                    map.organization_id,
5016                    map.sr_instance_id,
5017                    map.demand_class,
5018                    map.transaction_date,
5019                    x_demand_id(i),
5020                    NVL(map.relief_quantity, 0),
5021                    Decode(map.relief_type, 7, 51, 60),
5022                    --60,
5023                    p_order_number,
5024                    p_demand_source_type,--cmro
5025                    map.sales_order_line_id,
5026                    l_user_id,
5027                    l_sysdate,
5028                    l_user_id,
5029                    l_sysdate,
5030                    p_refresh_number,
5031                    -- CTO_PF_PRJ_2 Impacts
5032                    l_original_item_id(i),
5033                    l_original_demand_date(i),
5034                    Decode(map.relief_type, 7, 60, NULL),
5035                    --Decode(map.relief_type, 7, 51, 60),
5036                    Decode(map.relief_type, 7, 1, NULL)
5037                    -- pf_display_flag = 1 when offseting bucketed demand.
5038                    -- NULL will be the default value.
5039                    -- END CTO_PF_PRJ_2 Impacts
5040            FROM    msc_atp_pegging map
5041            WHERE   map.sr_instance_id = l_instance_id(i)
5042            AND     map.plan_id = p_plan_id
5043            AND     DECODE(map.demand_source_type,100,map.demand_source_type,-1)
5044                    =decode(p_demand_source_type,
5045                                                 100,
5046                                                 p_demand_source_type,
5047                                                 -1) --CMRO
5048            AND     map.sales_order_line_id in (p_identifier, p_config_line_id)
5049            AND     map.relief_type in (decode(map.offset_type,1,5,3),  7)  -- POD
5050            AND     NVL(map.original_item_id, map.inventory_item_id) =
5051                                NVL(l_original_item_id(i), x_inv_item_id(i))
5052            AND     map.relief_quantity = l_demand_qty(i)
5053            AND     NVL(map.original_date, l_sysdate) = NVL(l_original_demand_date(i), l_sysdate)
5054            -- FOR ATP created records only relieve PF, do not offset other demands
5055            -- as they are set to 0 already in Delete_Row.
5056            AND     NVL(map.supply_id,  100) = l_supply_id(i)
5057            --AND     NVL(map.supply_id, DECODE(map.relief_type, 7, -1, 100)) = l_supply_id(i)
5058            -- Bug 3890723 Use  pegging_id array to track pegging
5059            -- For filtering out released/firmed supplies instead of disposition_id array.
5060            -- Bug 3717618 Only offset demands pegged to supplies that are relieved
5061            -- using filter on disposition_id
5062            -- AND     map.disposition_id = l_disposition_id(i)
5063            AND     map.prev_pegging_id = l_pegging_id(i)
5064            -- End Bug 3890723
5065            AND     map.demand_id = l_offset_demand_id(i);
5066 
5067            FOR i in 1..x_demand_id.COUNT LOOP
5068               msc_sch_wb.atp_debug('Demand to be offset ' || l_offset_demand_id(i));
5069               msc_sch_wb.atp_debug('Original Item ' || l_original_item_id(i));
5070               msc_sch_wb.atp_debug('Actual Item ' || x_inv_item_id(i));
5071               msc_sch_wb.atp_debug('Original Date ' || l_original_demand_date(i));
5072               msc_sch_wb.atp_debug('Supply ID ' || l_supply_id(i));
5073               msc_sch_wb.atp_debug('New Demand ' || x_demand_id(i));
5074               msc_sch_wb.atp_debug('Add_Offset_Demands:  Number of Family rows inserted '||
5075                   'For Demand id '|| l_offset_demand_id(i) ||
5076                   ' with offset/relief_type 5 or 7 is ' || SQL%BULK_ROWCOUNT(i));
5077            END LOOP;
5078          IF PG_DEBUG in ('Y', 'C') THEN
5079                 msc_sch_wb.atp_debug('Add_Offset_Demands:  Number of Family and Alloc rows inserted '||
5080                       'with offset/relief_type = 7 or ' ||l_offset_type || 'is ' || SQL%ROWCOUNT);
5081          END IF;
5082 
5083          -- CTO_PF_PRJ_2
5084          -- Cascading SQLs no longer necessary
5085          --IF SQL%ROWCOUNT = 0 THEN
5086 
5087            -- Apply using standard demands relief_type
5088 
5089 
5090          -- END IF;
5091          -- End Bug 3344102
5092          -- END CTO_PF_PRJ_2
5093 
5094            IF PG_DEBUG in ('Y', 'C') THEN
5095                 msc_sch_wb.atp_debug('Add_Offset_Demands:  adjust stealing supplies');
5096                 msc_sch_wb.atp_debug(' Number of SO lines to be adjusted := ' || l_so_line_ids.count);
5097                 For i in 1..l_so_line_ids.count LOOP
5098                    msc_sch_wb.atp_debug('Line id # ' || i || ' := ' || l_so_line_ids(i));
5099                 END LOOP;
5100 
5101            END IF;
5102 
5103            ---update records due to supply/demand stealing
5104            IF l_so_line_ids.count > 0 THEN
5105               update msc_alloc_supplies
5106               set allocated_quantity = 0
5107               where plan_id = p_plan_id
5108               and   sr_instance_id = l_instance_id(1)
5109               and   ato_model_line_id  = p_identifier
5110               and     DECODE(demand_source_type,100,demand_source_type,-1)
5111                       =decode(p_demand_source_type,
5112                                                 100,
5113                                                 p_demand_source_type,
5114                                                 -1) --CMRO;
5115               and   order_type in (46, 47);
5116            END IF;
5117            IF PG_DEBUG in ('Y', 'C') THEN
5118                 msc_sch_wb.atp_debug('Add_Offset_Demands:  Number of stealing rows updated '||
5119                                SQL%ROWCOUNT);
5120            END IF;
5121 
5122       -- Offset Product Family Demands if any
5123       ELSE
5124          -- Try to apply the offsets using alloc specific relief_type.
5125 
5126          FORALL i in 1..x_demand_id.COUNT
5127            INSERT INTO MSC_ALLOC_DEMANDS(
5128                        PLAN_ID,
5129                        INVENTORY_ITEM_ID,
5130                        ORGANIZATION_ID,
5131                        SR_INSTANCE_ID,
5132                        DEMAND_CLASS,
5133                        DEMAND_DATE,
5134                        PARENT_DEMAND_ID,
5135                        ALLOCATED_QUANTITY,
5136                        ORIGINATION_TYPE,
5137                        ORDER_NUMBER,
5138                        DEMAND_SOURCE_TYPE,--cmro
5139                        SALES_ORDER_LINE_ID,
5140                        CREATED_BY,
5141                        CREATION_DATE,
5142                        LAST_UPDATED_BY,
5143                        LAST_UPDATE_DATE,
5144                        refresh_number,
5145                        -- CTO_PF_PRJ_2 Impacts
5146                        ORIGINAL_ITEM_ID,
5147                        ORIGINAL_DEMAND_DATE,
5148                        ORIGINAL_ORIGINATION_TYPE,
5149                        PF_DISPLAY_FLAG
5150                        -- END CTO_PF_PRJ_2 Impacts
5151                        )
5152            SELECT
5153                    map.plan_id,
5154                    map.inventory_item_id,
5155                    map.organization_id,
5156                    map.sr_instance_id,
5157                    map.demand_class,
5158                    map.transaction_date,
5159                    x_demand_id(i),
5160                    NVL(map.relief_quantity, 0),
5161                    Decode(map.relief_type, 7, 51, 60),
5162                    --60,
5163                    p_order_number,
5164                    p_demand_source_type,--cmro
5165                    map.sales_order_line_id,
5166                    l_user_id,
5167                    l_sysdate,
5168                    l_user_id,
5169                    l_sysdate,
5170                    p_refresh_number,
5171                    -- CTO_PF_PRJ_2 Impacts
5172                    l_original_item_id(i),
5173                    l_original_demand_date(i),
5174                    Decode(map.relief_type, 7, 60, NULL),
5175                    --Decode(map.relief_type, 7, 51, 60),
5176                    1  -- Always 1 for PF.
5177                    -- END CTO_PF_PRJ_2 Impacts
5178            FROM    msc_atp_pegging map
5179            WHERE   map.sr_instance_id = l_instance_id(i)
5180            AND     map.plan_id = p_plan_id
5181            AND     DECODE(map.demand_source_type,100,map.demand_source_type,-1)
5182                    =decode(p_demand_source_type,
5183                                                 100,
5184                                                 p_demand_source_type,
5185                                                 -1) --CMRO
5186            AND     map.sales_order_line_id in (p_identifier, p_config_line_id)
5187            AND     map.relief_type = 7   -- POD for family item.
5188            AND     NVL(map.original_item_id, map.inventory_item_id) =
5189                                NVL(l_original_item_id(i), x_inv_item_id(i))
5190            AND     map.relief_quantity = l_demand_qty(i)
5191            AND     NVL(map.original_date, l_sysdate) = NVL(l_original_demand_date(i), l_sysdate)
5192            AND     NVL(map.supply_id, -1) = l_supply_id(i)
5193            -- Bug 3890723 Use  pegging_id array to track pegging
5194            -- For filtering out released/firmed supplies instead of disposition_id array.
5195            -- Bug 3717618 Only offset demands pegged to supplies that are relieved
5196            -- using filter on disposition_id
5197            -- AND     map.disposition_id = l_disposition_id(i)
5198            AND     map.prev_pegging_id = l_pegging_id(i)
5199            -- End Bug 3890723
5200            AND     map.demand_id = l_offset_demand_id(i);
5201 
5202          IF PG_DEBUG in ('Y', 'C') THEN
5203            FOR i in 1..x_demand_id.COUNT LOOP
5204               msc_sch_wb.atp_debug('Demand to be offset ' || l_offset_demand_id(i));
5205               msc_sch_wb.atp_debug('Original Item ' || l_original_item_id(i));
5206               msc_sch_wb.atp_debug('Original Date ' || l_original_demand_date(i));
5207               msc_sch_wb.atp_debug('Supply ID ' || l_supply_id(i));
5208               msc_sch_wb.atp_debug('New Demand ' || x_demand_id(i));
5209               msc_sch_wb.atp_debug('Add_Offset_Demands:  Number of Family rows inserted '||
5210                   'For Demand id '|| l_offset_demand_id(i) ||
5211                   ' with offset/relief_type = 7 is ' || SQL%BULK_ROWCOUNT(i));
5212            END LOOP;
5213                 msc_sch_wb.atp_debug('Add_Offset_Demands:  Number of Family rows inserted '||
5214                       'with offset/relief_type = 7 is ' || SQL%ROWCOUNT);
5215          END IF;
5216       END IF; --IF ((MSC_ATP_PVT.G_INV_CTP = 4) AND  basically, IF ALLOC
5217 
5218   IF PG_DEBUG in ('Y', 'C') THEN
5219      msc_sch_wb.atp_debug('***** End Add_Offset_Demands *****');
5220   END IF;
5221 
5222 EXCEPTION
5223     WHEN OTHERS THEN
5224         my_sqlcode := SQLCODE;
5225         IF PG_DEBUG in ('Y', 'C') THEN
5226            msc_sch_wb.atp_debug('Add_Offset_Demands: ' ||
5227                 'error in insert row: sqlcode =  '|| to_char(my_sqlcode));
5228            msc_sch_wb.atp_debug('Add_Offset_Demands: ERROR- ' || sqlerrm );
5229         END IF;
5230 
5231         IF FND_MSG_PUB.Check_Msg_Level(FND_MSG_PUB.G_MSG_LVL_UNEXP_ERROR) THEN
5232             FND_MSG_PUB.Add_Exc_Msg(G_PKG_NAME , 'Add_Offset_Demands');
5233         END IF;
5234         x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
5235         -- Bug 3319810 Enable exception generation.
5236         RAISE FND_API.G_EXC_UNEXPECTED_ERROR;
5237 END Add_Offset_Demands;
5238 
5239 PROCEDURE Add_Offset_Supplies (
5240                      p_identifier                      IN NUMBER,
5241                      p_config_line_id                  IN NUMBER,
5242                      p_plan_id                         IN NUMBER,
5243                      p_refresh_number                  IN NUMBER,
5244                      p_order_number                    IN NUMBER,
5245                      p_demand_source_type              IN NUMBER,--cmro
5246                      x_inv_item_id                     IN OUT NoCopy MRP_ATP_PUB.Number_Arr,
5247                      x_supply_id                       IN OUT NoCopy MRP_ATP_PUB.Number_Arr,
5248                      x_supply_instance_id              OUT NoCopy MRP_ATP_PUB.Number_Arr, --Bug 3629191
5249                      x_return_status                   IN OUT NoCopy VARCHAR2
5250                      )
5251 IS
5252     l_del_rows                  NUMBER;
5253     i                           PLS_INTEGER;
5254     my_sqlcode                  NUMBER;
5255 
5256     l_supply_id                 MRP_ATP_PUB.Number_Arr := MRP_ATP_PUB.Number_Arr();
5257     l_instance_id               MRP_ATP_PUB.Number_Arr := MRP_ATP_PUB.Number_Arr();
5258     l_organization_id           MRP_ATP_PUB.Number_Arr := MRP_ATP_PUB.Number_Arr();
5259     l_inventory_item_id         MRP_ATP_PUB.Number_Arr := MRP_ATP_PUB.Number_Arr();
5260     l_supply_date               MRP_ATP_PUB.date_arr := MRP_ATP_PUB.date_arr();
5261     l_supply_qty                MRP_ATP_PUB.Number_Arr := MRP_ATP_PUB.Number_Arr();
5262     l_reference_item_id         MRP_ATP_PUB.Number_Arr := MRP_ATP_PUB.Number_Arr();
5263     l_demand_class              MRP_ATP_PUB.char30_arr := MRP_ATP_PUB.char30_arr();
5264     l_supplier_id               MRP_ATP_PUB.Number_Arr := MRP_ATP_PUB.Number_Arr();
5265     l_supplier_site_id          MRP_ATP_PUB.Number_Arr := MRP_ATP_PUB.Number_Arr();
5266     l_src_supplier_id           MRP_ATP_PUB.Number_Arr := MRP_ATP_PUB.Number_Arr();
5267     l_src_supplier_site_id      MRP_ATP_PUB.Number_Arr := MRP_ATP_PUB.Number_Arr();
5268     l_src_instance_id           MRP_ATP_PUB.Number_Arr := MRP_ATP_PUB.Number_Arr();
5269     l_src_org_id                MRP_ATP_PUB.Number_Arr := MRP_ATP_PUB.Number_Arr();
5270     l_process_seq_id            MRP_ATP_PUB.Number_Arr := MRP_ATP_PUB.Number_Arr();
5271     l_customer_id               MRP_ATP_PUB.Number_Arr := MRP_ATP_PUB.Number_Arr();
5272     l_ship_to_site_id           MRP_ATP_PUB.Number_Arr := MRP_ATP_PUB.Number_Arr();
5273     l_firm_planned_type         MRP_ATP_PUB.Number_Arr := MRP_ATP_PUB.Number_Arr();
5274 
5275     l_offset_supply_id          MRP_ATP_PUB.Number_Arr := MRP_ATP_PUB.Number_Arr();
5276     l_sysdate                   DATE;
5277     l_user_id                   number;
5278     l_dock_date                 MRP_ATP_PUB.date_arr := MRP_ATP_PUB.date_arr();
5279     l_ship_date                 MRP_ATP_PUB.date_arr := MRP_ATP_PUB.date_arr();
5280 
5281     -- Bug 3344102 A variable/handle for processing reliefs/offsets.
5282     l_offset_type               NUMBER := NULL;
5283 
5284     -- Bug 3381464 Array to track original supplies for updating msc_atp_pegging
5285     l_orig_supply_id            MRP_ATP_PUB.Number_Arr := MRP_ATP_PUB.Number_Arr();
5286     -- Bug 3717618 Introduce a pegging_id array to track pegging
5287     -- For filtering out released/firmed supplies and pegging both are needed.
5288     l_pegging_id                MRP_ATP_PUB.Number_Arr := MRP_ATP_PUB.Number_Arr();
5289 
5290 BEGIN
5291 
5292     IF PG_DEBUG in ('Y', 'C') THEN
5293         msc_sch_wb.atp_debug('***** Begin Add_Offset_Supplies *****');
5294     END IF;
5295     IF PG_DEBUG in ('Y', 'C') THEN
5296        msc_sch_wb.atp_debug('Add_Offset_Supplies: ' ||
5297                             'Offsetting msc_supplies for identifier = '
5298                             || p_identifier ||' : plan id = '||p_plan_id);
5299      msc_sch_wb.atp_debug('Add_Offset_Supplies: ' || 'Config Line Id = ' || p_config_line_id );
5300     END IF;
5301 
5302     x_return_status := FND_API.G_RET_STS_SUCCESS;
5303 
5304     l_sysdate := sysdate;
5305     l_user_id := FND_GLOBAL.USER_ID;
5306 
5307     -- CTO_PF_PRJ_2 Changes
5308     IF ((MSC_ATP_PVT.G_INV_CTP = 4) AND
5309       (MSC_ATP_PVT.G_ALLOCATED_ATP = 'Y') AND
5310       (MSC_ATP_PVT.G_HIERARCHY_PROFILE = 1) AND
5311       (MSC_ATP_PVT.G_ALLOCATION_METHOD = 1)) THEN
5312 
5313        l_offset_type := 6;
5314     ELSE
5315        l_offset_type := 2;
5316     END IF;
5317     -- End CTO_PF_PRJ_2 Changes
5318 
5319     IF PG_DEBUG in ('Y', 'C') THEN
5320        msc_sch_wb.atp_debug('Add_Offset_Supplies: Offset Type Set to '|| l_offset_type);
5321     END IF;
5322 
5323     -- Insert relief quantities as a Offsets in msc_supplies
5324 
5325     -- CTO_PF_PRJ_2 Changes
5326     SELECT   msc_supplies_s.nextval,
5327              map.sr_instance_id,
5328              map.organization_id,
5329              map.inventory_item_id,
5330              map.relief_quantity relief_quantity,
5331              map.transaction_date,
5332              -- Bug 3717618 Fetch pegging as well.
5333              map.pegging_id,
5334              -- Bug 3381464 Get original supply id
5335              s.transaction_id orig_supply_id,
5336              s.supplier_id,
5337              s.supplier_site_id,
5338              s.source_supplier_id,
5339              s.source_supplier_site_id,
5340              s.source_sr_instance_id,
5341              s.source_organization_id,
5342              s.process_seq_id,
5343              s.firm_planned_type,
5344              s.demand_class,
5345              s.customer_id,
5346              s.ship_to_site_id,
5347              s.transaction_id,
5348              s.new_ship_date,
5349              s.new_dock_date
5350     BULK COLLECT
5351     INTO     x_supply_id,
5352              l_instance_id,
5353              l_organization_id,
5354              x_inv_item_id,
5355              l_supply_qty,
5356              l_supply_date,
5357              -- Bug 3717618 Introduce a pegging_id array to track pegging
5358              -- For filtering out, released/firmed supplies and pegging both are needed.
5359              l_pegging_id,
5360              -- Bug 3381464 Get original supply id
5361              l_orig_supply_id,
5362              l_supplier_id,
5363              l_supplier_site_id,
5364              l_src_supplier_id,
5365              l_src_supplier_site_id,
5366              l_src_instance_id,
5367              l_src_org_id,
5368              l_process_seq_id,
5369              l_firm_planned_type,
5370              l_demand_class,
5371              l_customer_id,
5372              l_ship_to_site_id,
5373              l_offset_supply_id,
5374              l_ship_date,
5375              l_dock_date
5376     FROM
5377              msc_atp_pegging map,
5378              msc_supplies s
5379     WHERE    map.plan_id = p_plan_id
5380     --AND    map.sr_instance_id = p_instance_id  -- removed to support multiple instances in plan.
5381     AND      DECODE(map.demand_source_type,100,map.demand_source_type,-1)
5382                 =decode(p_demand_source_type,
5383                                         100,
5384                                         p_demand_source_type,
5385                                         -1) --CMRO;
5386     AND      map.sales_order_line_id in (p_identifier, p_config_line_id)
5387              -- CTO_PF_PRJ_2 Impacts Use the proper adjustment type.
5388     AND      map.relief_type = DECODE(map.offset_type, 1, 6, 2) --l_offset_type  -- PO
5389              -- End CTO_PF_PRJ_2 Impacts.
5390     -- Bug 3717618 Ensure that Firm or Released supplies are not included.
5391     AND      (map.supply_id, map.pegging_id) NOT IN
5392              (SELECT supply_id, pegging_id
5393               FROM   msc_atp_pegging mapeg1
5394               WHERE  plan_id = p_plan_id
5395               AND    DECODE(mapeg1.demand_source_type,100,mapeg1.demand_source_type,-1)
5396                      =decode(p_demand_source_type, 100,
5397                                      p_demand_source_type, -1) --CMRO
5398               AND    sales_order_line_id in (p_identifier, p_config_line_id)
5399               AND    relief_type in (1, DECODE(offset_type, 1, 6, 2))
5400               START WITH plan_id = p_plan_id
5401               AND    DECODE(mapeg1.demand_source_type,100,mapeg1.demand_source_type,-1)
5402                      =decode(p_demand_source_type, 100,
5403                                      p_demand_source_type, -1) --CMRO
5404               AND   sales_order_line_id in (p_identifier, p_config_line_id)
5405               AND   relief_type in (1, DECODE(offset_type, 1, 6, 2))
5406               AND   supply_id in
5407               (SELECT transaction_id
5408                FROM   msc_supplies S
5409                WHERE  S.plan_id = mapeg1.plan_id
5410                AND    S.sr_instance_id = mapeg1.sr_instance_id
5411                AND    S.transaction_id = mapeg1.supply_id
5412                AND    S.inventory_item_id = mapeg1.inventory_item_id
5413                AND    ((S.firm_planned_type = 1) -- firmed
5414                        OR -- released
5415                        NVL(S.implemented_quantity, 0) +
5416                        NVL(S.quantity_in_process, 0) >=
5417                        NVL(S.firm_quantity,S.new_order_quantity)
5418                       )
5419               )
5420               CONNECT BY prev_pegging_id = prior pegging_id
5421               AND   plan_id = p_plan_id
5422               AND   DECODE(mapeg1.demand_source_type,100,mapeg1.demand_source_type,-1)
5423                      =decode(p_demand_source_type, 100,
5424                                      p_demand_source_type, -1)
5425               AND   sales_order_line_id in (p_identifier, p_config_line_id)
5426               AND   relief_type in (1, DECODE(offset_type, 1, 6, 2))
5427               -- The Connect By clause sub_query traverses the pegging chain
5428               -- and helps in eliminating all supplies pegged to the firmed or released supply
5429              )
5430     -- End Bug 3717618
5431     AND      ABS(map.relief_quantity) > C_ZERO_APPROXIMATOR
5432     -- Bug 3761824 Use Precision figure while creating ofsets.
5433     AND      s.sr_instance_id = map.sr_instance_id
5434     AND      s.plan_id = map.plan_id
5435     AND      s.organization_id = map.organization_id
5436     AND      s.transaction_id = map.supply_id
5437     AND      s.inventory_item_id = map.inventory_item_id
5438     AND      s.order_type = 5
5439     ;
5440     -- End CTO_PF_PRJ_2 Impacts
5441 
5442     x_supply_instance_id := l_instance_id; --Bug 3629191
5443 
5444     l_del_rows := x_supply_id.COUNT;
5445 
5446     FORALL i in 1..l_del_rows
5447       INSERT into MSC_SUPPLIES (
5448                   plan_id,
5449                   transaction_id,
5450                   organization_id,
5451                   sr_instance_id,
5452                   inventory_item_id,
5453                   last_update_date,
5454                   last_updated_by,
5455                   creation_date,
5456                   created_by,
5457                   new_schedule_date,
5458                   disposition_status_type,
5459                   order_type,
5460                   new_order_quantity,
5461                   order_number,
5462                   supplier_id,
5463                   supplier_site_id,
5464                   source_supplier_id,
5465                   source_supplier_site_id,
5466                   source_sr_instance_id,
5467                   source_organization_id,
5468                   process_seq_id,
5469                   firm_planned_type,
5470                   demand_class,
5471                   customer_id,
5472                   ship_to_site_id,
5473                   record_source,
5474                   refresh_number,
5475                   new_ship_date,
5476                   new_dock_date
5477                  -- ,offset_supply_id
5478                   )
5479       VALUES      (p_plan_id,
5480                   x_supply_id(i),
5481                   l_organization_id(i),
5482                   l_instance_id(i),
5483                   x_inv_item_id(i),
5484                   l_sysdate,
5485                   l_user_id,
5486                   l_sysdate,
5487                   l_user_id,
5488                   --bug 3328421: Add at the end of the day
5489                   TRUNC(l_supply_date(i)) + MSC_ATP_PVT.G_END_OF_DAY,
5490                   --l_supply_date(i),
5491                   1,            -- 1512366: open status.
5492                   60,           -- offset sypply_type
5493                   l_supply_qty(i),
5494                   p_order_number,
5495                   l_supplier_id(i),
5496                   l_supplier_site_id(i),
5497                   l_src_supplier_id(i),
5498                   l_src_supplier_site_id(i),
5499                   l_src_instance_id(i),
5500                   l_src_org_id(i),
5501                   l_process_seq_id(i),
5502                   l_firm_planned_type(i),
5503                   l_demand_class(i),
5504                   l_customer_id(i),
5505                   l_ship_to_site_id(i),
5506                   2,            -- ATP created record
5507                   p_refresh_number,
5508                   l_ship_date(i),
5509                   l_dock_date(i)
5510                 --  ,l_offset_supply_id
5511                   );
5512 
5513            IF PG_DEBUG in ('Y', 'C') THEN
5514                 msc_sch_wb.atp_debug('Add_Offset_Supplies:  Number of rows inserted '||
5515                                SQL%ROWCOUNT);
5516            END IF;
5517 
5518     -- Bug 3381464 Update offset_supply_id in msc_atp_pegging.
5519     FORALL i in 1..l_del_rows
5520       UPDATE msc_atp_pegging map1
5521       SET    offset_supply_id = x_supply_id(i)
5522       WHERE  map1.plan_id = p_plan_id
5523       AND    DECODE(map1.demand_source_type,100,map1.demand_source_type,-1)
5524                 =decode(p_demand_source_type,
5525                                          100,
5526                                          p_demand_source_type,
5527                                          -1) --CMRO;
5528       AND    map1.sales_order_line_id in (p_identifier, p_config_line_id)
5529       AND    map1.relief_type = DECODE(map1.offset_type, 1, 6, 2)  -- PO, CTO_PF_PRJ_2
5530       AND    map1.inventory_item_id = x_inv_item_id(i)
5531              -- Bug 3717618 Use a pegging_id array to track pegging
5532              -- For filtering out, released/firmed supplies and pegging both are needed.
5533       AND    map1.pegging_id = l_pegging_id(i)
5534       AND    map1.supply_id = l_orig_supply_id(i);
5535 
5536       IF PG_DEBUG in ('Y', 'C') THEN
5537            msc_sch_wb.atp_debug('Add_Offset_Supplies:  Number of rows Updated '|| SQL%ROWCOUNT);
5538            FOR i in 1..l_del_rows LOOP
5539               msc_sch_wb.atp_debug('Add_Offset_Supplies:  Supply Id '|| l_orig_supply_id(i) ||
5540                                         ' Offset Supply Id ' || x_supply_id(i));
5541            END LOOP;
5542       END IF;
5543     -- End Bug 3381464.
5544 
5545 
5546       IF ((MSC_ATP_PVT.G_INV_CTP = 4) AND
5547           (MSC_ATP_PVT.G_ALLOCATED_ATP = 'Y') AND
5548           (MSC_ATP_PVT.G_HIERARCHY_PROFILE = 1) AND
5549           (MSC_ATP_PVT.G_ALLOCATION_METHOD = 1)) THEN
5550 
5551          IF PG_DEBUG in ('Y', 'C') THEN
5552               msc_sch_wb.atp_debug('Add_Offset_Supplies: ' ||
5553                   ' before insert into' || ' msc_alloc_supplies');
5554          END IF;
5555 
5556          -- CTO_PF_PRJ_2 relief_type already set above.
5557          -- Bug 3344102 First set offset type to 6 for supply alloc reliefs.
5558          -- l_offset_type := 6;
5559          -- End CTO_PF_PRJ_2
5560 
5561          -- Try to apply the offsets using alloc specific relief_type.
5562          FORALL i in 1..x_supply_id.COUNT
5563            INSERT INTO MSC_ALLOC_SUPPLIES(
5564                        PLAN_ID,
5565                        INVENTORY_ITEM_ID,
5566                        ORGANIZATION_ID,
5567                        SR_INSTANCE_ID,
5568                        DEMAND_CLASS,
5569                        SUPPLY_DATE,
5570                        PARENT_TRANSACTION_ID,
5571                        ALLOCATED_QUANTITY,
5572                        ORDER_TYPE,
5573                        SALES_ORDER_LINE_ID,
5574                        refresh_number,
5575                        CREATED_BY,
5576                        CREATION_DATE,
5577                        LAST_UPDATED_BY,
5578                        LAST_UPDATE_DATE
5579                        )
5580            SELECT
5581                    map.plan_id,
5582                    map.inventory_item_id,
5583                    map.organization_id,
5584                    map.sr_instance_id,
5585                    map.demand_class,
5586                    map.transaction_date,
5587                    x_supply_id(i),
5588                    NVL(map.relief_quantity, 0),
5589                    60,
5590                    map.sales_order_line_id,
5591                    p_refresh_number,
5592                    l_user_id,
5593                    l_sysdate,
5594                    l_user_id,
5595                    l_sysdate
5596            FROM    msc_atp_pegging map
5597            WHERE   map.sr_instance_id = l_instance_id(i)
5598            AND     map.plan_id = p_plan_id
5599            AND     DECODE(map.demand_source_type,100,map.demand_source_type,-1)
5600                    =decode(p_demand_source_type,
5601                                                 100,
5602                                                 p_demand_source_type,
5603                                                 -1) --CMRO;
5604 
5605            AND     map.sales_order_line_id in (p_identifier, p_config_line_id)
5606            AND     map.relief_type = DECODE(map.offset_type, 1, 6, 2) --PO
5607                    -- Bug 3717618 Use a pegging_id array to track pegging
5608                    -- For filtering out released/firmed supplies both are needed.
5609            AND     map.pegging_id = l_pegging_id(i)
5610            AND     ABS(map.relief_quantity) > C_ZERO_APPROXIMATOR
5611            -- Bug 3761824 Use Precision figure while creating ofsets.
5612            AND     map.supply_id = l_offset_supply_id(i); -- Original Supply
5613 
5614          IF PG_DEBUG in ('Y', 'C') THEN
5615              FOR i in 1..x_supply_id.COUNT LOOP
5616                 msc_sch_wb.atp_debug('Supply to be offset ' || l_offset_supply_id(i));
5617                 msc_sch_wb.atp_debug('Actual Item ' || x_inv_item_id(i));
5618                 msc_sch_wb.atp_debug('Relief Qty' || l_supply_qty(i));
5619                 msc_sch_wb.atp_debug('New Supply ' || x_supply_id(i));
5620                 msc_sch_wb.atp_debug('Add_Offset_Demands:  Number of rows inserted '||
5621                   'For Supply id '|| l_offset_supply_id(i) ||
5622                   ' with offset/relief_type = 6 is ' || SQL%BULK_ROWCOUNT(i));
5623              END LOOP;
5624               msc_sch_wb.atp_debug('Add_Offset_Supplies:  Number of Alloc rows inserted '||
5625                  'with offset/relief_type = ' ||l_offset_type || 'is ' || SQL%ROWCOUNT);
5626          END IF;
5627 
5628          -- CTO_PF_PRJ_2
5629          -- Cascading SQLs no longer necessary
5630          -- IF SQL%ROWCOUNT = 0 THEN
5631 
5632            -- Apply using standard supplies relief_type
5633 
5634          -- END IF;
5635          -- End Bug 3344102
5636          -- END CTO_PF_PRJ_2
5637 
5638 
5639       END IF;
5640 
5641 
5642     IF PG_DEBUG in ('Y', 'C') THEN
5643        msc_sch_wb.atp_debug('***** End Add_Offset_Supplies *****');
5644     END IF;
5645 
5646 EXCEPTION
5647     WHEN OTHERS THEN
5648        BEGIN
5649          -- Bug 3381464 Update offset_supply_id in msc_atp_pegging.
5650          FORALL i in 1..l_del_rows
5651             UPDATE msc_atp_pegging map1
5652             SET    offset_supply_id = NULL
5653             WHERE  map1.plan_id = p_plan_id
5654             AND    DECODE(map1.demand_source_type,100,map1.demand_source_type,-1)
5655                     =decode(p_demand_source_type,
5656                                          100,
5657                                          p_demand_source_type,
5658                                          -1) --CMRO;
5659             AND    map1.sales_order_line_id in (p_identifier, p_config_line_id)
5660             AND    map1.relief_type = decode(map1.offset_type, 1, 6, 2)  -- PO
5661             AND    map1.inventory_item_id = x_inv_item_id(i)
5662             AND    map1.supply_id = l_orig_supply_id(i);
5663          IF PG_DEBUG in ('Y', 'C') THEN
5664            msc_sch_wb.atp_debug('Add_Offset_Supplies:  Number of rows Updated '||
5665                              SQL%ROWCOUNT);
5666          END IF;
5667 
5668        EXCEPTION
5669         WHEN OTHERS THEN
5670          IF PG_DEBUG in ('Y', 'C') THEN
5671            msc_sch_wb.atp_debug('Add_Offset_Supplies: ' ||
5672                 'error in updating offset supplies =  '|| sqlerrm );
5673          END IF;
5674        END;
5675        -- End Bug 3381464.
5676 
5677         my_sqlcode := SQLCODE;
5678         IF PG_DEBUG in ('Y', 'C') THEN
5679            msc_sch_wb.atp_debug('Add_Offset_Supplies: ' ||
5680                 'error in insert row: sqlcode =  '|| to_char(my_sqlcode));
5681            msc_sch_wb.atp_debug('Add_Offset_Supplies: ERROR- ' || sqlerrm );
5682         END IF;
5683 
5684         IF FND_MSG_PUB.Check_Msg_Level(FND_MSG_PUB.G_MSG_LVL_UNEXP_ERROR) THEN
5685             FND_MSG_PUB.Add_Exc_Msg(G_PKG_NAME , 'Add_Offset_Supplies');
5686         END IF;
5687         x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
5688         -- Bug 3319810 Enable exception generation.
5689         RAISE FND_API.G_EXC_UNEXPECTED_ERROR;
5690 
5691 END Add_Offset_Supplies;
5692 
5693 PROCEDURE Add_Offset_Resource_Reqs (
5694                      p_identifier                      IN NUMBER,
5695                      p_config_line_id                  IN NUMBER,
5696                      p_plan_id                         IN NUMBER,
5697                      p_refresh_number                  IN NUMBER,
5698                      p_order_number                    IN NUMBER,
5699                      p_demand_source_type              IN NUMBER,--cmro
5700                      x_inv_item_id                     IN OUT NoCopy MRP_ATP_PUB.Number_Arr,
5701                      x_res_transactions                IN OUT NoCopy MRP_ATP_PUB.Number_Arr,
5702                      x_res_instance_id                 OUT NoCopy MRP_ATP_PUB.Number_Arr, --Bug 3629191
5703                      x_return_status                   IN OUT NoCopy VARCHAR2
5704                      )
5705 IS
5706     l_del_rows                  NUMBER;
5707     i                           PLS_INTEGER;
5708     my_sqlcode                  NUMBER;
5709 
5710     l_supply_id                 MRP_ATP_PUB.Number_Arr := MRP_ATP_PUB.Number_Arr();
5711     l_instance_id               MRP_ATP_PUB.Number_Arr := MRP_ATP_PUB.Number_Arr();
5712     l_organization_id           MRP_ATP_PUB.Number_Arr := MRP_ATP_PUB.Number_Arr();
5713     l_resource_seq_num          MRP_ATP_PUB.Number_Arr := MRP_ATP_PUB.Number_Arr();
5714     l_resource_id               MRP_ATP_PUB.Number_Arr := MRP_ATP_PUB.Number_Arr();
5715     l_department_id             MRP_ATP_PUB.Number_Arr := MRP_ATP_PUB.Number_Arr();
5716     l_start_date                MRP_ATP_PUB.Date_Arr := MRP_ATP_PUB.Date_Arr();
5717     l_end_date                  MRP_ATP_PUB.Date_Arr := MRP_ATP_PUB.Date_Arr();
5718     l_resource_hours            MRP_ATP_PUB.Number_Arr := MRP_ATP_PUB.Number_Arr();
5719     l_daily_resource_hours      MRP_ATP_PUB.Number_Arr := MRP_ATP_PUB.Number_Arr();
5720     l_load_rate                 MRP_ATP_PUB.Number_Arr := MRP_ATP_PUB.Number_Arr();
5721     l_assigned_units            MRP_ATP_PUB.Number_Arr := MRP_ATP_PUB.Number_Arr();
5722     l_std_op_code               MRP_ATP_PUB.char10_arr;
5723 
5724     l_basis_type                MRP_ATP_PUB.Number_Arr := MRP_ATP_PUB.Number_Arr();
5725     l_op_seq_num                MRP_ATP_PUB.Number_Arr := MRP_ATP_PUB.Number_Arr();
5726     l_parent_id                 MRP_ATP_PUB.Number_Arr := MRP_ATP_PUB.Number_Arr();
5727 
5728     l_sysdate                   DATE;
5729     l_user_id                   number;
5730 
5731     -- CTO_PF_PRJ_2 Changes
5732     l_offset_type               NUMBER;
5733 BEGIN
5734 
5735      IF PG_DEBUG in ('Y', 'C') THEN
5736         msc_sch_wb.atp_debug('***** Begin Add_Offset_Resource_Reqs *****');
5737      END IF;
5738      IF PG_DEBUG in ('Y', 'C') THEN
5739         msc_sch_wb.atp_debug('Add_Offset_Resource_Reqs: ' ||
5740                           'Offsetting msc_resource_requirements for identifier = '
5741                       || p_identifier ||' : plan id = '||p_plan_id);
5742      msc_sch_wb.atp_debug('Add_Offset_Resource_Reqs: Config Line Id = ' || p_config_line_id );
5743      END IF ;
5744 
5745      x_return_status := FND_API.G_RET_STS_SUCCESS;
5746 
5747      -- CTO_PF_PRJ_2 Changes
5748      IF ((MSC_ATP_PVT.G_INV_CTP = 4) AND
5749         (MSC_ATP_PVT.G_ALLOCATED_ATP = 'Y') AND
5750         (MSC_ATP_PVT.G_HIERARCHY_PROFILE = 1) AND
5751         (MSC_ATP_PVT.G_ALLOCATION_METHOD = 1)) THEN
5752 
5753          l_offset_type := 6;
5754      ELSE
5755          l_offset_type := 2;
5756      END IF;
5757      -- End CTO_PF_PRJ_2 Changes
5758 
5759      l_sysdate := sysdate;
5760      l_user_id := FND_GLOBAL.USER_ID;
5761 
5762   -- Insert demand into msc_resource_requirements
5763      SELECT
5764                   supply_id,
5765                   sr_instance_id,
5766                   msc_resource_requirements_s.nextval,
5767                   organization_id,
5768                   inventory_item_id,
5769                   basis_type,
5770                   operation_seq_num,
5771                   parent_id,
5772                   resource_seq_num,
5773                   resource_id,
5774                   department_id,
5775                   start_date,
5776                   end_date,
5777                   relief_quantity,
5778                   daily_relief_qty,
5779                   load_rate,
5780                   assigned_units,    -- 0 originally.
5781                   std_op_code
5782      BULK COLLECT
5783      INTO
5784                   l_supply_id,
5785                   l_instance_id,
5786                   x_res_transactions,
5787                   l_organization_id,
5788                   x_inv_item_id,
5789                   l_basis_type,
5790                   l_op_seq_num,
5791                   l_parent_id,
5792                   l_resource_seq_num,
5793                   l_resource_id,
5794                   l_department_id,
5795                   l_start_date,
5796                   l_end_date,
5797                   l_resource_hours,
5798                   l_daily_resource_hours,
5799                   l_load_rate,
5800                   l_assigned_units,
5801                   l_std_op_code
5802     FROM
5803          (SELECT  DISTINCT
5804                   -- Bug 3381464 Obtain the Offset Suuply_ID
5805                   map2.offset_supply_id supply_id,
5806                   -- REQ.supply_id,
5807                   -- This ensures that offset resource requirements are pegged to offset supplies.
5808                   -- End Bug 3381464.
5809                   map.sr_instance_id,
5810                   REQ.transaction_id,
5811                   map.organization_id,
5812                   map.inventory_item_id,
5813                   REQ.basis_type,
5814                   REQ.operation_seq_num,
5815                   REQ.parent_id,
5816                   REQ.resource_seq_num,
5817                   map.resource_id,
5818                   map.department_id,
5819                   NVL(map.start_date, REQ.start_date) start_date,
5820                             -- Bug 3443056, 3348095 ATP now tracks end date.
5821                   map.end_date,
5822                   map.relief_quantity,
5823                   map.daily_relief_qty,
5824                   decode(map.resource_id,-1,map.relief_quantity,to_number(null)) load_rate,
5825                   REQ.assigned_units,    -- 0 originally.
5826                   REQ.std_op_code
5827           FROM       msc_atp_pegging map,
5828                      msc_resource_requirements REQ,
5829                      -- Bug 3381464 -- Join to Pegging to obtain offset supply ids.
5830                      msc_atp_pegging map2
5831           WHERE   map.plan_id = p_plan_id
5832           --AND      map.sr_instance_id = p_instance_id  -- removed to support multiple instances in plan.
5833           AND      DECODE(map.demand_source_type,100,map.demand_source_type,-1)
5834                    =decode(p_demand_source_type,
5835                                                 100,
5836                                                 p_demand_source_type,
5837                                                 -1) --CMRO;
5838 
5839           AND      map.sales_order_line_id in (p_identifier, p_config_line_id)
5840           AND      map.relief_type = 4  -- REQ
5841           AND      ABS(map.relief_quantity) > C_ZERO_APPROXIMATOR
5842           -- Bug 3761824 Use Precision figure while creating ofsets.
5843           AND      REQ.sr_instance_id = map.sr_instance_id
5844           AND      REQ.plan_id = map.plan_id
5845           AND      REQ.organization_id = map.organization_id
5846           --AND      REQ.supply_id = map.supply_id
5847           AND      REQ.transaction_id = map.supply_id   -- Here resource transaction ids.
5848           AND      REQ.resource_id = map.resource_id
5849           AND      REQ.department_id = map.department_id
5850           AND      REQ.assembly_item_id = map.inventory_item_id
5851           AND      ( (NVL(REQ.record_source, 1) = 1 AND
5852                            TRUNC(REQ.start_date) = TRUNC(map.start_date))
5853                     OR (REQ.record_source = 2 AND TRUNC(REQ.end_date) = TRUNC(map.end_date)) )
5854                             -- Bug 3443056, 3348095 ATP now tracks end date.
5855           -- Bug 3381464 Get Offset Supply Data.
5856           AND      map2.sr_instance_id = REQ.sr_instance_id
5857           AND      map2.plan_id = REQ.plan_id
5858           AND      map2.organization_id = REQ.organization_id
5859           AND      map2.inventory_item_id = REQ.assembly_item_id
5860           AND      map2.supply_id = REQ.supply_id
5861           -- Bug 3717618 Ensure that supply is relieved
5862           -- Only those corresponding resource reqs will be offset.
5863           AND      map2.offset_supply_id is NOT NULL
5864           -- End Bug 3717618
5865           AND      map2.relief_type = decode(map2.offset_type,1,6,2) -- CTO_PF_PRJ_2
5866           AND      map2.sales_order_line_id = map.sales_order_line_id
5867           AND      DECODE(map2.demand_source_type,100,map2.demand_source_type,-1)
5868                    = DECODE(map.demand_source_type,100,map.demand_source_type,-1)
5869           -- End Bug 3381464
5870         )
5871      ;
5872 
5873      x_res_instance_id := l_instance_id; --Bug 3629191
5874 
5875      l_del_rows := x_res_transactions.COUNT;
5876 
5877      IF PG_DEBUG in ('Y', 'C') THEN
5878         msc_sch_wb.atp_debug('Add_Offset_Resource_Reqs: ' ||
5879                           'Total Rows to add = ' || l_del_rows );
5880      END IF;
5881      FORALL i in 1..l_del_rows
5882        INSERT into msc_resource_requirements
5883                  (plan_id,
5884                   supply_id,
5885                   transaction_id,
5886                   organization_id,
5887                   sr_instance_id,
5888                   assembly_item_id,
5889                   basis_type,
5890                   operation_seq_num,
5891                   parent_id,
5892                   record_source,
5893                   resource_seq_num,
5894                   resource_id,
5895                   department_id,
5896                   refresh_number,
5897                   start_date,
5898                   end_date,
5899                   resource_hours,
5900                   daily_resource_hours,
5901                   load_rate,
5902                   assigned_units,
5903                   supply_type, -- 1510686
5904                   std_op_code, --resource batching
5905                   last_update_date,
5906                   last_updated_by,
5907                   creation_date,
5908                   created_by)
5909        VALUES     (p_plan_id,
5910                    l_supply_id(i),
5911                    x_res_transactions(i),
5912                    l_organization_id(i),
5913                    l_instance_id(i),
5914                    x_inv_item_id(i),
5915                    l_basis_type(i),
5916                    l_op_seq_num(i),
5917                    l_parent_id(i),
5918                    2,                 -- ATP generated record.
5919                    l_resource_seq_num(i),
5920                    l_resource_id(i),
5921                    l_department_id(i),
5922                    p_refresh_number,
5923                    l_start_date(i),
5924                    l_end_date(i),
5925                    l_resource_hours(i),
5926                    l_daily_resource_hours(i),
5927                    l_load_rate(i),
5928                    l_assigned_units(i),   -- 0 originally.
5929                    60,                     -- for Resources offset supply type is applicable.
5930                    l_std_op_code(i),
5931                    l_sysdate,
5932                    l_user_id,
5933                    l_sysdate,
5934                    l_user_id ) ;
5935 
5936      IF PG_DEBUG in ('Y', 'C') THEN
5937           msc_sch_wb.atp_debug('Add_Offset_Resource_Reqs:  Number of rows inserted '||
5938                                SQL%ROWCOUNT);
5939      END IF;
5940 
5941 
5942     IF PG_DEBUG in ('Y', 'C') THEN
5943        msc_sch_wb.atp_debug('***** End Add_Offset_Resource_Reqs *****');
5944     END IF;
5945 EXCEPTION
5946     WHEN OTHERS THEN
5947         my_sqlcode := SQLCODE;
5948         IF PG_DEBUG in ('Y', 'C') THEN
5949            msc_sch_wb.atp_debug('Add_Offset_Resource_Reqs: ' ||
5950                 'error in processing: sqlcode =  '|| to_char(my_sqlcode));
5951            msc_sch_wb.atp_debug('Add_Offset_Resource_Reqs: ' ||
5952                 'error in processing: errmsg =  '|| sqlerrm );
5953         END IF;
5954 
5955         IF FND_MSG_PUB.Check_Msg_Level(FND_MSG_PUB.G_MSG_LVL_UNEXP_ERROR) THEN
5956             FND_MSG_PUB.Add_Exc_Msg(G_PKG_NAME , 'Add_Offset_Resource_Reqs');
5957         END IF;
5958         x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
5959         -- Bug 3319810 Enable exception generation.
5960         RAISE FND_API.G_EXC_UNEXPECTED_ERROR;
5961 
5962 END Add_Offset_Resource_Reqs;
5963 
5964 PROCEDURE Add_Offset_Data (
5965                     p_identifier       IN         NUMBER,
5966                     p_config_line_id   IN         NUMBER,
5967                     p_plan_id          IN         NUMBER,
5968                     p_refresh_number   IN         NUMBER,
5969                     p_order_number     IN         NUMBER,
5970                     p_demand_source_type IN       NUMBER,--cmro
5971                     x_inv_item_id      OUT NoCopy MRP_ATP_PUB.Number_Arr,
5972                     x_demand_id        OUT NoCopy MRP_ATP_PUB.Number_Arr,
5973                     x_supply_id        OUT NoCopy MRP_ATP_PUB.Number_Arr,
5974                     x_res_transactions OUT NoCopy MRP_ATP_PUB.Number_Arr,
5975                     x_demand_instance_id OUT NoCopy MRP_ATP_PUB.Number_Arr, --Bug 3629191
5976                     x_supply_instance_id OUT NoCopy MRP_ATP_PUB.Number_Arr, --Bug 3629191
5977                     x_res_instance_id    OUT NoCopy MRP_ATP_PUB.Number_Arr, --Bug 3629191
5978                     x_return_status    OUT NoCopy VARCHAR2
5979                     )
5980 IS
5981 
5982 l_inv_demand_items      MRP_ATP_PUB.Number_Arr := MRP_ATP_PUB.Number_Arr();
5983 l_inv_supply_items      MRP_ATP_PUB.Number_Arr := MRP_ATP_PUB.Number_Arr();
5984 j                       PLS_INTEGER;
5985 i                       PLS_INTEGER;
5986 match_found             NUMBER;
5987 l_supply_instance_id    MRP_ATP_PUB.Number_Arr := MRP_ATP_PUB.Number_Arr();
5988 BEGIN
5989 
5990     IF PG_DEBUG in ('Y', 'C')  THEN
5991         msc_sch_wb.atp_debug('**********Begin Add_Offset_Data Procedure************');
5992         msc_sch_wb.atp_debug('Add_Offset_Data p_identifier :' || p_identifier);
5993         msc_sch_wb.atp_debug('Add_Offset_Data p_config_line_id :' || p_config_line_id);
5994         msc_sch_wb.atp_debug('Add_Offset_Data p_plan_id :' || p_plan_id);
5995         msc_sch_wb.atp_debug('Add_Offset_Data p_refresh_number :' || p_refresh_number);
5996         msc_sch_wb.atp_debug('Add_Offset_Data p_order_number :' || p_order_number);
5997     END IF;
5998 
5999     x_return_status := FND_API.G_RET_STS_SUCCESS;
6000 
6001 
6002     -- Bug 3717618 Flip the order of calls to
6003     -- Add Offset records, First call Offset Supplies and
6004 
6005     Add_Offset_Supplies (p_identifier, p_config_line_id, p_plan_id,
6006                          p_refresh_number, p_order_number,p_demand_source_type,--cmro
6007                          l_inv_supply_items, x_supply_id, x_supply_instance_id, x_return_status); --Bug 3629191
6008 
6009     IF PG_DEBUG in ('Y', 'C')  THEN
6010         msc_sch_wb.atp_debug('Status After Call to Add_Offset_Supplies :' || x_return_status);
6011     END IF;
6012 
6013     -- and then call Offset Demands
6014     -- so that only those demands tied to offset supplies are relieved.
6015     Add_Offset_Demands (p_identifier, p_config_line_id, p_plan_id,
6016                         p_refresh_number, p_order_number,p_demand_source_type,--cmro
6017                         l_inv_demand_items, x_demand_id, x_demand_instance_id, x_return_status); --Bug 3629191
6018 
6019     IF PG_DEBUG in ('Y', 'C')  THEN
6020         msc_sch_wb.atp_debug('Status After Call to Add_Offset_Demands :' || x_return_status);
6021     END IF;
6022     -- End Bug 3717618 Flip the order of calls ...
6023 
6024     FOR j in 1..l_inv_supply_items.COUNT LOOP
6025 
6026       match_found := 2;  -- match found is set to false.
6027       FOR i in 1..l_inv_demand_items.COUNT LOOP
6028         IF (l_inv_demand_items(i) = l_inv_supply_items(j)) THEN
6029           -- match found exit loop
6030           match_found:= 1;
6031           EXIT;
6032         END IF;
6033       END LOOP;
6034 
6035       -- match not found, add to list of items.
6036       IF (match_found = 2) THEN
6037          l_inv_demand_items.EXTEND;
6038          l_inv_demand_items(l_inv_demand_items.COUNT) := l_inv_supply_items(j);
6039       END IF;
6040 
6041     END LOOP;
6042 
6043     Add_Offset_Resource_Reqs (p_identifier, p_config_line_id,  p_plan_id,
6044                               p_refresh_number, p_order_number,p_demand_source_type,--cmro
6045                               l_inv_supply_items, x_res_transactions, x_res_instance_id, x_return_status); --Bug 3629191
6046 
6047     IF PG_DEBUG in ('Y', 'C')  THEN
6048         msc_sch_wb.atp_debug('Status After Call to Add_Offset_Resource_Reqs :'
6049                                          || x_return_status);
6050     END IF;
6051 
6052 
6053     -- Finally assign to output list
6054     x_inv_item_id := l_inv_demand_items;
6055 
6056     IF PG_DEBUG in ('Y', 'C')  THEN
6057         msc_sch_wb.atp_debug('**********End Add_Offset_Data Procedure************');
6058     END IF;
6059 
6060 EXCEPTION
6061     WHEN OTHERS THEN
6062         IF FND_MSG_PUB.Check_Msg_Level(FND_MSG_PUB.G_MSG_LVL_UNEXP_ERROR) THEN
6063             FND_MSG_PUB.Add_Exc_Msg (G_PKG_NAME , 'Add_Offset_Data');
6064         END IF;
6065 
6066         IF PG_DEBUG in ('Y', 'C')  THEN
6067            msc_sch_wb.atp_debug('Add_Offset_Data: ERROR' || sqlerrm );
6068         END IF;
6069         x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
6070         -- Bug 3319810 Enable exception generation.
6071         RAISE FND_API.G_EXC_UNEXPECTED_ERROR;
6072 END Add_Offset_Data;
6073 
6074 PROCEDURE Remove_Offset_Demands (
6075              --p_identifiers      IN       MRP_ATP_PUB.Number_Arr,
6076              --p_plan_ids         IN       MRP_ATP_PUB.Number_Arr,
6077              p_atp_peg_demands_plan_ids  IN MRP_ATP_PUB.Number_Arr, --Bug 3629191
6078              p_inv_item_ids     IN       MRP_ATP_PUB.Number_Arr,
6079              p_del_demand_ids   IN       MRP_ATP_PUB.Number_Arr,
6080              p_demand_source_type IN     MRP_ATP_PUB.Number_Arr,--cmro
6081              x_return_status    IN OUT   NoCopy VARCHAR2
6082                                 )
6083 IS
6084 l_del_rows          NUMBER;
6085 i                   NUMBER;
6086 m                   PLS_INTEGER := 1;
6087 
6088 -- CTO_PF_PRJ_2 Impacts
6089 l_offset_type               NUMBER;
6090 -- End CTO_PF_PRJ_2 Impacts
6091 
6092 BEGIN
6093    IF PG_DEBUG in ('Y', 'C') THEN
6094         msc_sch_wb.atp_debug('**********Begin Remove_Offset_Demands Procedure************');
6095     END IF;
6096    IF PG_DEBUG in ('Y', 'C') THEN
6097        FOR i in 1..p_del_demand_ids.COUNT LOOP
6098             msc_sch_wb.atp_debug('Remove_Offset_Demands: ' ||
6099                              'p_del_demand_ids('||i||') = '|| p_del_demand_ids(i)||
6100                              --'p_inv_item_ids('||i||') = '|| p_inv_item_ids(i)||
6101                              'p_atp_peg_demands_plan_ids('||i||') = '|| p_atp_peg_demands_plan_ids(i)
6102                              --'p_plan_ids('||i||') = '|| p_plan_ids(i)||
6103                              --'p_identifiers('||i||') = '|| p_identifiers(i)
6104                              );
6105        END LOOP;
6106    END IF;
6107 
6108    x_return_status := FND_API.G_RET_STS_SUCCESS;
6109 
6110    -- CTO_PF_PRJ_2 Impacts
6111    IF ((MSC_ATP_PVT.G_INV_CTP = 4) AND
6112        (MSC_ATP_PVT.G_ALLOCATED_ATP = 'Y') AND
6113        (MSC_ATP_PVT.G_HIERARCHY_PROFILE = 1) AND
6114        (MSC_ATP_PVT.G_ALLOCATION_METHOD = 1)) THEN
6115 
6116       l_offset_type := 5;
6117    ELSE
6118       l_offset_type := 3;
6119    END IF;
6120    -- End CTO_PF_PRJ_2
6121 
6122    --Bug 3629191
6123    FORALL m IN 1..p_del_demand_ids.COUNT
6124       DELETE msc_demands
6125       WHERE
6126       -- Bug 3629191 :All where clause except plan_id and demand_id are commmented
6127       /* sr_instance_id  = p_instance_id
6128       (SELECT sr_instance_id
6129        FROM   msc_atp_pegging
6130        WHERE  plan_id = p_plan_ids(m)
6131        AND    sales_order_line_id = p_identifiers(m)
6132        AND     DECODE(demand_source_type,100,demand_source_type,-1)
6133                       =decode(p_demand_source_type(m),
6134                               100,
6135                               p_demand_source_type(m),
6136                               -1)  --CMRO;
6137        AND    inventory_item_id = p_inv_item_ids(m)
6138        -- CTO_PF_PRJ_2 Impacts
6139        AND    relief_type in (l_offset_type, 7)
6140        -- End CTO_PF_PRJ_2
6141       )
6142       AND */
6143              plan_id = p_atp_peg_demands_plan_ids(m)
6144       --AND  inventory_item_id = p_inv_item_ids(m) -- Bug 3629191
6145       AND    demand_id = p_del_demand_ids(m);
6146 
6147    -- Count how many rows were updated for each demand id
6148    IF PG_DEBUG in ('Y', 'C') THEN
6149         FOR m IN 1..p_del_demand_ids.COUNT LOOP
6150            msc_sch_wb.atp_debug('For Demand id '|| p_del_demand_ids(m)||': updated '||
6151                         SQL%BULK_ROWCOUNT(m)||' records');
6152         END LOOP;
6153    END IF;
6154 
6155    --    (MSC_ATP_PVT.G_ALLOCATION_METHOD = 1)) THEN
6156    -- Allocation Profiles check that was there before has been removed
6157    -- with the introduction of CTO_PF_PRJ_2 impacts.
6158    -- Relief_Type 7 can get created irrespective of allocation profiles.
6159 
6160       IF PG_DEBUG in ('Y', 'C') THEN
6161             msc_sch_wb.atp_debug('Remove_Offset_Demands: before delete from ' ||
6162                               ' msc_alloc_demands');
6163       END IF;
6164 
6165       --Bug 3629191
6166       FORALL m IN 1..p_del_demand_ids.COUNT
6167          DELETE msc_alloc_demands
6168          WHERE
6169          -- Bug 3629191 :All where clause except plan_id and parent_demand_id are commmented
6170          /*sr_instance_id IN
6171          (SELECT sr_instance_id
6172           FROM   msc_atp_pegging
6173           WHERE  plan_id = p_plan_ids(m)
6174           AND    sales_order_line_id = p_identifiers(m)
6175           AND    DECODE(demand_source_type,100,demand_source_type,-1)
6176                  =decode(p_demand_source_type(m),
6177                          100,
6178                          p_demand_source_type(m),
6179                          -1) --CMRO;
6180           AND    inventory_item_id = p_inv_item_ids(m)
6181           -- CTO_PF_PRJ_2 Impacts
6182           AND    relief_type in (l_offset_type, 7)
6183           -- End CTO_PF_PRJ_2
6184          )
6185          AND */
6186                 plan_id = p_atp_peg_demands_plan_ids(m)
6187          --AND  inventory_item_id = p_inv_item_ids(m) -- Bug 3629191
6188          AND    parent_demand_id = p_del_demand_ids(m)
6189 ;
6190 
6191          -- Count how many rows were updated for each demand id
6192       IF PG_DEBUG in ('Y', 'C') THEN
6193            FOR m IN 1..p_del_demand_ids.COUNT LOOP
6194               msc_sch_wb.atp_debug('For Demand id '|| p_del_demand_ids(m)||': updated '||
6195                       SQL%BULK_ROWCOUNT(m)||' records');
6196            END LOOP;
6197       END IF;
6198 
6199    IF PG_DEBUG in ('Y', 'C') THEN
6200         msc_sch_wb.atp_debug('**********End Remove_Offset_Demands Procedure************');
6201    END IF;
6202 
6203 EXCEPTION
6204     WHEN OTHERS THEN
6205         IF FND_MSG_PUB.Check_Msg_Level(FND_MSG_PUB.G_MSG_LVL_UNEXP_ERROR) THEN
6206             FND_MSG_PUB.Add_Exc_Msg (G_PKG_NAME , 'Remove_Offset_Demands');
6207         END IF;
6208 
6209         IF PG_DEBUG in ('Y', 'C')  THEN
6210            msc_sch_wb.atp_debug('Remove_Offset_Demands: ERROR' || sqlerrm );
6211         END IF;
6212         x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
6213         -- Bug 3319810 Enable exception generation.
6214         RAISE FND_API.G_EXC_UNEXPECTED_ERROR;
6215 
6216 END Remove_Offset_Demands;
6217 
6218 PROCEDURE Remove_Offset_Supplies (
6219              --p_identifiers      IN       MRP_ATP_PUB.Number_Arr,
6220              --p_plan_ids         IN       MRP_ATP_PUB.Number_Arr,
6221              p_atp_peg_supplies_plan_ids IN MRP_ATP_PUB.Number_Arr, --Bug 3629191
6222              p_inv_item_ids     IN       MRP_ATP_PUB.Number_Arr,
6223              p_del_supply_ids   IN       MRP_ATP_PUB.Number_Arr,
6224              p_demand_source_type IN     MRP_ATP_PUB.Number_Arr,--cmro
6225              x_return_status    IN OUT   NoCopy VARCHAR2
6226                                 )
6227 IS
6228 l_del_rows          NUMBER;
6229 i                   NUMBER;
6230 m                   PLS_INTEGER := 1;
6231 
6232 -- CTO_PF_PRJ_2 Impacts
6233 l_offset_type               NUMBER;
6234 -- End CTO_PF_PRJ_2 Impacts
6235 
6236 BEGIN
6237    IF PG_DEBUG in ('Y', 'C') THEN
6238         msc_sch_wb.atp_debug('**********Begin Remove_Offset_Supplies Procedure************');
6239     END IF;
6240    IF PG_DEBUG in ('Y', 'C') THEN
6241        FOR i in 1..p_del_supply_ids.COUNT LOOP
6242             msc_sch_wb.atp_debug('Remove_Offset_Supplies: ' ||
6243                              'p_del_supply_ids('||i||') = '|| p_del_supply_ids(i)||
6244                              --'p_inv_item_ids('||i||') = '|| p_inv_item_ids(i)||
6245                              --'p_plan_ids('||i||') = '|| p_plan_ids(i)||
6246                              'p_atp_peg_supplies_plan_ids('||i||') = '|| p_atp_peg_supplies_plan_ids(i)
6247                              --'p_identifiers('||i||') = '|| p_identifiers(i)
6248                              );
6249        END LOOP;
6250    END IF;
6251 
6252 
6253    x_return_status := FND_API.G_RET_STS_SUCCESS;
6254 
6255     -- CTO_PF_PRJ_2 Changes Set Relief Type
6256     IF ((MSC_ATP_PVT.G_INV_CTP = 4) AND
6257       (MSC_ATP_PVT.G_ALLOCATED_ATP = 'Y') AND
6258       (MSC_ATP_PVT.G_HIERARCHY_PROFILE = 1) AND
6259       (MSC_ATP_PVT.G_ALLOCATION_METHOD = 1)) THEN
6260 
6261        l_offset_type := 6;
6262     ELSE
6263        l_offset_type := 2;
6264     END IF;
6265     -- End CTO_PF_PRJ_2 Changes
6266 
6267    -- Bug 3381464 Update offset_supply_id in msc_atp_pegging.
6268    --Bug 3629191
6269    FORALL m in 1..p_del_supply_ids.COUNT
6270       UPDATE msc_atp_pegging map1
6271       SET    offset_supply_id = NULL
6272       WHERE  map1.plan_id = p_atp_peg_supplies_plan_ids(m)
6273       -- Bug 3629191: where clause on demand_source_type, sales_order_line_id
6274       -- and inventory_item_id are removed
6275       /*AND    DECODE(map1.demand_source_type,100,map1.demand_source_type,-1)
6276                       =decode(p_demand_source_type(m),
6277                               100,
6278                               p_demand_source_type(m),
6279                               -1) --CMRO;
6280       AND    map1.sales_order_line_id = p_identifiers(m) */
6281       AND    map1.relief_type = decode(map1.offset_type,1,6,2)  -- PO
6282       --AND  map1.inventory_item_id = p_inv_item_ids(m) -- Bug 3629191
6283       AND    map1.offset_supply_id = p_del_supply_ids(m);
6284 
6285       IF PG_DEBUG in ('Y', 'C') THEN
6286          msc_sch_wb.atp_debug('Remove_Offset_Supplies:  Number of rows Updated '||
6287                              SQL%ROWCOUNT);
6288       END IF;
6289    -- End Bug 3381464.
6290 
6291    -- CTO_PF_PRJ_2 Changes Set Relief Type
6292     IF ((MSC_ATP_PVT.G_INV_CTP = 4) AND
6293       (MSC_ATP_PVT.G_ALLOCATED_ATP = 'Y') AND
6294       (MSC_ATP_PVT.G_HIERARCHY_PROFILE = 1) AND
6295       (MSC_ATP_PVT.G_ALLOCATION_METHOD = 1)) THEN
6296 
6297        l_offset_type := 6;
6298     ELSE
6299        l_offset_type := 2;
6300     END IF;
6301     -- End CTO_PF_PRJ_2 Changes
6302 
6303    --Bug 3629191
6304    FORALL m IN 1..p_del_supply_ids.COUNT
6305       DELETE msc_supplies
6306       WHERE
6307       -- Bug 3629191 :All where clause except and transaction_id are commmented
6308       /* sr_instance_id = p_instance_id
6309       (SELECT sr_instance_id
6310        FROM   msc_atp_pegging
6311        WHERE  plan_id = p_plan_ids(m)
6312        AND    sales_order_line_id = p_identifiers(m)
6313        AND     DECODE(demand_source_type,100,demand_source_type,-1)
6314                       =decode(p_demand_source_type(m),
6315                               100,
6316                               p_demand_source_type(m),
6317                               -1) --CMRO;
6318        -- CTO_PF_PRJ_2 Changes Use Relief Type
6319        AND    relief_type = l_offset_type
6320        -- End CTO_PF_PRJ_2 Changes
6321        AND    inventory_item_id = p_inv_item_ids(m)
6322       )
6323       AND */
6324              plan_id = p_atp_peg_supplies_plan_ids(m)
6325       --AND  inventory_item_id = p_inv_item_ids(m) --Bug 3629191
6326       AND    transaction_id = p_del_supply_ids(m);
6327 
6328    -- Count how many rows were updated for each supply id
6329    IF PG_DEBUG in ('Y', 'C') THEN
6330         FOR m IN 1..p_del_supply_ids.COUNT LOOP
6331            msc_sch_wb.atp_debug('For Supply id '|| p_del_supply_ids(m)||': updated '||
6332                         SQL%BULK_ROWCOUNT(m)||' records');
6333         END LOOP;
6334    END IF;
6335 
6336    IF ((MSC_ATP_PVT.G_INV_CTP = 4) AND
6337        (MSC_ATP_PVT.G_ALLOCATED_ATP = 'Y') AND
6338        (MSC_ATP_PVT.G_HIERARCHY_PROFILE = 1) AND
6339        (MSC_ATP_PVT.G_ALLOCATION_METHOD = 1)) THEN
6340 
6341       IF PG_DEBUG in ('Y', 'C') THEN
6342             msc_sch_wb.atp_debug('Remove_Offset_Supplies: before delete from ' ||
6343                               ' msc_alloc_supplies');
6344       END IF;
6345 
6346       --Bug 3629191
6347       FORALL m IN 1..p_del_supply_ids.COUNT
6348          DELETE msc_alloc_supplies
6349          WHERE
6350          -- Bug 3629191 :All where clause except and parent_transaction_id are commmented
6351          /* sr_instance_id = p_instance_id
6352          (SELECT sr_instance_id
6353           FROM   msc_atp_pegging
6354           WHERE  plan_id = p_plan_ids(m)
6355           -- CTO_PF_PRJ_2 Changes Use Relief Type
6356           AND    relief_type = l_offset_type
6357           -- End CTO_PF_PRJ_2 Changes
6358           AND    sales_order_line_id = p_identifiers(m)
6359           AND     DECODE(demand_source_type,100,demand_source_type,-1)
6360                          =decode(p_demand_source_type(m),
6361                                  100,
6362                                  p_demand_source_type(m),
6363                                  -1) --CMRO;
6364           AND    inventory_item_id = p_inv_item_ids(m)
6365          )
6366          AND */
6367                 plan_id = p_atp_peg_supplies_plan_ids(m)
6368          --AND  inventory_item_id = p_inv_item_ids(m) --Bug 3629191
6369          AND    parent_transaction_id = p_del_supply_ids(m)
6370          ;
6371 
6372          -- Count how many rows were updated for each supply id
6373       IF PG_DEBUG in ('Y', 'C') THEN
6374            FOR m IN 1..p_del_supply_ids.COUNT LOOP
6375               msc_sch_wb.atp_debug('For Supply id '|| p_del_supply_ids(m)||': updated '||
6376                       SQL%BULK_ROWCOUNT(m)||' records');
6377            END LOOP;
6378       END IF;
6379    END IF;
6380 
6381    IF PG_DEBUG in ('Y', 'C') THEN
6382         msc_sch_wb.atp_debug('**********End Remove_Offset_Supplies Procedure************');
6383    END IF;
6384 
6385 EXCEPTION
6386     WHEN OTHERS THEN
6387         IF FND_MSG_PUB.Check_Msg_Level(FND_MSG_PUB.G_MSG_LVL_UNEXP_ERROR) THEN
6388             FND_MSG_PUB.Add_Exc_Msg (G_PKG_NAME , 'Remove_Offset_Supplies');
6389         END IF;
6390 
6391         IF PG_DEBUG in ('Y', 'C')  THEN
6392            msc_sch_wb.atp_debug('Remove_Offset_Supplies: ERROR' || sqlerrm );
6393         END IF;
6394         x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
6395         -- Bug 3319810 Enable exception generation.
6396         RAISE FND_API.G_EXC_UNEXPECTED_ERROR;
6397 
6398 END Remove_Offset_Supplies;
6399 
6400 
6401 PROCEDURE Remove_Offset_Resource_Reqs (
6402              --p_identifiers      IN       MRP_ATP_PUB.Number_Arr,
6403              --p_plan_ids         IN       MRP_ATP_PUB.Number_Arr,
6404              p_atp_peg_res_reqs_plan_ids IN MRP_ATP_PUB.Number_Arr, --Bug 3629191
6405              p_inv_item_ids     IN       MRP_ATP_PUB.Number_Arr,
6406              p_del_resrc_reqs   IN       MRP_ATP_PUB.Number_Arr,
6407              p_demand_source_type IN     MRP_ATP_PUB.Number_Arr,--cmro
6408              x_return_status    IN OUT   NoCopy VARCHAR2
6409                                 )
6410 IS
6411 l_del_rows          NUMBER;
6412 i                   NUMBER;
6413 m                   PLS_INTEGER := 1;
6414 BEGIN
6415    IF PG_DEBUG in ('Y', 'C') THEN
6416         msc_sch_wb.atp_debug('**********Begin Remove_Offset_Resource_Reqs Procedure************');
6417     END IF;
6418    IF PG_DEBUG in ('Y', 'C') THEN
6419        FOR i in 1..p_del_resrc_reqs.COUNT LOOP
6420             msc_sch_wb.atp_debug('Remove_Offset_Resource_Reqs: ' ||
6421                              'p_del_resrc_reqs('||i||') = '|| p_del_resrc_reqs(i)||
6422                              --'p_inv_item_ids('||i||') = '|| p_inv_item_ids(i)||
6423                              --'p_plan_ids('||i||') = '|| p_plan_ids(i)||
6424                              --'p_identifiers('||i||') = '|| p_identifiers(i)
6425                              'p_atp_peg_res_reqs_plan_ids('||i||') = '|| p_atp_peg_res_reqs_plan_ids(i)
6426                              );
6427        END LOOP;
6428    END IF;
6429 
6430    x_return_status := FND_API.G_RET_STS_SUCCESS;
6431 
6432    --Bug 3629191
6433    FORALL m IN 1..p_del_resrc_reqs.COUNT
6434       DELETE msc_resource_requirements
6435       WHERE
6436       -- Bug 3629191 :All where clause except and transaction_id are commmented
6437       /*sr_instance_id = p_instance_id
6438       (SELECT sr_instance_id
6439        FROM   msc_atp_pegging
6440        WHERE  plan_id = p_plan_ids(m)
6441        AND    sales_order_line_id = p_identifiers(m)
6442        AND     DECODE(demand_source_type,100,demand_source_type,-1)
6443                       =decode(p_demand_source_type(m),
6444                               100,
6445                               p_demand_source_type(m),
6446                               -1) --CMRO;
6447        AND    inventory_item_id = p_inv_item_ids(m)
6448        AND    relief_type = 4
6449       )
6450       AND */
6451              plan_id = p_atp_peg_res_reqs_plan_ids(m) --Bug 3629191
6452       --AND  assembly_item_id = p_inv_item_ids(m)
6453       AND    transaction_id = p_del_resrc_reqs(m);
6454 
6455    -- Count how many rows were updated for each resource transaction id
6456    IF PG_DEBUG in ('Y', 'C') THEN
6457         FOR m IN 1..p_del_resrc_reqs.COUNT LOOP
6458            msc_sch_wb.atp_debug('For Transaction id '|| p_del_resrc_reqs(m)||': updated '||
6459                         SQL%BULK_ROWCOUNT(m)||' records');
6460         END LOOP;
6461    END IF;
6462 
6463    IF PG_DEBUG in ('Y', 'C') THEN
6464         msc_sch_wb.atp_debug('**********End Remove_Offset_Resource_Reqs Procedure************');
6465    END IF;
6466 
6467 EXCEPTION
6468     WHEN OTHERS THEN
6469         IF FND_MSG_PUB.Check_Msg_Level(FND_MSG_PUB.G_MSG_LVL_UNEXP_ERROR) THEN
6470             FND_MSG_PUB.Add_Exc_Msg (G_PKG_NAME , 'Remove_Offset_Resource_Reqs');
6471         END IF;
6472 
6473         IF PG_DEBUG in ('Y', 'C')  THEN
6474            msc_sch_wb.atp_debug('Remove_Offset_Supplies: ERROR' || sqlerrm );
6475         END IF;
6476         x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
6477         -- Bug 3319810 Enable exception generation.
6478         RAISE FND_API.G_EXC_UNEXPECTED_ERROR;
6479 
6480 END Remove_Offset_Resource_Reqs;
6481 
6482 PROCEDURE Remove_Offset_Data (
6483                     --p_identifiers      IN         MRP_ATP_PUB.Number_Arr, --Bug 3629191
6484                     --p_plan_ids         IN         MRP_ATP_PUB.Number_Arr, --Bug 3629191
6485                     p_inv_item_ids     IN         MRP_ATP_PUB.Number_Arr,
6486                     p_del_demand_ids   IN         MRP_ATP_PUB.Number_Arr,
6487                     p_del_supply_ids   IN         MRP_ATP_PUB.Number_Arr,
6488                     p_del_resrc_reqs   IN         MRP_ATP_PUB.Number_Arr,
6489                     p_demand_source_type IN       MRP_ATP_PUB.Number_Arr,--cmro
6490                     p_atp_peg_demands_plan_ids  IN MRP_ATP_PUB.Number_Arr, --Bug 3629191
6491                     p_atp_peg_supplies_plan_ids IN MRP_ATP_PUB.Number_Arr, --Bug 3629191
6492                     p_atp_peg_res_reqs_plan_ids IN MRP_ATP_PUB.Number_Arr, --Bug 3629191
6493                     x_return_status    OUT NoCopy VARCHAR2
6494                     )
6495 IS
6496 BEGIN
6497 
6498    IF PG_DEBUG in ('Y', 'C') THEN
6499         msc_sch_wb.atp_debug('**********Begin Remove_Offset_Data Procedure************');
6500     END IF;
6501 
6502     x_return_status := FND_API.G_RET_STS_SUCCESS;
6503 
6504     Remove_Offset_Demands ( --p_identifiers, p_plan_ids,
6505                            p_atp_peg_demands_plan_ids, --Bug 3629191
6506                            p_inv_item_ids, p_del_demand_ids,p_demand_source_type, x_return_status);--cmro
6507 
6508     IF PG_DEBUG in ('Y', 'C')  THEN
6509         msc_sch_wb.atp_debug('Status After Call to Remove_Offset_Demands :'
6510                                                         || x_return_status);
6511     END IF;
6512 
6513     Remove_Offset_Supplies ( --p_identifiers, p_plan_ids,
6514                             p_atp_peg_supplies_plan_ids, --Bug 3629191
6515                             p_inv_item_ids, p_del_supply_ids,p_demand_source_type,x_return_status);--cmro
6516 
6517     IF PG_DEBUG in ('Y', 'C')  THEN
6518         msc_sch_wb.atp_debug('Status After Call to Remove_Offset_Supplies :'
6519                                                         || x_return_status);
6520     END IF;
6521 
6522     Remove_Offset_Resource_Reqs ( --p_identifiers, p_plan_ids,
6523                            p_atp_peg_res_reqs_plan_ids, --Bug 3629191
6524                            p_inv_item_ids, p_del_resrc_reqs,p_demand_source_type,x_return_status);--cmro
6525 
6526     IF PG_DEBUG in ('Y', 'C')  THEN
6527         msc_sch_wb.atp_debug('Status After Call to Remove_Offset_Resource_Reqs :'
6528                                                         || x_return_status);
6529     END IF;
6530 
6531 EXCEPTION
6532     WHEN OTHERS THEN
6533         IF FND_MSG_PUB.Check_Msg_Level(FND_MSG_PUB.G_MSG_LVL_UNEXP_ERROR) THEN
6534             FND_MSG_PUB.Add_Exc_Msg (G_PKG_NAME , 'Remove_Offset_Data');
6535         END IF;
6536 
6537         IF PG_DEBUG in ('Y', 'C')  THEN
6538            msc_sch_wb.atp_debug('Remove_Offset_Data: ERROR' || sqlerrm );
6539         END IF;
6540         x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
6541         -- Bug 3319810 Enable exception generation.
6542         RAISE FND_API.G_EXC_UNEXPECTED_ERROR;
6543 END Remove_Offset_Data;
6544 
6545 -- Create Simplified pegging data for PF ATP Scenario.
6546 -- CTO_PF_PRJ_2 New procedure for CTO PF Cross Project Impacts.
6547 PROCEDURE Create_PF_Atp_Pegging(
6548   p_reference_item_id      IN         NUMBER,
6549   p_model_order_line_id    IN         NUMBER,
6550   p_config_order_line_id   IN         NUMBER,
6551   p_demand_source_type     IN         NUMBER,--cmro
6552   p_end_demand_id          IN         NUMBER,
6553   p_plan_id                IN         NUMBER,
6554   x_return_status          IN OUT     NoCopy VARCHAR2
6555 )
6556 IS
6557 
6558 my_sqlcode                NUMBER;
6559 l_dmd_offset_typ          NUMBER;
6560 
6561 BEGIN
6562 
6563   IF PG_DEBUG in ('Y', 'C') THEN
6564      msc_sch_wb.atp_debug('***** Begin Create_PF_Atp_Pegging Procedure *****');
6565      msc_sch_wb.atp_debug('Reference Item Id : ' || p_reference_item_id);
6566      msc_sch_wb.atp_debug('Model Line Id p_model_order_line_id : ' || p_model_order_line_id);
6567      msc_sch_wb.atp_debug('Config. Line Id p_config_order_line_id : ' || p_config_order_line_id);
6568      msc_sch_wb.atp_debug('Demand Source Type : ' || p_demand_source_type);
6569      msc_sch_wb.atp_debug('SO End Demand Id : ' || p_end_demand_id);
6570      msc_sch_wb.atp_debug('Plan Id : ' || p_plan_id);
6571      msc_sch_wb.atp_debug('MSC_ATP_PVT.G_HYBRID_ALLOC_ATP : ' || MSC_ATP_PVT.G_HYBRID_ALLOC_ATP);
6572   END IF;
6573 
6574   x_return_status := FND_API.G_RET_STS_SUCCESS;
6575 
6576   IF ((MSC_ATP_PVT.G_INV_CTP = 4) AND
6577       (MSC_ATP_PVT.G_ALLOCATED_ATP = 'Y') AND
6578       (MSC_ATP_PVT.G_HIERARCHY_PROFILE = 1) AND
6579       (MSC_ATP_PVT.G_ALLOCATION_METHOD = 1)) THEN
6580 
6581      l_dmd_offset_typ := 5;
6582    ELSE
6583      l_dmd_offset_typ := 3;
6584    END IF;
6585   -- First create the demand records for component members and component family items.
6586 
6587   IF (MSC_ATP_PVT.G_HYBRID_ALLOC_ATP = 'Y' ) THEN
6588 
6589   INSERT INTO msc_atp_pegging
6590           (reference_item_id, inventory_item_id, plan_id, sr_instance_id,
6591            organization_id, sales_order_line_id, demand_source_type, bom_item_type, --cmro
6592            transaction_date, demand_id, demand_quantity,
6593            disposition_id, demand_class, supply_id, supply_quantity,
6594            allocated_quantity, relief_type, relief_quantity, daily_relief_qty,
6595            pegging_id, prev_pegging_id, end_pegging_id, end_demand_id,
6596            created_by, creation_date, last_updated_by, last_update_date,
6597            original_item_id, original_date,
6598            customer_id, customer_site_id, offset_type)
6599   SELECT mapt.reference_item_id, alocd.inventory_item_id, alocd.plan_id,
6600          alocd.sr_instance_id, alocd.organization_id,
6601          mapt.sales_order_line_id, mapt.demand_source_type,
6602          msi.bom_item_type, alocd.demand_date transaction_date,
6603          alocd.parent_demand_id demand_id, alocd.demand_quantity, mapt.disposition_id,
6604          alocd.demand_class, mapt.supply_id,
6605          mapt.supply_quantity, alocd.allocated_quantity, 7 relief_type,
6606          LEAST(ABS(mapt.relief_quantity), alocd.allocated_quantity) * SIGN(mapt.relief_quantity) *
6607          alocd.allocated_quantity/NVL(mapt.allocated_quantity,alocd.allocated_quantity) relief_quantity,
6608          LEAST(ABS(mapt.daily_relief_qty), alocd.allocated_quantity) * SIGN(mapt.relief_quantity) *
6609          alocd.allocated_quantity/NVL(mapt.allocated_quantity,alocd.allocated_quantity) daily_relief_qty,
6610          mapt.pegging_id, mapt.prev_pegging_id, mapt.end_pegging_id, mapt.end_demand_id,
6611          mapt.created_by, mapt.creation_date, mapt.last_updated_by, mapt.last_update_date,
6612          mapt.inventory_item_id, mapt.transaction_date,
6613          alocd.customer_id, alocd.ship_to_site_id,  DECODE(MSC_ATP_PVT.G_HIERARCHY_PROFILE, 2, 2,
6614 																		DECODE(MSC_ATP_PVT.G_ALLOCATION_METHOD, 2, 2,
6615 																		decode(alloc.inventory_item_id, null, 2 , 1)
6616 									)
6617 									) offset_type
6618   FROM   msc_atp_peg_temp mapt, msc_alloc_demands alocd,
6619          msc_system_items msi, msc_item_hierarchy_mv alloc
6620   WHERE  mapt.reference_item_id = p_reference_item_id
6621   AND    mapt.plan_id = p_plan_id
6622   AND    mapt.sales_order_line_id = NVL(p_config_order_line_id, p_model_order_line_id)
6623   --AND    mapt.demand_source_type = p_demand_source_type
6624   AND    mapt.end_demand_id = p_end_demand_id
6625   AND    mapt.relief_type = DECODE(MSC_ATP_PVT.G_HIERARCHY_PROFILE, 2, 3,
6626 																		DECODE(MSC_ATP_PVT.G_ALLOCATION_METHOD, 2, 3,
6627 																		decode(alloc.inventory_item_id, null, 2 , 5)
6628 									)
6629 									) --l_dmd_offset_typ
6630   AND    alocd.plan_id = mapt.plan_id
6631   AND    alocd.sr_instance_id = mapt.sr_instance_id
6632   AND    alocd.organization_id = mapt.organization_id
6633   AND    alocd.original_item_id = mapt.inventory_item_id
6634   AND    alocd.parent_demand_id = mapt.demand_id
6635   AND    msi.plan_id = alocd.plan_id
6636   AND    msi.sr_instance_id = alocd.sr_instance_id
6637   AND    msi.organization_id = alocd.organization_id
6638   AND    msi.inventory_item_id = alocd.inventory_item_id
6639   AND    msi.sr_instance_id = alloc.sr_instance_id(+)
6640   AND    msi.organization_id = alloc.organization_id(+)
6641   AND    msi.inventory_item_id = alloc.inventory_item_id(+)
6642   ;
6643 
6644   ELSE
6645     INSERT INTO msc_atp_pegging
6646           (reference_item_id, inventory_item_id, plan_id, sr_instance_id,
6647            organization_id, sales_order_line_id, demand_source_type, bom_item_type, --cmro
6648            transaction_date, demand_id, demand_quantity,
6649            disposition_id, demand_class, supply_id, supply_quantity,
6650            allocated_quantity, relief_type, relief_quantity, daily_relief_qty,
6651            pegging_id, prev_pegging_id, end_pegging_id, end_demand_id,
6652            created_by, creation_date, last_updated_by, last_update_date,
6653            original_item_id, original_date,
6654            customer_id, customer_site_id, offset_type)
6655   SELECT mapt.reference_item_id, alocd.inventory_item_id, alocd.plan_id,
6656          alocd.sr_instance_id, alocd.organization_id,
6657          mapt.sales_order_line_id, mapt.demand_source_type,
6658          msi.bom_item_type, alocd.demand_date transaction_date,
6659          alocd.parent_demand_id demand_id, alocd.demand_quantity, mapt.disposition_id,
6660          alocd.demand_class, mapt.supply_id,
6661          mapt.supply_quantity, alocd.allocated_quantity, 7 relief_type,
6662          LEAST(ABS(mapt.relief_quantity), alocd.allocated_quantity) * SIGN(mapt.relief_quantity) *
6663          alocd.allocated_quantity/NVL(mapt.allocated_quantity,alocd.allocated_quantity) relief_quantity,
6664          LEAST(ABS(mapt.daily_relief_qty), alocd.allocated_quantity) * SIGN(mapt.relief_quantity) *
6665          alocd.allocated_quantity/NVL(mapt.allocated_quantity,alocd.allocated_quantity) daily_relief_qty,
6666          mapt.pegging_id, mapt.prev_pegging_id, mapt.end_pegging_id, mapt.end_demand_id,
6667          mapt.created_by, mapt.creation_date, mapt.last_updated_by, mapt.last_update_date,
6668          mapt.inventory_item_id, mapt.transaction_date,
6669          alocd.customer_id, alocd.ship_to_site_id, 2
6670   FROM   msc_atp_peg_temp mapt, msc_alloc_demands alocd,
6671          msc_system_items msi
6672   WHERE  mapt.reference_item_id = p_reference_item_id
6673   AND    mapt.plan_id = p_plan_id
6674   AND    mapt.sales_order_line_id = NVL(p_config_order_line_id, p_model_order_line_id)
6675   --AND    mapt.demand_source_type = p_demand_source_type
6676   AND    mapt.end_demand_id = p_end_demand_id
6677   AND    mapt.relief_type = l_dmd_offset_typ
6678   AND    alocd.plan_id = mapt.plan_id
6679   AND    alocd.sr_instance_id = mapt.sr_instance_id
6680   AND    alocd.organization_id = mapt.organization_id
6681   AND    alocd.original_item_id = mapt.inventory_item_id
6682   AND    alocd.parent_demand_id = mapt.demand_id
6683   AND    msi.plan_id = alocd.plan_id
6684   AND    msi.sr_instance_id = alocd.sr_instance_id
6685   AND    msi.organization_id = alocd.organization_id
6686   AND    msi.inventory_item_id = alocd.inventory_item_id;
6687 
6688   END IF;
6689 
6690   IF PG_DEBUG in ('Y', 'C') THEN
6691      msc_sch_wb.atp_debug('Create_PF_Atp_Pegging:  Number of rows inserted Stage-1 '||
6692                                SQL%ROWCOUNT);
6693   END IF;
6694 
6695   -- Now Create Rest of the Records.
6696   INSERT INTO msc_atp_pegging
6697           (reference_item_id, inventory_item_id, plan_id, sr_instance_id,
6698            organization_id, sales_order_line_id, demand_source_type, bom_item_type, --cmro
6699            transaction_date, demand_id, demand_quantity,
6700            disposition_id, demand_class, supply_id, supply_quantity,
6701            allocated_quantity,
6702            resource_id, department_id, resource_hours, end_date,
6703            relief_type, relief_quantity, daily_relief_qty,
6704            pegging_id, prev_pegging_id, end_pegging_id, end_demand_id,
6705            created_by, creation_date, last_updated_by, last_update_date,
6706            customer_id, customer_site_id, offset_type)
6707   SELECT  reference_item_id, inventory_item_id, plan_id, sr_instance_id,
6708           organization_id, sales_order_line_id, demand_source_type, bom_item_type, --cmro
6709           transaction_date, demand_id, demand_quantity,
6710           disposition_id, demand_class, supply_id, supply_quantity,
6711           allocated_quantity,
6712           resource_id, department_id, resource_hours, end_date,
6713           relief_type, relief_quantity, daily_relief_qty,
6714           pegging_id, prev_pegging_id, end_pegging_id, end_demand_id,
6715           created_by, creation_date, last_updated_by, last_update_date,
6716           customer_id, customer_site_id, offset_type
6717   FROM    msc_atp_peg_temp mapt
6718   WHERE   mapt.reference_item_id = p_reference_item_id
6719   AND     mapt.plan_id = p_plan_id
6720   AND     mapt.sales_order_line_id = NVL(p_config_order_line_id, p_model_order_line_id)
6721   --AND     mapt.demand_source_type = p_demand_source_type
6722   AND     mapt.end_demand_id = p_end_demand_id
6723           -- Process everything except PF member and family demands.
6724   AND     mapt.inventory_item_id NOT IN
6725           (SELECT NVL(original_item_id, inventory_item_id)
6726            FROM   msc_atp_pegging
6727            WHERE  reference_item_id = p_reference_item_id
6728            AND    plan_id = p_plan_id
6729            AND    sales_order_line_id = NVL(p_config_order_line_id, p_model_order_line_id)
6730            --AND    demand_source_type = p_demand_source_type
6731            AND    end_demand_id = p_end_demand_id
6732            AND    relief_type = 7
6733           );
6734 
6735   IF PG_DEBUG in ('Y', 'C') THEN
6736      msc_sch_wb.atp_debug('Create_PF_Atp_Pegging:  Number of rows inserted Stage-2 '||
6737                                SQL%ROWCOUNT);
6738   END IF;
6739 
6740   IF PG_DEBUG in ('Y', 'C') THEN
6741      msc_sch_wb.atp_debug('***** End Create_PF_Atp_Pegging Procedure *****');
6742   END IF;
6743 
6744 EXCEPTION
6745     WHEN OTHERS THEN
6746         my_sqlcode := SQLCODE;
6747         IF PG_DEBUG in ('Y', 'C') THEN
6748            msc_sch_wb.atp_debug('Create_PF_Atp_Pegging: ' || my_sqlcode ||
6749                 ' error encountered while creating ATP Pegging : ERROR =  '|| sqlerrm);
6750         END IF;
6751 
6752         IF FND_MSG_PUB.Check_Msg_Level(FND_MSG_PUB.G_MSG_LVL_UNEXP_ERROR) THEN
6753             FND_MSG_PUB.Add_Exc_Msg(G_PKG_NAME , 'Create_PF_Atp_Pegging');
6754         END IF;
6755         x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
6756         RAISE FND_API.G_EXC_UNEXPECTED_ERROR;
6757 
6758 END Create_PF_Atp_Pegging;
6759 -- End CTO_PF_PRJ_2
6760 
6761 -- Create Simplified pegging data using ATP Pegging information.
6762 PROCEDURE Create_Atp_Pegging(
6763   p_identifier             IN      NUMBER,
6764   p_instance_id            IN      NUMBER,
6765   p_old_plan_id            IN      NUMBER,
6766   p_model_order_line_id    IN      NUMBER,
6767   p_config_order_line_id   IN      NUMBER,
6768   p_demand_source_type     IN      NUMBER,--cmro
6769   x_return_status          OUT     NoCopy VARCHAR2
6770 )
6771 IS
6772 
6773 l_reference_item_id       NUMBER;
6774 i                         NUMBER;
6775 atp_peg_rec               msc_atp_pegging%ROWTYPE;
6776 my_sqlcode                NUMBER;
6777 -- Bug 3334643 Track the plan_id
6778 l_plan_id                 NUMBER;
6779 
6780 -- CTO_PF_PRJ Get End Demand Id
6781 l_end_demand_id                 NUMBER;
6782 -- CTO_PF_PRJ_2 Impacts
6783 l_session_id                    NUMBER;
6784 l_insert_temp_table             VARCHAR2(30);
6785 l_sql_stmt                      VARCHAR2(800);
6786 l_sql_stmt_1                    VARCHAR2(8000);
6787 l_sup_offset_typ                NUMBER;
6788 l_dmd_offset_typ                NUMBER;
6789 l_peg_type                      NUMBER;
6790 -- End CTO_PF_PRJ_2 Impacts
6791 
6792 BEGIN
6793 
6794   IF PG_DEBUG in ('Y', 'C') THEN
6795      msc_sch_wb.atp_debug('***** Begin Create_Atp_Pegging Procedure *****');
6796      msc_sch_wb.atp_debug('End Pegging Id p_identifier : ' || p_identifier);
6797      msc_sch_wb.atp_debug('Instance Id p_instance_id : ' || p_instance_id);
6798      msc_sch_wb.atp_debug('Old Plan Id : ' || p_old_plan_id);
6799      msc_sch_wb.atp_debug('Model Line Id p_model_order_line_id : ' || p_model_order_line_id);
6800      msc_sch_wb.atp_debug('Config. Line Id p_config_order_line_id : ' || p_config_order_line_id);
6801      msc_sch_wb.atp_debug('Demand. Source Type p_demand_source_type : ' || p_demand_source_type);
6802      msc_sch_wb.atp_debug('MSC_ATP_PVT.G_HYBRID_ALLOC_ATP : ' || MSC_ATP_PVT.G_HYBRID_ALLOC_ATP);
6803   END IF;
6804 
6805   x_return_status := FND_API.G_RET_STS_SUCCESS;
6806 
6807    -- CTO_PF_PRJ_2 Impacts
6808    IF (MSC_ATP_PVT.G_CTO_PF_ATP = 'Y') THEN
6809       l_insert_temp_table := 'MSC_ATP_PEG_TEMP';
6810    ELSE
6811       l_insert_temp_table := 'MSC_ATP_PEGGING';
6812    END IF;
6813 
6814    IF ((MSC_ATP_PVT.G_INV_CTP = 4) AND
6815       (MSC_ATP_PVT.G_ALLOCATED_ATP = 'Y') AND
6816       (MSC_ATP_PVT.G_HIERARCHY_PROFILE = 1) AND
6817       (MSC_ATP_PVT.G_ALLOCATION_METHOD = 1)) THEN
6818 
6819      l_sup_offset_typ := 6;
6820      l_dmd_offset_typ := 5;
6821    ELSE
6822      l_sup_offset_typ := 2;
6823      l_dmd_offset_typ := 3;
6824    END IF;
6825    -- CTO_PF_PRJ_2 Impacts
6826 
6827    -- First Delete old pegging data.
6828    BEGIN
6829 
6830          DELETE from msc_atp_pegging
6831          WHERE  plan_id = p_old_plan_id
6832          AND    relief_type > 0
6833          AND    sales_order_line_id in (NVL(p_config_order_line_id, -1), p_model_order_line_id)
6834          AND     decode(demand_source_type,100,demand_source_type,-1)
6835                 =decode(p_demand_source_type,
6836                                                 100,
6837                                                 p_demand_source_type,
6838                                                 -1); --CMRO
6839       IF PG_DEBUG in ('Y', 'C') THEN
6840              msc_sch_wb.atp_debug('Create_Atp_Pegging:  Number of rows deleted '||
6841                                SQL%ROWCOUNT);
6842       END IF;
6843    EXCEPTION
6844       WHEN OTHERS THEN
6845         IF PG_DEBUG in ('Y', 'C') THEN
6846            msc_sch_wb.atp_debug('Create_Atp_Pegging:  Error '|| sqlerrm);
6847         END IF;
6848 
6849    END;
6850 
6851    msc_sch_wb.atp_debug('Create_Atp_Pegging:  l_insert_temp_table = '|| l_insert_temp_table);
6852    -- CTO_PF_PRJ_2 Impacts SQL are changed to Dynamic Ones
6853    --  first insert the sales order line to the ATP simplified pegging.
6854    -- ALLOC ATP CHANGES
6855    IF (MSC_ATP_PVT.G_HYBRID_ALLOC_ATP = 'N' ) THEN
6856    l_sql_stmt_1 := 'INSERT INTO ' || l_insert_temp_table ||
6857                '(reference_item_id, inventory_item_id, plan_id, sr_instance_id,
6858                 organization_id, sales_order_line_id,demand_source_type, bom_item_type, --cmro
6859                 transaction_date, demand_id, demand_quantity,
6860                 disposition_id, demand_class, supply_id, supply_quantity,
6861                 allocated_quantity,
6862                 resource_id, department_id, resource_hours, end_date, -- start_date,
6863                             -- Bug 3443056, 3348095 ATP now tracks end date.
6864                 relief_type, relief_quantity, daily_relief_qty,
6865                 pegging_id, prev_pegging_id, end_pegging_id, end_demand_id,
6866                 created_by, creation_date, last_updated_by, last_update_date,
6867                 customer_id, customer_site_id)
6868          SELECT dest_inv_item_id , NVL(DEST_INV_ITEM_ID, INVENTORY_ITEM_ID),
6869                 identifier2 plan_id, identifier1 sr_instance_id,
6870                 NVL(RECEIVING_ORGANIZATION_ID, organization_id) ,
6871                 NVL(:p_config_order_line_id, :p_model_order_line_id) sales_order_line_id,
6872                 :p_demand_source_type,--cmro
6873                 --bug 3328421
6874                 --NULL bom_item_type, NVL(required_date, supply_demand_date) transaction_date,
6875                 NULL bom_item_type, NVL(actual_supply_demand_date, supply_demand_date) transaction_date,
6876                 -- identifier3 contains the demand_id
6877                 -- supply_demand_quantity contains the demand_quantity
6878                 DECODE (pegging_type, :l_peg_type1,
6879                          identifier3, NULL) demand_id,
6880                 DECODE (pegging_type, :l_peg_type2,
6881                          supply_demand_quantity, NULL) supply_demand_quantity,
6882                 NULL disposition_id, demand_class,
6883                 -- identifier3 contains the transaction_id
6884                 -- supply_demand_quantity contains the supply_quantitiy
6885                 -- For ATP created pegging the allocated_qty is the same as supply_qty
6886                 DECODE (pegging_type,
6887                          :l_peg_type3, identifier3,
6888                          :l_peg_type4, identifier3,
6889                          :l_peg_type5, identifier3,
6890                           NULL) supply_id,
6891                 DECODE (pegging_type,
6892                          :l_peg_type6, supply_demand_quantity,
6893                          :l_peg_type7, supply_demand_quantity,
6894                          :l_peg_type8, supply_demand_quantity,
6895                           NULL) supply_quantity,
6896                 DECODE (pegging_type,
6897                          :l_peg_type9, supply_demand_quantity,
6898                          :l_peg_type10, supply_demand_quantity,
6899                          :l_peg_type11, supply_demand_quantity,
6900                           NULL) allocated_quantity,
6901                 resource_id, department_id,
6902                 DECODE (pegging_type,
6903                          :l_peg_type12, supply_demand_quantity,
6904                          NULL) resource_hours,
6905                 --bug 3328421
6906                 --NVL(required_date, supply_demand_date) start_date,
6907                 NVL(actual_supply_demand_date, supply_demand_date) end_date, -- start_date,
6908                             -- Bug 3443056, 3348095 ATP now tracks end date.
6909                 DECODE (pegging_type,
6910                         :l_peg_type13,
6911                           decode(pegging_id, end_pegging_id, 1, :l_dmd_offset_typ),
6912                            -- pegging_id is same as end_pegging_id then SO
6913                            -- otherwise POD
6914                          :l_peg_type14, :l_sup_offset_typ,      -- PO
6915                          :l_peg_type15, :l_sup_offset_typ,  -- PO
6916                          :l_peg_type16, 4 , -- REQ
6917                          :l_peg_type17, :l_sup_offset_typ )
6918                           relief_type,
6919                 decode(pegging_id, end_pegging_id, 0,
6920                       -1 *  supply_demand_quantity ) relief_quantity,
6921                 NULL daily_relief_qty,
6922                 pegging_id, parent_pegging_id, end_pegging_id,
6923                 DECODE (pegging_type, :l_peg_type18,
6924                          identifier3, NULL) end_demand_id,
6925                 created_by, creation_date, last_updated_by, last_update_date,
6926                 customer_id, customer_site_id
6927          FROM   mrp_atp_details_temp
6928          WHERE  pegging_id = :p_identifier
6929          AND    identifier1 = :p_instance_id
6930          AND    record_type = 3
6931          and    session_id = :l_session_id
6932          and    model_sd_flag = 1' -- ensure that we only obtain pegging for things in the order.
6933          ;
6934 
6935   IF PG_DEBUG in ('Y', 'C') THEN
6936              msc_sch_wb.atp_debug('Create_Atp_Pegging:  Insert SQL Statement '||
6937                                l_sql_stmt_1);
6938   END IF;
6939 
6940     EXECUTE IMMEDIATE l_sql_stmt_1 USING
6941            p_config_order_line_id,
6942            p_model_order_line_id,
6943            p_demand_source_type,
6944            MSC_ATP_PVT.ORG_DEMAND,
6945            MSC_ATP_PVT.ORG_DEMAND,
6946            MSC_ATP_PVT.MAKE_SUPPLY,
6947            MSC_ATP_PVT.TRANSFER_SUPPLY,
6948            MSC_ATP_PVT.BUY_SUPPLY,
6949            MSC_ATP_PVT.MAKE_SUPPLY,
6950            MSC_ATP_PVT.TRANSFER_SUPPLY,
6951            MSC_ATP_PVT.BUY_SUPPLY,
6952            MSC_ATP_PVT.MAKE_SUPPLY,
6953            MSC_ATP_PVT.TRANSFER_SUPPLY,
6954            MSC_ATP_PVT.BUY_SUPPLY,
6955            MSC_ATP_PVT.RESOURCE_DEMAND,
6956            MSC_ATP_PVT.ORG_DEMAND,
6957            l_dmd_offset_typ,
6958            MSC_ATP_PVT.MAKE_SUPPLY,
6959            l_sup_offset_typ,
6960            MSC_ATP_PVT.TRANSFER_SUPPLY,
6961            l_sup_offset_typ,
6962            MSC_ATP_PVT.RESOURCE_DEMAND,
6963            MSC_ATP_PVT.BUY_SUPPLY,
6964            l_sup_offset_typ,
6965            MSC_ATP_PVT.ORG_DEMAND,
6966            p_identifier,
6967            p_instance_id,
6968            MSC_ATP_PVT.G_SESSION_ID;
6969 
6970 	ELSE
6971 
6972    l_sql_stmt_1 := 'INSERT INTO ' || l_insert_temp_table ||
6973                '(reference_item_id, inventory_item_id, plan_id, sr_instance_id,
6974                 organization_id, sales_order_line_id,demand_source_type, bom_item_type, --cmro
6975                 transaction_date, demand_id, demand_quantity,
6976                 disposition_id, demand_class, supply_id, supply_quantity,
6977                 allocated_quantity,
6978                 resource_id, department_id, resource_hours, end_date, -- start_date,
6979                             -- Bug 3443056, 3348095 ATP now tracks end date.
6980                 relief_type, relief_quantity, daily_relief_qty,
6981                 pegging_id, prev_pegging_id, end_pegging_id, end_demand_id,
6982                 created_by, creation_date, last_updated_by, last_update_date,
6983                 customer_id, customer_site_id, offset_type)
6984          SELECT peg.dest_inv_item_id , NVL(peg.DEST_INV_ITEM_ID, peg.INVENTORY_ITEM_ID),
6985                 peg.identifier2 plan_id, peg.identifier1 sr_instance_id,
6986                 NVL(peg.RECEIVING_ORGANIZATION_ID, peg.organization_id) ,
6987                 NVL(:p_config_order_line_id, :p_model_order_line_id) sales_order_line_id,
6988                 :p_demand_source_type,--cmro
6989                 --bug 3328421
6990                 --NULL bom_item_type, NVL(required_date, supply_demand_date) transaction_date,
6991                 NULL bom_item_type, NVL(peg.actual_supply_demand_date, peg.supply_demand_date) transaction_date,
6992                 -- identifier3 contains the demand_id
6993                 -- supply_demand_quantity contains the demand_quantity
6994                 DECODE (peg.pegging_type, :l_peg_type1,
6995                          peg.identifier3, NULL) demand_id,
6996                 DECODE (peg.pegging_type, :l_peg_type2,
6997                          peg.supply_demand_quantity, NULL) supply_demand_quantity,
6998                 NULL disposition_id, peg.demand_class,
6999                 -- identifier3 contains the transaction_id
7000                 -- supply_demand_quantity contains the supply_quantitiy
7001                 -- For ATP created pegging the allocated_qty is the same as supply_qty
7002                 DECODE (peg.pegging_type,
7003                          :l_peg_type3, peg.identifier3,
7004                          :l_peg_type4, peg.identifier3,
7005                          :l_peg_type5, peg.identifier3,
7006                           NULL) supply_id,
7007                 DECODE (peg.pegging_type,
7008                          :l_peg_type6, peg.supply_demand_quantity,
7009                          :l_peg_type7, peg.supply_demand_quantity,
7010                          :l_peg_type8, peg.supply_demand_quantity,
7011                           NULL) supply_quantity,
7012                 DECODE (peg.pegging_type,
7013                          :l_peg_type9, peg.supply_demand_quantity,
7014                          :l_peg_type10, peg.supply_demand_quantity,
7015                          :l_peg_type11, peg.supply_demand_quantity,
7016                           NULL) allocated_quantity,
7017                 peg.resource_id, peg.department_id,
7018                 DECODE (peg.pegging_type,
7019                          :l_peg_type12, peg.supply_demand_quantity,
7020                          NULL) resource_hours,
7021                 --bug 3328421
7022                 --NVL(required_date, supply_demand_date) start_date,
7023                 NVL(peg.actual_supply_demand_date, peg.supply_demand_date) end_date, -- start_date,
7024                             -- Bug 3443056, 3348095 ATP now tracks end date.
7025                 DECODE (peg.pegging_type,
7026                         :l_peg_type13,
7027                           decode(peg.pegging_id, peg.end_pegging_id, 1, DECODE(:G_HIERARCHY_PROFILE, 2, 3,
7028 																		DECODE(:G_ALLOCATION_METHOD, 2, 3,
7029 																		decode(alloc.inventory_item_id, null, 2 , 5)
7030 									)
7031 									)),
7032                            -- pegging_id is same as end_pegging_id then SO
7033                            -- otherwise POD
7034                          :l_peg_type14, DECODE(:G_HIERARCHY_PROFILE, 2, 2,
7035 										DECODE(:G_ALLOCATION_METHOD, 2, 2,
7036 										decode(alloc.inventory_item_id, null, 2 , 6)
7037 									)
7038 									),      -- PO
7039                          :l_peg_type15, DECODE(:G_HIERARCHY_PROFILE, 2, 2,
7040 										DECODE(:G_ALLOCATION_METHOD, 2, 2,
7041 										decode(alloc.inventory_item_id, null, 2 , 6)
7042 									)
7043 									),  -- PO
7044                          :l_peg_type16, 4 , -- REQ
7045                          :l_peg_type17, DECODE(:G_HIERARCHY_PROFILE, 2, 2,
7046 										DECODE(:G_ALLOCATION_METHOD, 2, 2,
7047 										decode(alloc.inventory_item_id, null, 2 , 6)
7048 											)
7049 										) )
7050                           relief_type,
7051                 decode(peg.pegging_id, peg.end_pegging_id, 0,
7052                       -1 *  peg.supply_demand_quantity ) relief_quantity,
7053                 NULL daily_relief_qty,
7054                 peg.pegging_id, peg.parent_pegging_id, peg.end_pegging_id,
7055                 DECODE (peg.pegging_type, :l_peg_type18,
7056                          peg.identifier3, NULL) end_demand_id,
7057                 peg.created_by, peg.creation_date, peg.last_updated_by, peg.last_update_date,
7058                 peg.customer_id, peg.customer_site_id,
7059 				DECODE(:G_HIERARCHY_PROFILE, 2, 2,
7060 						DECODE(:G_ALLOCATION_METHOD, 2, 2,
7061 									decode(alloc.inventory_item_id, null, 2 , 1)
7062 								)
7063 					   ) offset_type
7064          FROM   mrp_atp_details_temp peg,
7065 		        msc_item_hierarchy_mv alloc,
7066 				msc_system_items lid
7067          WHERE  peg.pegging_id = :p_identifier
7068          AND    peg.identifier1 = :p_instance_id
7069 		 and    peg.session_id = :l_session_id
7070 		 AND    peg.record_type = 3
7071          and    lid.sr_inventory_item_id = peg.inventory_item_id
7072 		 and    lid.sr_instance_id = peg.identifier1
7073 		 and    lid.organization_id = peg.organization_id
7074 		 and    lid.plan_id = peg.identifier2
7075 		 and    alloc.inventory_item_id(+) = lid.inventory_item_id
7076 		 AND    alloc.sr_instance_id(+) = lid.sr_instance_id
7077 		 and    alloc.organization_id(+) = lid.organization_id
7078 		 and    peg.model_sd_flag = 1' -- ensure that we only obtain pegging for things in the order.
7079 		 ;
7080 
7081   IF PG_DEBUG in ('Y', 'C') THEN
7082              msc_sch_wb.atp_debug('Create_Atp_Pegging:  Insert SQL Statement 1 '||
7083                                l_sql_stmt_1);
7084   END IF;
7085 
7086     EXECUTE IMMEDIATE l_sql_stmt_1 USING
7087            p_config_order_line_id,
7088            p_model_order_line_id,
7089            p_demand_source_type,
7090            MSC_ATP_PVT.ORG_DEMAND,
7091            MSC_ATP_PVT.ORG_DEMAND,
7092            MSC_ATP_PVT.MAKE_SUPPLY,
7093            MSC_ATP_PVT.TRANSFER_SUPPLY,
7094            MSC_ATP_PVT.BUY_SUPPLY,
7095            MSC_ATP_PVT.MAKE_SUPPLY,
7096            MSC_ATP_PVT.TRANSFER_SUPPLY,
7097            MSC_ATP_PVT.BUY_SUPPLY,
7098            MSC_ATP_PVT.MAKE_SUPPLY,
7099            MSC_ATP_PVT.TRANSFER_SUPPLY,
7100            MSC_ATP_PVT.BUY_SUPPLY,
7101            MSC_ATP_PVT.RESOURCE_DEMAND,
7102            MSC_ATP_PVT.ORG_DEMAND,
7103            --l_dmd_offset_typ,
7104 		   MSC_ATP_PVT.G_HIERARCHY_PROFILE,
7105 		   MSC_ATP_PVT.G_ALLOCATION_METHOD,
7106            MSC_ATP_PVT.MAKE_SUPPLY,
7107            --l_sup_offset_typ,
7108            MSC_ATP_PVT.G_HIERARCHY_PROFILE,
7109 		   MSC_ATP_PVT.G_ALLOCATION_METHOD,
7110            MSC_ATP_PVT.TRANSFER_SUPPLY,
7111            --l_sup_offset_typ,
7112 		   MSC_ATP_PVT.G_HIERARCHY_PROFILE,
7113 		   MSC_ATP_PVT.G_ALLOCATION_METHOD,
7114            MSC_ATP_PVT.RESOURCE_DEMAND,
7115            MSC_ATP_PVT.BUY_SUPPLY,
7116            --l_sup_offset_typ,
7117 		   MSC_ATP_PVT.G_HIERARCHY_PROFILE,
7118 		   MSC_ATP_PVT.G_ALLOCATION_METHOD,
7119            MSC_ATP_PVT.ORG_DEMAND,
7120 		   MSC_ATP_PVT.G_HIERARCHY_PROFILE,
7121 		   MSC_ATP_PVT.G_ALLOCATION_METHOD,
7122            p_identifier,
7123            p_instance_id,
7124            MSC_ATP_PVT.G_SESSION_ID;
7125    -- End CTO_PF_PRJ_2 Impacts SQL are changed to Dynamic Ones
7126 	END IF;
7127 
7128    -- End CTO_PF_PRJ_2 Impacts SQL are changed to Dynamic Ones
7129 
7130   IF PG_DEBUG in ('Y', 'C') THEN
7131              msc_sch_wb.atp_debug('Create_Atp_Pegging:  Number of rows inserted-1 '||
7132                                SQL%ROWCOUNT);
7133   END IF;
7134 
7135    SELECT       DEST_INV_ITEM_ID, identifier2,
7136                 -- Bug 3334643 Track the plan_id
7137                 -- CTO_PF_PRJ Get End Demand Id
7138                 DECODE (pegging_type, MSC_ATP_PVT.ORG_DEMAND,
7139                          identifier3, NULL) end_demand_id
7140    INTO         l_reference_item_id, l_plan_id, l_end_demand_id
7141                 -- End CTO_PF_PRJ Get End Demand Id
7142                 -- Bug 3334643 Track the plan_id
7143    FROM         mrp_atp_details_temp
7144    WHERE        pegging_id = p_identifier
7145    AND          identifier1 = p_instance_id
7146    AND          record_type = 3
7147    AND          model_sd_flag = 1
7148    AND          session_id = MSC_ATP_PVT.G_SESSION_ID;
7149 
7150   IF PG_DEBUG in ('Y', 'C') THEN
7151      msc_sch_wb.atp_debug('Create_Atp_Pegging: l_reference_item_id ' ||
7152                                    l_reference_item_id);
7153                 -- Bug 3334643 Track the plan_id
7154      msc_sch_wb.atp_debug('Create_Atp_Pegging: l_plan_id ' ||
7155                                    l_plan_id);
7156                 -- CTO_PF_PRJ Get End Demand Id
7157      msc_sch_wb.atp_debug('Create_Atp_Pegging: End Demand Id ' ||
7158                                    l_end_demand_id);
7159                 -- End CTO_PF_PRJ Get End Demand Id
7160   END IF;
7161 
7162   -- ORG_DEMAND             CONSTANT NUMBER := 1; POD, SO
7163   -- SUPPLIER_DEMAND        CONSTANT NUMBER := 2;
7164   -- ATP_SUPPLY             CONSTANT NUMBER := 3;
7165   -- MAKE_SUPPLY            CONSTANT NUMBER := 4; PO
7166   -- BUY_SUPPLY             CONSTANT NUMBER := 5; PO
7167   -- TRANSFER_SUPPLY        CONSTANT NUMBER := 6; PO
7168   -- ATP_SUPPLIER           CONSTANT NUMBER := 7;
7169   -- RESOURCE_DEMAND        CONSTANT NUMBER := 8; RES REQ
7170   -- RESOURCE_SUPPLY        CONSTANT NUMBER := 9;
7171 
7172   -- CTO_PF_PRJ_2 Impacts SQL are changed to Dynamic Ones
7173   -- Then Add all other lines in the pegging.
7174   -- ALLOC ATP CHANGES
7175 
7176   IF (MSC_ATP_PVT.G_HYBRID_ALLOC_ATP = 'N' ) THEN
7177   l_sql_stmt_1 := 'INSERT INTO ' || l_insert_temp_table ||
7178                '(reference_item_id, inventory_item_id, plan_id, sr_instance_id,
7179                 organization_id, sales_order_line_id,demand_source_type,bom_item_type, --cmro
7180                 transaction_date, demand_id, demand_quantity,
7181                 disposition_id, demand_class, supply_id, supply_quantity,
7182                 allocated_quantity,
7183                 resource_id, department_id, resource_hours, end_date, -- start_date,
7184                             -- Bug 3443056, 3348095 ATP now tracks end date.
7185                 relief_type, relief_quantity, daily_relief_qty,
7186                 pegging_id, prev_pegging_id, end_pegging_id, end_demand_id,
7187                 created_by, creation_date, last_updated_by, last_update_date,
7188                 customer_id, customer_site_id)
7189          SELECT :l_reference_item_id , NVL(DEST_INV_ITEM_ID, INVENTORY_ITEM_ID),
7190                 identifier2 plan_id, identifier1 sr_instance_id,
7191                 NVL(RECEIVING_ORGANIZATION_ID, organization_id),
7192                 NVL(:p_config_order_line_id, :p_model_order_line_id) sales_order_line_id,
7193                 :p_demand_source_type, --cmro
7194                 --3328421
7195                 --NULL bom_item_type, NVL(required_date, supply_demand_date) transaction_date,
7196                 NULL bom_item_type, NVL(actual_supply_demand_date, supply_demand_date) transaction_date,
7197                 -- identifier3 contains the demand_id
7198                 -- supply_demand_quantity contains the demand_quantity
7199                 DECODE (pegging_type, :l_peg_type1,
7200                          identifier3, NULL) demand_id,
7201                 DECODE (pegging_type, :l_peg_type2,
7202                          supply_demand_quantity, NULL) supply_demand_quantity,
7203                 NULL disposition_id, demand_class,
7204                 -- identifier3 contains the transaction_id
7205                 -- supply_demand_quantity contains the supply_quantitiy
7206                 -- For ATP created pegging the allocated_qty is the same as supply_qty
7207                 DECODE (pegging_type,
7208                          :l_peg_type3, identifier3,
7209                          :l_peg_type4, identifier3,
7210                          :l_peg_type5, identifier3,
7211                          :l_peg_type6, identifier3, -- REQ
7212                           NULL) supply_id,
7213                 DECODE (pegging_type,
7214                          :l_peg_type7, supply_demand_quantity,
7215                          :l_peg_type8, supply_demand_quantity,
7216                          :l_peg_type9, supply_demand_quantity,
7217                           NULL) supply_quantity,
7218                 DECODE (pegging_type,
7219                          :l_peg_type10, supply_demand_quantity,
7220                          :l_peg_type11, supply_demand_quantity,
7221                          :l_peg_type12, supply_demand_quantity,
7222                           NULL) allocated_quantity,
7223                 resource_id, department_id,
7224                 DECODE (pegging_type,
7225                          :l_peg_type13, supply_demand_quantity,
7226                          NULL) resource_hours,
7227                 --bug 3328421
7228                 --NVL(required_date, supply_demand_date) start_date,
7229                 NVL(actual_supply_demand_date, supply_demand_date) end_date, -- start_date,
7230                             -- Bug 3443056, 3348095 ATP now tracks end date.
7231                 DECODE (pegging_type,
7232                         :l_peg_type14,
7233                           decode(pegging_id, end_pegging_id, 1, :l_dmd_offset_typ),
7234                            -- pegging_id is same as end_pegging_id then SO
7235                            -- otherwise POD
7236                          :l_peg_type15, :l_sup_offset_typ,      -- PO
7237                          :l_peg_type16, :l_sup_offset_typ,  -- PO
7238                          :l_peg_type17, 4 , -- REQ
7239                          :l_peg_type18, :l_sup_offset_typ )
7240                           relief_type,
7241                 decode(pegging_id, end_pegging_id, 0,
7242                       -1 *  supply_demand_quantity ) relief_quantity,
7243                 NULL daily_relief_qty,
7244                 pegging_id, parent_pegging_id, end_pegging_id, :l_end_demand_id,
7245                 created_by, creation_date, last_updated_by, last_update_date,
7246                 customer_id, customer_site_id
7247          FROM   mrp_atp_details_temp
7248          WHERE  pegging_id <> :p_identifier
7249          AND    record_type in (3, 4)
7250          and    session_id = :l_session_id
7251          and    model_sd_flag = 1  -- ensure that we only obtain pegging for things in the order.
7252          -- Bug 3334643 Ensure that line is a PDS line.
7253          and    identifier2 > 0
7254          START  WITH pegging_id = :p_identifier
7255          AND    session_id = :l_session_id
7256          AND    record_type = 3
7257          CONNECT BY parent_pegging_id = prior pegging_id
7258          AND    session_id = prior session_id
7259          AND    record_type in (3,4)';
7260 
7261   IF PG_DEBUG in ('Y', 'C') THEN
7262              msc_sch_wb.atp_debug('Create_Atp_Pegging:  Insert SQL Statement '||
7263                                l_sql_stmt_1);
7264   END IF;
7265 
7266     EXECUTE IMMEDIATE l_sql_stmt_1 USING
7267            l_reference_item_id,
7268            p_config_order_line_id,
7269            p_model_order_line_id,
7270            p_demand_source_type,
7271            MSC_ATP_PVT.ORG_DEMAND,
7272            MSC_ATP_PVT.ORG_DEMAND,
7273            MSC_ATP_PVT.MAKE_SUPPLY,
7274            MSC_ATP_PVT.TRANSFER_SUPPLY,
7275            MSC_ATP_PVT.BUY_SUPPLY,
7276            MSC_ATP_PVT.RESOURCE_DEMAND,
7277            MSC_ATP_PVT.MAKE_SUPPLY,
7278            MSC_ATP_PVT.TRANSFER_SUPPLY,
7279            MSC_ATP_PVT.BUY_SUPPLY,
7280            MSC_ATP_PVT.MAKE_SUPPLY,
7281            MSC_ATP_PVT.TRANSFER_SUPPLY,
7282            MSC_ATP_PVT.BUY_SUPPLY,
7283            MSC_ATP_PVT.RESOURCE_DEMAND,
7284            MSC_ATP_PVT.ORG_DEMAND,
7285            l_dmd_offset_typ,
7286            MSC_ATP_PVT.MAKE_SUPPLY,
7287            l_sup_offset_typ,
7288            MSC_ATP_PVT.TRANSFER_SUPPLY,
7289            l_sup_offset_typ,
7290            MSC_ATP_PVT.RESOURCE_DEMAND,
7291            MSC_ATP_PVT.BUY_SUPPLY,
7292            l_sup_offset_typ,
7293            l_end_demand_id,
7294            p_identifier,
7295            MSC_ATP_PVT.G_SESSION_ID,
7296            p_identifier,
7297            MSC_ATP_PVT.G_SESSION_ID;
7298 
7299 	ELSE -- HYBRID ALLOC ATP
7300 	l_sql_stmt_1 := 'INSERT INTO ' || l_insert_temp_table ||
7301                '(reference_item_id, inventory_item_id, plan_id, sr_instance_id,
7302                 organization_id, sales_order_line_id,demand_source_type,bom_item_type, --cmro
7303                 transaction_date, demand_id, demand_quantity,
7304                 disposition_id, demand_class, supply_id, supply_quantity,
7305                 allocated_quantity,
7306                 resource_id, department_id, resource_hours, end_date, -- start_date,
7307                             -- Bug 3443056, 3348095 ATP now tracks end date.
7308                 relief_type, relief_quantity, daily_relief_qty,
7309                 pegging_id, prev_pegging_id, end_pegging_id, end_demand_id,
7310                 created_by, creation_date, last_updated_by, last_update_date,
7311                 customer_id, customer_site_id, offset_type)
7312          SELECT :l_reference_item_id , NVL(peg.DEST_INV_ITEM_ID, peg.INVENTORY_ITEM_ID),
7313                 peg.identifier2 plan_id, peg.identifier1 sr_instance_id,
7314                 NVL(peg.RECEIVING_ORGANIZATION_ID, peg.organization_id),
7315                 NVL(:p_config_order_line_id, :p_model_order_line_id) sales_order_line_id,
7316                 :p_demand_source_type, --cmro
7317                 --3328421
7318                 --NULL bom_item_type, NVL(required_date, supply_demand_date) transaction_date,
7319                 NULL bom_item_type, NVL(peg.actual_supply_demand_date, peg.supply_demand_date) transaction_date,
7320                 -- identifier3 contains the demand_id
7321                 -- supply_demand_quantity contains the demand_quantity
7322                 DECODE (peg.pegging_type, :l_peg_type1,
7323                          peg.identifier3, NULL) demand_id,
7324                 DECODE (peg.pegging_type, :l_peg_type2,
7325                          peg.supply_demand_quantity, NULL) supply_demand_quantity,
7326                 NULL disposition_id, peg.demand_class,
7327                 -- identifier3 contains the transaction_id
7328                 -- supply_demand_quantity contains the supply_quantitiy
7329                 -- For ATP created pegging the allocated_qty is the same as supply_qty
7330                 DECODE (peg.pegging_type,
7331                          :l_peg_type3, peg.identifier3,
7332                          :l_peg_type4, peg.identifier3,
7333                          :l_peg_type5, peg.identifier3,
7334                          :l_peg_type6, peg.identifier3, -- REQ
7335                           NULL) supply_id,
7336                 DECODE (peg.pegging_type,
7337                          :l_peg_type7, peg.supply_demand_quantity,
7338                          :l_peg_type8, peg.supply_demand_quantity,
7339                          :l_peg_type9, peg.supply_demand_quantity,
7340                           NULL) supply_quantity,
7341                 DECODE (peg.pegging_type,
7342                          :l_peg_type10, peg.supply_demand_quantity,
7343                          :l_peg_type11, peg.supply_demand_quantity,
7344                          :l_peg_type12, peg.supply_demand_quantity,
7345                           NULL) allocated_quantity,
7346                 peg.resource_id, peg.department_id,
7347                 DECODE (peg.pegging_type,
7348                          :l_peg_type13, peg.supply_demand_quantity,
7349                          NULL) resource_hours,
7350                 --bug 3328421
7351                 --NVL(required_date, supply_demand_date) start_date,
7352                 NVL(peg.actual_supply_demand_date, peg.supply_demand_date) end_date, -- start_date,
7353                             -- Bug 3443056, 3348095 ATP now tracks end date.
7354                 DECODE (peg.pegging_type,
7355                         :l_peg_type14,
7356                           decode(peg.pegging_id, peg.end_pegging_id, 1,  DECODE(:G_HIERARCHY_PROFILE, 2, 3,
7357 																		DECODE(:G_ALLOCATION_METHOD, 2, 3,
7358 																		decode(alloc.inventory_item_id, null, 2 , 5)
7359 									)
7360 									)),
7361                            -- pegging_id is same as end_pegging_id then SO
7362                            -- otherwise POD
7363                          :l_peg_type15, DECODE(:G_HIERARCHY_PROFILE, 2, 2,
7364 										DECODE(:G_ALLOCATION_METHOD, 2, 2,
7365 										decode(alloc.inventory_item_id, null, 2 , 6)
7366 									)
7367 									),      -- PO
7368                          :l_peg_type16, DECODE(:G_HIERARCHY_PROFILE, 2, 2,
7369 										DECODE(:G_ALLOCATION_METHOD, 2, 2,
7370 										decode(alloc.inventory_item_id, null, 2 , 6)
7371 									)
7372 									),  -- PO
7373                          :l_peg_type17, 4 , -- REQ
7374                          :l_peg_type18, DECODE(:G_HIERARCHY_PROFILE, 2, 2,
7375 										DECODE(:G_ALLOCATION_METHOD, 2, 2,
7376 										decode(alloc.inventory_item_id, null, 2 , 6)
7377 									)
7378 									) )
7379                           relief_type,
7380                 decode(peg.pegging_id, peg.end_pegging_id, 0,
7381                       -1 *  peg.supply_demand_quantity ) relief_quantity,
7382                 NULL daily_relief_qty,
7383                 peg.pegging_id, peg.parent_pegging_id, peg.end_pegging_id, :l_end_demand_id,
7384                 peg.created_by, peg.creation_date, peg.last_updated_by, peg.last_update_date,
7385                 peg.customer_id, peg.customer_site_id,
7386 				DECODE(:G_HIERARCHY_PROFILE, 2, 2,
7387 						DECODE(:G_ALLOCATION_METHOD, 2, 2,
7388 									decode(alloc.inventory_item_id, null, 2 , 1)
7389 								)
7390 					   ) offset_type
7391          FROM   mrp_atp_details_temp peg,
7392 		        msc_item_hierarchy_mv alloc,
7393 				msc_system_items lid
7394          WHERE  peg.pegging_id <> :p_identifier
7395          AND    peg.record_type in (3, 4)
7396          and    peg.session_id = :l_session_id
7397 		 and    lid.sr_inventory_item_id = peg.inventory_item_id
7398 		 and    lid.sr_instance_id = peg.identifier1
7399 		 and    lid.organization_id = peg.organization_id
7400 		 and    lid.plan_id = peg.identifier2
7401 		 and    alloc.inventory_item_id(+) = lid.inventory_item_id
7402 		 AND    alloc.sr_instance_id(+) = lid.sr_instance_id
7403 		 and    alloc.organization_id(+) = lid.organization_id
7404          and    peg.model_sd_flag = 1  -- ensure that we only obtain pegging for things in the order.
7405          -- Bug 3334643 Ensure that line is a PDS line.
7406          and    peg.identifier2 > 0
7407          START  WITH peg.pegging_id = :p_identifier
7408          AND    peg.session_id = :l_session_id
7409          AND    peg.record_type = 3
7410          CONNECT BY peg.parent_pegging_id = prior peg.pegging_id
7411          AND    peg.session_id = prior peg.session_id
7412          AND    peg.record_type in (3,4)';
7413 
7414   IF PG_DEBUG in ('Y', 'C') THEN
7415              msc_sch_wb.atp_debug('Create_Atp_Pegging:  Insert SQL Statement 2'||
7416                                l_sql_stmt_1);
7417   END IF;
7418 
7419     EXECUTE IMMEDIATE l_sql_stmt_1 USING
7420            l_reference_item_id,
7421            p_config_order_line_id,
7422            p_model_order_line_id,
7423            p_demand_source_type,
7424            MSC_ATP_PVT.ORG_DEMAND,
7425            MSC_ATP_PVT.ORG_DEMAND,
7426            MSC_ATP_PVT.MAKE_SUPPLY,
7427            MSC_ATP_PVT.TRANSFER_SUPPLY,
7428            MSC_ATP_PVT.BUY_SUPPLY,
7429            MSC_ATP_PVT.RESOURCE_DEMAND,
7430            MSC_ATP_PVT.MAKE_SUPPLY,
7431            MSC_ATP_PVT.TRANSFER_SUPPLY,
7432            MSC_ATP_PVT.BUY_SUPPLY,
7433            MSC_ATP_PVT.MAKE_SUPPLY,
7434            MSC_ATP_PVT.TRANSFER_SUPPLY,
7435            MSC_ATP_PVT.BUY_SUPPLY,
7436            MSC_ATP_PVT.RESOURCE_DEMAND,
7437            MSC_ATP_PVT.ORG_DEMAND,
7438            --l_dmd_offset_typ,
7439 		   MSC_ATP_PVT.G_HIERARCHY_PROFILE,
7440 		   MSC_ATP_PVT.G_ALLOCATION_METHOD,
7441            MSC_ATP_PVT.MAKE_SUPPLY,
7442            --l_sup_offset_typ,
7443 		   MSC_ATP_PVT.G_HIERARCHY_PROFILE,
7444 		   MSC_ATP_PVT.G_ALLOCATION_METHOD,
7445            MSC_ATP_PVT.TRANSFER_SUPPLY,
7446            --l_sup_offset_typ,
7447 		   MSC_ATP_PVT.G_HIERARCHY_PROFILE,
7448 		   MSC_ATP_PVT.G_ALLOCATION_METHOD,
7449            MSC_ATP_PVT.RESOURCE_DEMAND,
7450            MSC_ATP_PVT.BUY_SUPPLY,
7451            --l_sup_offset_typ,
7452 		   MSC_ATP_PVT.G_HIERARCHY_PROFILE,
7453 		   MSC_ATP_PVT.G_ALLOCATION_METHOD,
7454            l_end_demand_id,
7455 		   MSC_ATP_PVT.G_HIERARCHY_PROFILE,
7456 		   MSC_ATP_PVT.G_ALLOCATION_METHOD,
7457            p_identifier,
7458            MSC_ATP_PVT.G_SESSION_ID,
7459            p_identifier,
7460            MSC_ATP_PVT.G_SESSION_ID;
7461 	END IF;
7462 
7463    -- End CTO_PF_PRJ_2 Impacts SQL are changed to Dynamic Ones
7464 
7465   IF PG_DEBUG in ('Y', 'C') THEN
7466              msc_sch_wb.atp_debug('Create_Atp_Pegging:  Number of rows inserted '||
7467                                SQL%ROWCOUNT);
7468   END IF;
7469 
7470   -- CTO_PF_PRJ Impacts
7471   IF (MSC_ATP_PVT.G_CTO_PF_ATP = 'Y') THEN
7472       -- Call Procedure to insert data from temp table to main table
7473       -- For PF items, PF related processing will be done.
7474       Create_PF_Atp_Pegging ( l_reference_item_id   ,
7475                               p_model_order_line_id ,
7476                               p_config_order_line_id,
7477                               p_demand_source_type  ,
7478                               l_end_demand_id       ,
7479                               l_plan_id             ,
7480                               x_return_status        );
7481   END IF;
7482   -- CTO_PF_PRJ Impacts
7483 
7484   IF PG_DEBUG in ('Y', 'C') THEN
7485      msc_sch_wb.atp_debug('***** End Create_Atp_Pegging Procedure *****');
7486   END IF;
7487 
7488 EXCEPTION
7489     WHEN OTHERS THEN
7490         my_sqlcode := SQLCODE;
7491         IF PG_DEBUG in ('Y', 'C') THEN
7492            msc_sch_wb.atp_debug('Create_Atp_Pegging: ' || my_sqlcode ||
7493                 ' error encountered while creating ATP Pegging : ERROR =  '|| sqlerrm);
7494         END IF;
7495 
7496         IF FND_MSG_PUB.Check_Msg_Level(FND_MSG_PUB.G_MSG_LVL_UNEXP_ERROR) THEN
7497             FND_MSG_PUB.Add_Exc_Msg(G_PKG_NAME , 'Create_Atp_Pegging');
7498         END IF;
7499         x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
7500         RAISE FND_API.G_EXC_UNEXPECTED_ERROR;
7501 
7502 END Create_Atp_Pegging;
7503 
7504 END MSC_ATP_PEG;