DBA Data[Home] [Help]

PACKAGE BODY: APPS.CSTPAVCP

Source


1 PACKAGE BODY CSTPAVCP AS
2 /* $Header: CSTAVCPB.pls 120.53 2012/02/18 00:16:47 anjha ship $ */
3 
4 G_PKG_NAME  CONSTANT VARCHAR2(30) := 'CSTPAVCP';
5 G_DEBUG CONSTANT VARCHAR2(1)     := NVL(FND_PROFILE.VALUE('MRP_DEBUG'),'N');
6 G_CST_APPLICATION_ID CONSTANT NUMBER       := 707;
7 G_INV_APPLICATION_ID CONSTANT NUMBER       := 401;
8 
9 -- PROCEDURE
10 --  cost_processor      Costs inventory transactions
11 --
12 procedure cost_processor(
13   I_ORG_ID              IN NUMBER,
14   I_TXN_ID              IN NUMBER,
15   I_LAYER_ID            IN NUMBER,
16   I_COST_TYPE           IN NUMBER,
17   I_COST_METHOD         IN NUMBER,
18   I_MAT_CT_ID           IN NUMBER,
19   I_AVG_RATES_ID        IN NUMBER,
20   I_ITEM_ID             IN NUMBER,
21   I_TXN_QTY             IN NUMBER,
22   I_TXN_ACTION_ID       IN NUMBER,
23   I_TXN_SRC_TYPE        IN NUMBER,
24   I_TXN_ORG_ID          IN NUMBER,
25   I_TXFR_ORG_ID         IN NUMBER,
26   I_COST_GRP_ID         IN NUMBER,
27   I_TXFR_COST_GRP       IN NUMBER,
28   I_TXFR_LAYER_ID       IN NUMBER,
29   I_FOB_POINT           IN NUMBER,
30   I_EXP_ITEM            IN NUMBER,
31   I_EXP_FLAG            IN NUMBER,
32   I_CITW_FLAG           IN NUMBER,
33   I_FLOW_SCHEDULE       IN NUMBER,
34   I_USER_ID             IN NUMBER,
35   I_LOGIN_ID            IN NUMBER,
36   I_REQ_ID              IN NUMBER,
37   I_PRG_APPL_ID         IN NUMBER,
38   I_PRG_ID              IN NUMBER,
39   I_TPRICE_OPTION       IN NUMBER,
40   I_TXF_PRICE           IN NUMBER,
41   O_Err_Num             OUT NOCOPY NUMBER,
42   O_Err_Code            OUT NOCOPY VARCHAR2,
43   O_Err_Msg             OUT NOCOPY VARCHAR2
44 ) IS
45   l_txn_qty             NUMBER;
46   l_hook                NUMBER;
47   l_new_cost            NUMBER;
48   l_exp_flag            NUMBER;
49   l_interorg_rec        NUMBER;
50   l_no_update_mmt       NUMBER;
51   l_layer_chg           NUMBER;
52   l_txn_action_id       NUMBER;
53   l_layer_id            NUMBER;
54   l_org_id              NUMBER;
55   l_err_num             NUMBER;
56   l_err_code            VARCHAR2(240);
57   l_err_msg             VARCHAR2(240);
58   process_error         EXCEPTION;
59   LOGICAL_SORECEIPT_ERROR EXCEPTION;
60   l_stmt_num            NUMBER;
61 -- borrow/payback
62   l_txn_type_id         NUMBER;
63 -- borrow/paybackend
64 
65   /* OPM INVCONV umoogala */
66   l_pd_txfr_ind         BINARY_INTEGER;  -- Process-Discrete Xfer Flag
67 
68   l_so_line_id          NUMBER; -- Revenue COGS Matching
69 
70 BEGIN
71   -- initialize local variables
72   l_err_num := 0;
73   l_err_code := '';
74   l_err_msg := '';
75   l_txn_qty := i_txn_qty;
76   l_org_id := i_org_id;
77   l_no_update_mmt := 0;
78   l_interorg_rec := 0;
79   l_exp_flag := i_exp_flag;
80   l_hook := 0;
81   l_new_cost := 0;
82   l_txn_action_id := 0;
83   l_stmt_num := 0;
84 
85   if (g_debug = 'Y') then
86     fnd_file.put_line(fnd_file.log,'>>In CSTPAVCP.cost_processor Cost Processor');
87   end if;
88 
89   /* INVCONV sschinch Check if this transaction is a process discrete transfer */
90   SELECT MOD(SUM(DECODE(mp.process_enabled_flag, 'Y', 1, 2)), 2)
91     INTO l_pd_txfr_ind
92     FROM mtl_parameters mp, mtl_material_transactions mmt
93    WHERE mmt.transaction_id   = i_txn_id
94      AND (mmt.organization_id = mp.organization_id
95           OR mmt.transfer_organization_id = mp.organization_id);
96 
97   /*
98       ((i_txn_action_id = 15) OR
99        (i_txn_action_id = 12 AND i_fob_point = 2) OR
100        (i_txn_action_id = 3 AND i_txn_qty > 0)))
101   */
102   if ((l_pd_txfr_ind = 1) AND
103       ((i_txn_action_id IN (3, 15, 12, 21, 22)) OR
104        (i_txn_src_type = 8 AND i_txn_action_id = 1)) -- Bug 5349860: Internal Order issues to exp
105      )
106   then
107 
108    --
109    -- OPM INVCONV umoogala/sschinch Process-Discrete Transfers Enh.:
110    -- Processing for
111    --  1. Logical  Intransit Receipt
112    --       This is a new transaction type introduced for p-d xfers enh. only.
113    --  2. Physical Intransit Receipt and
114    --  3. Direct Xfer receipt.
115    --
116    CSTPAVCP.cost_logical_itr_receipt(i_org_id,
117                         i_txn_id,
118                         i_layer_id,
119                         i_cost_type,
120                         i_item_id,
121                         i_txn_action_id,
122                         i_txn_org_id,
123                         i_txfr_org_id,
124                         i_cost_grp_id,
125                         i_txfr_cost_grp,
126                         i_fob_point,
127                         i_user_id,
128                         i_login_id,
129                         i_req_id,
130                         i_prg_appl_id,
131                         i_prg_id,
132                         i_tprice_option,
133                         i_txf_price,
134                         l_txn_qty,
135                         l_interorg_rec,
136                         l_no_update_mmt,
137                         l_exp_flag,
138                         l_err_num,
139                         l_err_code,
140                         l_err_msg);
141     if (l_err_num <> 0) then
142       -- Error occured
143       raise process_error;
144     end if;
145 
146 
147   elsif (i_txn_action_id in (3,12,21)) then
148     -- The l_exp_flag determines if this is an expense item or the transaction
149     -- involves an expense subinventory.
150 
151     -- If this is an interorg transfer transaction, call interorg procedure
152     -- to figure out transfer cost and transaction cost.
153 
154     l_stmt_num := 10;
155 
156   if (g_debug = 'Y') then
157     fnd_file.put_line(fnd_file.log,'>>Inter Org Transaction');
158     fnd_file.put_line(fnd_file.log,'>>Calling CSTPACVP.interorg');
159   end if;
160 
161     CSTPAVCP.interorg(i_org_id,
162                         i_txn_id,
163                         i_layer_id,
164                         i_cost_type,
165                         i_item_id,
166                         i_txn_action_id,
167                         i_txn_org_id,
168                         i_txfr_org_id,
169                         i_cost_grp_id,
170                         i_txfr_cost_grp,
171                         i_fob_point,
172                         i_user_id,
173                         i_login_id,
174                         i_req_id,
175                         i_prg_appl_id,
176                         i_prg_id,
177                         i_tprice_option,
178                         i_txf_price,
179                         i_exp_item,
180                         l_txn_qty,
181                         l_interorg_rec,
182                         l_no_update_mmt,
183                         l_exp_flag,
184                         l_hook,
185                         l_err_num,
186                         l_err_code,
187                         l_err_msg);
188     if (l_err_num <> 0) then
189       -- Error occured
190       raise process_error;
191     end if;
192 
193   if (g_debug = 'Y') then
194     fnd_file.put_line(fnd_file.log,'<<Returning from CSTPACVP.interorg');
195   end if;
196 
197     -- Some transactions do not need to be cost processed and only need cost
198     -- distribution!
199     -- 1) The intransit shipment from standard to average with fob receipt
200     -- 2) The intransit receipt to standard from average with fob shipment
201     -- 3) The direct interorg shipment from standard to average
202     -- 4) The direct interorg receipt from average to standard.
203     -- 5) The intransit receipt from process to discrete
204     l_stmt_num := 15;
205     if ((i_txn_action_id = 21 and i_fob_point = 2 and i_txfr_org_id = i_org_id)
206         OR
207         (i_txn_action_id = 12 and i_fob_point = 1 and i_txfr_org_id = i_org_id)
208         OR
209         (i_txn_action_id = 3 and i_txfr_org_id = i_org_id and i_txn_qty < 0)
210         OR
211         (i_txn_action_id = 3 and i_txfr_org_id = i_org_id and i_txn_qty > 0)
212         OR
213         (i_txn_action_id = 12 and l_pd_txfr_ind = 1 and i_fob_point = 2)
214          -- OPM INVCONV sschinch/umoogala
215          -- For process-discrete xfers, we need not cost physical receipt since
216          -- we compute the avg cost using logical txn i.e., using
217          -- InterOrg Intransit Receipt (15) using new procedure
218          -- CSTPAVCP.cost_logical_itr_receipt
219         OR
220         (i_txn_action_id = 21 and i_fob_point = 1 and l_pd_txfr_ind = 1 and i_org_id = i_txn_org_id))
221         -- OPM INVCONV sschinch/umoogala
222         -- For process-discrete xfers, this is a shipment line from discrete-to-process.
223         -- So, no need to avg. Avg Cost is computed on the OPM side
224        then
225       return;
226     end if;
227 
228   elsif (i_citw_flag = 1) then
229   -- Common Issue to WIP is processed separately. There
230   -- is no hook available for this transaction.
231 
232     -- Treat it as a subinventory transfer
233     l_txn_action_id := 2;
234     l_stmt_num := 20;
235 
236     if (g_debug = 'Y') then
237       fnd_file.put_line(fnd_file.log,'>>Common Issue to WIP');
238     end if;
239 
240     /* Added Bug#4259926 modified the code to change the layer id. */
241         if (i_txn_action_id = 27 and  i_txn_src_type = 5 and i_citw_flag = 1 ) then
242             l_layer_id := i_txfr_layer_id;
243         else
244             l_layer_id := i_layer_id;
245         end if;
246 
247     l_new_cost := CSTPAVCP.compute_actual_cost(
248                                 i_org_id,
249                                 i_txn_id,
250                                 l_layer_id, /* Bug#4259926 changed i_layer_id to l_layer_id */
251                                 i_cost_type,
252                                 i_mat_ct_id,
253                                 i_avg_rates_id,
254                                 i_item_id,
255                                 l_txn_qty,
256                                 l_txn_action_id,
257                                 i_txn_src_type,
258                                 l_interorg_rec,
259                                 l_exp_flag,
260                                 i_user_id,
261                                 i_login_id,
262                                 i_req_id,
263                                 i_prg_appl_id,
264                                 i_prg_id,
265                                 l_err_num,
266                                 l_err_code,
267                                 l_err_msg);
268     if (l_err_num <> 0) then
269       -- Error occured
270       raise process_error;
271     end if;
272 
273     l_stmt_num := 30;
274 
275     CSTPAVCP.common_issue_to_wip(
276                         i_org_id,
277                         i_txn_id,
278                         i_layer_id,
279                         i_cost_type,
280                         i_item_id,
281                         l_txn_qty,
282                         l_txn_action_id,
283                         l_new_cost,
284                         i_txfr_layer_id,
285                         i_cost_method,
286                         i_avg_rates_id,
287                         i_cost_grp_id,
288                         i_txfr_cost_grp,
289                         l_exp_flag,
290                         i_exp_item,
291                         i_citw_flag,
292                         i_flow_schedule,
293                         i_user_id,
294                         i_login_id,
295                         i_req_id,
296                         i_prg_appl_id,
297                         i_prg_id,
298                         l_err_num,
299                         l_err_code,
300                         l_err_msg);
301     if (l_err_num <> 0) then
302       -- Error occured
303       raise process_error;
304     end if;
305 
306     -- done
307     return;
308 
309   elsif (i_txn_action_id = 24) then /*Removed i_txn_src_type_id = 15 for bug 6030287*/
310     -- Average Cost Update is processed separately.  There
311     -- is no hook available for this transaction.
312     l_stmt_num := 40;
313 
314     if (g_debug = 'Y') then
315       fnd_file.put_line(fnd_file.log,'>>Average Cost update');
316     end if;
317 
318     average_cost_update(i_org_id,
319                         i_txn_id,
320                         i_layer_id,
321                         i_cost_type,
322                         i_item_id,
323                         i_txn_action_id,
324                         i_txn_qty,/*LCM*/
325                         l_exp_flag,
326                         i_user_id,
327                         i_login_id,
328                         i_req_id,
329                         i_prg_appl_id,
330                         i_prg_id,
331                         l_err_num,
332                         l_err_code,
333                         l_err_msg);
334     if (l_err_num <> 0) then
335       -- Error occured
336       raise process_error;
337     end if;
338 
339     -- done
340     return;
341 
342   elsif (i_exp_item = 0) then
343     -- Call the Actual Cost Hook for asset items
344     l_stmt_num := 50;
345     if (g_debug = 'Y') then
346        fnd_file.put_line(fnd_file.log,'Actual Cost Hook invoked: CSTPACHK.actual_cost_hook');
347     end if;
348     l_hook := CSTPACHK.actual_cost_hook(i_org_id,
349                                         i_txn_id,
350                                         i_layer_id,
351                                         i_cost_type,
352                                         i_cost_method,
353                                         i_user_id,
354                                         i_login_id,
355                                         i_req_id,
356                                         i_prg_appl_id,
357                                         i_prg_id,
358                                         l_err_num,
359                                         l_err_code,
360                                         l_err_msg);
361     IF (l_hook = 1) THEN
362                 IF g_debug = 'Y' THEN
363                     fnd_file.put_line(fnd_file.log, '>>>>Hook has been used. Calling CSTPAVCP.validate_actual_cost_hook');
364                 END IF;
365 
366                 CSTPAVCP.validate_actual_cost_hook(i_txn_id     =>        i_txn_id,
367                                                    i_org_id     =>      i_org_id,
368                                                    i_layer_id   =>      i_layer_id,
369                                                    i_req_id     =>      i_req_id,
370                                                    i_prg_appl_id=>      i_prg_appl_id,
371                                                    i_prg_id     =>      i_prg_id,
372                                                    o_err_num    =>      l_err_num,
373                                                    o_err_code   =>      l_err_code,
374                                                    o_err_msg    =>      l_err_msg);
375     END IF;
376     if (l_err_num <> 0) then
377       -- Error occured
378       raise process_error;
379     end if;
380   end if;
381      if (g_debug = 'Y') then
382         fnd_file.put_line(fnd_file.log,'l_hook: '||to_char(l_hook));
383      end if;
384   if (l_hook = 0) then
385 -- borrow /payback
386 -- if hook is not used and it is a payback transaction, we need to populate MCTCD
387 -- with the borrowed cost.
388      l_stmt_num := 60;
389      if (g_debug = 'Y') then
390         fnd_file.put_line(fnd_file.log,'Actual Cost Hook not used');
391      end if;
392 
393      /* Changes for VMI. Adding Planning Transfer Transaction */
394      if i_txn_action_id IN (2,5,28,55) then
395          l_stmt_num := 70;
396          select transaction_type_id
397          into l_txn_type_id
398          from mtl_material_transactions
399          where transaction_id = i_txn_id;
400 
401          if (l_txn_type_id = 68) and (i_layer_id <> i_txfr_layer_id) then
402            -- if payback txn and txn involved different projects then populate MCTCD
403            -- with the borrowed cost
404             l_stmt_num := 80;
405             if (g_debug = 'Y') then
406                 fnd_file.put_line(fnd_file.log,'Borrow Payback');
407             end if;
408             borrow_cost(i_org_id,
409                         i_txn_id,
410                         i_user_id,
411                         i_login_id,
412                         i_req_id,
413                         i_prg_appl_id,
414                         i_prg_id,
415                         i_item_id,
416                         0, -- hook is not used
417                         i_txfr_layer_id,
418                         l_err_num,
419                         l_err_code,
420                         l_err_msg);
421             if (l_err_num <> 0) then
422             -- Error occured
423                raise process_error;
424             end if;
425 
426          end if; -- l_txn_type_id = 68, if it is payback transaction
427       end if;  -- i_txn_action_id = 2, if it is sub or staging transfer
428 -- borrow /paybackend
429 
430 
431   /*
432   Changes during Revenue / COGS Matching to make RMA Receipts Cost Owned -
433   The following section will populate MCTCD for RMA Receipts. If the RMA Receipt
434   references a Sales Order, the average cost of the Sales Order Issues will be used.
435   If the RMA Receipt does not reference a Sales Order, MCTCD will not be populated
436   and the RMA Receipt will be processed at the latest average cost (e.g. as a cost
437   derived transaction)
438   */
439 
440   -- Check if the transaction is an RMA receipt
441   IF i_txn_action_id = 27 AND i_txn_src_type = 12 THEN
442     -- Check if Sales Order is referenced
443     l_stmt_num := 83;
444     SELECT MIN(OOLA.reference_line_id)
445     INTO   l_so_line_id
446     FROM   mtl_material_transactions MMT,
447            oe_order_lines_all OOLA
448     WHERE  MMT.transaction_id = i_txn_id
449     AND    OOLA.line_id = MMT.trx_source_line_id;
450 
451     IF l_so_line_id IS NOT NULL THEN
452 
453     --{BUG#8553255
454       l_stmt_num := 87;
455       --
456       -- Cost owned transactions within the same ledger across inv org
457       --
458       INSERT  INTO   mtl_cst_txn_cost_details (
459                transaction_id,
460                organization_id,
461                inventory_item_id,
462                cost_element_id,
463                level_type,
464                transaction_cost,
465                last_update_date,
466                last_updated_by,
467                creation_date,
468                created_by,
469                last_update_login,
470                request_id,
471                program_application_id,
472                program_id,
473                program_update_date
474              )
475       SELECT i_txn_id,
476              i_org_id,
477              i_item_id,
478              MCACD.cost_element_id,
479              MCACD.level_type,
480              SUM(MMT.primary_quantity*MCACD.actual_cost)/SUM(MMT.primary_quantity),
481              SYSDATE,
482              i_user_id,
483              SYSDATE,
484              i_user_id,
485              i_login_id,
486              i_req_id,
487              i_prg_appl_id,
488              i_prg_id,
489              SYSDATE
490       FROM   oe_order_lines_all          OOLA,   /*BUG 5768680 Changes introduced to improve performance*/
491              oe_order_headers_all        OOHA,   /* of the layer cost worker*/
492              mtl_sales_orders            MSO,
493              mtl_material_transactions   MMT,
494              mtl_cst_actual_cost_details MCACD,
495              cst_cogs_events             cce
496       WHERE  OOLA.line_id                   = l_so_line_id
497       AND    OOHA.header_id                 = OOLA.header_id
498       AND    MSO.segment1                   = TO_CHAR(OOHA.order_number) -- extraneous MSOs are possible
499       AND    MMT.trx_source_line_id         = l_so_line_id               -- filter MMTs corresponding to extraneous MSOs
500       AND    OOLA.line_id                   = cce.cogs_om_line_id
501       AND    cce.event_type                 = 1
502       AND    mmt.transaction_id             = cce.mmt_transaction_id
503       AND    MMT.transaction_source_id      = MSO.sales_order_id
504       AND    MMT.transaction_action_id      IN (1,7)
505       AND    MMT.transaction_source_type_id = 2
506       AND    MMT.inventory_item_id          = i_item_id
507       AND    MCACD.transaction_id           = MMT.transaction_id
508       AND    EXISTS (SELECT NULL
509                      FROM cst_acct_info_v v1,cst_acct_info_v v2
510                      WHERE v1.organization_id = MMT.organization_id
511                      AND   v2.organization_id = i_org_id
512                      AND   v1.ledger_id       = v2.ledger_id)
513       GROUP
514       BY     MCACD.cost_element_id,
515              MCACD.level_type;
516       --}
517 
518       -- A Sales Order is referenced, use the average cost of the Sales Order Issues
519       IF SQL%NOTFOUND THEN
520       -- A Sales Order is referenced, use the average cost of the Sales Order Issues
521       -- Try the old Code prevention of regression
522           l_stmt_num := 86;
523       INSERT
524       INTO   mtl_cst_txn_cost_details (
525                transaction_id,
526                organization_id,
527                inventory_item_id,
528                cost_element_id,
529                level_type,
530                transaction_cost,
531                last_update_date,
532                last_updated_by,
533                creation_date,
534                created_by,
535                last_update_login,
536                request_id,
537                program_application_id,
538                program_id,
539                program_update_date
540              )
541       SELECT i_txn_id,
542              i_org_id,
543              i_item_id,
544              MCACD.cost_element_id,
545              MCACD.level_type,
546              SUM(MMT.primary_quantity*MCACD.actual_cost)/SUM(MMT.primary_quantity),
547              SYSDATE,
548              i_user_id,
549              SYSDATE,
550              i_user_id,
551              i_login_id,
552              i_req_id,
553              i_prg_appl_id,
554              i_prg_id,
555              SYSDATE
556       FROM   oe_order_lines_all OOLA,   /*BUG 5768680 Changes introduced to improve performance*/
557              oe_order_headers_all OOHA, /* of the layer cost worker*/
558              mtl_sales_orders MSO,
559              mtl_material_transactions MMT,
560              mtl_cst_actual_cost_details MCACD
561       WHERE  OOLA.line_id = l_so_line_id
562       AND    OOHA.header_id = OOLA.header_id
563       AND    MSO.segment1 = TO_CHAR(OOHA.order_number) -- extraneous MSOs are possible
564       AND    MMT.transaction_source_id = MSO.sales_order_id
565       AND    MMT.trx_source_line_id = l_so_line_id -- filter MMTs corresponding to extraneous MSOs
566       AND    MMT.transaction_action_id in (1,7)
567       AND    MMT.transaction_source_type_id = 2
568       AND    MMT.organization_id = i_org_id
569       AND    MMT.inventory_item_id = i_item_id
570       AND    MCACD.transaction_id = MMT.transaction_id
571       GROUP
572       BY     MCACD.cost_element_id,
573              MCACD.level_type;
574       END IF;
575     END IF; -- Check if Sales Order is referenced
576   END IF; -- Check if transaction is an RMA receipt
577 
578 
579     -- when we process transfer org's txn(i.e. intransit txfr),
580     -- we need to use txfr_layer_id instead.
581     -- bug 2471598 also use txfr_layer_id when processing
582     -- the receipt txn in the receipt org of an fob shipment txfr
583     l_stmt_num := 90;
584     if ((i_org_id <> i_txn_org_id) or
585         (i_txn_action_id = 12 and i_fob_point = 1)) then
586       l_layer_id := i_txfr_layer_id;
587     else
588       l_layer_id := i_layer_id;
589     end if;
590 
591     l_stmt_num := 100;
592     IF g_debug = 'Y' THEN
593        fnd_file.put_line(fnd_file.log, '>>Calling CSTPAVCP.compute_actual_cost');
594     END IF;
595     l_new_cost := CSTPAVCP.compute_actual_cost(
596                                 i_org_id,
597                                 i_txn_id,
598                                 l_layer_id,
599                                 i_cost_type,
600                                 i_mat_ct_id,
601                                 i_avg_rates_id,
602                                 i_item_id,
603                                 l_txn_qty,
604                                 i_txn_action_id,
605                                 i_txn_src_type,
606                                 l_interorg_rec,
607                                 l_exp_flag,
608                                 i_user_id,
609                                 i_login_id,
610                                 i_req_id,
611                                 i_prg_appl_id,
612                                 i_prg_id,
613                                 l_err_num,
614                                 l_err_code,
615                                 l_err_msg);
616 
617     if (l_err_num <> 0) then
618       -- Error occured
619       raise process_error;
620     end if;
621 
622     IF g_debug = 'Y' THEN
623        fnd_file.put_line(fnd_file.log, '<<Returned from CSTPAVCP.compute_actual_cost');
624     END IF;
625 
626   else
627     -- user populated actual cost.
628     l_new_cost := 1;
629   end if;
630 
631   -- If this transaction is a subinventory or staging transfer then call the
632   -- sub_transfer special function.  We treat interorg intransit
633   -- shipment for FOB receipt and interorg intransit for FOB shipment
634   -- as sub_transfer transactions.
635   /* Changes for VMI. Adding Planning Transfer Transaction */
636   if ((i_txn_action_id IN (2,5,28,55)) or
637       (i_txn_action_id = 21 and i_org_id = i_txn_org_id and i_fob_point = 2) or
638       (i_txn_action_id = 12 and i_org_id = i_txn_org_id and i_fob_point = 1))
639         then
640     l_stmt_num := 110;
641     IF g_debug = 'Y' THEN
642        fnd_file.put_line(fnd_file.log, '>>Calling from CSTPAVCP.sub_transfer');
643     END IF;
644     CSTPAVCP.sub_transfer(
645                         i_org_id,
646                         i_txn_id,
647                         i_layer_id,
648                         i_cost_type,
649                         i_item_id,
650                         l_txn_qty,
651                         i_txn_action_id,
652                         l_new_cost,
653                         l_hook,
654                         i_txfr_layer_id,
655                         i_citw_flag,
656                         i_flow_schedule,
657                         i_user_id,
658                         i_login_id,
659                         i_req_id,
660                         i_prg_appl_id,
661                         i_prg_id,
662                         l_err_num,
663                         l_err_code,
664                         l_err_msg);
665 
666     if (l_err_num <> 0) then
667       raise process_error;
668     end if;
669     IF g_debug = 'Y' THEN
670        fnd_file.put_line(fnd_file.log, '<<Returned from CSTPAVCP.sub_transfer');
671     END IF;
672 
673   -- If this transaction is using a new cost and it is not an
674   -- expense item than we need to recalculate
675   -- average cost
676   elsif ((l_new_cost = 1) and (l_exp_flag <> 1) and
677          (i_txn_action_id <> 30)) then
678 
679     -- when we process transfer org's txn(i.e. intransit txfr),
680     -- we need to use txfr_layer_id instead.
681     l_stmt_num := 120;
682     if (i_org_id <> i_txn_org_id) then
683       l_layer_id := i_txfr_layer_id;
684       l_txn_qty := -1 * l_txn_qty;
685     else
686       l_layer_id := i_layer_id;
687     end if;
688 
689     l_stmt_num := 130;
690    IF g_debug = 'Y' THEN
691        fnd_file.put_line(fnd_file.log, '>>Calling CSTPAVCP.calc_average_cost');
692    END IF;
693     CSTPAVCP.calc_average_cost(
694                                 i_org_id,
695                                 i_txn_id,
696                                 l_layer_id,
697                                 i_cost_type,
698                                 i_item_id,
699                                 l_txn_qty,
700                                 i_txn_action_id,
701                                 l_no_update_mmt,
702                                 i_user_id,
703                                 i_login_id,
704                                 i_req_id,
705                                 i_prg_appl_id,
706                                 i_prg_id,
707                                 l_err_num,
708                                 l_err_code,
709                                 l_err_msg);
710     if (l_err_num <> 0) then
711       -- Error occured
712       raise process_error;
713     end if;
714    IF g_debug = 'Y' THEN
715        fnd_file.put_line(fnd_file.log, '<<Returned from CSTPAVCP.calc_average_cost');
716    END IF;
717   else
718     -- when we process transfer org's txn(i.e. intransit txfr),
719     -- we need to use txfr_layer_id instead.
720     if (i_org_id <> i_txn_org_id) then
721       l_layer_id := i_txfr_layer_id;
722       l_txn_qty := -1 * l_txn_qty;
723       l_org_id := i_txn_org_id;
724     else
725       l_layer_id := i_layer_id;
726       l_org_id := i_org_id;
727     end if;
728 
729     l_stmt_num := 140;
730     IF g_debug = 'Y' THEN
731        fnd_file.put_line(fnd_file.log, '>>Calling CSTPAVCP.current_average_cost');
732     END IF;
733     CSTPAVCP.current_average_cost(
734                                 l_org_id,
735                                 i_txn_id,
736                                 l_layer_id,
737                                 i_cost_type,
738                                 i_item_id,
739                                 l_txn_qty,
740                                 i_txn_action_id,
741                                 l_exp_flag,
742                                 l_no_update_mmt,
743                                 0,
744                                 i_user_id,
745                                 i_login_id,
746                                 i_req_id,
747                                 i_prg_appl_id,
748                                 i_prg_id,
749                                 l_err_num,
750                                 l_err_code,
751                                 l_err_msg);
752     if (l_err_num <> 0) then
753       -- Error occured
754       raise process_error;
755     end if;
756    IF g_debug = 'Y' THEN
757        fnd_file.put_line(fnd_file.log, '<<Returned from CSTPAVCP.current_average_cost');
758    END IF;
759     -- For Internal Order Issue transactons to Expense destinations,
760     -- call Cost_LogicalSOReceipt API to cost the Receipt transaction.
761     l_stmt_num := 150;
762 
763     select transaction_type_id
764     into   l_txn_type_id
765     from   mtl_material_transactions
766     where  transaction_id = i_txn_id;
767 
768     l_stmt_num := 160;
769     IF ( I_TXN_ACTION_ID = 1 AND L_TXN_TYPE_ID = 34 AND I_TXN_SRC_TYPE = 8) THEN
770       CSTPAVCP.Cost_LogicalSOReceipt (
771         p_parent_txn_id => i_txn_id,
772         p_user_id       => i_user_id,
773         p_request_id    => i_req_id,
774         p_prog_id       => i_prg_id,
775         p_prog_app_id   => i_prg_appl_id,
776         p_login_id      => i_login_id,
777         x_err_num       => l_err_num,
778         x_err_code      => l_err_code,
779         x_err_msg       => l_err_msg
780       );
781       IF l_err_num <> 0 THEN
782         RAISE LOGICAL_SORECEIPT_ERROR;
783       END IF;
784     END IF;
785   end if;
786   if (g_debug = 'Y') then
787     fnd_file.put_line(fnd_file.log,'>>Exiting Cost Processor');
788   end if;
789 
790   EXCEPTION
791     when process_error then
792       o_err_num := l_err_num;
793       o_err_code := l_err_code;
794       o_err_msg := l_err_msg;
795     when LOGICAL_SORECEIPT_ERROR then
796       rollback;
797       o_err_num := SQLCODE;
798       o_err_msg := 'CSTPAVCP.Cost_Processor (' || to_char(l_stmt_num) || '): '
799                 || 'Error in CSTPAVCP.Cost_LogicalReceipt';
800     when OTHERS then
801       rollback;
802       o_err_num := SQLCODE;
803       o_err_msg := 'CSTPAVCP.Cost_Processor (' || to_char(l_stmt_num) || '): '
804                 || substr(SQLERRM,1,200);
805 
806 END cost_processor;
807 
808 
809 -- PROCEDURE
810 --  average_cost_update         Cost process the average cost update
811 --                              transaction.
812 
813 procedure average_cost_update(
814   I_ORG_ID      IN        NUMBER,
815   I_TXN_ID      IN        NUMBER,
816   I_LAYER_ID    IN        NUMBER,
817   I_COST_TYPE   IN        NUMBER,
818   I_ITEM_ID     IN        NUMBER,
819   I_TXN_ACTION_ID IN    NUMBER,
820   I_TXN_QTY     IN      NUMBER,/*LCM*/
821   I_EXP_FLG     IN        NUMBER,
822   I_USER_ID     IN        NUMBER,
823   I_LOGIN_ID    IN      NUMBER,
824   I_REQ_ID      IN        NUMBER,
825   I_PRG_APPL_ID IN        NUMBER,
826   I_PRG_ID      IN         NUMBER,
827   O_Err_Num     OUT NOCOPY        NUMBER,
828   O_Err_Code    OUT NOCOPY        VARCHAR2,
829   O_Err_Msg     OUT NOCOPY        VARCHAR2
830 ) IS
831   neg_cost_error        EXCEPTION;
832   l_neg_cost            NUMBER;
833   l_mandatory_update    NUMBER;
834   l_err_num             NUMBER;
835   l_err_code            VARCHAR2(240);
836   l_err_msg             VARCHAR2(240);
837   l_stmt_num            NUMBER;
838   process_error         EXCEPTION;
839   l_num_cost_groups     NUMBER;
840   l_layer_quantity      NUMBER;
841 
842 BEGIN
843   -- Initialize variables.
844   l_neg_cost := 0;
845   l_err_num := 0;
846   l_err_code := '';
847   l_err_msg := '';
848 
849   if (g_debug = 'Y') then
850        fnd_file.put_line(fnd_file.log,'Average Cost Update <<<');
851   end if;
852 
853   l_stmt_num := 10;
854   -- First insert records into mtl_cst_actual_cost_details.
855 
856   insert into mtl_cst_actual_cost_details (
857         transaction_id,
858         organization_id,
859         layer_id,
860         cost_element_id,
861         level_type,
862         transaction_action_id,
863         last_update_date,
864         last_updated_by,
865         creation_date,
866         created_by,
867         last_update_login,
868         request_id,
869         program_application_id,
870         program_id,
871         program_update_date,
872         inventory_item_id,
873         actual_cost,
874         prior_cost,
875         new_cost,
876         insertion_flag,
877         variance_amount,
878         user_entered,
879         onhand_variance_amount)
880   select
881         i_txn_id,
882         i_org_id,
883         i_layer_id,
884         ctcd.cost_element_id,
885         ctcd.level_type,
886         i_txn_action_id,
887         sysdate,
888         i_user_id,
889         sysdate,
890         i_user_id,
891         i_login_id,
892         i_req_id,
893         i_prg_appl_id,
894         i_prg_id,
895         sysdate,
896         ctcd.inventory_item_id,
897         decode(ctcd.new_average_cost,NULL,
898              decode(ctcd.percentage_change,NULL,
899                   /* value change formula */
900                   decode(sign(cql.layer_quantity),1,
901                     decode(sign(i_txn_qty),1,
902                      decode(sign(cql.layer_quantity-i_txn_qty),-1,
903                          decode(sign(nvl(clcd.item_cost,0) * cql.layer_quantity +
904                                      (ctcd.value_change/i_txn_qty*cql.layer_quantity)),-1,
905                             0,
906                             (nvl(clcd.item_cost,0)*nvl(cql.layer_quantity,0) +
907                              (ctcd.value_change/i_txn_qty*cql.layer_quantity))/nvl(cql.layer_quantity,-1)),
908                        decode(sign(nvl(clcd.item_cost,0) * cql.layer_quantity + ctcd.value_change),-1,
909                             0,
910                             (nvl(clcd.item_cost,0)*nvl(cql.layer_quantity,0) +
911                              ctcd.value_change)/nvl(cql.layer_quantity,-1))),
912                        decode(sign(nvl(clcd.item_cost,0) * cql.layer_quantity + ctcd.value_change),-1,
913                             0,
914                             (nvl(clcd.item_cost,0)*nvl(cql.layer_quantity,0) +
915                              ctcd.value_change)/nvl(cql.layer_quantity,-1))),
916                        nvl(clcd.item_cost,0)),
917                    /* percentage change formula */
918                    nvl(clcd.item_cost,0)*(1+ctcd.percentage_change/100)),
919              /* new average cost formula */
920              ctcd.new_average_cost),
921         nvl(clcd.item_cost,0),
922         decode(ctcd.new_average_cost,NULL,
923              decode(ctcd.percentage_change,NULL,
924                   /* value change formula */
925                   decode(sign(cql.layer_quantity),1,
926                     decode(sign(i_txn_qty),1,
927                      decode(sign(cql.layer_quantity-i_txn_qty),-1,
928                          decode(sign(nvl(clcd.item_cost,0) * cql.layer_quantity +
929                                      (ctcd.value_change/i_txn_qty*cql.layer_quantity)),-1,
930                             0,
931                             (nvl(clcd.item_cost,0)*nvl(cql.layer_quantity,0) +
932                              (ctcd.value_change/i_txn_qty*cql.layer_quantity))/nvl(cql.layer_quantity,-1)),
933                        decode(sign(nvl(clcd.item_cost,0) * cql.layer_quantity + ctcd.value_change),-1,
934                             0,
935                             (nvl(clcd.item_cost,0)*nvl(cql.layer_quantity,0) +
936                              ctcd.value_change)/nvl(cql.layer_quantity,-1))),
937                        decode(sign(nvl(clcd.item_cost,0) * cql.layer_quantity + ctcd.value_change),-1,
938                             0,
939                             (nvl(clcd.item_cost,0)*nvl(cql.layer_quantity,0) +
940                              ctcd.value_change)/nvl(cql.layer_quantity,-1))),
941                        nvl(clcd.item_cost,0)),
942                    /* percentage change formula */
943                    nvl(clcd.item_cost,0)*(1+ctcd.percentage_change/100)),
944              /* new average cost formula */
945              ctcd.new_average_cost),
946         'Y',
947         decode(ctcd.value_change,NULL,
948              0,
949              decode(sign(cql.layer_quantity),1,
950                 decode(sign(i_txn_qty),1,
951                  decode(sign(cql.layer_quantity-i_txn_qty),-1,
952                   decode(sign(nvl(clcd.item_cost,0) * cql.layer_quantity + (ctcd.value_change/i_txn_qty*cql.layer_quantity)),-1,
953                        (ctcd.value_change/i_txn_qty*cql.layer_quantity) + nvl(clcd.item_cost,0) * cql.layer_quantity,
954                        0),
955                   decode(sign(nvl(clcd.item_cost,0) * cql.layer_quantity + ctcd.value_change),-1,
956                        ctcd.value_change + nvl(clcd.item_cost,0) * cql.layer_quantity,
957                        0)),
958                   decode(sign(nvl(clcd.item_cost,0) * cql.layer_quantity + ctcd.value_change),-1,
959                        ctcd.value_change + nvl(clcd.item_cost,0) * cql.layer_quantity,
960                        0)),
961                   ctcd.value_change)),
962         'N',
963         /*LCM*/
964     decode(ctcd.value_change,NULL,
965            0,
966            decode(sign(i_txn_qty),1,
967                   decode(sign(cql.layer_quantity),1,
968                          decode(sign(cql.layer_quantity-i_txn_qty),-1,
969                                 ctcd.value_change*(1-cql.layer_quantity/i_txn_qty),
970                                 0
971                                 ),
972                          0
973                          ),
974                   0
975                   )
976            )
977   FROM mtl_cst_txn_cost_details ctcd,
978        cst_quantity_layers cql,
979        cst_layer_cost_details clcd
980   WHERE ctcd.transaction_id = i_txn_id
981   AND ctcd.organization_id = i_org_id
982   AND cql.layer_id = i_layer_id
983   AND cql.inventory_item_id = ctcd.inventory_item_id
984   AND cql.organization_id = ctcd.organization_id
985   AND clcd.layer_id (+) = i_layer_id
986   AND clcd.cost_element_id (+) = ctcd.cost_element_id
987   AND clcd.level_type (+) = ctcd.level_type;
988   -- Verify there are no negative costs!
989   l_stmt_num := 20;
990 
991 /*  select count(*)
992   into l_neg_cost
993   from mtl_cst_actual_cost_details
994   where transaction_id = i_txn_id
995   and organization_id = i_org_id
996   and layer_id = i_layer_id
997   and new_cost < 0;
998 
999   if (l_neg_cost > 0) then
1000     raise neg_cost_error;
1001   end if; */ -- removed for bug #4005770
1002 
1003  l_stmt_num  := 21 ;
1004 /**************************************************
1005 Issue : Bug 8652819
1006 Added to include elemental level cost which are not present in
1007 MCTCD or MCACD but present in CLCD.When first txn for any item is PO txn and not costed
1008 and if immediately average cost update performs then average cost update transaction gets
1009 populated before costing of PO txn as a result it does not contain cost_element 2 cost,which has been
1010 introduced by PO.These changes are similarto change done for India localization case
1011 
1012 Fix :
1013 1) Following insert statement would ensure that existing costs against other CE/Level
1014 should not lost
1015 2) We have already changed the Average Cost update form (through bug6407296 ) to make
1016 fields "LEVEL" and "COST ELEMENT" as a  non updatable fields
1017 
1018 Above two changes will make behaviour consitent.
1019 
1020 ***************************************************/
1021   insert into mtl_cst_actual_cost_details (
1022         transaction_id,
1023         organization_id,
1024         layer_id,
1025         cost_element_id,
1026         level_type,
1027         transaction_action_id,
1028         last_update_date,
1029         last_updated_by,
1030         creation_date,
1031         created_by,
1032         last_update_login,
1033         request_id,
1034         program_application_id,
1035         program_id,
1036         program_update_date,
1037         inventory_item_id,
1038         actual_cost,
1039         prior_cost,
1040         new_cost,
1041         insertion_flag,
1042         variance_amount,
1043         user_entered)
1044   select i_txn_id,
1045         i_org_id,
1046         i_layer_id,
1047         clcd.cost_element_id,
1048         clcd.level_type,
1049         i_txn_action_id,
1050         sysdate,
1051         i_user_id,
1052         sysdate,
1053         i_user_id,
1054         i_login_id,
1055         i_req_id,
1056         i_prg_appl_id,
1057         i_prg_id,
1058         sysdate,
1059         i_item_id,
1060         clcd.item_cost,
1061         clcd.item_cost,
1062         clcd.item_cost,
1063         'Y',
1064         0,
1065         'N'
1066   from cst_layer_cost_details clcd
1067   where layer_id = i_layer_id
1068   and not exists
1069         (select 'this detail is not in cacd already'
1070          from mtl_cst_actual_cost_details cacd
1071          where cacd.transaction_id = i_txn_id
1072          and cacd.organization_id = i_org_id
1073          and cacd.layer_id = i_layer_id
1074          and cacd.cost_element_id = clcd.cost_element_id
1075          and cacd.level_type = clcd.level_type);
1076 
1077 
1078 /* Changes for bug 8649362 and 8652819 are over*/
1079 
1080 
1081 
1082   /********************************************************************
1083    ** Delete from cst_layer_cost_details and insert the new rows     **
1084    ** from mtl_cst_actual_cost_details.                              **
1085    ********************************************************************/
1086   l_stmt_num := 30;
1087 
1088   Delete from cst_layer_cost_details
1089   where layer_id = i_layer_id;
1090 
1091   l_stmt_num := 40;
1092   Insert into cst_layer_cost_details (
1093         layer_id,
1094         cost_element_id,
1095         level_type,
1096         last_update_date,
1097         last_updated_by,
1098         creation_date,
1099         created_by,
1100         last_update_login,
1101         request_id,
1102         program_application_id,
1103         program_id,
1104         program_update_date,
1105         item_cost)
1106   select i_layer_id,
1107         cacd.cost_element_id,
1108         cacd.level_type,
1109         sysdate,
1110         i_user_id,
1111         sysdate,
1112         i_user_id,
1113         i_login_id,
1114         i_req_id,
1115         i_prg_appl_id,
1116         i_prg_id,
1117         sysdate,
1118         cacd.new_cost
1119   from mtl_cst_actual_cost_details cacd
1120   where cacd.transaction_id = i_txn_id
1121   and cacd.organization_id = i_org_id
1122   and cacd.layer_id = i_layer_id
1123   and cacd.insertion_flag = 'Y'
1124   and cacd.new_cost <> 0;
1125 
1126   if sql%rowcount  =  0 then
1127   Insert into cst_layer_cost_details (
1128         layer_id,
1129         cost_element_id,
1130         level_type,
1131         last_update_date,
1132         last_updated_by,
1133         creation_date,
1134         created_by,
1135         last_update_login,
1136         request_id,
1137         program_application_id,
1138         program_id,
1139         program_update_date,
1140         item_cost)
1141   select i_layer_id,
1142         cacd.cost_element_id,
1143         cacd.level_type,
1144         sysdate,
1145         i_user_id,
1146         sysdate,
1147         i_user_id,
1148         i_login_id,
1149         i_req_id,
1150         i_prg_appl_id,
1151         i_prg_id,
1152         sysdate,
1153         cacd.new_cost
1154   from mtl_cst_actual_cost_details cacd
1155   where cacd.transaction_id = i_txn_id
1156   and cacd.organization_id = i_org_id
1157   and cacd.layer_id = i_layer_id
1158   and cacd.insertion_flag = 'Y'
1159   and cacd.cost_element_id = (select min(cost_element_id)
1160       from mtl_cst_actual_cost_details
1161       where transaction_id = i_txn_id
1162        and organization_id = i_org_id
1163        and layer_id = i_layer_id
1164        and insertion_flag = 'Y');
1165   end if;
1166 
1167   /********************************************************************
1168    ** Update cst_quanity_layers                                      **
1169    ********************************************************************/
1170   l_stmt_num := 50;
1171   /* Used the Base Table instead of View Bug 4773025 */
1172   Update cst_quantity_layers cql
1173   Set (last_updated_by,
1174         last_update_date,
1175         last_update_login,
1176         request_id,
1177         program_application_id,
1178         program_id,
1179         program_update_date,
1180         update_transaction_id,
1181         pl_material,
1182         pl_material_overhead,
1183         pl_resource,
1184         pl_outside_processing,
1185         pl_overhead,
1186         tl_material,
1187         tl_material_overhead,
1188         tl_resource,
1189         tl_outside_processing,
1190         tl_overhead,
1191         material_cost,
1192         material_overhead_cost,
1193         resource_cost,
1194         outside_processing_cost,
1195         overhead_cost,
1196         pl_item_cost,
1197         tl_item_cost,
1198         item_cost,
1199         unburdened_cost,
1200         burden_cost) =
1201   (SELECT
1202         i_user_id,
1203         sysdate,
1204         i_login_id,
1205         i_req_id,
1206         i_prg_appl_id,
1207         i_prg_id,
1208         sysdate,
1209         i_txn_id,
1210         SUM(DECODE(LEVEL_TYPE, 2, DECODE(COST_ELEMENT_ID, 1, ITEM_COST, 0), 0)),
1211         SUM(DECODE(LEVEL_TYPE, 2, DECODE(COST_ELEMENT_ID, 2, ITEM_COST, 0), 0)),
1212         SUM(DECODE(LEVEL_TYPE, 2, DECODE(COST_ELEMENT_ID, 3, ITEM_COST, 0), 0)),
1213         SUM(DECODE(LEVEL_TYPE, 2, DECODE(COST_ELEMENT_ID, 4, ITEM_COST, 0), 0)),
1214         SUM(DECODE(LEVEL_TYPE, 2, DECODE(COST_ELEMENT_ID, 5, ITEM_COST, 0), 0)),
1215         SUM(DECODE(LEVEL_TYPE, 1, DECODE(COST_ELEMENT_ID, 1, ITEM_COST, 0), 0)),
1216         SUM(DECODE(LEVEL_TYPE, 1,DECODE(COST_ELEMENT_ID, 2, ITEM_COST, 0), 0)),
1217         SUM(DECODE(LEVEL_TYPE, 1, DECODE(COST_ELEMENT_ID, 3, ITEM_COST, 0), 0)),
1218         SUM(DECODE(LEVEL_TYPE ,1, DECODE(COST_ELEMENT_ID ,4, ITEM_COST, 0), 0)),
1219         SUM(DECODE(LEVEL_TYPE, 1, DECODE(COST_ELEMENT_ID, 5, ITEM_COST, 0), 0)),
1220         SUM(DECODE(COST_ELEMENT_ID, 1, ITEM_COST, 0)),
1221         SUM(DECODE(COST_ELEMENT_ID, 2, ITEM_COST, 0)),
1222         SUM(DECODE(COST_ELEMENT_ID, 3, ITEM_COST, 0)),
1223         SUM(DECODE(COST_ELEMENT_ID, 4, ITEM_COST, 0)),
1224         SUM(DECODE(COST_ELEMENT_ID, 5, ITEM_COST, 0)),
1225         SUM(DECODE(LEVEL_TYPE, 2, ITEM_COST, 0)),
1226         SUM(DECODE(LEVEL_TYPE, 1, ITEM_COST, 0)),
1227         SUM(ITEM_COST),
1228         SUM(DECODE(COST_ELEMENT_ID, 2, DECODE(LEVEL_TYPE, 2, ITEM_COST, 0), ITEM_COST)),
1229         SUM(DECODE(COST_ELEMENT_ID, 2, DECODE(LEVEL_TYPE, 1, ITEM_COST, 0), 0))
1230    from CST_LAYER_COST_DETAILS clcd
1231    where clcd.layer_id = i_layer_id)
1232   where cql.layer_id = i_layer_id
1233   and exists
1234      (select 'there is detail cost'
1235       from cst_layer_cost_details clcd
1236       where clcd.layer_id = i_layer_id);
1237 
1238   l_stmt_num := 60;
1239   /********************************************************************
1240    ** Update Mtl_Material_Transactions                               **
1241    ********************************************************************/
1242   CSTPAVCP.update_mmt(
1243                         i_org_id,
1244                         i_txn_id,
1245                         -1,                -- txfr_txn_id is not applicable
1246                         i_layer_id,
1247                         1,
1248                         i_user_id,
1249                         i_login_id,
1250                         i_req_id,
1251                         i_prg_appl_id,
1252                         i_prg_id,
1253                         l_err_num,
1254                         l_err_code,
1255                         l_err_msg);
1256 
1257   if (l_err_num <> 0) then
1258     -- Error occured
1259     raise process_error;
1260   end if;
1261 
1262   l_stmt_num := 70;
1263   /* 3509390
1264 
1265      If the item is held in only one cost group for the organization,
1266      it is okay to update CIC with the cost when quantity is 0.
1267 
1268      The default behavior is not to require mandatory update unless the
1269      above property (one cost group, zero quantity) is found to be true.
1270      When total layer quantity is positive, CIC is updated regardless of the
1271      value of l_mandatory_update.
1272   */
1273 
1274   l_mandatory_update := 0;
1275 /* Bug10324713
1276   SELECT count(*)
1277   INTO   l_num_cost_groups
1278   FROM   cst_quantity_layers
1279   WHERE  inventory_item_id = i_item_id
1280   AND    organization_id   = i_org_id;
1281 
1282   IF (l_num_cost_groups = 1) THEN
1283     SELECT layer_quantity
1284     INTO   l_layer_quantity
1285     FROM   cst_quantity_layers
1286     WHERE  inventory_item_id = i_item_id
1287     AND    organization_id   = i_org_id;
1288 
1289     IF (l_layer_quantity = 0) THEN
1290       l_mandatory_update := 1;
1291     END IF;
1292   END IF;
1293 */
1294   l_stmt_num := 80;
1295   /********************************************************************
1296    ** Update Item Cost and Item Cost Details                         **
1297    ********************************************************************/
1298   CSTPAVCP.update_item_cost(
1299                         i_org_id,
1300                         i_txn_id,
1301                         i_layer_id,
1302                         i_cost_type,
1303                         i_item_id,
1304                         0,/*l_mandatory_update,*/
1305                         i_user_id,
1306                         i_login_id,
1307                         i_req_id,
1308                         i_prg_appl_id,
1309                         i_prg_id,
1310                         l_err_num,
1311                         l_err_code,
1312                         l_err_msg);
1313   if (l_err_num <> 0) then
1314     -- Error occured
1315     raise process_error;
1316   end if;
1317   if (g_debug = 'Y') then
1318        fnd_file.put_line(fnd_file.log,'Average Cost Update >>>');
1319   end if;
1320 
1321   EXCEPTION
1322     when neg_cost_error then
1323       rollback;
1324       o_err_num := 9999;
1325       o_err_code := 'CST_NEG_ITEM_COST';
1326       FND_MESSAGE.set_name('BOM', 'CST_NEG_ITEM_COST');
1327       o_err_msg := FND_MESSAGE.Get;
1328     when process_error then
1329       o_err_num := l_err_num;
1330       o_err_code := l_err_code;
1331       o_err_msg := l_err_msg;
1332     when others then
1333       rollback;
1334       o_err_num := SQLCODE;
1335       o_err_msg := 'CSTPAVCP.average_cost_update (' || to_char(l_stmt_num) ||
1336                    '): '
1337                    || substr(SQLERRM, 1,200);
1338 END average_cost_update;
1339 
1340 -- PROCEDURE
1341 --  sub_transfer                Cost process the subinventory transfer
1342 --                              transaction.
1343 
1344 procedure sub_transfer(
1345   I_ORG_ID              IN NUMBER,
1346   I_TXN_ID              IN NUMBER,
1347   I_LAYER_ID            IN NUMBER,
1348   I_COST_TYPE           IN NUMBER,
1349   I_ITEM_ID             IN NUMBER,
1350   I_TXN_QTY             IN NUMBER,
1351   I_TXN_ACTION_ID       IN NUMBER,
1352   I_NEW_COST            IN NUMBER,
1353   I_HOOK                IN NUMBER,
1354   I_TXFR_LAYER_ID       IN NUMBER,
1355   I_CITW_FLAG           IN NUMBER,
1356   I_FLOW_SCHEDULE       IN NUMBER,
1357   I_USER_ID             IN NUMBER,
1358   I_LOGIN_ID            IN NUMBER,
1359   I_REQ_ID              IN NUMBER,
1360   I_PRG_APPL_ID         IN NUMBER,
1361   I_PRG_ID              IN NUMBER,
1362   O_Err_Num             OUT NOCOPY NUMBER,
1363   O_Err_Code            OUT NOCOPY VARCHAR2,
1364   O_Err_Msg             OUT NOCOPY VARCHAR2
1365 ) IS
1366   l_layer_chg           NUMBER;
1367   l_exp_item            NUMBER;
1368   l_exp1                NUMBER;
1369   l_exp2                NUMBER;
1370   l_from_layer          NUMBER;
1371   l_to_layer            NUMBER;
1372   l_from_exp            NUMBER;
1373   l_to_exp              NUMBER;
1374   l_from_qty            NUMBER;
1375   l_ret_val             NUMBER;
1376   l_no_update_qty       NUMBER;
1377   l_new_cost            NUMBER;
1378   l_txf_txn_id          NUMBER;
1379   l_err_num             NUMBER;
1380   l_err_code            VARCHAR2(240);
1381   l_err_msg             VARCHAR2(240);
1382   l_stmt_num            NUMBER;
1383   process_error         EXCEPTION;
1384 -- borrow payback
1385   l_txn_type_id         NUMBER;
1386     /* Added for bug 6635134 */
1387   l_txn_action_id       NUMBER;
1388   l_cur_cost            NUMBER;
1389 -- borrow payback end
1390   l_no_upd_mmt          NUMBER:=0; /* Bug 9758017 */
1391 BEGIN
1392   -- initialize local variables
1393   l_err_num := 0;
1394   l_err_code := '';
1395   l_err_msg := '';
1396   l_new_cost := i_new_cost;
1397   l_stmt_num := 0;
1398 
1399   IF g_debug = 'Y' THEN
1400     fnd_file.put_line(fnd_file.log, 'Sub_Transfer <<<');
1401   END IF;
1402 
1403  /********************************************************************
1404   ** Figure out layer_change flag                                   **
1405   ** A layer change occurs when we transfer material between        **
1406   ** two different layers within the same org.                      **
1407   ********************************************************************/
1408 -- borrow / payback
1409   l_stmt_num := 10;
1410   /* Modified for bug 6635134 */
1411   select transaction_type_id, transaction_action_id
1412     into l_txn_type_id, l_txn_action_id
1413     from mtl_material_transactions
1414     where transaction_id = i_txn_id;
1415 -- borrow / payback end
1416 
1417   l_stmt_num := 15;
1418   if ((i_txfr_layer_id is not NULL) and (i_txfr_layer_id <> i_layer_id)) then
1419     l_layer_chg := 1;
1420   else
1421     l_layer_chg := 0;
1422   end if;
1423 
1424   if (g_debug = 'Y') then
1425        fnd_file.put_line(fnd_file.log,'Layer change: ' || to_char(l_layer_chg));
1426   end if;
1427 
1428   l_stmt_num := 20;
1429   select decode(inventory_asset_flag, 'Y',0,1)
1430   into l_exp_item
1431   from mtl_system_items
1432   where inventory_item_id = i_item_id
1433   and organization_id = i_org_id;
1434 
1435   if (g_debug = 'Y') then
1436        fnd_file.put_line(fnd_file.log,'Expense Item: ' || to_char(l_exp_item));
1437   end if;
1438 
1439   l_stmt_num := 30;
1440 
1441   select decode(asset_inventory,1,0,1)
1442   into l_exp1
1443   from mtl_secondary_inventories msi
1444   , mtl_material_transactions mmt
1445   where msi.secondary_inventory_name = mmt.subinventory_code
1446   and msi.organization_id = i_org_id
1447   and mmt.transaction_id = i_txn_id
1448   and mmt.organization_id = i_org_id;
1449 
1450 
1451   l_stmt_num := 40;
1452 
1453 
1454   -- the nature of project sub is the same as project job, except
1455   -- asset common to expense project job issue case.
1456   --
1457   -- Common     Proj Sub        Proj Job
1458   --  asset      asset                 asset
1459   --  asset      asset *         exp *                <= special case
1460   --  exp        asset                 asset
1461   --  exp        exp                 exp
1462 
1463   -- we divide into three cases to figure out the type of txfr sub.
1464   --  1. common issue to wip
1465   --  2. normal subinventory txfr
1466   --  3. others
1467 
1468   if (i_citw_flag = 1) then
1469     l_stmt_num := 42;
1470     if (g_debug = 'Y') then
1471         fnd_file.put_line(fnd_file.log,'Common Issue to WIP');
1472     end if;
1473 
1474     if(i_flow_schedule = 1) then
1475       -- cfm then use wip_flow_schedules
1476       -- class_type 1 and 3 : asset job, 4 : exp job
1477       l_stmt_num := 44;
1478       if (g_debug = 'Y') then
1479            fnd_file.put_line(fnd_file.log,'Flow Schedule');
1480       end if;
1481 
1482       select decode(wac.class_type, 1, 0,
1483                                     3, 0,
1484                                     6, 0,
1485                                     4, decode(l_exp1, 1, 1, 0))
1486       into   l_exp2
1487       from   mtl_material_transactions mmt,
1488              wip_flow_schedules wfs,
1489              wip_accounting_classes wac
1490       where  mmt.transaction_id = i_txn_id
1491       and    mmt.organization_id = i_org_id
1492       and    wfs.organization_id = i_org_id
1493       and    wfs.wip_entity_id = mmt.transaction_source_id
1494       and    wac.organization_id = i_org_id
1495       and    wac.class_code = wfs.class_code;
1496     else
1497       -- non cfm then use wip_discrete_jobs
1498       -- class_type 1 and 3 : asset job, 4 : exp job
1499       select decode(wac.class_type, 1, 0,
1500                                     3, 0,
1501                                     6, 0,
1502                                     4, decode(l_exp1, 1, 1, 0))
1503       into   l_exp2
1504       from   mtl_material_transactions mmt,
1505              wip_discrete_jobs wdj,
1506              wip_accounting_classes wac
1507       where  mmt.transaction_id = i_txn_id
1508       and    mmt.organization_id = i_org_id
1509       and    wdj.organization_id = i_org_id
1510       and    wdj.wip_entity_id = mmt.transaction_source_id
1511       and    wac.organization_id = i_org_id
1512       and    wac.class_code = wdj.class_code;
1513     end if;
1514   /* Changes for VMI. Adding Planning Transfer Transaction */
1515   elsif (i_txn_action_id IN (2,5,28)) then
1516     l_stmt_num := 46;
1517     if (g_debug = 'Y') then
1518          fnd_file.put_line(fnd_file.log,'Transfer Subinventory asset flag : ' || to_char(l_exp2));
1519     end if;
1520 
1521     select decode(asset_inventory,1,0,1)
1522     into l_exp2
1523     from mtl_secondary_inventories msi
1524     , mtl_material_transactions mmt
1525     where msi.secondary_inventory_name = mmt.transfer_subinventory
1526     and msi.organization_id = i_org_id
1527     and mmt.transaction_id = i_txn_id
1528     and mmt.organization_id = i_org_id;
1529      elsif(i_txn_action_id = 55 ) then
1530     l_stmt_num := 47;
1531     l_exp2 := l_exp1; /* Txfr sub asset flag is equal to from sub asset flag in cost grp txfrs */
1532     if (g_debug = 'Y') then
1533          fnd_file.put_line(fnd_file.log,'Transfer Subinventory asset flag : '||to_char(l_exp2));
1534     end if;
1535   else
1536     l_stmt_num := 48;
1537     l_exp2 := 0;
1538   end if;
1539 
1540   /* Changes for VMI. Adding Planning Transfer Transaction */
1541   if (i_txn_action_id in (2,5,28,55,21)) then
1542     l_stmt_num := 50;
1543     l_from_layer := i_layer_id;
1544     l_to_layer := i_txfr_layer_id;
1545     l_from_exp := l_exp1;
1546     l_to_exp := l_exp2;
1547     l_from_qty := i_txn_qty;
1548   else
1549     l_stmt_num := 60;
1550     l_from_layer := i_txfr_layer_id;
1551     l_to_layer := i_layer_id;
1552     l_from_exp := l_exp2;
1553     l_to_exp := l_exp1;
1554     l_from_qty :=-1 * i_txn_qty;
1555   end if;
1556 
1557   if (g_debug = 'Y') then
1558          fnd_file.put_line(fnd_file.log,'From layer ID :' || to_char(l_from_layer));
1559          fnd_file.put_line(fnd_file.log,'To Layer ID : ' || to_char(l_to_layer));
1560          fnd_file.put_line(fnd_file.log,'From subinv Asset flag : ' || to_char(l_exp1));
1561          fnd_file.put_line(fnd_file.log,'To subinv Asset flag : ' || to_char(l_exp2));
1562   end if;
1563   -- Just in case i_txfr_layer_id is NULL, always set from and to layer
1564   -- to layer_id for same layer transfers.
1565   l_stmt_num := 70;
1566   if (l_layer_chg = 0) then
1567     l_from_layer := i_layer_id;
1568     l_to_layer := i_layer_id;
1569     if (g_debug = 'Y') then
1570           fnd_file.put_line(fnd_file.log,'No Layer change');
1571           fnd_file.put_line(fnd_file.log,'From Layer : ' || to_char(l_from_layer));
1572           fnd_file.put_line(fnd_file.log,'To Layer : ' || to_char(l_to_layer));
1573     end if;
1574   end if;
1575 
1576   -- If we are changing layers, then need to create another layer information
1577   -- in mtl_cst_actual_cost_details.
1578   l_stmt_num := 80;
1579 
1580   if (l_layer_chg = 1) then
1581     if (g_debug = 'Y') then
1582          fnd_file.put_line(fnd_file.log,'Layer change');
1583     end if;
1584 
1585     insert into mtl_cst_actual_cost_details(
1586         transaction_id,
1587         organization_id,
1588         layer_id,
1589         cost_element_id,
1590         level_type,
1591         transaction_action_id,
1592         last_update_date,
1593         last_updated_by,
1594         creation_date,
1595         created_by,
1596         last_update_login,
1597         request_id,
1598         program_application_id,
1599         program_id,
1600         program_update_date,
1601         inventory_item_id,
1602         actual_cost,
1603         prior_cost,
1604         new_cost,
1605         insertion_flag,
1606         variance_amount,
1607         user_entered)
1608     select
1609         i_txn_id,
1610         i_org_id,
1611         l_to_layer,
1612         cacd.cost_element_id,
1613         cacd.level_type,
1614         i_txn_action_id,
1615         sysdate,
1616         i_user_id,
1617         sysdate,
1618         i_user_id,
1619         i_login_id,
1620         i_req_id,
1621         i_prg_appl_id,
1622         i_prg_id,
1623         sysdate,
1624         i_item_id,
1625         cacd.actual_cost,
1626         cacd.actual_cost,
1627         cacd.actual_cost,
1628         'Y',
1629         0,
1630         'N'
1631     from mtl_cst_actual_cost_details cacd
1632     where transaction_id = i_txn_id
1633     and organization_id = i_org_id
1634     and layer_id = l_from_layer;
1635 
1636   end if;
1637 
1638   -- if the hook has been used and it is an asset to asset transfer for
1639   -- the same layer of an asset/expense item then ignore the hook.
1640   if (l_layer_chg = 0 and l_from_exp = 0 and l_to_exp = 0
1641       and l_new_cost = 1)
1642 --borrow payback, the following stmt make sure it is not borrow payback txn
1643       and (l_txn_type_id <> 68 or (l_txn_type_id = 68 and l_layer_chg = 0))then
1644 
1645     l_stmt_num := 90;
1646 
1647     l_ret_val := CSTPAVCP.compute_actual_cost(
1648                                 i_org_id,
1649                                 i_txn_id,
1650                                 i_layer_id,
1651                                 NULL,
1652                                 NULL,
1653                                 NULL,
1654                                 i_item_id,
1655                                 i_txn_qty,
1656                                 i_txn_action_id,
1657                                 NULL,
1658                                 0,
1659                                 0,
1660                                 i_user_id,
1661                                 i_login_id,
1662                                 i_req_id,
1663                                 i_prg_appl_id,
1664                                 i_prg_id,
1665                                 l_err_num,
1666                                 l_err_code,
1667                                 l_err_msg);
1668     l_new_cost := 0;
1669   end if;
1670 
1671   -- For sub transfers of expense items and transfers into an expense
1672   -- subinventory and asset transfers within the same layer, the receiving
1673   -- layer has no qty or cost impact.
1674   -- Fix Bug 798970 by changing no_update_mmt flag to 0, so even if
1675   -- no cost/quantity change, the mmt will still be updated with
1676   -- current cost
1677 
1678   if (l_exp_item = 1 or l_to_exp = 1 or
1679       (l_from_exp = 0 and l_to_exp = 0 and l_layer_chg = 0))
1680 --borrow payback, the following stmt make sure it is not borrow payback txn
1681       and (l_txn_type_id <> 68 or (l_txn_type_id = 68 and l_layer_chg = 0))then
1682     l_stmt_num := 100;
1683 
1684     CSTPAVCP.current_average_cost(
1685                                 i_org_id,
1686                                 i_txn_id,
1687                                 l_to_layer,
1688                                 i_cost_type,
1689                                 i_item_id,
1690                                 -1 * l_from_qty,
1691                                 i_txn_action_id,
1692                                 0,
1693                                 0,
1694                                 1,
1695                                 i_user_id,
1696                                 i_login_id,
1697                                 i_req_id,
1698                                 i_prg_appl_id,
1699                                 i_prg_id,
1700                                 l_err_num,
1701                                 l_err_code,
1702                                 l_err_msg);
1703     if (l_err_num <> 0) then
1704       -- Error occured
1705       raise process_error;
1706     end if;
1707   end if;
1708 
1709   if (l_new_cost = 1 and l_from_exp = 0)
1710 --borrow payback, the following stmt make sure it is not borrow payback txn
1711       and (l_txn_type_id <> 68 or (l_txn_type_id = 68 and l_layer_chg = 0))then
1712     l_stmt_num := 110;
1713 
1714     CSTPAVCP.calc_average_cost(
1715                                 i_org_id,
1716                                 i_txn_id,
1717                                 l_from_layer,
1718                                 i_cost_type,
1719                                 i_item_id,
1720                                 l_from_qty,
1721                                 i_txn_action_id,
1722                                 0,
1723                                 i_user_id,
1724                                 i_login_id,
1725                                 i_req_id,
1726                                 i_prg_appl_id,
1727                                 i_prg_id,
1728                                 l_err_num,
1729                                 l_err_code,
1730                                 l_err_msg);
1731     if (l_err_num <> 0) then
1732       -- Error occured
1733       raise process_error;
1734     end if;
1735   end if;
1736 
1737   if (l_new_cost = 0 and l_from_exp = 0 and
1738      (l_to_exp = 1 or (l_to_exp = 0 and l_layer_chg = 1)))
1739 --borrow payback, the following stmt make sure it is not borrow payback txn
1740       and (l_txn_type_id <> 68 or (l_txn_type_id = 68 and l_layer_chg = 0))then
1741     l_stmt_num := 120;
1742 
1743     /* Added Bug#4259926 Do not call current_average_cost  */
1744       /* Modified for bug 6635134 */
1745     if (l_txn_action_id = 27 and i_citw_flag = 1 ) then
1746           NULL;
1747        else
1748 
1749            CSTPAVCP.current_average_cost(
1750                                 i_org_id,
1751                                 i_txn_id,
1752                                 l_from_layer,
1753                                 i_cost_type,
1754                                 i_item_id,
1755                                 l_from_qty,
1756                                 i_txn_action_id,
1757                                 0,
1758                                 0,
1759                                 0,
1760                                 i_user_id,
1761                                 i_login_id,
1762                                 i_req_id,
1763                                 i_prg_appl_id,
1764                                 i_prg_id,
1765                                 l_err_num,
1766                                 l_err_code,
1767                                 l_err_msg);
1768             if (l_err_num <> 0) then
1769                -- Error occured
1770             raise process_error;
1771             end if;
1772         end if;
1773   end if;
1774 
1775   if ((l_to_exp = 0 and l_layer_chg = 1) or (l_new_cost =1 and l_to_exp = 0))
1776 --borrow payback, the following stmt make sure it is not borrow payback txn
1777       and (l_txn_type_id <> 68 or (l_txn_type_id = 68 and l_layer_chg = 0)) then
1778     l_stmt_num := 130;
1779 
1780     /* Added Bug#4259926 */
1781     /* Modified for bug 6635134 */
1782     if (l_txn_action_id = 27 and i_citw_flag = 1) then
1783            l_from_qty :=l_from_qty;
1784        else
1785            l_from_qty := -1 * l_from_qty;
1786            if i_citw_flag = 1 then /* Bug 9758017: For CITW, MMT should not be updated for the tfr CG */
1787 	     l_no_upd_mmt := 1;
1788            end if;
1789        end if;
1790 
1791     CSTPAVCP.calc_average_cost(
1792                                 i_org_id,
1793                                 i_txn_id,
1794                                 l_to_layer,
1795                                 i_cost_type,
1796                                 i_item_id,
1797                                 l_from_qty, /* Added Bug#4259926  */
1798                                 i_txn_action_id,
1799                                 l_no_upd_mmt, /*Bug 9758017*/
1800                                 i_user_id,
1801                                 i_login_id,
1802                                 i_req_id,
1803                                 i_prg_appl_id,
1804                                 i_prg_id,
1805                                 l_err_num,
1806                                 l_err_code,
1807                                 l_err_msg);
1808     if (l_err_num <> 0) then
1809       -- Error occured
1810       raise process_error;
1811     end if;
1812   end if;
1813 
1814   if (l_from_exp = 1 and l_to_exp = 0 and l_layer_chg = 0)
1815       and (l_txn_type_id <> 68 or (l_txn_type_id = 68 and l_layer_chg = 0))then
1816 --then
1817     l_stmt_num := 140;
1818 
1819     CSTPAVCP.current_average_cost(
1820                                 i_org_id,
1821                                 i_txn_id,
1822                                 l_to_layer,
1823                                 i_cost_type,
1824                                 i_item_id,
1825                                 -1 * l_from_qty,  -- increase qty
1826                                 i_txn_action_id,
1827                                 0,
1828                                 0,
1829                                 0,        -- exp to asset, thus update qty
1830                                 i_user_id,
1831                                 i_login_id,
1832                                 i_req_id,
1833                                 i_prg_appl_id,
1834                                 i_prg_id,
1835                                 l_err_num,
1836                                 l_err_code,
1837                                 l_err_msg);
1838     if (l_err_num <> 0) then
1839       -- Error occured
1840       raise process_error;
1841     end if;
1842   end if;
1843 
1844 -- borrow payback
1845 -- if it is payback transaction, and no hook is introduced then
1846   if (l_txn_type_id = 68) and (i_hook <> 1) and ( l_layer_chg = 1)then
1847 
1848 -- update return sub with current cost
1849 -- the MCACD for return sub was populated with borrowed cost at
1850 -- the beginning of cost processor, however, we want to
1851 -- store the current cost of the item (from CLCD) into the return sub.
1852 --
1853   l_stmt_num := 150;
1854 
1855      delete from mtl_cst_actual_cost_details
1856       where transaction_id = i_txn_id
1857         and layer_id = l_from_layer;
1858 
1859   l_stmt_num := 160;
1860      insert into mtl_cst_actual_cost_details(
1861         transaction_id,
1862         organization_id,
1863         layer_id,
1864         cost_element_id,
1865         level_type,
1866         transaction_action_id,
1867         last_update_date,
1868         last_updated_by,
1869         creation_date,
1870         created_by,
1871         last_update_login,
1872         request_id,
1873         program_application_id,
1874         program_id,
1875         program_update_date,
1876         inventory_item_id,
1877         actual_cost,
1878         prior_cost,
1879         new_cost,
1880         insertion_flag,
1881         variance_amount,
1882         user_entered)
1883       select
1884         i_txn_id,
1885         i_org_id,
1886         l_from_layer,
1887         clcd.cost_element_id,
1888         clcd.level_type,
1889         i_txn_action_id,
1890         sysdate,
1891         i_user_id,
1892         sysdate,
1893         i_user_id,
1894         i_login_id,
1895         i_req_id,
1896         i_prg_appl_id,
1897         i_prg_id,
1898         sysdate,
1899         i_item_id,
1900         clcd.item_cost,
1901         clcd.item_cost,
1902         clcd.item_cost,
1903         'N',
1904         0,
1905         'N'
1906       from cst_layer_cost_details clcd
1907       where layer_id = l_from_layer;
1908 
1909 -- bug 925262, need to update the layer quantity of the payback side
1910 
1911     CSTPAVCP.current_average_cost(
1912                                 i_org_id,
1913                                 i_txn_id,
1914                                 l_from_layer,
1915                                 i_cost_type,
1916                                 i_item_id,
1917                                 l_from_qty,
1918                                 i_txn_action_id,
1919                                 0,
1920                                 0,
1921                                 0,
1922                                 i_user_id,
1923                                 i_login_id,
1924                                 i_req_id,
1925                                 i_prg_appl_id,
1926                                 i_prg_id,
1927                                 l_err_num,
1928                                 l_err_code,
1929                                 l_err_msg);
1930 
1931 -- if it is payback transaction, and hook is used then
1932   elsif ((l_txn_type_id = 68) and (i_hook = 1) and (l_layer_chg = 1)) then
1933 -- if hook is used, need to update the TO SUB's MCACD with the borrow cost
1934 
1935             borrow_cost(i_org_id,
1936                         i_txn_id,
1937                         i_user_id,
1938                         i_login_id,
1939                         i_req_id,
1940                         i_prg_appl_id,
1941                         i_prg_id,
1942                         i_item_id,
1943                         1, -- hook is used
1944                         l_to_layer,
1945                         l_err_num,
1946                         l_err_code,
1947                         l_err_msg);
1948             if (l_err_num <> 0) then
1949             -- Error occured
1950                raise process_error;
1951             end if;
1952 
1953 -- since hook is introduced so we need to
1954 -- reaverage the from sub and then figure out the variance
1955 
1956     -- update new cost and then find variance
1957     -- base on new cost
1958     CSTPAVCP.calc_average_cost(
1959                                 i_org_id,
1960                                 i_txn_id,
1961                                 l_from_layer,
1962                                 i_cost_type,
1963                                 i_item_id,
1964                                 l_from_qty,
1965                                 i_txn_action_id,
1966                                 0,
1967                                 i_user_id,
1968                                 i_login_id,
1969                                 i_req_id,
1970                                 i_prg_appl_id,
1971                                 i_prg_id,
1972                                 l_err_num,
1973                                 l_err_code,
1974                                 l_err_msg);
1975     if (l_err_num <> 0) then
1976       -- Error occured
1977       raise process_error;
1978     end if;
1979   end if;  -- end borrow payback
1980 
1981 -- if it is a borrow payback transaction with layer change
1982 -- we need to store the variance in MCACD by calling
1983 -- store_bp_variance, also we need to calculate the
1984 -- new average cost for the to sub.
1985   if (l_txn_type_id = 68) and ( l_layer_chg = 1)then
1986     store_bp_variance(i_txn_id,
1987                       l_from_layer,
1988                       l_to_layer,
1989                       l_err_num,
1990                       l_err_code,
1991                       l_err_msg);
1992     if (l_err_num <> 0) then
1993       -- Error occured
1994       raise process_error;
1995     end if;
1996 
1997 
1998     CSTPAVCP.calc_average_cost(
1999                                 i_org_id,
2000                                 i_txn_id,
2001                                 l_to_layer,
2002                                 i_cost_type,
2003                                 i_item_id,
2004                                 -1 * l_from_qty,
2005                                 i_txn_action_id,
2006                                 0,
2007                                 i_user_id,
2008                                 i_login_id,
2009                                 i_req_id,
2010                                 i_prg_appl_id,
2011                                 i_prg_id,
2012                                 l_err_num,
2013                                 l_err_code,
2014                                 l_err_msg);
2015     if (l_err_num <> 0) then
2016       -- Error occured
2017       raise process_error;
2018     end if;
2019 
2020   end if;
2021 -- borrow payback end
2022 
2023 --Borrow Payback Enhancements Bug 2665290
2024 if (l_txn_type_id = 68 and l_layer_chg = 0) then
2025 
2026    payback_variance(
2027        i_org_id,
2028        i_txn_id,
2029        l_from_layer,
2030        i_user_id,
2031        i_login_id,
2032        i_req_id,
2033        i_prg_appl_id,
2034        i_prg_id,
2035        l_err_num,
2036        l_err_code,
2037        l_err_msg);
2038 
2039       if (l_err_num <> 0) then
2040       -- Error occured
2041       raise process_error;
2042     end if;
2043 
2044 end if;
2045 
2046 --Borrow Payback Enhancements
2047 
2048   if ((l_layer_chg = 1) or (l_from_exp <> l_to_exp)) then
2049     l_no_update_qty := 0;
2050   else
2051     l_no_update_qty := 1;
2052   end if;
2053 
2054   l_stmt_num := 180;
2055 
2056   /* Populate the cost columns in MMT for the receiving transactions */
2057   IF i_txn_action_id IN (2,5,28,55)
2058   THEN
2059     IF g_debug = 'Y'
2060     THEN
2061          fnd_file.put_line(fnd_file.log,'Update mmt for receiving side');
2062     END IF;
2063 
2064     l_stmt_num := 190;
2065     SELECT transfer_transaction_id
2066     INTO   l_txf_txn_id
2067     FROM   mtl_material_transactions
2068     WHERE  transaction_id = i_txn_id;
2069 
2070     l_stmt_num := 200;
2071     UPDATE mtl_material_transactions MMT
2072     SET    (
2073              last_update_date,
2074              last_updated_by,
2075              last_update_login,
2076              request_id,
2077              program_application_id,
2078              program_id,
2079              program_update_date,
2080              actual_cost,
2081              prior_cost,
2082              new_cost,
2083              variance_amount
2084            )
2085     =      (
2086              SELECT SYSDATE,
2087                     i_user_id,
2088                     i_login_id,
2089                     i_req_id,
2090                     i_prg_appl_id,
2091                     i_prg_id,
2092                     SYSDATE,
2093                     SUM(NVL(MCACD.actual_cost,0)),
2094                     SUM(NVL(MCACD.prior_cost,0)),
2095                     SUM(NVL(MCACD.new_cost,0)),
2096                     SUM(NVL(MCACD.variance_amount,0))
2097              FROM   mtl_cst_actual_cost_details MCACD
2098              WHERE  MCACD.transaction_id = i_txn_id
2099              AND    MCACD.layer_id = l_to_layer
2100            )
2101     WHERE  MMT.transaction_id = l_txf_txn_id
2102     AND    MMT.primary_quantity > 0;
2103   END IF;
2104   IF g_debug = 'Y' THEN
2105     fnd_file.put_line(fnd_file.log, 'Sub_Transfer >>>');
2106   END IF;
2107 
2108   EXCEPTION
2109     when process_error then
2110       o_err_num := l_err_num;
2111       o_err_code := l_err_code;
2112       o_err_msg := l_err_msg;
2113     when others then
2114       rollback;
2115       o_err_num := SQLCODE;
2116       o_err_msg := 'CSTPAVCP.sub_transfer (' || to_char(l_stmt_num) ||
2117                    '): '
2118                    || substr(SQLERRM, 1,200);
2119 END sub_transfer;
2120 
2121 
2122 -- PROCEDURE
2123 --  common_issue_to_wip         Cost process the common issue to wip
2124 --                              transaction.
2125 
2126 procedure common_issue_to_wip(
2127   I_ORG_ID              IN NUMBER,
2128   I_TXN_ID              IN NUMBER,
2129   I_LAYER_ID            IN NUMBER,
2130   I_COST_TYPE           IN NUMBER,
2131   I_ITEM_ID             IN NUMBER,
2132   I_TXN_QTY             IN NUMBER,
2133   I_TXN_ACTION_ID       IN NUMBER,
2134   I_NEW_COST            IN NUMBER,
2135   I_TXFR_LAYER_ID       IN NUMBER,
2136   I_COST_METHOD         IN NUMBER,
2137   I_AVG_RATES_ID        IN NUMBER,
2138   I_COST_GRP_ID         IN NUMBER,
2139   I_TXFR_COST_GRP       IN NUMBER,
2140   I_EXP_FLAG            IN NUMBER,
2141   I_EXP_ITEM            IN NUMBER,
2142   I_CITW_FLAG           IN NUMBER,
2143   I_FLOW_SCHEDULE       IN NUMBER,
2144   I_USER_ID             IN NUMBER,
2145   I_LOGIN_ID            IN NUMBER,
2146   I_REQ_ID              IN NUMBER,
2147   I_PRG_APPL_ID         IN NUMBER,
2148   I_PRG_ID              IN NUMBER,
2149   O_Err_Num             OUT NOCOPY NUMBER,
2150   O_Err_Code            OUT NOCOPY VARCHAR2,
2151   O_Err_Msg             OUT NOCOPY VARCHAR2
2152 ) IS
2153   l_txn_qty             NUMBER;
2154   l_new_cost            NUMBER;
2155   l_exp_flag            NUMBER;
2156   l_err_num             NUMBER;
2157   l_err_code            VARCHAR2(240);
2158   l_err_msg             VARCHAR2(240);
2159   l_stmt_num            NUMBER;
2160   /* Added Bug#4259926 */
2161   l_txn_action_id       NUMBER;
2162   l_src_type            NUMBER;
2163   l_layer_id            NUMBER;
2164   process_error         EXCEPTION;
2165 BEGIN
2166   -- initialize local variables
2167   l_err_num := 0;
2168   l_err_code := '';
2169   l_err_msg := '';
2170 
2171   l_txn_qty := i_txn_qty;
2172 
2173   IF g_debug = 'Y' THEN
2174     fnd_file.put_line(fnd_file.log, 'Common_Issue_To_WIP <<<');
2175   END IF;
2176 
2177   -- No user entered new cost is allowed for common issue to wip
2178   l_new_cost := 0;
2179 
2180   l_stmt_num := 5;
2181   /* Added Bug#4259926 */
2182   select transaction_action_id, transaction_source_type_id
2183   into l_txn_action_id,l_src_type
2184   from mtl_material_transactions
2185   where transaction_id = i_txn_id;
2186 
2187   if ( l_txn_action_id = 27 and  I_CITW_FLAG = 1 and l_src_type = 5 ) then
2188        l_layer_id := i_txfr_layer_id;
2189   else
2190   l_layer_id := i_layer_id;
2191   end if;
2192 
2193 -- item cost history, update the transfer_prior_costed_quantity
2194 -- is necessary because we need both the from and the to information
2195 -- in item cost history
2196         UPDATE mtl_material_transactions mmt
2197         SET TRANSFER_PRIOR_COSTED_QUANTITY =
2198         (SELECT
2199                 layer_quantity
2200         FROM        cst_quantity_layers cql
2201         WHERE        cql.layer_id = i_txfr_layer_id)   /* Modified for bug 6635134 */
2202         WHERE mmt.transaction_id = i_txn_id
2203         AND EXISTS (
2204                         SELECT 'X'
2205                         FROM cst_quantity_layers cql
2206                         WHERE cql.layer_id = i_txfr_layer_id);  /* Modified for bug 6635134 */
2207 
2208 -- item cost history
2209   l_stmt_num := 10;
2210 
2211   -- We break down common issue to WIP transaction into two parts.
2212   --   1. common to project sub
2213   --      treat it as a subinventory transfer
2214   --   2. project sub to project job issue
2215   --      insert a separate row in MCACD and call wip cost processor
2216   --      and distribution processor
2217 
2218 /* Added Bug#4259926
2219   if ( l_txn_action_id = 27 and  I_CITW_FLAG = 1 and l_src_type = 5 ) then  */
2220 
2221   /* Modified for bug 6635134 - Moved the insert into MCACD outside the if-else clause */
2222  if l_txn_action_id = 1 then
2223 
2224             CSTPAVCP.sub_transfer(
2225                            i_org_id,
2226                            i_txn_id,
2227                            i_layer_id,
2228                            i_cost_type,
2229                            i_item_id,
2230                            l_txn_qty,
2231                            i_txn_action_id,
2232                            l_new_cost,
2233                            NULL,
2234                            i_txfr_layer_id,
2235                            i_citw_flag,
2236                            i_flow_schedule,
2237                            i_user_id,
2238                            i_login_id,
2239                            i_req_id,
2240                            i_prg_appl_id,
2241                            i_prg_id,
2242                            l_err_num,
2243                            l_err_code,
2244                            l_err_msg);
2245 
2246         /*  Bug# 6635134
2247 	if (l_err_num <> 0) then
2248              raise process_error;
2249           end if;
2250 
2251            insert into mtl_cst_actual_cost_details(
2252            transaction_id,
2253            organization_id,
2254            layer_id,
2255            cost_element_id,
2256            level_type,
2257            transaction_action_id,
2258            last_update_date,
2259            last_updated_by,
2260            creation_date,
2261            created_by,
2262            last_update_login,
2263            request_id,
2264            program_application_id,
2265            program_id,
2266            program_update_date,
2267            inventory_item_id,
2268            actual_cost,
2269            prior_cost,
2270            new_cost,
2271            insertion_flag,
2272            variance_amount,
2273            user_entered)
2274            select
2275                    i_txn_id,
2276                    i_org_id,
2277                    i_txfr_layer_id,
2278                    cacd.cost_element_id,
2279                    cacd.level_type,
2280                    27,
2281                    sysdate,
2282                    i_user_id,
2283                    sysdate,
2284                    i_user_id,
2285                    i_login_id,
2286                    i_req_id,
2287                    i_prg_appl_id,
2288                    i_prg_id,
2289                    sysdate,
2290                    i_item_id,
2291                    cacd.new_cost,
2292                    cacd.new_cost,
2293                    cacd.new_cost,
2294                    'N',                        -- check
2295                    0,
2296                    'N'
2297            from mtl_cst_actual_cost_details cacd
2298            where transaction_id = i_txn_id
2299            and organization_id = i_org_id
2300            and layer_id = i_txfr_layer_id
2301            and transaction_action_id = i_txn_action_id; */
2302   else
2303 
2304      CSTPAVCP.sub_transfer(
2305                         i_org_id,
2306                         i_txn_id,
2307                         i_txfr_layer_id,
2308                         i_cost_type,
2309                         i_item_id,
2310                         l_txn_qty,
2311                         i_txn_action_id,
2312                         l_new_cost,
2313                         NULL,
2314                         i_layer_id,
2315                         i_citw_flag,
2316                         i_flow_schedule,
2317                         i_user_id,
2318                         i_login_id,
2319                         i_req_id,
2320                         i_prg_appl_id,
2321                         i_prg_id,
2322                         l_err_num,
2323                         l_err_code,
2324                         l_err_msg);
2325 
2326   end if;
2327 
2328      if (l_err_num <> 0) then
2329      raise process_error;
2330      end if;
2331 
2332      l_stmt_num := 20;
2333 
2334      -- insert a row in MCACD for WIP issue / return transaction
2335      insert into mtl_cst_actual_cost_details(
2336            transaction_id,
2337            organization_id,
2338            layer_id,
2339            cost_element_id,
2340            level_type,
2341            transaction_action_id,
2342            last_update_date,
2343            last_updated_by,
2344            creation_date,
2345            created_by,
2346            last_update_login,
2347            request_id,
2348            program_application_id,
2349            program_id,
2350            program_update_date,
2351            inventory_item_id,
2352            actual_cost,
2353            prior_cost,
2354            new_cost,
2355            insertion_flag,
2356            variance_amount,
2357            user_entered)
2358      select
2359            i_txn_id,
2360            i_org_id,
2361            i_txfr_layer_id,
2362            cacd.cost_element_id,
2363            cacd.level_type,
2364            l_txn_action_id,
2365            sysdate,
2366            i_user_id,
2367            sysdate,
2368            i_user_id,
2369            i_login_id,
2370            i_req_id,
2371            i_prg_appl_id,
2372            i_prg_id,
2373            sysdate,
2374            i_item_id,
2375            cacd.new_cost,
2376            cacd.new_cost,
2377            cacd.new_cost,
2378            'N',                        -- check
2379            0,
2380            'N'
2381      from mtl_cst_actual_cost_details cacd
2382      where transaction_id = i_txn_id
2383        and organization_id = i_org_id
2384        and layer_id = i_txfr_layer_id
2385        and transaction_action_id = i_txn_action_id;
2386   -- end if;
2387 
2388   l_stmt_num := 30;
2389 
2390   -- figure out project sub asset type, it depends on project job type and
2391   -- from subinventory asset type.
2392   if (i_flow_schedule = 1) then
2393     l_stmt_num := 33;
2394     select decode(wac.class_type, 1, 0,
2395                                   3, 0,
2396                                   6, 0,
2397                                   4, decode(i_exp_flag, 1, 1, 0))
2398     into   l_exp_flag
2399     from   mtl_material_transactions mmt,
2400            wip_flow_schedules wfs,
2401            wip_accounting_classes wac
2402     where  mmt.transaction_id = i_txn_id
2403     and    mmt.organization_id = i_org_id
2404     and    wfs.organization_id = i_org_id
2405     and    wfs.wip_entity_id = mmt.transaction_source_id
2406     and    wac.organization_id = i_org_id
2407     and    wac.class_code = wfs.class_code;
2408   else
2409     l_stmt_num := 37;
2410     select decode(wac.class_type, 1, 0,
2411                                   3, 0,
2412                                   6, 0,
2413                                   4, decode(i_exp_flag, 1, 1, 0))
2414     into   l_exp_flag
2415     from   mtl_material_transactions mmt,
2416            wip_discrete_jobs wdj,
2417            wip_accounting_classes wac
2418     where  mmt.transaction_id = i_txn_id
2419     and    mmt.organization_id = i_org_id
2420     and    wdj.organization_id = i_org_id
2421     and    wdj.wip_entity_id = mmt.transaction_source_id
2422     and    wac.organization_id = i_org_id
2423     and    wac.class_code = wdj.class_code;
2424   end if;
2425 
2426   l_stmt_num := 40;
2427 
2428   -- Process WIP issue transaction
2429  /* Added Bug#4259926 */
2430 if l_txn_action_id = 27 then
2431       NULL; /* Bug# 6635134  If return txn, then there is no cost impact on proj cg,
2432                        so we can avoid all the database hits involved in incrementing and
2433 		       decrementing the quantity for this cg */
2434 
2435  else
2436 
2437   CSTPAVCP.current_average_cost(i_org_id,
2438                                 i_txn_id,
2439                                 i_txfr_layer_id,
2440                                 i_cost_type,
2441                                 i_item_id,
2442                                 l_txn_qty,
2443                                 1,                -- wip issue txn
2444                                 l_exp_flag,
2445                                 /* Bug 9758017: For CITW, MMT should not be updated for the tfr CG */
2446 				1,
2447                                 0,
2448                                 i_user_id,
2449                                 i_login_id,
2450                                 i_req_id,
2451                                 i_prg_appl_id,
2452                                 i_prg_id,
2453                                 l_err_num,
2454                                 l_err_code,
2455                                 l_err_msg);
2456     if (l_err_num <> 0) then
2457       -- Error occured
2458     raise process_error;
2459     end if;
2460  end if;
2461 
2462   l_stmt_num := 50;
2463 
2464   CSTPACWP.cost_wip_trx(i_txn_id,
2465                         i_citw_flag,
2466                         i_cost_type,
2467                         i_cost_method,
2468                         i_avg_rates_id,
2469                         i_cost_grp_id,
2470                         i_txfr_cost_grp,
2471                         l_exp_flag,
2472                         i_exp_item,
2473                         i_flow_schedule,
2474                         i_user_id,
2475                         i_login_id,
2476                         i_req_id,
2477                         i_prg_id,
2478                         i_prg_appl_id,
2479                         l_err_num,
2480                         l_err_code,
2481                         l_err_msg);
2482 
2483 
2484   if (l_err_num <> 0) then
2485     raise process_error;
2486   end if;
2487   IF g_debug = 'Y' THEN
2488     fnd_file.put_line(fnd_file.log, 'Common_Issue_To_WIP >>>');
2489   END IF;
2490 
2491   EXCEPTION
2492     when process_error then
2493       o_err_num := l_err_num;
2494       o_err_code := l_err_code;
2495       o_err_msg := l_err_msg;
2496     when others then
2497       rollback;
2498       o_err_num := SQLCODE;
2499       o_err_msg := 'CSTPAVCP.common_issue_to_wip (' || to_char(l_stmt_num) ||
2500                    '): '
2501                    || substr(SQLERRM, 1,200);
2502 END common_issue_to_wip;
2503 
2504 
2505 
2506 
2507 
2508 -- FUNCTION
2509 --  compute_actual_cost         Populate the actual cost details table
2510 --
2511 -- RETURN VALUES
2512 --  integer             1        The actual cost is different from the
2513 --                              current average cost.
2514 --                      0        The actual cost is the same as the current
2515 --                              average cost.
2516 
2517 function compute_actual_cost(
2518   I_ORG_ID      IN        NUMBER,
2519   I_TXN_ID      IN         NUMBER,
2520   I_LAYER_ID    IN        NUMBER,
2521   I_COST_TYPE   IN        NUMBER,
2522   I_MAT_CT_ID   IN        NUMBER,
2523   I_AVG_RATES_ID IN     NUMBER,
2524   I_ITEM_ID     IN        NUMBER,
2525   I_TXN_QTY     IN        NUMBER,
2526   I_TXN_ACTION_ID IN    NUMBER,
2527   I_TXN_SRC_TYPE IN     NUMBER,
2528   I_INTERORG_REC IN     NUMBER,
2529   I_EXP_FLAG    IN        NUMBER,
2530   I_USER_ID     IN        NUMBER,
2531   I_LOGIN_ID    IN      NUMBER,
2532   I_REQ_ID      IN        NUMBER,
2533   I_PRG_APPL_ID IN        NUMBER,
2534   I_PRG_ID      IN         NUMBER,
2535   O_Err_Num     OUT NOCOPY        NUMBER,
2536   O_Err_Code    OUT NOCOPY        VARCHAR2,
2537   O_Err_Msg     OUT NOCOPY        VARCHAR2
2538 )
2539 return integer IS
2540   l_txn_cost_exist      NUMBER;
2541   l_cost_details        NUMBER;
2542   l_act_cost            NUMBER;
2543   l_cur_cost            NUMBER;
2544   l_qty                 NUMBER;
2545   l_level               NUMBER;
2546   l_ret_val             NUMBER;
2547   l_err_num             NUMBER;
2548   l_err_code            VARCHAR2(240);
2549   l_err_msg             VARCHAR2(240);
2550   l_stmt_num            NUMBER;
2551   l_count               NUMBER;
2552   process_error         EXCEPTION;
2553 
2554   /* EAM Acct Enh Project */
2555   l_zero_cost_flag      NUMBER;
2556   l_return_status       VARCHAR2(1);
2557   l_msg_count           NUMBER;
2558   l_msg_data            VARCHAR2(8000);
2559   l_api_message         VARCHAR2(8000);
2560 
2561 BEGIN
2562   -- initialize local variables
2563   l_err_num := 0;
2564   l_err_code := '';
2565   l_err_msg := '';
2566   l_txn_cost_exist := 0;
2567   l_cost_details := 0;
2568 
2569   l_msg_data := NULL;
2570   l_msg_count := 0;
2571 
2572   l_return_status := fnd_api.g_ret_sts_success;
2573 
2574   l_zero_cost_flag := -1;
2575 
2576   IF g_debug = 'Y' THEN
2577     fnd_file.put_line(fnd_file.log, '>>>Inside Compute_Actual_Cost');
2578   END IF;
2579   l_stmt_num := 10;
2580 
2581   --
2582   -- Make sure the transaction cost is positive
2583   --
2584 
2585   Select count(*)
2586   into l_txn_cost_exist
2587   from mtl_cst_txn_cost_details
2588   where transaction_id = i_txn_id
2589   and organization_id = i_org_id
2590   /* and transaction_cost >= 0 */; -- modified for bug#3835412
2591 
2592     if (g_debug = 'Y') then
2593          fnd_file.put_line(fnd_file.log,'>>>MCTCD: '||to_char(l_txn_cost_exist)||' i_txn_id: '||to_char(i_txn_id)||' i_org_id:'||to_char(i_org_id));
2594     end if;
2595 
2596   if (l_txn_cost_exist > 0) then
2597 
2598     l_ret_val := 1;
2599     l_stmt_num := 20;
2600     if (g_debug = 'Y') then
2601          fnd_file.put_line(fnd_file.log,'>>>Insert into MCACD using MCTCD values');
2602     end if;
2603 
2604     --
2605     -- Make sure the mcacd should not have any -ve cost
2606     --
2607 
2608     insert into mtl_cst_actual_cost_details (
2609         transaction_id,
2610         organization_id,
2611         layer_id,
2612         cost_element_id,
2613         level_type,
2614         transaction_action_id,
2615         last_update_date,
2616         last_updated_by,
2617         creation_date,
2618         created_by,
2619         last_update_login,
2620         request_id,
2621         program_application_id,
2622         program_id,
2623         program_update_date,
2624         inventory_item_id,
2625         actual_cost,
2626         prior_cost,
2627         new_cost,
2628         insertion_flag,
2629         variance_amount,
2630         user_entered)
2631     select
2632         i_txn_id,
2633         i_org_id,
2634         i_layer_id,
2635         ctcd.cost_element_id,
2636         ctcd.level_type,
2637         i_txn_action_id,
2638         sysdate,
2639         i_user_id,
2640         sysdate,
2641         i_user_id,
2642         i_login_id,
2643         i_req_id,
2644         i_prg_appl_id,
2645         i_prg_id,
2646         sysdate,
2647         ctcd.inventory_item_id,
2648         ctcd.transaction_cost,
2649         0,
2650         NULL,
2651         'Y',
2652         0,
2653         'N'
2654     FROM mtl_cst_txn_cost_details ctcd
2655     WHERE ctcd.transaction_id = i_txn_id
2656     AND ctcd.organization_id = i_org_id
2657     /* AND ctcd.transaction_cost >= 0 */; -- modified for bug#3835412
2658 
2659 if (g_debug = 'Y') then
2660     select count(*) into l_count
2661     from mtl_cst_actual_cost_details
2662     where transaction_id = i_txn_id
2663     and organization_id = i_org_id;
2664          fnd_file.put_line(fnd_file.log,'>>>MCACD: '||to_char(l_count)||' i_txn_id: '||to_char(i_txn_id)||' i_org_id:'||to_char(i_org_id));
2665 end if;
2666 
2667   else
2668     /* no transaction cost details. copy actual cost from current avg. *
2669      * for scrap transactions, no transaction cost means 0 cost.       */
2670 
2671     l_ret_val := 0;
2672     /********************************************************************
2673      ** Create detail rows in MTL_CST_ACTUAL_COST_DETAILS based on     **
2674      ** records in CST_LAYER_COST_DETAILS.  Since we are using current **
2675      ** average the actual cost, prior cost and new cost are all the   **
2676      ** same.  If detail rows do not exist in CST_LAYER_COST_DETAILS,  **
2677      ** we will insert a TL material 0 cost layer.                     **
2678      ********************************************************************/
2679     if (g_debug = 'Y') then
2680          fnd_file.put_line(fnd_file.log,'>>>No Txn details in MCTCD');
2681     end if;
2682 
2683     l_stmt_num := 30;
2684 
2685     select count(*)
2686     into l_cost_details
2687     from cst_layer_cost_details
2688     where layer_id = i_layer_id;
2689 
2690     if ((l_cost_details > 0) and (i_txn_action_id <> 30)) then
2691 
2692       l_stmt_num := 35;
2693       /* EAM Acct Enh Project */
2694       CST_Utility_PUB.get_zeroCostIssue_flag (
2695         p_api_version                =>        1.0,
2696         x_return_status        =>        l_return_status,
2697         x_msg_count                =>        l_msg_count,
2698         x_msg_data                =>        l_msg_data,
2699         p_txn_id                =>        i_txn_id,
2700         x_zero_cost_flag        =>        l_zero_cost_flag
2701         );
2702 
2703       if (l_return_status <> fnd_api.g_ret_sts_success) then
2704         FND_FILE.put_line(FND_FILE.log, l_msg_data);
2705         l_api_message := 'get_zeroCostIssue_flag returned unexpected error';
2706         FND_MESSAGE.set_name('BOM','CST_API_MESSAGE');
2707         FND_MESSAGE.set_token('TEXT', l_api_message);
2708         FND_MSG_pub.add;
2709         raise fnd_api.g_exc_unexpected_error;
2710       end if;
2711 
2712       if (g_debug = 'Y') then
2713         FND_FILE.PUT_LINE(FND_FILE.LOG,'>>>Zero Cost Issue Flag:'|| to_char(l_zero_cost_flag));
2714       end if;
2715 
2716       l_stmt_num := 40;
2717       insert into mtl_cst_actual_cost_details(
2718         transaction_id,
2719         organization_id,
2720         layer_id,
2721         cost_element_id,
2722         level_type,
2723         transaction_action_id,
2724         last_update_date,
2725         last_updated_by,
2726         creation_date,
2727         created_by,
2728         last_update_login,
2729         request_id,
2730         program_application_id,
2731         program_id,
2732         program_update_date,
2733         inventory_item_id,
2734         actual_cost,
2735         prior_cost,
2736         new_cost,
2737         insertion_flag,
2738         variance_amount,
2739         user_entered)
2740       select
2741         i_txn_id,
2742         i_org_id,
2743         i_layer_id,
2744         clcd.cost_element_id,
2745         clcd.level_type,
2746         i_txn_action_id,
2747         sysdate,
2748         i_user_id,
2749         sysdate,
2750         i_user_id,
2751         i_login_id,
2752         i_req_id,
2753         i_prg_appl_id,
2754         i_prg_id,
2755         sysdate,
2756         i_item_id,
2757         decode(l_zero_cost_flag, 1, 0, clcd.item_cost),
2758         clcd.item_cost,
2759         clcd.item_cost,
2760         'N',
2761         0,
2762         'N'
2763       from cst_layer_cost_details clcd
2764       where layer_id = i_layer_id;
2765     else
2766       l_stmt_num := 50;
2767       if (g_debug = 'Y') then
2768            fnd_file.put_line(fnd_file.log,'>>>No cost values, Inserting zero cost in MCACD');
2769       end if;
2770 
2771       insert into mtl_cst_actual_cost_details(
2772         transaction_id,
2773         organization_id,
2774         layer_id,
2775         cost_element_id,
2776         level_type,
2777         transaction_action_id,
2778         last_update_date,
2779         last_updated_by,
2780         creation_date,
2781         created_by,
2782         last_update_login,
2783         request_id,
2784         program_application_id,
2785         program_id,
2786         program_update_date,
2787         inventory_item_id,
2788         actual_cost,
2789         prior_cost,
2790         new_cost,
2791         insertion_flag,
2792         variance_amount,
2793         user_entered)
2794       values(
2795         i_txn_id,
2796         i_org_id,
2797         i_layer_id,
2798         1,
2799         1,
2800         i_txn_action_id,
2801         sysdate,
2802         i_user_id,
2803         sysdate,
2804         i_user_id,
2805         i_login_id,
2806         i_req_id,
2807         i_prg_appl_id,
2808         i_prg_id,
2809         sysdate,
2810         i_item_id,
2811         0,
2812         NULL,
2813         0,
2814         'N',
2815         0,
2816         'N');
2817     end if;
2818    end if;
2819 
2820   /* Apply material overhead to certain txns which are asset item and
2821      asset subinventory. */
2822   if ((i_exp_flag <> 1)
2823       AND
2824       ((i_txn_action_id = 27 and i_txn_src_type = 1) /* PO receipt */
2825       OR
2826        (i_txn_action_id = 6 and (i_txn_src_type =13 or i_txn_src_type = 1)) /*Change of ownership */
2827       OR
2828       (i_txn_action_id = 1 and i_txn_src_type = 1) /* RTV */
2829       OR
2830       (i_txn_action_id = 29 and i_txn_src_type = 1) /* Delivery Adj. */
2831       OR
2832       (i_txn_action_id = 31 and i_txn_src_type = 5)
2833         /* WIP completions */
2834       OR
2835       (i_txn_action_id = 32 and i_txn_src_type = 5) /* Assembly return */
2836       OR
2837       (i_interorg_rec = 1)
2838      )) then
2839     l_level := 1;
2840 
2841 
2842     apply_material_ovhd(i_org_id,
2843                         i_txn_id,
2844                         i_layer_id,
2845                         i_cost_type,
2846                         i_mat_ct_id,
2847                         i_avg_rates_id,
2848                         i_item_id,
2849                         i_txn_qty,
2850                         i_txn_action_id,
2851                         l_level,
2852                         i_user_id,
2853                         i_login_id,
2854                         i_req_id,
2855                         i_prg_appl_id,
2856                         i_prg_id,
2857                         l_err_num,
2858                         l_err_code,
2859                         l_err_msg);
2860 
2861     if (l_err_num <> 0) then
2862       -- Error occured
2863       raise process_error;
2864     end if;
2865     l_ret_val := 1;
2866   end if;
2867 
2868 /*  IF g_debug = 'Y' THEN
2869     fnd_file.put_line(fnd_file.log, 'Compute_Actual_Cost >>>');
2870   END IF;*/
2871   return l_ret_val;
2872 
2873   EXCEPTION
2874     when process_error then
2875       o_err_num := l_err_num;
2876       o_err_code := l_err_code;
2877       o_err_msg := l_err_msg;
2878       return l_ret_val;
2879     when OTHERS then
2880       rollback;
2881       o_err_num := SQLCODE;
2882       o_err_msg := 'CSTPAVCP.compute_actual_cost (' || to_char(l_stmt_num) ||
2883                    '): '
2884                    || substr(SQLERRM,1,200);
2885       return l_ret_val;
2886 END compute_actual_cost;
2887 
2888 
2889 -- PROCEDURE
2890 --  apply_material_ovhd         Applying this level material overhead based
2891 --                              on the pre-defined rates in the material
2892 --
2893 
2894 procedure apply_material_ovhd(
2895   I_ORG_ID      IN        NUMBER,
2896   I_TXN_ID      IN         NUMBER,
2897   I_LAYER_ID    IN        NUMBER,
2898   I_COST_TYPE   IN        NUMBER,
2899   I_MAT_CT_ID   IN        NUMBER,
2900   I_AVG_RATES_ID IN     NUMBER,
2901   I_ITEM_ID     IN        NUMBER,
2902   I_TXN_QTY     IN        NUMBER,
2903   I_TXN_ACTION_ID IN    NUMBER,
2904   I_LEVEL       IN        NUMBER,
2905   I_USER_ID     IN        NUMBER,
2906   I_LOGIN_ID    IN        NUMBER,
2907   I_REQ_ID      IN        NUMBER,
2908   I_PRG_APPL_ID IN        NUMBER,
2909   I_PRG_ID      IN        NUMBER,
2910   O_Err_Num     OUT NOCOPY        NUMBER,
2911   O_Err_Code    OUT NOCOPY        VARCHAR2,
2912   O_Err_Msg     OUT NOCOPY        VARCHAR2
2913 ) IS
2914   l_mat_ovhds   NUMBER;
2915   l_item_cost   NUMBER;
2916   l_res_id      NUMBER;
2917   l_err_num             NUMBER;
2918   l_err_code            VARCHAR2(240);
2919   l_err_msg             VARCHAR2(240);
2920   l_stmt_num            NUMBER;
2921   overhead_error        EXCEPTION;
2922   avg_rates_no_ovhd     EXCEPTION;
2923   l_mcacd_ovhd  NUMBER;
2924   l_ovhd_cost   NUMBER;
2925   l_elemental_visible varchar2(1);
2926   l_from_org    NUMBER;
2927   l_to_org      NUMBER;
2928   l_txn_org_id      NUMBER;
2929   l_txfr_org_id NUMBER;
2930   l_txn_qty     NUMBER;
2931 
2932   l_earn_moh    NUMBER;
2933   l_return_status VARCHAR2(1);
2934   l_msg_count NUMBER;
2935   l_msg_data VARCHAR2(240);
2936   moh_rules_error EXCEPTION;
2937   l_default_MOH_subelement NUMBER; ---------------Bug 3959770
2938 
2939 BEGIN
2940   -- initialize local variables
2941   l_err_num := 0;
2942   l_err_code := '';
2943   l_err_msg := '';
2944 
2945 /* Added for bug 3959770*/
2946 /* Get the Default MOH sub element of the organization*/
2947 
2948  select DEFAULT_MATL_OVHD_COST_ID
2949  into l_default_MOH_subelement
2950  from mtl_parameters
2951  where organization_id= I_ORG_ID;
2952 
2953   IF g_debug = 'Y' THEN
2954     fnd_file.put_line(fnd_file.log, 'Apply_Material_Overhead <<<');
2955   END IF;
2956   l_earn_moh := 1;
2957   l_return_status := fnd_api.g_ret_sts_success;
2958   l_msg_count := 0;
2959 
2960   -- Applying material overhead on the sum(actual_cost) in CACD.  There should
2961   -- not be any material overhead rows! This check will need to be
2962   -- removed once we support freight and duty charges at PO receipt.  But right
2963   -- now if this transaction had this level materail overhead, I don't have
2964   -- subelement detail so must error out!
2965   -- When i_level is 1 this level material overhead only. 0 mean both
2966   -- previous and this level material.
2967   -- In the current implementation, the i_level will always be 1, meaning
2968   -- absorb only this level material overhead.
2969 
2970   l_stmt_num := 10;
2971 /* Changes for MOH Absorption Rules engine */
2972    cst_mohRules_pub.apply_moh(
2973                               1.0,
2974                               p_organization_id => i_org_id,
2975                               p_earn_moh =>l_earn_moh,
2976                               p_txn_id => i_txn_id,
2977                               p_item_id => i_item_id,
2978                               x_return_status => l_return_status,
2979                               x_msg_count => l_msg_count,
2980                               x_msg_data => l_msg_data);
2981 
2982   IF l_return_status <> FND_API.g_ret_sts_success THEN
2983 
2984          CST_UTILITY_PUB.writelogmessages
2985                           ( p_api_version   => 1.0,
2986                             p_msg_count     => l_msg_count,
2987                             p_msg_data      => l_msg_data,
2988                             x_return_status => l_return_status);
2989          RAISE moh_rules_error;
2990   END IF;
2991 
2992   IF(l_earn_moh = 0) THEN
2993 
2994     IF g_debug = 'Y' THEN
2995       fnd_file.put_line(fnd_file.log, '---Material Overhead Absorption Overridden--');
2996     END IF;
2997 
2998   ELSE
2999 
3000   l_stmt_num := 11;
3001 
3002 
3003   select count(*)
3004   into l_mat_ovhds
3005   from mtl_cst_actual_cost_details cacd
3006   where transaction_id = i_txn_id
3007   and organization_id = i_org_id
3008   and layer_id = i_layer_id
3009   and cost_element_id = 2
3010   and level_type = decode(i_level,1,1,level_type);
3011 
3012   l_stmt_num := 12;
3013 
3014   select organization_id, transfer_organization_id, primary_quantity
3015   into l_txn_org_id, l_txfr_org_id, l_txn_qty
3016   from mtl_material_transactions
3017   where transaction_id = i_txn_id;
3018 
3019   -- Figure the from and to org for this transaction.
3020   if (i_txn_action_id = 21) then
3021      l_from_org := l_txn_org_id;
3022      l_to_org := l_txfr_org_id;
3023   elsif (i_txn_action_id = 12) then
3024      l_from_org := l_txfr_org_id;
3025      l_to_org := l_txn_org_id;
3026   elsif (i_txn_action_id =3 and l_txn_qty <0) then
3027      l_from_org := l_txn_org_id;
3028      l_to_org := l_txfr_org_id;
3029   else
3030      l_from_org := l_txfr_org_id;
3031      l_to_org := l_txn_org_id;
3032   end if;
3033 
3034   l_stmt_num := 14;
3035   -- do elemental visibility check for interorg transfer
3036   if (i_txn_action_id in (12,21,3)) then
3037      select NVL(elemental_visibility_enabled,'N')
3038      into l_elemental_visible
3039      from mtl_interorg_parameters
3040      where from_organization_id = l_from_org
3041      and to_organization_id = l_to_org;
3042   end if;
3043 
3044   -- this condition is added because we added the interorg transfer elemental
3045   -- costs visibility enhancement, for all interorg transactions
3046   -- it is possible that we have data in the material overhead row in MCACD
3047   -- that is why we don't need to check this for direct interorg transfer and intransit
3048   -- transactions.
3049   if not ((i_txn_action_id in (12,21,3)) and (l_elemental_visible = 'Y')) then -- do this check
3050                                                                                -- only if it is not
3051                                                                                -- interorg transaction
3052                                                                                -- with elemental visible
3053                                     -- because for interorg transaction with elemental visible,
3054                                     -- overhead might  already be inserted into MCACD.
3055      if (l_mat_ovhds > 0) then
3056        raise overhead_error;
3057      end if;
3058 
3059   end if;
3060 
3061   if (i_mat_ct_id <> i_cost_type) then /* Not average cost type */
3062 
3063     l_stmt_num := 20;
3064 
3065     select nvl(sum(actual_cost),0)
3066     into l_item_cost
3067     from mtl_cst_actual_cost_details cacd
3068     where transaction_id = i_txn_id
3069     and organization_id = i_org_id
3070     and layer_id = i_layer_id;
3071 
3072 /* Added this check to keep the LIFO/FIFO costing and Average costing in sync.
3073   The check ensures that the resource ID is not null in CICD before inserting into the
3074   MACS. If it is null it replaces the value of resource_id for MOH with the default
3075   value for the same defined in the organization. */
3076 /* Bug 3959770*/
3077 
3078        l_stmt_num := 25;
3079        select count(*)
3080        into l_res_id
3081        from cst_item_cost_details cicd
3082        where inventory_item_id = i_item_id
3083           and organization_id = i_org_id
3084           and cost_type_id = i_mat_ct_Id
3085           and basis_type in (1,2,5,6)
3086           and cost_element_id = 2
3087           and resource_id IS NULL
3088 	  and level_type = decode(i_level,1,1,level_type);
3089 
3090        if (l_res_id > 0) then
3091         if (l_default_MOH_subelement IS NOT NULL) then
3092                        update CST_ITEM_COST_DETAILS
3093                        set resource_id = l_default_MOH_subelement
3094                        where inventory_item_id = i_item_id
3095                 and organization_id = i_org_id
3096                 and cost_type_id = i_mat_ct_Id
3097                 and basis_type in (1,2,5,6)
3098                 and cost_element_id = 2
3099 		and level_type = decode(i_level,1,1,level_type)
3100                 and resource_id IS NULL;
3101         else
3102                 raise avg_rates_no_ovhd;
3103         end if;
3104        end if;
3105 
3106     l_stmt_num := 30;
3107 
3108     Insert into mtl_actual_cost_subelement(
3109         transaction_id,
3110         organization_id,
3111         layer_id,
3112         cost_element_id,
3113         level_type,
3114         resource_id,
3115         last_update_date,
3116         last_updated_by,
3117         creation_date,
3118         created_by,
3119         last_update_login,
3120         request_id,
3121         program_application_id,
3122         program_id,
3123         program_update_date,
3124         actual_cost,
3125         user_entered)
3126     select i_txn_id,
3127          i_org_id,
3128          i_layer_id,
3129          cicd.cost_element_id,
3130          cicd.level_type,
3131          cicd.resource_id,
3132          sysdate,
3133          i_user_id,
3134          sysdate,
3135          i_user_id,
3136          i_login_id,
3137          i_req_id,
3138          i_prg_appl_id,
3139          i_prg_id,
3140          sysdate,
3141          decode(cicd.basis_type, 1, cicd.usage_rate_or_amount,
3142                                        2, cicd.usage_rate_or_amount/abs(i_txn_qty),
3143                                  5, cicd.usage_rate_or_amount * l_item_cost,
3144                                  6, cicd.usage_rate_or_amount * cicd.basis_factor,0),
3145          'N'
3146     from cst_item_cost_details cicd
3147     where inventory_item_id = i_item_id
3148     and organization_id = i_org_id
3149     and cost_type_id = i_mat_ct_Id
3150     and basis_type in (1,2,5,6)
3151     and cost_element_id = 2
3152     and level_type = decode(i_level, 1,1,level_type);
3153 
3154   else /* material overhead cost type is average cost type */
3155     -- In this case we will charge the material overhead in the average
3156     -- cost type using the first material overhead in the average rates
3157     -- cost type.  This function will error out if material overhead
3158     -- exists in average cost type and none is defined in the average rates
3159     -- cost type.
3160 
3161     l_stmt_num := 40;
3162     select count(*)
3163     into l_mat_ovhds
3164     from cst_layer_cost_details
3165     where layer_id = i_layer_id
3166     and cost_element_id = 2
3167     and level_type = 1;
3168 
3169     if (l_mat_ovhds >0 ) then /* material overhead exists in the average
3170                                  cost type */
3171       l_stmt_num := 50;
3172       select count(*)
3173       into l_res_id
3174       from cst_item_cost_details
3175       where cost_type_id = i_avg_rates_id
3176       and inventory_item_id = i_item_id
3177       and organization_id = i_org_id;
3178 
3179       if (l_res_id > 0) then
3180         l_stmt_num := 60;
3181         select resource_id
3182         into l_res_id
3183         from cst_item_cost_details
3184         where cost_type_id = i_avg_rates_id
3185         and inventory_item_id = i_item_id
3186         and organization_id = i_org_id
3187         and cost_element_id = 2
3188 	and level_type = 1
3189 	and rownum = 1;
3190       end if;
3191 
3192 
3193    /* Changed this check for bug 3959770*/
3194         if (l_res_id = 0) then
3195                 raise avg_rates_no_ovhd;
3196          elsif (l_res_id is NULL) then
3197                 if (l_default_MOH_subelement IS NOT NULL) then
3198                         l_res_id := l_default_MOH_subelement;
3199 
3200 			update cst_item_cost_details
3201 			set resource_id = l_default_MOH_subelement
3202 			where cost_type_id = i_avg_rates_id
3203 	                and inventory_item_id = i_item_id
3204 	                and organization_id = i_org_id
3205 	                and cost_element_id = 2
3206 			and resource_id IS NULL
3207 			and level_type = 1
3208 	                and rownum =1;
3209 		else
3210 			raise avg_rates_no_ovhd;
3211         	end if;
3212 	end if ;
3213 
3214 
3215       l_stmt_num := 70;
3216       Insert into mtl_actual_cost_subelement(
3217         transaction_id,
3218         organization_id,
3219         layer_id,
3220         cost_element_id,
3221         level_type,
3222         resource_id,
3223         last_update_date,
3224         last_updated_by,
3225         creation_date,
3226         created_by,
3227         last_update_login,
3228         request_id,
3229         program_application_id,
3230         program_id,
3231         program_update_date,
3232         actual_cost,
3233         user_entered)
3234       select i_txn_id,
3235          i_org_id,
3236          i_layer_id,
3237          clcd.cost_element_id,
3238          clcd.level_type,
3239          l_res_id,
3240          sysdate,
3241          i_user_id,
3242          sysdate,
3243          i_user_id,
3244          i_login_id,
3245          i_req_id,
3246          i_prg_appl_id,
3247          i_prg_id,
3248          sysdate,
3249          clcd.item_cost,
3250          'N'
3251       from cst_layer_cost_details clcd
3252       where layer_id = i_layer_id
3253       and cost_element_id = 2
3254       and level_type = 1;
3255     end if;
3256   end if;
3257 
3258   l_stmt_num := 80;
3259   select count(*)
3260   into l_mat_ovhds
3261   from mtl_actual_cost_subelement
3262   where transaction_id = i_txn_id
3263   and organization_id = i_org_id
3264   and layer_id = i_layer_id
3265   and cost_element_id = 2
3266   and level_type = decode(i_level, 1,1,level_type);
3267 
3268 
3269   -- because of the elemental costs visibility functionality
3270   -- we need to check interorg transfer specially.
3271   if i_txn_action_id in (12,21,3) and (l_elemental_visible = 'Y')then -- interorg transfer
3272   l_stmt_num := 83;
3273 
3274      -- check if there is data in material overhead for this transaction
3275      select count(*)
3276      into l_mcacd_ovhd
3277      from mtl_cst_actual_cost_details cacd
3278      where transaction_id = i_txn_id
3279      and organization_id = i_org_id
3280      and layer_id = i_layer_id
3281      and cost_element_id = 2
3282      and level_type = decode(i_level,1,1,level_type);
3283 
3284      -- if there is data is MACS then modify MCACD
3285      -- if there is no data in MACS then we don't need to do anything.
3286      if (l_mat_ovhds > 0) then
3287         -- if there is data in mcacd then do an update,
3288         -- in this case, with overhead data in mcacd,
3289         -- we added the actual_cost in cost element 2
3290         -- to the overhead cost and then update MCACD.
3291         if (l_mcacd_ovhd > 0) then --update mcacd
3292           l_stmt_num := 85;
3293           select sum(actual_cost)
3294           into l_ovhd_cost
3295           from mtl_actual_cost_subelement
3296           where transaction_id = i_txn_id
3297           and organization_id = i_org_id
3298           and layer_id = i_layer_id
3299           and cost_element_id = 2;
3300 
3301           l_stmt_num := 87;
3302           update mtl_cst_actual_cost_details mcacd
3303           set mcacd.actual_cost = mcacd.actual_cost + l_ovhd_cost
3304           where mcacd.transaction_id = i_txn_id
3305           and mcacd.organization_id = i_org_id
3306           and mcacd.layer_id = i_layer_id
3307           and mcacd.inventory_item_id = i_item_id
3308           and mcacd.level_type = 1
3309           and mcacd.cost_element_id = 2;
3310         -- if there is no data in MCACD but there is data in MACS then
3311         -- do an insert the sum of overhead cost into MCACD.
3312         else -- insert into MCACD.
3313           l_stmt_num := 89;
3314           insert into mtl_cst_actual_cost_details(
3315              transaction_id,
3316              organization_id,
3317              layer_id,
3318              cost_element_id,
3319              level_type,
3320              transaction_action_id,
3321              last_update_date,
3322              last_updated_by,
3323              creation_date,
3324              created_by,
3325              last_update_login,
3326              request_id,
3327              program_application_id,
3328              program_id,
3329              program_update_date,
3330              inventory_item_id,
3331              actual_cost,
3332              prior_cost,
3333              new_cost,
3334              insertion_flag,
3335              variance_amount,
3336              user_entered)
3337           select
3338              i_txn_id,
3339              i_org_id,
3340              i_layer_id,
3341              2,
3342              1,
3343              i_txn_action_id,
3344              sysdate,
3345              i_user_id,
3346              sysdate,
3347              i_user_id,
3348              i_login_id,
3349              i_req_id,
3350              i_prg_appl_id,
3351              i_prg_id,
3352              sysdate,
3353              i_item_id,
3354              sum(actual_cost),
3355              0,
3356              NULL,
3357              'Y',
3358              0,
3359              'N'
3360           from mtl_actual_cost_subelement
3361           where transaction_id = i_txn_id
3362           and organization_id = i_org_id
3363           and layer_id = i_layer_id
3364           and cost_element_id = 2;
3365          end if;
3366       end if;
3367    else -- the else part handle all the non-interorg transfer
3368         -- or interorg txn with elemental visibility disabled
3369     l_stmt_num := 90;
3370     -- if there is data in MACS, then insert into MCACD.
3371     if (l_mat_ovhds > 0) then
3372       insert into mtl_cst_actual_cost_details(
3373           transaction_id,
3374           organization_id,
3375           layer_id,
3376           cost_element_id,
3377           level_type,
3378           transaction_action_id,
3379           last_update_date,
3380           last_updated_by,
3381           creation_date,
3382           created_by,
3383           last_update_login,
3384           request_id,
3385           program_application_id,
3386           program_id,
3387           program_update_date,
3388           inventory_item_id,
3389           actual_cost,
3390           prior_cost,
3391           new_cost,
3392           insertion_flag,
3393           variance_amount,
3394           user_entered)
3395       select
3396           i_txn_id,
3397           i_org_id,
3398           i_layer_id,
3399           2,
3400           1,
3401           i_txn_action_id,
3402           sysdate,
3403           i_user_id,
3404           sysdate,
3405           i_user_id,
3406           i_login_id,
3407           i_req_id,
3408           i_prg_appl_id,
3409           i_prg_id,
3410           sysdate,
3411           i_item_id,
3412           sum(actual_cost),
3413           0,
3414           NULL,
3415           'Y',
3416           0,
3417           'N'
3418       from mtl_actual_cost_subelement
3419       where transaction_id = i_txn_id
3420       and organization_id = i_org_id
3421       and layer_id = i_layer_id
3422       and cost_element_id = 2;
3423     end if;
3424   end if;
3425  END IF;
3426 
3427   IF g_debug = 'Y' THEN
3428     fnd_file.put_line(fnd_file.log, 'Apply_Material_Overhead >>>');
3429   END IF;
3430 
3431   EXCEPTION
3432     when avg_rates_no_ovhd then
3433       rollback;
3434       o_err_num := 9999;
3435       o_err_code := 'CST_NO_MAT_OVHDS';
3436       FND_MESSAGE.set_name('BOM', 'CST_NO_MAT_OVHDS');
3437       o_err_msg := FND_MESSAGE.Get;
3438     when overhead_error then
3439       rollback;
3440       o_err_num := 9999;
3441       o_err_code := 'CST_MAT_OVERHEAD';
3442       FND_MESSAGE.set_name('BOM', 'CST_MAT_OVERHEAD');
3443       o_err_msg := FND_MESSAGE.Get;
3444     when moh_rules_error then
3445       rollback;
3446       o_err_num := 9999;
3447       o_err_code := 'CST_RULES_ERROR';
3448       FND_MESSAGE.set_name('BOM', 'CST_RULES_ERROR');
3449       o_err_msg := FND_MESSAGE.Get;
3450     when others then
3451       rollback;
3452       o_err_num := SQLCODE;
3453       o_err_msg := 'CSTPAVCP.apply_material_ovhd (' || to_char(l_stmt_num) ||
3454                    '): '
3455                    || substr(SQLERRM, 1,200);
3456 
3457 END apply_material_ovhd;
3458 
3459 -- PROCEDURE
3460 --  calc_average_cost           Compute new average cost.
3461 --
3462 
3463 procedure calc_average_cost(
3464   I_ORG_ID      IN        NUMBER,
3465   I_TXN_ID      IN         NUMBER,
3466   I_LAYER_ID    IN        NUMBER,
3467   I_COST_TYPE   IN        NUMBER,
3468   I_ITEM_ID     IN        NUMBER,
3469   I_TXN_QTY     IN        NUMBER,
3470   I_TXN_ACTION_ID IN    NUMBER,
3471   I_NO_UPDATE_MMT IN    NUMBER,
3472   I_USER_ID     IN        NUMBER,
3473   I_LOGIN_ID    IN         NUMBER,
3474   I_REQ_ID      IN        NUMBER,
3475   I_PRG_APPL_ID IN      NUMBER,
3476   I_PRG_ID      IN        NUMBER,
3477   O_Err_Num     OUT NOCOPY        NUMBER,
3478   O_Err_Code    OUT NOCOPY        VARCHAR2,
3479   O_Err_Msg     OUT NOCOPY        VARCHAR2
3480 ) IS
3481   l_txfr_txn_id NUMBER;
3482   total_qty     NUMBER;
3483   l_cur_onhand  NUMBER;
3484   l_new_onhand  NUMBER;
3485   l_err_num             NUMBER;
3486   l_err_code            VARCHAR2(240);
3487   l_err_msg             VARCHAR2(240);
3488   l_stmt_num    NUMBER;
3489   process_error EXCEPTION;
3490 BEGIN
3491   -- initialize local variables
3492   l_err_num := 0;
3493   l_err_code := '';
3494   l_err_msg := '';
3495 
3496 
3497   IF g_debug = 'Y' THEN
3498     fnd_file.put_line(fnd_file.log, '>>>Inside Calc_Average_Cost');
3499   END IF;
3500   /********************************************************************
3501    ** Update mtl_cst_actual_cost_details and update the prior cost   **
3502    ** to the current average for the elements that exists and insert **
3503    ** in to mtl_cst_actual_cost_details the current average cost for **
3504    ** the elements that do not exist.                                **
3505    ********************************************************************/
3506   l_stmt_num := 5;
3507 
3508   Update mtl_cst_actual_cost_details cacd
3509   Set prior_cost = 0,
3510       new_cost = NULL
3511   Where transaction_id = i_txn_id
3512   and organization_id = i_org_id
3513   and layer_id = i_layer_id
3514   and transaction_action_id = i_txn_action_id;
3515 
3516   l_stmt_num := 10;
3517 
3518   Update mtl_cst_actual_cost_details cacd
3519   Set (prior_cost, insertion_flag) =
3520   (Select clcd.item_cost,
3521           'N'
3522    From cst_layer_cost_details clcd
3523    Where clcd.layer_id = i_layer_id
3524    and clcd.cost_element_id = cacd.cost_element_id
3525    and clcd.level_type = cacd.level_type)
3526   Where cacd.transaction_id = i_txn_id
3527   and cacd.organization_id = i_org_id
3528   and cacd.layer_id = i_layer_id
3529   and cacd.transaction_action_id = i_txn_action_id
3530   and exists
3531         (select 'there is details in clcd'
3532         from cst_layer_cost_details clcd
3533         where clcd.layer_id = i_layer_id
3534         and clcd.cost_element_id = cacd.cost_element_id
3535         and clcd.level_type = cacd.level_type);
3536 
3537   insert into mtl_cst_actual_cost_details (
3538         transaction_id,
3539         organization_id,
3540         layer_id,
3541         cost_element_id,
3542         level_type,
3543         transaction_action_id,
3544         last_update_date,
3545         last_updated_by,
3546         creation_date,
3547         created_by,
3548         last_update_login,
3549         request_id,
3550         program_application_id,
3551         program_id,
3552         program_update_date,
3553         inventory_item_id,
3554         actual_cost,
3555         prior_cost,
3556         new_cost,
3557         insertion_flag,
3558         variance_amount,
3559         user_entered)
3560   select i_txn_id,
3561         i_org_id,
3562         i_layer_id,
3563         clcd.cost_element_id,
3564         clcd.level_type,
3565         i_txn_action_id,
3566         sysdate,
3567         i_user_id,
3568         sysdate,
3569         i_user_id,
3570         i_login_id,
3571         i_req_id,
3572         i_prg_appl_id,
3573         i_prg_id,
3574         sysdate,
3575         i_item_id,
3576         0,
3577         clcd.item_cost,
3578         NULL,
3579         'N',
3580         0,
3581         'N'
3582   from cst_layer_cost_details clcd
3583   where layer_id = i_layer_id
3584   and not exists
3585         (select 'this detail is not in cacd already'
3586          from mtl_cst_actual_cost_details cacd
3587          where cacd.transaction_id = i_txn_id
3588          and cacd.organization_id = i_org_id
3589          and cacd.layer_id = i_layer_id
3590          and cacd.cost_element_id = clcd.cost_element_id
3591          and cacd.level_type = clcd.level_type);
3592 
3593 
3594   /********************************************************************
3595    ** Compute new average cost.                                      **
3596    ********************************************************************/
3597   l_stmt_num := 20;
3598 
3599   select layer_quantity
3600   into l_cur_onhand
3601   from cst_quantity_layers cql
3602   where cql.layer_id = i_layer_id;
3603 
3604   l_new_onhand := l_cur_onhand + i_txn_qty;
3605 
3606   l_stmt_num := 30;
3607 
3608   Update mtl_cst_actual_cost_details cacd
3609   Set new_cost =
3610         decode(sign(l_cur_onhand),-1,
3611                decode(sign(i_txn_qty), -1,
3612                       (cacd.prior_cost*l_cur_onhand + cacd.actual_cost*i_txn_qty)/l_new_onhand,
3613                       decode(sign(l_new_onhand),-1, cacd.prior_cost,
3614                              cacd.actual_cost)),
3615                decode(sign(i_txn_qty), -1,
3616                       decode(sign(l_new_onhand), 1,
3617                             decode(sign((abs(cacd.prior_cost)*l_cur_onhand + abs(cacd.actual_cost)*i_txn_qty)/l_new_onhand),1,
3618                                    (cacd.prior_cost*l_cur_onhand + cacd.actual_cost*i_txn_qty)/l_new_onhand,
3619                                    0)
3620                              ,cacd.actual_cost),
3621                       (cacd.prior_cost*l_cur_onhand + cacd.actual_cost*i_txn_qty)/l_new_onhand)),
3622         -- variance amount
3623       variance_amount =
3624         decode(sign(l_cur_onhand),
3625                -1, decode(sign(i_txn_qty),
3626                           -1, 0,
3627                           decode(sign(l_new_onhand),
3628                                  -1, (cacd.actual_cost * i_txn_qty) - (cacd.prior_cost * i_txn_qty),
3629                                        (cacd.actual_cost * abs(i_txn_qty)) - ((cacd.prior_cost * abs(l_cur_onhand)) + cacd.actual_cost *l_new_onhand)
3630                                 )
3631                    ),
3632                decode(sign(i_txn_qty),
3633                       -1, decode(sign(l_new_onhand),
3634                                  1, decode(sign(abs(cacd.actual_cost * i_txn_qty) - abs(cacd.prior_cost * l_cur_onhand)),
3635                                            1, (cacd.prior_cost * abs(l_cur_onhand)) - (cacd.actual_cost * abs(i_txn_qty)),
3636                                            0
3637                                           ),
3638                                  (cacd.prior_cost * l_cur_onhand) + (cacd.actual_cost * abs(l_new_onhand)) - (cacd.actual_cost * abs(i_txn_qty))
3639                                 ),
3640                       0
3641                      )
3642               )
3643   where cacd.transaction_id = i_txn_id
3644   and cacd.organization_id = i_org_id
3645   and cacd.layer_id = i_layer_id
3646   and cacd.transaction_action_id = i_txn_action_id;
3647 
3648   l_stmt_num := 40;
3649 
3650   Update cst_layer_cost_details clcd
3651   set last_update_date = sysdate,
3652       last_updated_by = i_user_id,
3653       last_update_login = i_login_id,
3654       request_id = i_req_id,
3655       program_application_id = i_prg_appl_id,
3656       program_id = i_prg_id,
3657       program_update_date = sysdate,
3658       item_cost =
3659         (select new_cost
3660         from mtl_cst_actual_cost_details cacd
3661         where cacd.transaction_id = i_txn_id
3662         and cacd.organization_id = i_org_id
3663         and cacd.layer_id = i_layer_id
3664         and cacd.cost_element_id = clcd.cost_element_id
3665         and cacd.level_type = clcd.level_type)
3666   where clcd.layer_id = i_layer_id;
3667 
3668   l_stmt_num := 50;
3669 
3670   Insert into cst_layer_cost_details(
3671         layer_id,
3672         cost_element_id,
3673         level_type,
3674         last_update_date,
3675         last_updated_by,
3676         creation_date,
3677         created_by,
3678         last_update_login,
3679         request_id,
3680         program_application_id,
3681         program_id,
3682         program_update_date,
3683         item_cost)
3684   select i_layer_id,
3685         cacd.cost_element_id,
3686         cacd.level_type,
3687         sysdate,
3688         i_user_id,
3689         sysdate,
3690         i_user_id,
3691         i_login_id,
3692         i_req_id,
3693         i_prg_appl_id,
3694         i_prg_id,
3695         sysdate,
3696         cacd.new_cost
3697   from mtl_cst_actual_cost_details cacd
3698   where cacd.transaction_id = i_txn_id
3699   and cacd.organization_id = i_org_id
3700   and cacd.layer_id = i_layer_id
3701   and cacd.insertion_flag = 'Y';
3702 
3703 
3704   /********************************************************************
3705    ** Update Mtl_Material_Transactions                               **
3706    ** Need to update prior_costed_quantity now.                      **
3707    ********************************************************************/
3708   if (i_no_update_mmt = 0) then
3709 
3710     -- subinventory or staging transfer for receipt side, we need to pass
3711     -- txfr_txn_id to update proper transaction in MMT.
3712     /* Changes for VMI. Adding Planning Transfer Transaction */
3713     if (i_txn_action_id IN (2,5,28,55) and i_txn_qty > 0) then
3714       select transfer_transaction_id
3715       into l_txfr_txn_id
3716       from mtl_material_transactions
3717       where transaction_id = i_txn_id;
3718     else
3719       l_txfr_txn_id := -1;
3720     end if;
3721 
3722   IF g_debug = 'Y' THEN
3723     fnd_file.put_line(fnd_file.log, '>>>Calling CSTPAVCP.update_mmt');
3724   END IF;
3725     CSTPAVCP.update_mmt(
3726                         i_org_id,
3727                         i_txn_id,
3728                         l_txfr_txn_id,
3729                         i_layer_id,
3730                         0,
3731                         i_user_id,
3732                         i_login_id,
3733                         i_req_id,
3734                         i_prg_appl_id,
3735                         i_prg_id,
3736                         l_err_num,
3737                         l_err_code,
3738                         l_err_msg);
3739     if (l_err_num <> 0) then
3740       raise process_error;
3741     end if;
3742   IF g_debug = 'Y' THEN
3743     fnd_file.put_line(fnd_file.log, '<<<Returned from CSTPAVCP.update_mmt');
3744   END IF;
3745   end if;
3746 
3747   /********************************************************************
3748    ** Update layer quantity and layer costs information              **
3749    ********************************************************************/
3750   l_stmt_num := 60;
3751   /* Used the Base Table instead of View Bug 4773025 */
3752   Update cst_quantity_layers cql
3753   Set (last_updated_by,
3754         last_update_date,
3755         last_update_login,
3756         request_id,
3757         program_application_id,
3758         program_id,
3759         program_update_date,
3760         layer_quantity,
3761         update_transaction_id,
3762         pl_material,
3763         pl_material_overhead,
3764         pl_resource,
3765         pl_outside_processing,
3766         pl_overhead,
3767         tl_material,
3768         tl_material_overhead,
3769         tl_resource,
3770         tl_outside_processing,
3771         tl_overhead,
3772         material_cost,
3773         material_overhead_cost,
3774         resource_cost,
3775         outside_processing_cost,
3776         overhead_cost,
3777         pl_item_cost,
3778         tl_item_cost,
3779         item_cost,
3780         unburdened_cost,
3781         burden_cost) =
3782   (SELECT
3783         i_user_id,
3784         sysdate,
3785         i_login_id,
3786         i_req_id,
3787         i_prg_appl_id,
3788         i_prg_id,
3789         sysdate,
3790         l_cur_onhand + i_txn_qty,
3791         i_txn_id,
3792         SUM(DECODE(LEVEL_TYPE, 2, DECODE(COST_ELEMENT_ID, 1, ITEM_COST, 0), 0)),
3793         SUM(DECODE(LEVEL_TYPE, 2, DECODE(COST_ELEMENT_ID, 2, ITEM_COST, 0), 0)),
3794         SUM(DECODE(LEVEL_TYPE, 2, DECODE(COST_ELEMENT_ID, 3, ITEM_COST, 0), 0)),
3795         SUM(DECODE(LEVEL_TYPE, 2, DECODE(COST_ELEMENT_ID, 4, ITEM_COST, 0), 0)),
3796         SUM(DECODE(LEVEL_TYPE, 2, DECODE(COST_ELEMENT_ID, 5, ITEM_COST, 0), 0)),
3797         SUM(DECODE(LEVEL_TYPE, 1, DECODE(COST_ELEMENT_ID, 1, ITEM_COST, 0), 0)),
3798         SUM(DECODE(LEVEL_TYPE, 1,DECODE(COST_ELEMENT_ID, 2, ITEM_COST, 0), 0)),
3799         SUM(DECODE(LEVEL_TYPE, 1, DECODE(COST_ELEMENT_ID, 3, ITEM_COST, 0), 0)),
3800         SUM(DECODE(LEVEL_TYPE ,1, DECODE(COST_ELEMENT_ID ,4, ITEM_COST, 0), 0)),
3801         SUM(DECODE(LEVEL_TYPE, 1, DECODE(COST_ELEMENT_ID, 5, ITEM_COST, 0), 0)),
3802         SUM(DECODE(COST_ELEMENT_ID, 1, ITEM_COST, 0)),
3803         SUM(DECODE(COST_ELEMENT_ID, 2, ITEM_COST, 0)),
3804         SUM(DECODE(COST_ELEMENT_ID, 3, ITEM_COST, 0)),
3805         SUM(DECODE(COST_ELEMENT_ID, 4, ITEM_COST, 0)),
3806         SUM(DECODE(COST_ELEMENT_ID, 5, ITEM_COST, 0)),
3807         SUM(DECODE(LEVEL_TYPE, 2, ITEM_COST, 0)),
3808         SUM(DECODE(LEVEL_TYPE, 1, ITEM_COST, 0)),
3809         SUM(ITEM_COST),
3810         SUM(DECODE(COST_ELEMENT_ID, 2, DECODE(LEVEL_TYPE, 2, ITEM_COST, 0), ITEM_COST)),
3811         SUM(DECODE(COST_ELEMENT_ID, 2, DECODE(LEVEL_TYPE, 1, ITEM_COST, 0), 0))
3812        from CST_LAYER_COST_DETAILS clcd
3813    where clcd.layer_id = i_layer_id)
3814   where cql.layer_id = i_layer_id
3815   and exists
3816       (select 'there is detail cost'
3817       from cst_layer_cost_details clcd
3818       where clcd.layer_id = i_layer_id);
3819 
3820   /********************************************************************
3821    ** Update Item Cost and Item Cost Details                         **
3822    ********************************************************************/
3823   IF g_debug = 'Y' THEN
3824     fnd_file.put_line(fnd_file.log, '>>>Calling CSTPAVCP.update_item_cost');
3825   END IF;
3826   CSTPAVCP.update_item_cost(
3827                         i_org_id,
3828                         i_txn_id,
3829                         i_layer_id,
3830                         i_cost_type,
3831                         i_item_id,
3832                         0,          -- mandatory_update flag is not set
3833                         i_user_id,
3834                         i_login_id,
3835                         i_req_id,
3836                         i_prg_appl_id,
3837                         i_prg_id,
3838                         l_err_num,
3839                         l_err_code,
3840                         l_err_msg);
3841   if (l_err_num <> 0) then
3842     raise process_error;
3843   end if;
3844 
3845   IF g_debug = 'Y' THEN
3846     fnd_file.put_line(fnd_file.log, '<<<Returned from CSTPAVCP.update_item_cost');
3847   END IF;
3848   EXCEPTION
3849     when process_error then
3850       o_err_num := l_err_num;
3851       o_err_code := l_err_code;
3852       o_err_msg := l_err_msg;
3853     when others then
3854       rollback;
3855       o_err_num := SQLCODE;
3856       o_err_msg := 'CSTPAVCP.calc_average_cost (' || to_char(l_stmt_num) ||
3857                    '): '
3858                    || substr(SQLERRM, 1,200);
3859 
3860 END calc_average_cost;
3861 
3862 -- PROCEDURE
3863 --  current_average_cost        Using current average cost for the transaction.
3864 --
3865 procedure current_average_cost(
3866   I_ORG_ID      IN        NUMBER,
3867   I_TXN_ID      IN         NUMBER,
3868   I_LAYER_ID    IN        NUMBER,
3869   I_COST_TYPE   IN        NUMBER,
3870   I_ITEM_ID     IN        NUMBER,
3871   I_TXN_QTY     IN        NUMBER,
3872   I_TXN_ACTION_ID IN    NUMBER,
3873   I_EXP_FLAG    IN        NUMBER,
3874   I_NO_UPDATE_MMT IN    NUMBER,
3875   I_NO_UPDATE_QTY IN    NUMBER,
3876   I_USER_ID     IN        NUMBER,
3877   I_LOGIN_ID    IN        NUMBER,
3878   I_REQ_ID      IN        NUMBER,
3879   I_PRG_APPL_ID IN      NUMBER,
3880   I_PRG_ID      IN        NUMBER,
3881   O_Err_Num     OUT NOCOPY        NUMBER,
3882   O_Err_Code    OUT NOCOPY        VARCHAR2,
3883   O_Err_Msg     OUT NOCOPY        VARCHAR2
3884 ) IS
3885   layer_qty     NUMBER;
3886   l_err_num             NUMBER;
3887   l_err_code            VARCHAR2(240);
3888   l_err_msg             VARCHAR2(240);
3889   l_stmt_num            NUMBER;
3890   process_error         EXCEPTION;
3891 
3892 BEGIN
3893   -- initialize local variables
3894   l_err_num := 0;
3895   l_err_code := '';
3896   l_err_msg := '';
3897 
3898 
3899   IF g_debug = 'Y' THEN
3900     fnd_file.put_line(fnd_file.log, 'Current_Average_Cost <<<');
3901   END IF;
3902   /********************************************************************
3903    ** Update Mtl_Material_Transactions to set actual cost, prior     **
3904    ** cost, new cost and prior costed quantity.                      **
3905    ********************************************************************/
3906   if (i_no_update_mmt = 0) then
3907     CSTPAVCP.update_mmt(
3908                         i_org_id,
3909                         i_txn_id,
3910                         -1,                -- txfr_txn_id is not applicable
3911                         i_layer_id,
3912                         0,
3913                         i_user_id,
3914                         i_login_id,
3915                         i_req_id,
3916                         i_prg_appl_id,
3917                         i_prg_id,
3918                         l_err_num,
3919                         l_err_code,
3920                         l_err_msg);
3921   -- handle error case.
3922     if (l_err_num <> 0) then
3923       raise process_error;
3924     end if;
3925   end if;
3926 
3927   /********************************************************************
3928    ** Update layer quantity information in cst_quantity_layers.      **
3929    ** There is no need to update the layer quantity for the          **
3930    ** following transactions:                                        **
3931    ** 1) wip scrap transactions                                      **
3932    ** 2) Expense flag = 1                                            **
3933    ********************************************************************/
3934   if ((i_txn_action_id = 30) or (i_no_update_qty = 1) or (i_exp_flag = 1)
3935       ) then
3936     return;
3937   else
3938 
3939     l_stmt_num := 10;
3940 
3941     Update cst_quantity_layers cql
3942     set last_update_date = sysdate,
3943         last_updated_by = i_user_id,
3944         last_update_login = i_login_id,
3945         request_id = i_req_id,
3946         program_application_id = i_prg_appl_id,
3947         program_id = i_prg_id,
3948         program_update_date = sysdate,
3949         layer_quantity = (cql.layer_quantity + decode(i_txn_action_id, 22, -1*abs(i_txn_qty), i_txn_qty)),
3950         update_transaction_id = i_txn_id
3951     where layer_id = i_layer_id;
3952   end if;
3953 
3954   -- If qty is going to be positive, need to reflect item cost in
3955   -- cst_item_cost table.
3956   CSTPAVCP.update_item_cost(
3957                         i_org_id,
3958                         i_txn_id,
3959                         i_layer_id,
3960                         i_cost_type,
3961                         i_item_id,
3962                         0,                -- mandatory_update flag is not set
3963                         i_user_id,
3964                         i_login_id,
3965                         i_req_id,
3966                         i_prg_appl_id,
3967                         i_prg_id,
3968                         l_err_num,
3969                         l_err_code,
3970                         l_err_msg);
3971   if (l_err_num <> 0) then
3972     -- Error occured
3973     raise process_error;
3974   end if;
3975 
3976   IF g_debug = 'Y' THEN
3977     fnd_file.put_line(fnd_file.log, 'Current_Average_Cost >>>');
3978   END IF;
3979 
3980   EXCEPTION
3981     when process_error then
3982       o_err_num := l_err_num;
3983       o_err_code := l_err_code;
3984       o_err_msg := l_err_msg;
3985     when others then
3986       rollback;
3987       o_err_num := SQLCODE;
3988       o_err_msg := 'CSTPAVCP.current_average_cost (' || to_char(l_stmt_num) ||
3989                    '): '
3990                    || substr(SQLERRM, 1,200);
3991 
3992 END current_average_cost;
3993 
3994 -- PROCEDURE
3995 --  Update_MMT
3996 --
3997 procedure update_mmt(
3998   I_ORG_ID      IN        NUMBER,
3999   I_TXN_ID      IN         NUMBER,
4000   I_TXFR_TXN_ID IN         NUMBER,
4001   I_LAYER_ID    IN        NUMBER,
4002   I_COST_UPDATE IN        NUMBER,
4003   I_USER_ID     IN        NUMBER,
4004   I_LOGIN_ID    IN        NUMBER,
4005   I_REQ_ID      IN        NUMBER,
4006   I_PRG_APPL_ID IN      NUMBER,
4007   I_PRG_ID      IN        NUMBER,
4008   O_Err_Num     OUT NOCOPY        NUMBER,
4009   O_Err_Code    OUT NOCOPY        VARCHAR2,
4010   O_Err_Msg     OUT NOCOPY        VARCHAR2
4011 ) IS
4012   layer_qty             NUMBER;
4013   l_txn_id              NUMBER;
4014   l_cost_exists         NUMBER;
4015   l_citw_flag           NUMBER;
4016   l_err_num             NUMBER;
4017   l_err_code            VARCHAR2(240);
4018   l_err_msg             VARCHAR2(240);
4019   l_stmt_num            NUMBER;
4020 -- for item cost history
4021   l_transaction_action_id NUMBER;
4022   l_item_id             NUMBER;
4023   l_transfer_cost_grp_id NUMBER;
4024   l_transfer_txn_id     NUMBER;
4025   l_from_inv            NUMBER;
4026   l_to_inv              NUMBER;
4027 -- for item cost history
4028  l_asset_item_flag     VARCHAR2(1);
4029 
4030 BEGIN
4031   -- initialize local variables
4032   l_err_num := 0;
4033   l_err_code := '';
4034   l_err_msg := '';
4035 
4036   IF g_debug = 'Y' THEN
4037     fnd_file.put_line(fnd_file.log, '>>>>Inside Update_MMT');
4038   END IF;
4039 -- for item cost history
4040 
4041   l_stmt_num := 5;
4042   Select transaction_action_id
4043   into   l_transaction_action_id
4044   from mtl_material_transactions
4045   where transaction_id = i_txn_id;
4046 -- for item cost history
4047 
4048   -- Since we are processing shipment side of subinventory
4049   -- transfer, we need to use txfr_txn_id for receipt
4050   -- transaction in MMT.
4051 
4052   if (i_txfr_txn_id = -1) then
4053     l_txn_id := i_txn_id;
4054   else
4055     l_txn_id := i_txfr_txn_id;
4056   end if;
4057 
4058   l_stmt_num := 10;
4059 
4060   Select layer_quantity
4061   into layer_qty
4062   from cst_quantity_layers cql
4063   where cql.layer_id = i_layer_id;
4064 
4065   l_stmt_num := 20;
4066 
4067   select count(*)
4068   into l_cost_exists
4069   from mtl_cst_actual_cost_details cacd
4070   where cacd.transaction_id = i_txn_id
4071   and cacd.organization_id = i_org_id
4072   and cacd.layer_id = i_layer_id;
4073 
4074   if (l_cost_exists > 0) then
4075     l_stmt_num := 30;
4076 
4077     -- set common issue to wip flag
4078     /* Added  for Bug#4259926 check for transaction_action_id = 27 in decode */
4079     select decode(transaction_action_id, 1,
4080              decode(transaction_source_type_id, 5,
4081                decode(cost_group_id, NVL(transfer_cost_group_id, cost_group_id), 0, 1)
4082                ,0),
4083               27,decode(transaction_source_type_id, 5,
4084                           decode(cost_group_id, NVL(transfer_cost_group_id, cost_group_id), 0, 1),
4085                           0)
4086              ,0)
4087     into l_citw_flag
4088     from mtl_material_transactions
4089     where transaction_id = i_txn_id;
4090 
4091     -- Added for Bug# 5137993
4092       -- Actual cost should not be populated for expense item
4093       l_stmt_num := 33;
4094 
4095       SELECT inventory_asset_flag
4096         INTO l_asset_item_flag
4097         FROM mtl_system_items
4098        WHERE organization_id = i_org_id
4099          AND inventory_item_id = (SELECT inventory_item_id
4100                                     FROM mtl_material_transactions
4101                                    WHERE transaction_id = i_txn_id);
4102        -- end of changes for Bug# 5137993
4103 
4104     /* Added Bug#4259926 */
4105       If (i_txfr_txn_id is NULL and l_citw_flag=1 ) Then
4106           l_txn_id := i_txn_id;
4107       End if;
4108 
4109     l_stmt_num := 35;
4110     Update mtl_material_transactions mmt
4111     set (last_update_date,
4112          last_updated_by,
4113          last_update_login,
4114          request_id,
4115          program_application_id,
4116          program_id,
4117          program_update_date,
4118          actual_cost,
4119          prior_cost,
4120          new_cost,
4121          variance_amount,
4122          prior_costed_quantity,
4123          quantity_adjusted) =
4124     (select sysdate,
4125             i_user_id,
4126             i_login_id,
4127             i_req_id,
4128             i_prg_appl_id,
4129             i_prg_id,
4130             sysdate,
4131             SUM(DECODE(l_asset_item_flag, 'N', 0, NVL(actual_cost,0))), -- Bug5137993
4132             sum(nvl(prior_cost,0)),
4133             sum(nvl(new_cost,0)),
4134             sum(nvl(variance_amount,0)),
4135             layer_qty,
4136             decode(i_cost_update,1,layer_qty,NULL)
4137       from mtl_cst_actual_cost_details cacd
4138       where cacd.transaction_id = i_txn_id
4139       and cacd.organization_id = i_org_id
4140       and cacd.layer_id = i_layer_id
4141       and cacd.transaction_action_id =
4142           decode(l_citw_flag, 1, 2,             -- for citw, just select
4143                  cacd.transaction_action_id))   -- sub_txfr rows
4144     where mmt.transaction_id = l_txn_id;
4145   else
4146     l_stmt_num := 40;
4147 
4148     Update mtl_material_transactions mmt
4149     set last_update_date = sysdate,
4150         last_updated_by = i_user_id,
4151         last_update_login = i_login_id,
4152         request_id = i_req_id,
4153         program_application_id = i_prg_appl_id,
4154         program_id = i_prg_id,
4155         program_update_date = sysdate,
4156         actual_cost = 0,
4157         prior_cost = 0,
4158         new_cost = 0,
4159         variance_amount=0,
4160         prior_costed_quantity = layer_qty
4161     where mmt.transaction_id = l_txn_id;
4162   end if;
4163 -- item cost history for citw, this part is added to fix the problem
4164 -- for common issue to wip, the prior_costed_quantity is populated with
4165 -- the transfer side qty instead of the from side, which is the qty from
4166 -- common cost group
4167 
4168 /* Commented for bug 9758017:
4169    IF (l_citw_flag = 1) then -- if this is common issue to wip
4170       l_stmt_num := 42;
4171       SELECT
4172          mmt.inventory_item_id
4173       INTO
4174          l_item_id
4175       FROM mtl_material_transactions mmt
4176       WHERE mmt.transaction_id = i_txn_id;
4177 
4178       l_stmt_num := 44;
4179       UPDATE mtl_material_transactions mmt
4180       SET    prior_costed_quantity = (
4181                SELECT cql.layer_quantity - mmt.primary_quantity
4182                FROM   cst_quantity_layers cql,
4183                      mtl_parameters mp
4184               WHERE  cql.organization_id = i_org_id
4185               AND    cql.inventory_item_id = l_item_id
4186               AND    cql.cost_group_id = mp.default_cost_group_id
4187               AND    mp.organization_id = i_org_id
4188             )
4189       WHERE mmt.transaction_id = i_txn_id
4190       AND   EXISTS (
4191               SELECT 'X'
4192               FROM   cst_quantity_layers cql,
4193                      mtl_parameters mp
4194               WHERE  cql.organization_id = i_org_id
4195               AND    cql.inventory_item_id = l_item_id
4196               AND    cql.cost_group_id = mp.default_cost_group_id
4197               AND    mp.organization_id = i_org_id
4198            );
4199    END IF; */
4200 
4201 -- the added part is mainly for item cost history,
4202 -- for subinventory transfer from expense sub to asset sub
4203 -- eg: from expense SUB A to asset SUB B
4204 -- there will be 2 rows in mmt, say MMT_A for SUB A
4205 -- and MMT_B for SUB B
4206 -- the cost worker will only pick up row MMT_A to process
4207 -- base on the above update statement, it will only update the prior_costed_quantity
4208 -- for row MMT_A
4209 -- however, in item cost history, MMT_B (the asset sub)
4210 -- will use MMT_B.prior_costed_quantity
4211 -- the following part is added to populate MMT_B.prior_costed_quantity
4212 -- when expense to asset happens
4213 -- item cost history stuff for sub transfer
4214 
4215   /* Changes for VMI. Adding Planning Transfer Transaction */
4216   if (l_transaction_action_id IN (2,5,28,55)) then
4217 -- item cost history stuff
4218    l_stmt_num := 45;
4219 
4220    SELECT nvl(msi.asset_inventory,-9),
4221           mmt.transfer_transaction_id,
4222           mmt.inventory_item_id,
4223           mmt.transfer_cost_group_id
4224    INTO l_from_inv,
4225         l_transfer_txn_id,
4226         l_item_id,
4227         l_transfer_cost_grp_id
4228    FROM mtl_material_transactions mmt,
4229         mtl_secondary_inventories msi
4230    WHERE mmt.transaction_id = i_txn_id
4231    AND mmt.subinventory_code = msi.secondary_inventory_name
4232    AND mmt.organization_id = msi.organization_id;
4233 
4234    l_stmt_num := 55;
4235    SELECT nvl(msi.asset_inventory,-9)
4236    INTO l_to_inv
4237    FROM mtl_material_transactions mmt,
4238         mtl_secondary_inventories msi
4239    WHERE mmt.transaction_id = i_txn_id
4240    AND nvl(mmt.transfer_subinventory,mmt.subinventory_code) = msi.secondary_inventory_name
4241    AND mmt.organization_id = msi.organization_id;
4242 
4243 -- item cost history stuff
4244 -- from expense to asset sub-transfer
4245    IF ((l_from_inv = 2) and (l_to_inv = 1))then
4246         l_stmt_num := 60;
4247         UPDATE mtl_material_transactions mmt
4248         SET prior_costed_quantity =
4249         (SELECT
4250                 layer_quantity
4251         FROM        cst_quantity_layers cql
4252         WHERE        cql.organization_id = i_org_id
4253         AND        cql.inventory_item_id = l_item_id
4254         AND        cql.cost_group_id = l_transfer_cost_grp_id)
4255         WHERE mmt.transaction_id = l_transfer_txn_id
4256         AND EXISTS (
4257                         SELECT 'X'
4258                         FROM cst_quantity_layers cql
4259                         WHERE cql.organization_id = i_org_id
4260                         AND   cql.inventory_item_id = l_item_id
4261                         AND   cql.cost_group_id = l_transfer_cost_grp_id);
4262 
4263 
4264         IF SQL%ROWCOUNT = 0 THEN
4265           update mtl_material_transactions mmt
4266                  set prior_costed_quantity = 0
4267           where  mmt.transaction_id = l_transfer_txn_id;
4268         END IF;
4269    END IF;
4270 
4271   END IF;
4272 
4273 -- item cost history stuff for sub transfer
4274 
4275 
4276 /*  IF g_debug = 'Y' THEN
4277     fnd_file.put_line(fnd_file.log, 'Update_MMT >>>');
4278   END IF;*/
4279   EXCEPTION
4280     when OTHERS then
4281       rollback;
4282       o_err_num := SQLCODE;
4283       o_err_msg := 'CSTPAVCP.update_mmt (' || to_char(l_stmt_num) ||
4284                    '): '
4285                    || substr(SQLERRM,1,200);
4286 
4287 END update_mmt;
4288 
4289 -- PROCEDURE
4290 --   update_item_cost
4291 --
4292 -- There are 3 cases for updating item cost in cicd :
4293 -- 1. Total qty in cql > 0
4294 --    The item cost in cicd = weighted average of item cost in clcd
4295 --                            acrros different layer.
4296 -- 2. Total qty in cql <= 0 and mandatory_update flag is not set (0)
4297 --    Item cost in cicd will not be updated.
4298 -- 3. Total qty in cql <= 0 and mandatory_update flag is set.
4299 --    Item cost will be copied from clcd to cicd.
4300 --    The caller must make sure that the item only exist in common
4301 --    cost group. In other words, the org must have PJM flag disabled.
4302 --    The average_cost_update() routine is the only routine that uses
4303 --    this case. It's added to fix bug ? related to rollup issue.
4304 --
4305 -- bug 1756613, the cost will not be updated if qty is negative irrespective of the
4306 -- organization being project references enabled
4307 
4308 PROCEDURE update_item_cost(
4309   I_ORG_ID      IN        NUMBER,
4310   I_TXN_ID      IN        NUMBER,
4311   I_LAYER_ID    IN        NUMBER,
4312   I_COST_TYPE   IN        NUMBER,
4313   I_ITEM_ID     IN        NUMBER,
4314   I_MANDATORY_UPDATE    IN      NUMBER,
4315   I_USER_ID     IN        NUMBER,
4316   I_LOGIN_ID    IN        NUMBER,
4317   I_REQ_ID      IN        NUMBER,
4318   I_PRG_APPL_ID IN        NUMBER,
4319   I_PRG_ID      IN        NUMBER,
4320   O_Err_Num     OUT NOCOPY        NUMBER,
4321   O_Err_Code    OUT NOCOPY        VARCHAR2,
4322   O_Err_Msg     OUT NOCOPY        VARCHAR2
4323 ) IS
4324   total_value   NUMBER;  -- Added for bug 4905189
4325   total_qty     NUMBER;
4326   l_err_num             NUMBER;
4327   l_err_code            VARCHAR2(240);
4328   l_err_msg             VARCHAR2(240);
4329   l_stmt_num            NUMBER;
4330   l_default_MOH_subelement NUMBER;
4331   l_num_cost_groups NUMBER;/*Bug 10324713*/
4332 
4333 BEGIN
4334   -- initialize local variables
4335   l_err_num := 0;
4336   l_err_code := '';
4337   l_err_msg := '';
4338 
4339  /* Get the Default MOH sub element of the organization*/
4340 
4341  select DEFAULT_MATL_OVHD_COST_ID
4342  into l_default_MOH_subelement
4343  from mtl_parameters
4344  where organization_id= I_ORG_ID;
4345 
4346   IF g_debug = 'Y' THEN
4347     fnd_file.put_line(fnd_file.log, '>>>>Inside Update_Item_Cost');
4348   END IF;
4349   l_stmt_num := 10;
4350 
4351   -- Bug 4905189, added the calculation for total_value
4352   select nvl(sum(layer_quantity),0), nvl(sum(layer_quantity*nvl(item_cost,0)),0),count(1)
4353   into total_qty, total_value,l_num_cost_groups
4354   from cst_quantity_layers cql
4355   where cql.inventory_item_id = i_item_id
4356   and cql.organization_id = i_org_id;
4357 
4358   -- If total quantity is <= 0 and the mandatory_update flag is not set,
4359   -- don't update cic or cicd. This is case #2 (look explanation above).
4360   if ( (total_qty <= 0) and (i_mandatory_update = 0) and (l_num_cost_groups > 1) ) then
4361     return;
4362   end if;
4363 
4364   -- Bug 4905189, do not allow negative item cost
4365   if ( (total_qty > 0) and (total_value < 0) ) then
4366      return;
4367   end if;
4368 
4369   l_stmt_num := 20;
4370 
4371   Delete from cst_item_cost_details
4372   where inventory_item_id = i_item_id
4373   and organization_id = i_org_id
4374   and cost_type_id = i_cost_type;
4375 
4376   l_stmt_num := 30;
4377 
4378   -- At this point, we left with case 1 and case 3.(look explanation above)
4379   -- For case 1, total qty > 0 means that sign(total_qty) = 1
4380   -- For case 3, total qty <= 0 means that sign(total_qty) = 0/-1
4381   -- Use the sign(total_qty) to differentiate those 2 cases.
4382   Insert into cst_item_cost_details (
4383         inventory_item_id,
4384         organization_id,
4385         cost_type_id,
4386         last_update_date,
4387         last_updated_by,
4388         creation_date,
4389         created_by,
4390         last_update_login,
4391         level_type,
4392         usage_rate_or_amount,
4393         basis_type,
4394         basis_factor,
4395         net_yield_or_shrinkage_factor,
4396         item_cost,
4397         cost_element_id,
4398         rollup_source_type,
4399         request_id,
4400         program_application_id,
4401         program_id,
4402         program_update_date,
4403         resource_id)        -----------------Bug 3959770
4404   select
4405         i_item_id,
4406         i_org_id,
4407         i_cost_type,
4408         sysdate,
4409         i_user_id,
4410         sysdate,
4411         i_user_id,
4412         i_login_id,
4413         clcd.level_type,
4414         (sum(clcd.item_cost*decode(sign(total_qty),1,cql.layer_quantity,1)))
4415            /decode(sign(total_qty),1,total_qty,1), -- modified for bug#3835412
4416         1,
4417         1,
4418         1,
4419         (sum(clcd.item_cost*decode(sign(total_qty),1,cql.layer_quantity,1)))
4420            /decode(sign(total_qty),1,total_qty,1), -- modified for bug#3835412
4421 	clcd.cost_element_id,
4422 	1,
4423 	i_req_id,
4424       	i_prg_appl_id,
4425       	i_prg_id,
4426       	sysdate,
4427 	decode(clcd.cost_element_id,2,decode(clcd.level_type,1,l_default_MOH_subelement,
4428 	                                                     NULL),
4429 	                           NULL)
4430   from cst_layer_cost_details clcd,
4431        cst_quantity_layers cql
4432   where cql.organization_id = i_org_id
4433   and cql.inventory_item_id = i_item_id
4434   and cql.layer_id = clcd.layer_id
4435   group by cost_element_id, level_type;
4436 
4437   l_stmt_num := 40;
4438   /* Used the Base Table instead of View Bug 4773025 */
4439     Update cst_item_costs cic
4440   Set (last_updated_by,
4441         last_update_date,
4442         last_update_login,
4443         request_id,
4444         program_application_id,
4445         program_id,
4446         program_update_date,
4447         pl_material,
4448         pl_material_overhead,
4449         pl_resource,
4450         pl_outside_processing,
4451         pl_overhead,
4452         tl_material,
4453         tl_material_overhead,
4454         tl_resource,
4455         tl_outside_processing,
4456         tl_overhead,
4457         material_cost,
4458         material_overhead_cost,
4459         resource_cost,
4460         outside_processing_cost,
4461         overhead_cost,
4462         pl_item_cost,
4463         tl_item_cost,
4464         item_cost,
4465         unburdened_cost,
4466         burden_cost) =
4467   (SELECT
4468         i_user_id,
4469         sysdate,
4470         i_login_id,
4471         i_req_id,
4472         i_prg_appl_id,
4473         i_prg_id,
4474         sysdate,
4475         SUM(DECODE(LEVEL_TYPE,2,DECODE(COST_ELEMENT_ID,1,ITEM_COST,0),0)),
4476         SUM(DECODE(LEVEL_TYPE,2,DECODE(COST_ELEMENT_ID,2,ITEM_COST,0),0)),
4477         SUM(DECODE(LEVEL_TYPE,2,DECODE(COST_ELEMENT_ID,3,ITEM_COST,0),0)),
4478         SUM(DECODE(LEVEL_TYPE,2,DECODE(COST_ELEMENT_ID,4,ITEM_COST,0),0)),
4479         SUM(DECODE(LEVEL_TYPE,2,DECODE(COST_ELEMENT_ID,5,ITEM_COST,0),0)),
4480         SUM(DECODE(LEVEL_TYPE,1,DECODE(COST_ELEMENT_ID,1,ITEM_COST,0),0)),
4481         SUM(DECODE(LEVEL_TYPE,1,DECODE(COST_ELEMENT_ID,2,ITEM_COST,0),0)),
4482         SUM(DECODE(LEVEL_TYPE,1,DECODE(COST_ELEMENT_ID,3,ITEM_COST,0),0)),
4483         SUM(DECODE(LEVEL_TYPE,1,DECODE(COST_ELEMENT_ID,4,ITEM_COST,0),0)),
4484         SUM(DECODE(LEVEL_TYPE,1,DECODE(COST_ELEMENT_ID,5,ITEM_COST,0),0)),
4485         SUM(DECODE(COST_ELEMENT_ID,1,ITEM_COST)),
4486         SUM(DECODE(COST_ELEMENT_ID,2,ITEM_COST)),
4487         SUM(DECODE(COST_ELEMENT_ID,3,ITEM_COST)),
4488         SUM(DECODE(COST_ELEMENT_ID,4,ITEM_COST)),
4489         SUM(DECODE(COST_ELEMENT_ID,5,ITEM_COST)),
4490         SUM(DECODE(LEVEL_TYPE,2,ITEM_COST,0)),
4491         SUM(DECODE(LEVEL_TYPE,1,ITEM_COST,0)),
4492         SUM(ITEM_COST),
4493         SUM(DECODE(COST_ELEMENT_ID, 2,DECODE(LEVEL_TYPE,2,ITEM_COST,0), ITEM_COST)),
4494         SUM(DECODE(COST_ELEMENT_ID, 2,DECODE(LEVEL_TYPE,1,ITEM_COST,0),0))
4495    from CST_ITEM_COST_DETAILS  cicd
4496    where cicd.inventory_item_id = i_item_id
4497    and cicd.organization_id = i_org_id
4498    and cicd.cost_type_id = i_cost_type)
4499   where cic.inventory_item_id = i_item_id
4500   and cic.organization_id = i_org_id
4501   and cic.cost_type_id = i_cost_type
4502   and exists
4503      (select 'there is detail cost'
4504       from cst_item_cost_details cicd
4505       where cicd.inventory_item_id = i_item_id
4506       and cicd.organization_id = i_org_id
4507       and cicd.cost_type_id = i_cost_type);
4508 
4509 /*  IF g_debug = 'Y' THEN
4510     fnd_file.put_line(fnd_file.log, 'Update_Item_Cost >>>');
4511   END IF;
4512 */
4513 EXCEPTION
4514     when others then
4515       rollback;
4516       o_err_num := SQLCODE;
4517       o_err_msg := 'CSTPAVCP.update_item_cost (' || to_char(l_stmt_num) ||
4518                    '): '
4519                    || substr(SQLERRM, 1,200);
4520 
4521 END update_item_cost;
4522 
4523 
4524 -- PROCEDURE
4525 --  Interorg
4526 --  This procedure will compute the transfer cost of an intransit
4527 --  interorg transaction.  It will also compute the transaction cost
4528 --  of this transfer.
4529 procedure interorg(
4530   I_ORG_ID      IN      NUMBER,
4531   I_TXN_ID      IN      NUMBER,
4532   I_LAYER_ID    IN      NUMBER,
4533   I_COST_TYPE   IN      NUMBER,
4534   I_ITEM_ID     IN      NUMBER,
4535   I_TXN_ACTION_ID IN    NUMBER,
4536   I_TXN_ORG_ID  IN      NUMBER,
4537   I_TXFR_ORG_ID  IN     NUMBER,
4538   I_COST_GRP_ID IN      NUMBER,
4539   I_TXFR_COST_GRP IN    NUMBER,
4540   I_FOB_POINT   IN      NUMBER,
4541   I_USER_ID     IN      NUMBER,
4542   I_LOGIN_ID    IN      NUMBER,
4543   I_REQ_ID      IN      NUMBER,
4544   I_PRG_APPL_ID IN      NUMBER,
4545   I_PRG_ID      IN      NUMBER,
4546   I_TPRICE_OPTION  IN   NUMBER,
4547   I_TXF_PRICE      IN   NUMBER,
4548   I_EXP_ITEM       IN   NUMBER,
4549   O_TXN_QTY     IN OUT NOCOPY   NUMBER,
4550   O_INTERORG_REC IN OUT NOCOPY  NUMBER,
4551   O_NO_UPDATE_MMT IN OUT NOCOPY NUMBER,
4552   O_EXP_FLAG    IN OUT NOCOPY   NUMBER,
4553   O_HOOK_USED   OUT NOCOPY      NUMBER,
4554   O_Err_Num     OUT NOCOPY      NUMBER,
4555   O_Err_Code    OUT NOCOPY      VARCHAR2,
4556   O_Err_Msg     OUT NOCOPY      VARCHAR2
4557 ) IS
4558   l_err_num     NUMBER;
4559   l_err_code    VARCHAR2(240);
4560   l_err_msg     VARCHAR2(240);
4561   l_stmt_num    NUMBER;
4562   process_error EXCEPTION;
4563   l_txn_update_id NUMBER;
4564   l_compute_txn_cost NUMBER;
4565   l_from_org    NUMBER;
4566   l_to_org      NUMBER;
4567   l_from_cost_grp NUMBER;
4568   l_to_cost_grp NUMBER;
4569   l_cost_type_id NUMBER;
4570   l_snd_txn_cost        NUMBER;
4571   l_rcv_txn_cost        NUMBER;
4572   l_txn_cost    NUMBER;
4573   l_txfr_cost   NUMBER;
4574   l_trans_cost  NUMBER;
4575   l_std_from_org        NUMBER;
4576   l_std_to_org          NUMBER;
4577   l_std_org             NUMBER;
4578   l_std_cost_org        NUMBER;   /* bugfix 3048258 */
4579   l_std_exp             NUMBER;
4580   l_update_std          NUMBER;
4581   l_snd_sob_id          NUMBER;
4582   l_snd_curr            VARCHAR2(10);
4583   l_rcv_sob_id          NUMBER;
4584   l_rcv_curr            VARCHAR2(10);
4585   l_curr_type           VARCHAR2(30);
4586   l_conv_rate           NUMBER;
4587   l_conv_date           DATE;
4588   l_snd_uom             VARCHAR2(3);
4589   l_rcv_uom             VARCHAR2(3);
4590   l_snd_qty             NUMBER;
4591   l_count               NUMBER;
4592 -- item cost history stuff
4593   l_transfer_layer_id   NUMBER;
4594   l_transfer_layer_qty  NUMBER;
4595   l_which_org           NUMBER;
4596   l_which_cst_grp       NUMBER;
4597 -- item cost history stuff
4598 -- elemental visibility
4599   l_movh                NUMBER;
4600   l_movh_cost           NUMBER;
4601   l_rec_movh_cost       NUMBER;
4602   l_mctcd_ovhd          NUMBER;
4603   l_from_layer_id       NUMBER;
4604   l_elemental_visible   varchar2(1);
4605 -- elemental visibility
4606   l_um_rate             NUMBER;
4607   l_return_status       VARCHAR2(1);
4608   l_msg_count           NUMBER;
4609   l_msg_data            VARCHAR2(240);
4610   l_earn_moh            NUMBER;
4611   moh_rules_error       EXCEPTION;
4612 
4613   -- Added for bug 2827548
4614   l_xfer_conv_rate      NUMBER;
4615   l_new_txn_cost        NUMBER;
4616 
4617   /* added for bug 3679625 */
4618   l_txfr_txn_id         NUMBER;
4619   l_txfr_std_exp        NUMBER;
4620   /* added for bug 3761538 */
4621   l_to_std_exp          NUMBER;
4622 
4623   /*Added for Actual Cost Enhancement for Inter Org*/
4624   l_test_mcacd          NUMBER := 0;
4625   l_cost_hook_io        NUMBER := 0;
4626   l_test_clcd           NUMBER := 0;
4627   l_ave_to_ave          NUMBER := 0;
4628   no_mcacd_for_hook     EXCEPTION;
4629 
4630 BEGIN
4631   -- initialize local variables
4632   l_err_num := 0;
4633   l_err_code := '';
4634   l_err_msg := '';
4635   l_update_std := 0;
4636   l_snd_qty := o_txn_qty;
4637   l_std_exp := 0;
4638   o_hook_used := 0;
4639   l_ave_to_ave := 0;
4640 
4641   IF g_debug = 'Y' THEN
4642     fnd_file.put_line(fnd_file.log, '>>>Inside CSTPAVCP.interorg Interorg');
4643   END IF;
4644   l_earn_moh := 1;
4645   l_return_status := fnd_api.g_ret_sts_success;
4646   l_msg_count := 0;
4647 
4648   l_txfr_std_exp := 0;
4649   l_to_std_exp := 0;
4650 
4651 
4652   -- Figure the from and to org for this transaction.
4653   if (i_txn_action_id = 21) then
4654     l_from_org := i_txn_org_id;
4655     l_to_org := i_txfr_org_id;
4656     l_from_cost_grp := i_cost_grp_id;
4657     l_to_cost_grp := i_txfr_cost_grp;
4658   elsif (i_txn_action_id = 12) then
4659     l_from_org := i_txfr_org_id;
4660     l_to_org := i_txn_org_id;
4661     l_from_cost_grp := i_txfr_cost_grp;
4662     l_to_cost_grp := i_cost_grp_id;
4663   elsif (i_txn_action_id =3 and o_txn_qty <0) then
4664     l_from_org := i_txn_org_id;
4665     l_to_org := i_txfr_org_id;
4666     l_from_cost_grp := i_cost_grp_id;
4667     l_to_cost_grp := i_txfr_cost_grp;
4668   else
4669     l_from_org := i_txfr_org_id;
4670     l_to_org := i_txn_org_id;
4671     l_from_cost_grp := i_txfr_cost_grp;
4672     l_to_cost_grp := i_cost_grp_id;
4673   end if;
4674 
4675   l_stmt_num := 2;
4676   l_std_from_org := standard_cost_org(l_from_org);
4677   l_stmt_num := 4;
4678   l_std_to_org := standard_cost_org(l_to_org);
4679 
4680   l_stmt_num := 6;
4681   select NVL(elemental_visibility_enabled,'N')
4682   into l_elemental_visible
4683   from mtl_interorg_parameters
4684   where from_organization_id = l_from_org
4685   and to_organization_id = l_to_org;
4686 
4687   l_stmt_num := 7;
4688   select decode(primary_cost_method, 2,
4689                 (select decode(primary_cost_method, 2, 1, 0)
4690                 from mtl_parameters
4691                 where organization_id = l_from_org),
4692                 0)
4693   into l_ave_to_ave
4694   from mtl_parameters
4695   where organization_id = l_to_org;
4696 
4697   IF g_debug = 'Y' THEN
4698     fnd_file.put_line(fnd_file.log, '>>>Transaction action:'||to_char(i_txn_action_id)||' From Org:'||to_char(l_from_org)||' To Org:'||to_char(l_to_org));
4699     fnd_file.put_line(fnd_file.log, '>>>Elemental Visibility: '||to_char(l_elemental_visible));
4700   END IF;
4701 
4702   l_stmt_num := 10;
4703 
4704   /* Bug 2926258 - changed default to be -1 to support org_id=0 */
4705   select decode(l_std_from_org, 1, l_from_org,
4706     decode(l_std_to_org,1,l_to_org,-1))
4707   into l_std_org
4708   from dual;
4709 
4710 
4711   /* bug 3048258: For std costing, item cost from cost organization should be used */
4712   l_stmt_num := 15;
4713   IF ( l_std_from_org = 1 OR l_std_to_org = 1 ) THEN
4714     select cost_organization_id
4715     into l_std_cost_org
4716     from mtl_parameters
4717     where organization_id = l_std_org;
4718   END IF;
4719 
4720   if (l_std_org = i_txn_org_id) then
4721     l_stmt_num :=  20;
4722     select decode(inventory_asset_flag, 'Y', 0, 1)
4723     into l_std_exp
4724     from mtl_system_items
4725     where inventory_item_id = i_item_id
4726     and organization_id = l_std_org;
4727 
4728     l_stmt_num := 30;
4729     select decode(l_std_exp,1,1,decode(asset_inventory,1,0,1))
4730     into l_std_exp
4731     from mtl_secondary_inventories msi
4732         ,mtl_material_transactions mmt
4733     where mmt.transaction_id = i_txn_id
4734     and mmt.organization_id = l_std_org
4735     and msi.organization_id = l_std_org
4736     and msi.secondary_inventory_name = mmt.subinventory_code;
4737   end if;
4738 
4739   IF g_debug = 'Y' THEN
4740     fnd_file.put_line(fnd_file.log, '>>>Calling Get_Snd_Rcv_UOM');
4741   END IF;
4742 
4743   get_snd_rcv_uom(i_item_id, l_from_org, l_to_org, l_snd_uom, l_rcv_uom,
4744       l_err_num, l_err_code, l_err_msg);
4745   if (l_err_num <> 0) then
4746     raise process_error;
4747   end if;
4748 
4749   IF g_debug = 'Y' THEN
4750     fnd_file.put_line(fnd_file.log, '<<<Returning from Get_Snd_Rcv_UOM');
4751   END IF;
4752 
4753   -- If the transaction organization id is not the organization id of this
4754   -- cost worker then we have to make sure this transaction record in mmt
4755   -- does not get updated. Most likely this is an intrasit interorg transaction
4756   -- and we are processing either the shipping or the receiving side. For the
4757   -- same reason we cannot rely on the expense flag since it is based on
4758   -- the current record's subinventory code.
4759   --
4760   if ((i_org_id <> i_txn_org_id)  and (i_txn_action_id in (12,21))) then
4761     o_no_update_mmt := 1;
4762     if (l_from_org = i_org_id) then
4763       o_txn_qty := inv_convert.inv_um_convert
4764         (i_item_id, NULL, o_txn_qty,
4765            l_rcv_uom, l_snd_uom, NULL, NULL);
4766       l_snd_qty := o_txn_qty;
4767     else
4768       o_txn_qty := inv_convert.inv_um_convert
4769         (i_item_id, NULL, o_txn_qty,
4770            l_snd_uom, l_rcv_uom, NULL, NULL);
4771     end if;
4772 
4773     l_stmt_num := 40;
4774 
4775     select decode(inventory_asset_flag, 'Y',0,1)
4776     into o_exp_flag
4777     from mtl_system_items
4778     where inventory_item_id = i_item_id
4779     and organization_id = i_org_id;
4780   end if;
4781 
4782   -- The following are considered interorg receipt transactions.
4783   -- These are transactions where ownership changes and the current org
4784   -- is the receiving org.
4785   if ((i_txn_action_id = 3 and o_txn_qty > 0 and i_txn_org_id = i_org_id) OR
4786       (i_txn_action_id = 21 and i_txfr_org_id = i_org_id and i_fob_point = 1)
4787      OR (i_txn_action_id = 12 and i_txn_org_id = i_org_id and i_fob_point = 2))
4788      then
4789     o_interorg_rec := 1;
4790   else
4791     o_interorg_rec :=0;
4792   end if;
4793 
4794  IF g_debug = 'Y' THEN
4795     fnd_file.put_line(fnd_file.log, '>>>o_interorg_rec:'||to_char(o_interorg_rec));
4796   END IF;
4797 
4798 -- item cost history stuff
4799 
4800   if( ( (i_txn_action_id = 21) and (i_fob_point = 1) and (l_std_to_org = 0) ) OR
4801       ( (i_txn_action_id = 12) and (i_fob_point = 1) and (l_std_to_org = 0) ) OR
4802       ( (i_txn_action_id = 21) and (i_fob_point = 2) and (l_std_from_org = 0) ) OR
4803       ( (i_txn_action_id = 12) and (i_fob_point = 2) and (l_std_to_org = 0) ) ) then
4804     -- intransit ship, fob ship, receiving org is avg org.
4805     if ( (i_txn_action_id = 21) and (i_fob_point = 1) and (l_std_to_org = 0) ) then
4806       l_which_org := l_to_org;
4807       l_which_cst_grp := i_txfr_cost_grp;
4808     -- intransit receipt, fob ship, receiving org is avg org.
4809     elsif ( (i_txn_action_id = 12) and (i_fob_point = 1) and (l_std_to_org = 0) ) then
4810       l_which_org := l_to_org;
4811       l_which_cst_grp := i_cost_grp_id;
4812     -- intransit ship, fob receipt, sending org is avg org.
4813     -- bug 729138
4814     elsif ( (i_txn_action_id = 21) and (i_fob_point = 2) and (l_std_from_org = 0) ) then
4815       l_which_org := l_from_org;
4816       l_which_cst_grp := i_txfr_cost_grp;
4817     -- intransit receipt, fob receipt, receiving org is avg org.
4818     elsif ( (i_txn_action_id = 12) and (i_fob_point = 2) and (l_std_to_org = 0) ) then
4819       l_which_org := l_from_org;
4820       l_which_cst_grp := i_txfr_cost_grp;
4821     end if;
4822 
4823     if i_org_id = l_which_org then  -- this takes care the case R/R,
4824                                     -- cost worker will process the same mmt
4825                                     -- transaction twice
4826         l_stmt_num := 50;
4827   UPDATE mtl_material_transactions mmt
4828   SET TRANSFER_PRIOR_COSTED_QUANTITY =
4829   (SELECT
4830     layer_quantity
4831   FROM  cst_quantity_layers cql
4832   WHERE cql.organization_id = l_which_org
4833   AND   cql.inventory_item_id = i_item_id
4834   AND   cql.cost_group_id = l_which_cst_grp)
4835   WHERE mmt.transaction_id = i_txn_id
4836   AND EXISTS (
4837       SELECT 'X'
4838       FROM cst_quantity_layers cql
4839       WHERE cql.organization_id = l_which_org
4840       AND   cql.inventory_item_id = i_item_id
4841                         AND   cql.cost_group_id = l_which_cst_grp);
4842 
4843   IF SQL%ROWCOUNT = 0 THEN
4844           update mtl_material_transactions mmt
4845      set TRANSFER_PRIOR_COSTED_QUANTITY = 0
4846           where  mmt.transaction_id = i_txn_id;
4847   END IF;
4848     end if;
4849   end if;
4850 
4851 ---- end for item cost history
4852 
4853   -- bug 2827548 - took following IF condition out of the one that follows it because we
4854   -- need to update txn_cost of receit txn before returning if shipment is already costed
4855   if  (i_txn_action_id = 12 and i_org_id = i_txn_org_id and i_fob_point = 1) then
4856     UPDATE mtl_material_transactions mmt
4857     SET mmt.transaction_cost = (select (mmt1.transaction_cost * mmt1.currency_conversion_rate)
4858                                 from mtl_material_transactions mmt1
4859                                 where mmt1.transaction_id = mmt.transfer_transaction_id
4860                                 and mmt1.costed_flag is null)
4861     WHERE mmt.transaction_id = i_txn_id
4862     AND nvl(mmt.transaction_cost,0) = 0;
4863     return;
4864   end if;
4865 
4866   -- If this is an intransit shipment with FOB point receipt
4867   -- or if this is an interorg receipt transaction from
4868   -- another average cost org, or if this is a direct
4869   -- interorg receipt transaction, then we are all done!!!
4870   if ((i_txn_action_id = 21 and i_org_id = i_txn_org_id and i_fob_point = 2) or
4871       (o_interorg_rec = 1 and (i_txn_action_id = 3 or l_std_from_org <> 1)))
4872     then
4873     return;
4874   end if;
4875 
4876   /***********************************************************************
4877    ** In the following conditions we will be doing distribution for the **
4878    ** standard org, so need populate mtl_cst_actual_cost_details with   **
4879    ** the standard costs.                                               **
4880    ** 1. intransit interorg and one of the orgs is standard.            **
4881    ** 2. direct interorg and the txn_org_id is standard.                **
4882    ***********************************************************************/
4883   if ((i_txn_action_id = 3 and l_std_org = i_txn_org_id) OR
4884       (i_txn_action_id in (12,21) and
4885        (l_std_from_org = 1 or l_std_to_org = 1))) then
4886 
4887 /* for bug 3761538 */
4888         if (i_txn_action_id in (12,21) and i_fob_point = 1 and l_std_to_org = 1) then
4889                 -- for the receiving transaction of a intransit fob shipment interorg transfer,
4890                 -- if the receiving org is standard and item is expense in the std org,
4891                 -- set l_to_std_exp = 1 to later insert into mcacd from mctcd.
4892                     l_stmt_num := 102;
4893                         select decode(inventory_asset_flag, 'Y', 0, 1)
4894                         into l_to_std_exp
4895                         from mtl_system_items
4896                         where inventory_item_id = i_item_id
4897                         and organization_id = l_std_org;
4898         end if;
4899         if (l_to_std_exp = 1) then
4900            if g_debug = 'Y' THEN
4901              fnd_file.put_line(fnd_file.log, 'Item is Expense in Receiving Std. Org');
4902            end if;
4903         elsif
4904 /* end for bug 3671538 */
4905     ((l_std_exp <> 1) or (l_std_from_org = 1) or
4906         (l_std_to_org = 1 and i_txn_action_id = 12 and i_fob_point = 1))
4907        then
4908 
4909        /* Use standard costs only for non-expense or not interorg shipements*/
4910        /* Need to use sending org cost for expense interorg receipts */
4911       l_stmt_num := 60;
4912 
4913       l_count := 0;
4914 
4915       select count(*)
4916       into l_count
4917       from cst_item_cost_details
4918       where /* organization_id = l_std_org : bugfix 3048258 */
4919             organization_id = l_std_cost_org
4920       and cost_type_id = 1
4921       and inventory_item_id = i_item_id;
4922 
4923       l_stmt_num := 70;
4924       /* If no rows exist in cicd (item hasn't been costed), insert into */
4925       /* mcacd using 0 value of this level material */
4926       if (l_count > 0) then
4927         insert into mtl_cst_actual_cost_details (
4928     transaction_id,
4929     organization_id,
4930     layer_id,
4931     cost_element_id,
4932     level_type,
4933     transaction_action_id,
4934     last_update_date,
4935     last_updated_by,
4936     creation_date,
4937     created_by,
4938     last_update_login,
4939     request_id,
4940     program_application_id,
4941     program_id,
4942     program_update_date,
4943     inventory_item_id,
4944     actual_cost,
4945     prior_cost,
4946     new_cost,
4947     insertion_flag,
4948     variance_amount,
4949     user_entered)
4950         select i_txn_id,
4951     l_std_org,
4952     -1,
4953     cicd.cost_element_id,
4954     cicd.level_type,
4955     i_txn_action_id,
4956     sysdate,
4957           i_user_id,
4958           sysdate,
4959           i_user_id,
4960           i_login_id,
4961           i_req_id,
4962           i_prg_appl_id,
4963           i_prg_id,
4964           sysdate,
4965     i_item_id,
4966           nvl(sum(cicd.item_cost),0),
4967           NULL,
4968     NULL,
4969           'N',
4970           0,
4971           'N'
4972         from cst_item_cost_details cicd
4973         where /* organization_id = l_std_org : bugfix 3048258 */
4974               organization_id = l_std_cost_org
4975         and cost_type_id = 1
4976         and inventory_item_id = i_item_id
4977         group by cost_element_id, level_type;
4978       else
4979         insert into mtl_cst_actual_cost_details (
4980     transaction_id,
4981     organization_id,
4982     layer_id,
4983     cost_element_id,
4984     level_type,
4985     transaction_action_id,
4986     last_update_date,
4987     last_updated_by,
4988     creation_date,
4989     created_by,
4990     last_update_login,
4991     request_id,
4992     program_application_id,
4993     program_id,
4994     program_update_date,
4995     inventory_item_id,
4996     actual_cost,
4997     prior_cost,
4998     new_cost,
4999     insertion_flag,
5000     variance_amount,
5001     user_entered)
5002         values ( i_txn_id,
5003     l_std_org,
5004     -1,
5005     1,
5006     1,
5007     i_txn_action_id,
5008     sysdate,
5009           i_user_id,
5010           sysdate,
5011           i_user_id,
5012           i_login_id,
5013           i_req_id,
5014           i_prg_appl_id,
5015           i_prg_id,
5016           sysdate,
5017     i_item_id,
5018           0,
5019           NULL,
5020     NULL,
5021           'N',
5022           0,
5023           'N');
5024       end if;
5025 
5026       -- Need to apply material overheads if standard org is receiving
5027       if (l_std_to_org =1) then
5028         l_stmt_num := 80;
5029 /* Changes for MOH Absorption engine */
5030         cst_mohRules_pub.apply_moh(
5031                               1.0,
5032                               p_organization_id => l_std_org,
5033                               p_earn_moh =>l_earn_moh,
5034                               p_txn_id => i_txn_id,
5035                               p_item_id => i_item_id,
5036                               x_return_status => l_return_status,
5037                               x_msg_count => l_msg_count,
5038                               x_msg_data => l_msg_data);
5039 
5040          IF l_return_status <> FND_API.g_ret_sts_success THEN
5041 
5042               CST_UTILITY_PUB.writelogmessages
5043                           ( p_api_version   => 1.0,
5044                             p_msg_count     => l_msg_count,
5045                             p_msg_data      => l_msg_data,
5046                             x_return_status => l_return_status);
5047              RAISE moh_rules_error;
5048         END IF;
5049 
5050         if (l_earn_moh = 0 ) then
5051 
5052           if g_debug = 'Y' THEN
5053             fnd_file.put_line(fnd_file.log, '--Material Overhead Absorption overridden--');
5054           end if;
5055         else
5056           if g_debug = 'Y' then
5057             FND_FILE.PUT_LINE(fnd_file.log, to_char(l_stmt_num) || 'Insert into MACS from CICD');
5058           end if;
5059           Insert into mtl_actual_cost_subelement(
5060             layer_id,
5061             transaction_id,
5062             organization_id,
5063             cost_element_id,
5064             level_type,
5065             resource_id,
5066             last_update_date,
5067             last_updated_by,
5068             creation_date,
5069             created_by,
5070             last_update_login,
5071             request_id,
5072             program_application_id,
5073             program_id,
5074             program_update_date,
5075             actual_cost,
5076             user_entered)
5077           select
5078             -1,
5079             i_txn_id,
5080             l_std_org,
5081             cicd.cost_element_id,
5082             cicd.level_type,
5083             cicd.resource_id,
5084             sysdate,
5085             i_user_id,
5086             sysdate,
5087             i_user_id,
5088             i_login_id,
5089             i_req_id,
5090             i_prg_appl_id,
5091             i_prg_id,
5092             sysdate,
5093             cicd.item_cost,
5094             'N'
5095           from cst_item_cost_details cicd
5096           where inventory_item_id = i_item_id
5097           and /* organization_id = l_std_org : bugfix 3048258 */
5098               organization_id = l_std_cost_org
5099           and cost_type_id = 1
5100           and cost_element_id = 2
5101           and level_type = 1;
5102       end if;
5103      end if;
5104 
5105       if (i_txn_org_id = l_std_org) then
5106       -- update actual cost column of mmt.
5107         l_stmt_num := 90;
5108         update mtl_material_transactions mmt
5109         set (last_update_date,
5110      last_updated_by,
5111      last_update_login,
5112      request_id,
5113      program_application_id,
5114          program_id,
5115      program_update_date,
5116      actual_cost) =
5117         (select sysdate,
5118     i_user_id,
5119     i_login_id,
5120     i_req_id,
5121     i_prg_appl_id,
5122     i_prg_id,
5123     sysdate,
5124     nvl(sum(actual_cost),0)
5125          from mtl_cst_actual_cost_details cacd
5126          where cacd.transaction_id = i_txn_id
5127          and cacd.organization_id = l_std_org
5128    and cacd.layer_id = -1)
5129         where mmt.transaction_id = i_txn_id;
5130       end if;
5131     else
5132       l_update_std := 1;
5133     end if;
5134   end if;
5135 
5136   -- If this is a direct interorg transfer then we need to update the
5137   -- transaction cost and transaction cost details using the transaction_id
5138   -- in the transafer_transaction_id.
5139 
5140   if (i_txn_action_id = 3) then
5141     l_stmt_num := 100;
5142 
5143     select transfer_transaction_id
5144     into l_txn_update_id
5145     from mtl_material_transactions
5146     where transaction_id = i_txn_id;
5147   else
5148     l_txn_update_id := i_txn_id;
5149   end if;
5150 
5151   IF g_debug = 'Y' THEN
5152     fnd_file.put_line(fnd_file.log, '>>>Transaction update id'||to_char(l_txn_update_id));
5153   END IF;
5154 
5155 
5156   -- If we are shipping from a standard cost org to an average cost org, the
5157   -- transaction cost must be computed at the time of the average cost worker
5158   -- for the receiving organization.  This is an exception to the general case
5159   -- where the shipping organization always figures out the transaction cost
5160   -- and populate the details rows for the receiving org.
5161   if ((i_txn_action_id = 21 and i_fob_point = 1 and l_to_org = i_org_id)
5162       OR
5163       (i_txn_action_id = 12 and i_fob_point = 2 and l_to_org = i_org_id)
5164       OR
5165       (i_txn_action_id = 3 and o_txn_qty <0 and l_std_org = i_txn_org_id)) then
5166     l_compute_txn_cost := l_std_from_org;
5167     l_cost_type_id := 1;
5168   elsif ((i_txn_action_id = 21 and i_fob_point = 1 and l_from_org = i_org_id)
5169          OR
5170          (i_txn_action_id = 12 and i_fob_point = 2 and l_from_org = i_org_id)
5171          OR
5172          (i_txn_action_id = 3 and o_txn_qty <0 and l_from_org = i_org_id))
5173         then
5174     l_compute_txn_cost := 2;
5175     l_cost_type_id := i_cost_type;
5176   else
5177     l_compute_txn_cost := 0;
5178   end if;
5179 
5180   -- compute transfer cost and compute transaction cost.
5181   if (l_compute_txn_cost > 0) then
5182     -- Figure out the transaction cost from the sending org.
5183     if (l_compute_txn_cost = 1) then
5184       l_stmt_num := 110;
5185       /* Exception block inserted for bug 1399079, (non costed items) */
5186       BEGIN
5187          select item_cost, -1
5188          into l_snd_txn_cost, l_from_layer_id
5189          from cst_item_costs
5190          where cost_type_id = l_cost_type_id
5191          and inventory_item_id = i_item_id
5192          /* and organization_id = l_from_org; : bugfix 3048258 */
5193          and organization_id = l_std_cost_org;
5194       EXCEPTION
5195          when no_data_found then
5196            l_snd_txn_cost := 0;
5197            l_from_layer_id := -1;
5198       END;
5199 
5200 
5201     else
5202 -- get layer id first?
5203       l_stmt_num := 130;
5204 
5205 
5206 
5207 /*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
5208 Arrow Cost hook enhancement
5209 We should be calling the actual_cost_hook if the transaction is one of the following:
5210 Only in Average to Average transfers (l_std_org = -1)
5211 Only for asset items (i_exp_item = 0)
5212 FOB Shipment -- shipment    call hook when txn_org_id = org_id
5213 FOB Receipt  -- receipt      call hook when txn_org_id is NOT the org_id
5214 Direct Inter org -- quantity <0
5215 We should always call the hook for the shipping org and NOT the receiving org
5216 o_interorg_rec will need to be zero, it already contains the validations for this cases
5217 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
5218 
5219       IF ((l_ave_to_ave = 1) and (o_interorg_rec=0) and (l_std_org = -1) and (i_txn_action_id IN (3,21,12)) and (i_exp_item = 0)) THEN
5220             IF g_debug = 'Y' THEN
5221               fnd_file.put_line(fnd_file.log, '>>>Conditions met to call the actual cost hook');
5222               fnd_file.put_line(fnd_file.log, '>>>Calling the actual cost hook');
5223             END IF;
5224               l_cost_hook_io := CSTPACHK.actual_cost_hook(i_org_id      =>        i_org_id,
5225                                                           i_txn_id         =>        i_txn_id,
5226                                                           i_layer_id         =>        i_layer_id,
5227                                                           i_cost_type         =>        i_cost_type,
5228                                                           i_cost_method        =>        2,
5229                                                           i_user_id        =>        i_user_id,
5230                                                           i_login_id        =>        i_login_id,
5231                                                           i_req_id        =>        i_req_id,
5232                                                           i_prg_appl_id =>        i_prg_appl_id,
5233                                                           i_prg_id      =>        i_prg_id,
5234                                                           o_err_num        =>        l_err_num,
5235                                                           o_err_code        =>        l_err_code,
5236                                                           o_err_msg        =>        l_err_msg);
5237 
5238           IF (l_cost_hook_io=1) THEN
5239                 IF g_debug = 'Y' THEN
5240                     fnd_file.put_line(fnd_file.log, '>>>>Hook has been used. Calling CSTPAVCP.validate_actual_cost_hook');
5241                 END IF;
5242 
5243                 CSTPAVCP.validate_actual_cost_hook(i_txn_id     =>        i_txn_id,
5244                                                    i_org_id     =>      i_org_id,
5245                                                    i_layer_id   =>      i_layer_id,
5246                                                    i_req_id     =>      i_req_id,
5247                                                    i_prg_appl_id=>      i_prg_appl_id,
5248                                                    i_prg_id     =>      i_prg_id,
5249                                                    o_err_num    =>      l_err_num,
5250                                                    o_err_code   =>      l_err_code,
5251                                                    o_err_msg    =>      l_err_msg);
5252                 IF (l_err_num <> 0) THEN
5253                     -- Error occured
5254                     raise process_error;
5255                 END IF;
5256 
5257                 IF g_debug = 'Y' THEN
5258                      fnd_file.put_line(fnd_file.log, '<<<<Calling CSTPAVCP.validate_actual_cost_hook');
5259                 END IF;
5260 
5261                 select sum(actual_cost), layer_id
5262                 into l_snd_txn_cost, l_from_layer_id
5263                 from mtl_cst_actual_cost_details
5264                 where transaction_id= i_txn_id
5265                 and   organization_id= i_org_id
5266                 and   layer_id= i_layer_id
5267                 group by layer_id;
5268 
5269           ELSE
5270                 IF g_debug = 'Y' THEN
5271                   fnd_file.put_line(fnd_file.log, '>>>Hook not used');
5272                 END IF;
5273                 select item_cost, layer_id
5274                 into l_snd_txn_cost, l_from_layer_id
5275                 from cst_quantity_layers
5276                 where organization_id = l_from_org
5277                 and inventory_item_id = i_item_id
5278                 and cost_group_id = l_from_cost_grp;
5279           END IF;
5280       ELSE
5281         IF g_debug = 'Y' THEN
5282            fnd_file.put_line(fnd_file.log, '>>>Hook not used');
5283         END IF;
5284 
5285         select item_cost, layer_id
5286         into l_snd_txn_cost, l_from_layer_id
5287         from cst_quantity_layers
5288         where organization_id = l_from_org
5289         and inventory_item_id = i_item_id
5290         and cost_group_id = l_from_cost_grp;
5291       END IF;
5292     end if;
5293   IF g_debug = 'Y' THEN
5294     fnd_file.put_line(fnd_file.log, '>>>l_snd_txn_cost: '||l_snd_txn_cost||' layer_id: '||l_from_layer_id);
5295   END IF;
5296 
5297 o_hook_used:=l_cost_hook_io;
5298 
5299     -- Get the conversion_rate.
5300     -- receiving_currency = sending_currency * conversion_rate
5301     l_stmt_num := 140;
5302 
5303   IF g_debug = 'Y' THEN
5304     fnd_file.put_line(fnd_file.log, '>>>Calling Get_Snd_Rcv_Rate');
5305   END IF;
5306 
5307     get_snd_rcv_rate(i_txn_id, l_from_org, l_to_org,
5308          l_snd_sob_id, l_snd_curr, l_rcv_sob_id, l_rcv_curr,
5309          l_curr_type,
5310          l_conv_rate, l_conv_date, l_err_num, l_err_code,
5311          l_err_msg);
5312 
5313     if (l_err_num <> 0) then
5314       raise process_error;
5315     end if;
5316 
5317   IF g_debug = 'Y' THEN
5318     fnd_file.put_line(fnd_file.log, '<<<Returning from Get_Snd_Rcv_Rate');
5319   END IF;
5320 
5321 
5322     -- Need to get UOM conversion
5323     -- l_snd_uom = l_um_rate * l_rcv_uom
5324     -- 1 Dozen = 12 * 1 each
5325     l_um_rate := inv_convert.inv_um_convert(i_item_id, NULL, 1,
5326                                             l_snd_uom, l_rcv_uom, NULL, NULL);
5327 
5328     -- Added for bug 2827548
5329     if (i_txn_action_id = 12 and i_fob_point = 2) then -- receiving txn for FOB receipt
5330       l_xfer_conv_rate := l_conv_rate;
5331     else
5332       l_xfer_conv_rate := 1;
5333     end if;
5334 
5335     -- the transfer cost is always in shipping UOM and currency
5336     -- For FOB receipt, need to convert the primary_quantity (in receiving UOM)
5337     -- to sending primary quantity.
5338     l_stmt_num := 150;
5339     Update mtl_material_transactions
5340     Set transfer_cost =
5341      (select decode(nvl(transfer_percentage, -999),-999, transfer_cost,
5342                    (transfer_percentage * l_snd_txn_cost *
5343         decode(i_txn_action_id, 12, abs(primary_quantity)/l_um_rate,
5344                     abs(primary_quantity)))*l_xfer_conv_rate/100) -- bug 2827548-added l_xfer_conv_rate
5345       from mtl_material_transactions
5346       where transaction_id = i_txn_id)
5347     where transaction_id = i_txn_id
5348        or (transaction_id = decode(i_txn_action_id,3,l_txn_update_id,-1));
5349 
5350     -- Get transfer cost and transportation cost from mmt which is in sending currency.
5351     l_stmt_num := 160;
5352 
5353     select nvl(transfer_cost,0), nvl(transportation_cost,0),
5354            decode(i_txn_action_id,12,(primary_quantity / l_um_rate),primary_quantity)
5355     into l_txfr_cost, l_trans_cost, l_snd_qty
5356     from mtl_material_transactions
5357     where transaction_id = i_txn_id;
5358 
5359   IF g_debug = 'Y' THEN
5360     fnd_file.put_line(fnd_file.log, '>>>Transfer cost: '||to_char(l_txfr_cost)||' Transportation cost: '||to_char(l_trans_cost)||' Sending quantity: '||to_char(l_snd_qty));
5361   END IF;
5362 
5363     /* TPRICE: If the transfer pricing option is yes, set transfer credit to be zero */
5364     if (i_tprice_option <> 0) then
5365        l_txfr_cost := 0;
5366          IF g_debug = 'Y' THEN
5367              fnd_file.put_line(fnd_file.log, '>>>Transfer price active setting transfer credit to zero');
5368          END IF;
5369     end if;
5370 
5371     -- change for bug 2827548
5372     if (i_txn_action_id = 12 and i_fob_point = 2) then
5373       l_rcv_txn_cost := ( ((l_snd_txn_cost * abs(l_snd_qty)) * l_conv_rate ) +
5374                             l_txfr_cost + l_trans_cost) / (abs(l_snd_qty)*l_um_rate);
5375       l_new_txn_cost := l_rcv_txn_cost;
5376     elsif ((i_txn_action_id = 12 and i_fob_point = 1) or (i_txn_action_id = 3 and o_txn_qty > 0)) then
5377       l_rcv_txn_cost := ( ((l_snd_txn_cost * abs(l_snd_qty)) + l_txfr_cost + l_trans_cost) *
5378                             l_conv_rate / l_um_rate) / abs(l_snd_qty);
5379       l_new_txn_cost := l_rcv_txn_cost;
5380     else
5381       l_new_txn_cost := (l_snd_txn_cost * abs(l_snd_qty) + l_txfr_cost +
5382                          l_trans_cost) / abs(l_snd_qty);
5383       l_rcv_txn_cost := l_new_txn_cost * l_conv_rate / l_um_rate;
5384     end if;
5385     if (i_txn_action_id<>12 or i_fob_point<>2) then
5386       l_trans_cost := l_trans_cost * l_conv_rate;
5387       l_txfr_cost := l_txfr_cost * l_conv_rate;
5388     end if;
5389 
5390   IF g_debug = 'Y' THEN
5391     fnd_file.put_line(fnd_file.log, '>>>Receiving cost: '||to_char(l_rcv_txn_cost));
5392   END IF;
5393 
5394     /* TPRICE: If the transfter pricing option is to treat the price as the incoming cost,
5395                insert price into MCTCD */
5396     if (i_tprice_option = 2) then
5397        l_rcv_txn_cost := i_txf_price;
5398        l_elemental_visible := 'N';
5399           IF g_debug = 'Y' THEN
5400              fnd_file.put_line(fnd_file.log, '>>>Transfer price as incomming cost, hook will not be used');
5401           END IF;
5402     end if;
5403 
5404     if (l_elemental_visible = 'Y') then
5405           IF g_debug = 'Y' THEN
5406              fnd_file.put_line(fnd_file.log, '>>>Calling interorg_elemental_detail');
5407           END IF;   /*BUG 9311174 Modified the way we call inteorg_elemental_detail*/
5408                     /*            to rectify we call the signature correctly       */
5409        interorg_elemental_detail(       i_txn_id                 =>         i_txn_id,
5410                                         i_compute_txn_cost         =>         l_compute_txn_cost,
5411                                         i_cost_type_id                =>        l_cost_type_id,
5412                                         i_from_layer_id                =>        l_from_layer_id,
5413                                         i_item_id                =>        i_item_id,
5414                                         i_txn_update_id                =>        l_txn_update_id,
5415                                         i_from_org                =>        l_from_org,
5416                                         i_to_org                =>        l_to_org,
5417                                         i_snd_qty                =>        l_snd_qty,
5418                                         i_txfr_cost                =>        l_txfr_cost,
5419                                         i_trans_cost                =>        l_trans_cost,
5420                                         i_conv_rate                =>        l_conv_rate,
5421                                         i_um_rate                =>        l_um_rate,
5422                                         i_user_id                 =>        i_user_id,
5423                                         i_login_id                =>        i_login_id,
5424                                         i_req_id                =>        i_req_id,
5425                                         i_prg_appl_id                =>        i_prg_appl_id,
5426                                         i_prg_id                =>        i_prg_id,
5427                                         i_hook_used                =>        l_cost_hook_io,
5428                                         o_err_num                =>        l_err_num,
5429                                         o_err_code                =>        l_err_code,
5430                                         o_err_msg                =>        l_err_msg);
5431        if (l_err_num <> 0) then
5432          raise process_error;
5433        end if;
5434           IF g_debug = 'Y' THEN
5435              fnd_file.put_line(fnd_file.log, '<<<Returned interorg_elemental_detail');
5436           END IF;
5437     else
5438        insert into mtl_cst_txn_cost_details (
5439           transaction_id,
5440           organization_id,
5441         cost_element_id,
5442         level_type,
5443         last_update_date,
5444         last_updated_by,
5445         creation_date,
5446         created_by,
5447         last_update_login,
5448         request_id,
5449         program_application_id,
5450         program_id,
5451         program_update_date,
5452         inventory_item_id,
5453         transaction_cost,
5454         new_average_cost,
5455         percentage_change,
5456         value_change)
5457           values (l_txn_update_id,
5458         l_to_org,
5459         1,
5460           1,
5461         sysdate,
5462               i_user_id,
5463               sysdate,
5464               i_user_id,
5465               i_login_id,
5466               i_req_id,
5467               i_prg_appl_id,
5468               i_prg_id,
5469               sysdate,
5470               i_item_id,
5471               l_rcv_txn_cost,
5472         0,
5473         0,
5474         0);
5475     END IF;
5476 
5477     -- Update the transaction cost column if appropriate.
5478     /* Begin changes and additions for bug 2827548 */
5479     Update mtl_material_transactions
5480     Set transaction_cost = l_new_txn_cost
5481     where transaction_id = i_txn_id;
5482 
5483     if (i_txn_action_id = 3) then
5484       Update mtl_material_transactions
5485       Set transaction_cost = l_rcv_txn_cost
5486       where transaction_id = l_txn_update_id;
5487     end if;
5488 
5489     -- Update the transaction_cost column for receipt txn w/ fob shipment
5490     -- in the receiving org's currency
5491     if (i_txn_action_id = 21 and i_fob_point = 1) then
5492       update mtl_material_transactions mmt
5493       set mmt.transaction_cost = l_rcv_txn_cost
5494       where mmt.transfer_transaction_id = i_txn_id
5495       and mmt.transaction_action_id = 12;
5496     -- Update the transaction_cost column for shipment txn w/ fob receipt
5497     -- in the sending org's currency
5498     elsif (i_txn_action_id = 12 and i_fob_point = 2) then
5499       update mtl_material_transactions mmt
5500       set mmt.transaction_cost = l_snd_txn_cost
5501       where mmt.transaction_id =
5502         (select mmt1.transfer_transaction_id
5503          from mtl_material_transactions mmt1
5504          where mmt1.transaction_id = i_txn_id)
5505       and mmt.transaction_action_id = 21
5506       and nvl(mmt.transaction_cost,0) = 0;
5507     end if;
5508 
5509     /* End changes for bug 2827548 */
5510 
5511 
5512   /* Added for Bug #3679625
5513    * To handle direct transfers from avg to std org, where item/sub is expense
5514    * in the receiving org */
5515   if (l_std_org = i_txfr_org_id and i_txn_action_id = 3) then
5516     l_stmt_num :=  170;
5517     select decode(inventory_asset_flag, 'Y', 0, 1)
5518     into l_txfr_std_exp
5519     from mtl_system_items
5520     where inventory_item_id = i_item_id
5521     and organization_id = l_std_org;
5522 
5523     l_stmt_num :=  180;
5524     select transfer_transaction_id
5525     into l_txfr_txn_id
5526     from mtl_material_transactions mmt
5527     where mmt.transaction_id = i_txn_id;
5528 
5529     l_stmt_num := 190;
5530     select decode(l_txfr_std_exp,1,1,decode(asset_inventory,1,0,1))
5531     into l_txfr_std_exp
5532     from mtl_secondary_inventories msi
5533         ,mtl_material_transactions mmt
5534     where mmt.transaction_id = l_txfr_txn_id
5535     and mmt.organization_id = l_std_org
5536     and msi.organization_id = l_std_org
5537     and msi.secondary_inventory_name = mmt.subinventory_code;
5538 
5539     if (l_txfr_std_exp = 1) then
5540       l_stmt_num :=  200;
5541       insert into mtl_cst_actual_cost_details (
5542           transaction_id,
5543           organization_id,
5544           layer_id,
5545           cost_element_id,
5546           level_type,
5547           transaction_action_id,
5548           last_update_date,
5549           last_updated_by,
5550           creation_date,
5551           created_by,
5552           last_update_login,
5553           request_id,
5554           program_application_id,
5555           program_id,
5556           program_update_date,
5557           inventory_item_id,
5558           actual_cost,
5559           prior_cost,
5560           new_cost,
5561           insertion_flag,
5562           variance_amount,
5563           user_entered)
5564       select
5565           l_txfr_txn_id,
5566           l_std_org,
5567           -1,
5568           decode(l_elemental_visible,'Y',ctcd.cost_element_id,1),
5569           decode(l_elemental_visible,'Y',ctcd.level_type,1),
5570           i_txn_action_id,
5571           sysdate,
5572           i_user_id,
5573           sysdate,
5574           i_user_id,
5575           i_login_id,
5576           i_req_id,
5577           i_prg_appl_id,
5578           i_prg_id,
5579           sysdate,
5580           ctcd.inventory_item_id,
5581           decode(l_elemental_visible,'Y',ctcd.transaction_cost,l_rcv_txn_cost),
5582           NULL,
5583           NULL,
5584           'N',
5585           0,
5586           'N'
5587       FROM mtl_cst_txn_cost_details ctcd
5588       WHERE ctcd.transaction_id = l_txn_update_id
5589       AND ctcd.organization_id = l_std_org
5590       /* AND ctcd.transaction_cost >= 0 */; -- modified for bug#3835412
5591 
5592           update mtl_material_transactions mmt
5593           set (last_update_date,
5594                         last_updated_by,
5595                         last_update_login,
5596                         request_id,
5597                         program_application_id,
5598                         program_id,
5599                         program_update_date,
5600                         actual_cost) =
5601                 (select sysdate,
5602                         i_user_id,
5603                         i_login_id,
5604                         i_req_id,
5605                         i_prg_appl_id,
5606                         i_prg_id,
5607                         sysdate,
5608                         nvl(sum(actual_cost),0)
5609                         from mtl_cst_actual_cost_details cacd
5610                         where cacd.transaction_id = l_txn_update_id
5611                         and cacd.organization_id = l_std_org
5612                         and cacd.layer_id = -1)
5613           where mmt.transaction_id = l_txn_update_id;
5614     end if;
5615   end if;
5616   /*end changes for 3679625 */
5617 
5618     if (l_update_std = 1) then
5619        /*  the receiving org is standard exp. */
5620       l_stmt_num := 210;
5621       -- if the receiving org is std exp, copy the txn info
5622       -- into MCACD from MCTCD.
5623       insert into mtl_cst_actual_cost_details (
5624           transaction_id,
5625           organization_id,
5626           layer_id,
5627           cost_element_id,
5628           level_type,
5629           transaction_action_id,
5630           last_update_date,
5631           last_updated_by,
5632           creation_date,
5633           created_by,
5634           last_update_login,
5635           request_id,
5636           program_application_id,
5637           program_id,
5638           program_update_date,
5639           inventory_item_id,
5640           actual_cost,
5641           prior_cost,
5642           new_cost,
5643           insertion_flag,
5644           variance_amount,
5645           user_entered)
5646       select
5647     i_txn_id,
5648           l_std_org,
5649     -1,
5650           decode(l_elemental_visible,'Y',ctcd.cost_element_id,1),
5651           decode(l_elemental_visible,'Y',ctcd.level_type,1),
5652     i_txn_action_id,
5653           sysdate,
5654           i_user_id,
5655           sysdate,
5656           i_user_id,
5657           i_login_id,
5658           i_req_id,
5659           i_prg_appl_id,
5660           i_prg_id,
5661           sysdate,
5662           ctcd.inventory_item_id,
5663           decode(l_elemental_visible,'Y',ctcd.transaction_cost,l_rcv_txn_cost),
5664           NULL,
5665           NULL,
5666           'N',
5667           0,
5668           'N'
5669       FROM mtl_cst_txn_cost_details ctcd
5670       WHERE ctcd.transaction_id = l_txn_update_id
5671       AND ctcd.organization_id = l_std_org
5672       /* AND ctcd.transaction_cost >= 0 */; -- modified for bug#3835412
5673 
5674       if (l_std_org = i_txn_org_id or i_txn_action_id = 3) then
5675         l_stmt_num := 220;
5676         update mtl_material_transactions mmt
5677         set (last_update_date,
5678      last_updated_by,
5679      last_update_login,
5680      request_id,
5681      program_application_id,
5682          program_id,
5683      program_update_date,
5684      actual_cost) =
5685         (select sysdate,
5686     i_user_id,
5687     i_login_id,
5688     i_req_id,
5689     i_prg_appl_id,
5690     i_prg_id,
5691     sysdate,
5692     nvl(sum(actual_cost),0)
5693          from mtl_cst_actual_cost_details cacd
5694          where cacd.transaction_id = l_txn_update_id
5695          and cacd.organization_id = l_std_org
5696    and cacd.layer_id = -1)
5697         where mmt.transaction_id = l_txn_update_id;
5698       end if;
5699     end if;
5700 
5701   end if;
5702 
5703 /* begin bug 3761538
5704  * handle intransit interorg transfers with fob pt = shipment,
5705  * from average costing org to standard costing org
5706  * where item is expense in the receiving org.
5707  */
5708 if (l_to_std_exp = 1) then
5709         if (i_txn_org_id = l_std_org) then
5710         select transfer_transaction_id
5711         into l_txfr_txn_id
5712         from mtl_material_transactions mmt
5713         where mmt.transaction_id = i_txn_id;
5714         end if;
5715 
5716         l_stmt_num :=  260;
5717         insert into mtl_cst_actual_cost_details (
5718           transaction_id,
5719           organization_id,
5720           layer_id,
5721           cost_element_id,
5722           level_type,
5723           transaction_action_id,
5724           last_update_date,
5725           last_updated_by,
5726           creation_date,
5727           created_by,
5728           last_update_login,
5729           request_id,
5730           program_application_id,
5731           program_id,
5732           program_update_date,
5733           inventory_item_id,
5734           actual_cost,
5735           prior_cost,
5736           new_cost,
5737           insertion_flag,
5738           variance_amount,
5739           user_entered)
5740   select
5741           i_txn_id,
5742           l_std_org,
5743           -1,
5744           ctcd.cost_element_id,
5745           ctcd.level_type,
5746           i_txn_action_id,
5747           sysdate,
5748           i_user_id,
5749           sysdate,
5750           i_user_id,
5751           i_login_id,
5752           i_req_id,
5753           i_prg_appl_id,
5754           i_prg_id,
5755           sysdate,
5756           ctcd.inventory_item_id,
5757           ctcd.transaction_cost,
5758           NULL,
5759           NULL,
5760           'N',
5761           0,
5762           'N'
5763         FROM mtl_cst_txn_cost_details ctcd
5764         WHERE ctcd.transaction_id = decode(i_txn_org_id, l_std_org, l_txfr_txn_id, l_txn_update_id) -- sending txn id
5765         AND ctcd.organization_id = l_std_org
5766         /* AND ctcd.transaction_cost >= 0 */; -- modified for bug#3835412
5767 
5768         -- update mmt if this is the receiving transaction id
5769         if (i_txn_org_id = l_std_org) then
5770                 update mtl_material_transactions mmt
5771                 set (last_update_date,
5772                         last_updated_by,
5773                         last_update_login,
5774                         request_id,
5775                         program_application_id,
5776                         program_id,
5777                         program_update_date,
5778                         actual_cost) =
5779                 (select sysdate,
5780                         i_user_id,
5781                         i_login_id,
5782                         i_req_id,
5783                         i_prg_appl_id,
5784                         i_prg_id,
5785                         sysdate,
5786                         nvl(sum(actual_cost),0)
5787                         from mtl_cst_actual_cost_details cacd
5788                         where cacd.transaction_id = l_txn_update_id
5789                         and cacd.organization_id = l_std_org
5790                         and cacd.layer_id = -1)
5791                 where mmt.transaction_id = l_txn_update_id;
5792         end if;
5793 end if;
5794 /* end bug 3761538 */
5795 /*  IF g_debug = 'Y' THEN
5796     fnd_file.put_line(fnd_file.log, 'Interorg >>>');
5797   END IF;
5798 */
5799 
5800   EXCEPTION
5801     when process_error then
5802       o_err_num := l_err_num;
5803       o_err_code := l_err_code;
5804       o_err_msg := l_err_msg;
5805    when moh_rules_error then
5806       o_err_num := 9999;
5807       o_err_code := 'CST_RULES_ERROR';
5808       FND_MESSAGE.set_name('BOM', 'CST_RULES_ERROR');
5809       o_err_msg := FND_MESSAGE.Get;
5810     when others then
5811       rollback;
5812       o_err_num := SQLCODE;
5813       o_err_msg := 'CSTPAVCP.interorg (' || to_char(l_stmt_num) ||
5814                    '): '
5815        || substr(SQLERRM, 1,200);
5816 
5817 END interorg;
5818 
5819 PROCEDURE get_snd_rcv_rate(
5820   I_TXN_ID      IN        NUMBER,
5821   I_FROM_ORG    IN        NUMBER,
5822   I_TO_ORG      IN        NUMBER,
5823   O_SND_SOB_ID  OUT NOCOPY        NUMBER,
5824   O_SND_CURR    OUT NOCOPY        VARCHAR2,
5825   O_RCV_SOB_ID  OUT NOCOPY        NUMBER,
5826   O_RCV_CURR    OUT NOCOPY        VARCHAR2,
5827   O_CURR_TYPE   OUT NOCOPY        VARCHAR2,
5828   O_CONV_RATE   OUT NOCOPY        NUMBER,
5829   O_CONV_DATE   OUT NOCOPY        DATE,
5830   O_Err_Num     OUT NOCOPY        NUMBER,
5831   O_Err_Code    OUT NOCOPY        VARCHAR2,
5832   O_Err_Msg     OUT NOCOPY        VARCHAR2
5833 )IS
5834   l_snd_sob_id  NUMBER;
5835   l_snd_curr    VARCHAR2(10);
5836   l_rcv_sob_id  NUMBER;
5837   l_rcv_curr    VARCHAR2(10);
5838   l_curr_type   VARCHAR2(30);
5839   l_conv_rate   NUMBER;
5840   l_conv_date   DATE;
5841   l_txn_date    DATE;
5842   l_err_num             NUMBER;
5843   l_err_code            VARCHAR2(240);
5844   l_err_msg             VARCHAR2(240);
5845   l_stmt_num            NUMBER;
5846 
5847 BEGIN
5848   -- initialize local variables
5849   l_err_num := 0;
5850   l_err_code := '';
5851   l_err_msg := '';
5852 
5853   IF g_debug = 'Y' THEN
5854     fnd_file.put_line(fnd_file.log, '>>>>Inside Get_Snd_Rcv_Rate');
5855   END IF;
5856   l_stmt_num := 10;
5857 
5858 /* The following FROM clause in the select statement has been commented out
5859    because we now have to refer CST_ORGANIZATION_DEFINITIONS as a result of the
5860    impact of the HR-PROFILE option  */
5861 
5862   select set_of_books_id
5863   into l_snd_sob_id
5864   /*from org_organization_definitions */
5865   from cst_organization_definitions
5866   where organization_id = i_from_org;
5867 
5868   l_stmt_num := 20;
5869 
5870   select currency_code
5871   into l_snd_curr
5872   from gl_sets_of_books
5873   where set_of_books_id = l_snd_sob_id;
5874 
5875   l_stmt_num := 30;
5876 
5877 /* The following line in the FROM clause of the select statement has been
5878    commented out because it will now be refering to cst_organization_definitions   as an impact of the HR-PROFILE option */
5879 
5880   select set_of_books_id
5881   into l_rcv_sob_id
5882   /*from org_organization_definitions */
5883   from cst_organization_definitions
5884   where organization_id = i_to_org;
5885 
5886   l_stmt_num := 40;
5887 
5888   select currency_code
5889   into l_rcv_curr
5890   from gl_sets_of_books
5891   where set_of_books_id = l_rcv_sob_id;
5892 
5893   l_stmt_num := 50;
5894 
5895   select currency_conversion_type, TRUNC(transaction_date)
5896   into l_curr_type, l_txn_date
5897   from mtl_material_transactions
5898   where transaction_id = i_txn_id;
5899 
5900   if (l_curr_type is NULL) then
5901     FND_PROFILE.get('CURRENCY_CONVERSION_TYPE', l_curr_type);
5902   end if;
5903 
5904   if (l_rcv_curr <> l_snd_curr) then
5905     l_stmt_num := 60;
5906 
5907  /* --- replacing gl table hit by gl currency api
5908 
5909     select conversion_rate, conversion_date
5910     into l_conv_rate, l_conv_date
5911     from gl_daily_conversion_rates
5912     where set_of_books_id = l_rcv_sob_id
5913     and from_currency_code = l_snd_curr
5914     and conversion_type = l_curr_type
5915     and conversion_date =
5916           (select max(conversion_date)
5917            from gl_daily_conversion_rates
5918            where set_of_books_id = l_rcv_sob_id
5919            and from_currency_code = l_snd_curr
5920            and conversion_type = l_curr_type
5921            and conversion_date <= l_txn_date);
5922  -------------------------------------------------------------*/
5923 
5924    l_conv_rate := gl_currency_api.get_rate(l_rcv_sob_id,l_snd_curr,l_txn_date,
5925                                            l_curr_type);
5926   else
5927     l_conv_rate := 1;
5928   end if;
5929 
5930   o_snd_sob_id := l_snd_sob_id;
5931   o_snd_curr := l_snd_curr;
5932   o_rcv_sob_id := l_rcv_sob_id;
5933   o_rcv_curr := l_rcv_curr;
5934   o_curr_type := l_curr_type;
5935   o_conv_rate := l_conv_rate;
5936   o_conv_date := l_conv_date;
5937 
5938 /*  IF g_debug = 'Y' THEN
5939     fnd_file.put_line(fnd_file.log, 'Get_Snd_Rcv_Rate >>>');
5940   END IF; */
5941   EXCEPTION
5942 
5943  when gl_currency_api.NO_RATE then
5944  rollback;
5945  O_err_num := 9999;
5946  O_err_code := 'CST_NO_GL_RATE';
5947  FND_MESSAGE.set_name('BOM', 'CST_NO_GL_RATE');
5948  O_err_msg := FND_MESSAGE.Get;
5949 
5950     when others then
5951       rollback;
5952       o_err_num := SQLCODE;
5953       o_err_msg := 'CSTPAVCP.get_snd_rcv_rate (' || to_char(l_stmt_num) ||
5954                    '): '
5955                    || substr(SQLERRM, 1,200);
5956 
5957 END get_snd_rcv_rate;
5958 
5959 PROCEDURE get_snd_rcv_uom(
5960   I_ITEM_ID     IN        NUMBER,
5961   I_FROM_ORG    IN        NUMBER,
5962   I_TO_ORG      IN        NUMBER,
5963   O_SND_UOM     OUT NOCOPY        VARCHAR2,
5964   O_RCV_UOM     OUT NOCOPY        VARCHAR2,
5965   O_Err_Num     OUT NOCOPY        NUMBER,
5966   O_Err_Code    OUT NOCOPY        VARCHAR2,
5967   O_Err_Msg     OUT NOCOPY        VARCHAR2
5968 )IS
5969   l_err_num             NUMBER;
5970   l_err_code            VARCHAR2(240);
5971   l_err_msg             VARCHAR2(240);
5972   l_stmt_num            NUMBER;
5973 
5974 BEGIN
5975   -- initialize local variables
5976   l_err_num := 0;
5977   l_err_code := '';
5978   l_err_msg := '';
5979   IF g_debug = 'Y' THEN
5980     fnd_file.put_line(fnd_file.log, '>>>>Inside Get_Snd_Rcv_UOM');
5981   END IF;
5982 
5983   l_stmt_num := 10;
5984 
5985   select primary_uom_code
5986   into o_snd_uom
5987   from mtl_system_items
5988   where organization_id = i_from_org
5989   and inventory_item_id = i_item_id;
5990 
5991   l_stmt_num := 20;
5992 
5993   select primary_uom_code
5994   into o_rcv_uom
5995   from mtl_system_items
5996   where organization_id = i_to_org
5997   and inventory_item_id = i_item_id;
5998 
5999 /*  IF g_debug = 'Y' THEN
6000     fnd_file.put_line(fnd_file.log, 'Get_Snd_Rcv_UOM >>>');
6001   END IF; */
6002 
6003   EXCEPTION
6004     when others then
6005       rollback;
6006       o_err_num := SQLCODE;
6007       o_err_msg := 'CSTPAVCP.get_snd_rcv_uom (' || to_char(l_stmt_num) ||
6008                    '): '
6009                    || substr(SQLERRM, 1,200);
6010 
6011 END get_snd_rcv_uom;
6012 
6013 FUNCTION standard_cost_org(
6014   I_ORG_ID      IN        NUMBER
6015 ) RETURN INTEGER IS
6016   l_ret_val     NUMBER;
6017 BEGIN
6018   select decode(primary_cost_method,1,1,0)
6019   into l_ret_val
6020   from mtl_parameters
6021   where organization_id = i_org_id;
6022 
6023   return l_ret_val;
6024 END standard_cost_org;
6025 
6026 PROCEDURE borrow_cost(
6027   I_ORG_ID      IN        NUMBER,
6028   I_TXN_ID      IN        NUMBER,
6029   I_USER_ID     IN        NUMBER,
6030   I_LOGIN_ID    IN        NUMBER,
6031   I_REQ_ID      IN        NUMBER,
6032   I_PRG_APPL_ID IN        NUMBER,
6033   I_PRG_ID      IN        NUMBER,
6034   I_ITEM_ID     IN        NUMBER,
6035   I_HOOK        IN        NUMBER,
6036   I_TO_LAYER    IN        NUMBER,
6037   O_Err_Num     OUT NOCOPY        NUMBER,
6038   O_Err_Code    OUT NOCOPY        VARCHAR2,
6039   O_Err_Msg     OUT NOCOPY        VARCHAR2
6040 )IS
6041 -- the borrow_cost procedure is to find out the
6042 -- average borrowed cost of several borrow transactions
6043 -- and store it in MCTCD.
6044 -- If hook is used, it'll update MCACD with the correct
6045 -- payback cost other than the hook cost.
6046 
6047 -- this cursor is to find out all the related
6048 -- borrow transactions for a specific payback
6049 -- transaction
6050 cursor c_payback_txn(c_cur_txn_id number) is
6051        select pbp.borrow_transaction_id,
6052               pbp.payback_quantity
6053          from pjm_borrow_paybacks pbp
6054          where pbp.payback_transaction_id = c_cur_txn_id;
6055 
6056 -- this cursor is to find out all the mcacd data
6057 -- for a specific transaction_id
6058 cursor c_mcacd_data (c_transaction_id number)is
6059      select mcacd.transaction_id,
6060             mcacd.cost_element_id,
6061             mcacd.level_type,
6062             mcacd.inventory_item_id,
6063             mcacd.actual_cost,
6064             mcacd.prior_cost,
6065             mcacd.new_cost,
6066             mcacd.layer_id
6067        from mtl_cst_actual_cost_details mcacd
6068        where mcacd.transaction_id = c_transaction_id
6069        and mcacd.layer_id = i_to_layer;
6070 
6071   type t_cst_element is table of number
6072         index by binary_integer;
6073 
6074   l_temp_element_cost t_cst_element;
6075   l_level_type          NUMBER;
6076   l_total_bp_qty        NUMBER;
6077   l_err_num             NUMBER;
6078   l_err_code            VARCHAR2(240);
6079   l_err_msg             VARCHAR2(240);
6080   l_stmt_num            NUMBER;
6081   l_cost_element        t_cst_element;
6082   l_count               NUMBER;
6083 
6084 BEGIN
6085   -- initialize local variables
6086   l_err_num := 0;
6087   l_err_code := '';
6088   l_err_msg := '';
6089 
6090   IF g_debug = 'Y' THEN
6091     fnd_file.put_line(fnd_file.log, 'Borrow_Cost <<<');
6092   END IF;
6093   l_stmt_num := 10;
6094 
6095 -- initialize array with 0
6096 
6097    for l_index_counter in 1..10 loop
6098       l_temp_element_cost(l_index_counter):=0;
6099       if (l_index_counter <= 5) then
6100         l_cost_element(l_index_counter) := 0;
6101       end if;
6102    end loop;
6103 
6104 -- loop through all the payaback txn to find the borrowing cost
6105 -- from MCACD and sum it up.
6106    l_total_bp_qty := 0;
6107       for c_payback_rec in c_payback_txn(i_txn_id) loop
6108          for c_mcacd_rec in c_mcacd_data(c_payback_rec.borrow_transaction_id) LOOP
6109             if c_mcacd_rec.level_type =1 then
6110                l_temp_element_cost(c_mcacd_rec.cost_element_id):=
6111                l_temp_element_cost(c_mcacd_rec.cost_element_id) +
6112                c_mcacd_rec.actual_cost * abs(c_payback_rec.payback_quantity);
6113             elsif c_mcacd_rec.level_type = 2 then
6114                l_temp_element_cost(c_mcacd_rec.cost_element_id + 5):=
6115                l_temp_element_cost(c_mcacd_rec.cost_element_id + 5) +
6116                c_mcacd_rec.actual_cost * abs(c_payback_rec.payback_quantity);
6117             end if;
6118             if c_mcacd_rec.cost_element_id = 1 then
6119                 l_cost_element(1) :=1;
6120             elsif c_mcacd_rec.cost_element_id = 2 then
6121                 l_cost_element(2) :=2;
6122             elsif c_mcacd_rec.cost_element_id = 3 then
6123                 l_cost_element(3) :=3;
6124             elsif c_mcacd_rec.cost_element_id = 4 then
6125                 l_cost_element(4) :=4;
6126             elsif c_mcacd_rec.cost_element_id = 5 then
6127                 l_cost_element(5) :=5;
6128             End if;
6129          END LOOP; -- end looping c_mcacd_rec
6130          l_total_bp_qty := l_total_bp_qty + abs(c_payback_rec.payback_quantity);
6131       END LOOP; -- end looping c_payback_rec
6132 
6133 -- do a division here to find out the average cost
6134       for l_index_counter in 1..10 loop
6135          l_temp_element_cost(l_index_counter):=l_temp_element_cost(l_index_counter) / l_total_bp_qty;
6136       end loop;
6137 
6138 ------- populate MCTCD from here
6139       for l_index_counter in 1..10 loop
6140          if l_index_counter < 6 then
6141             l_level_type := 1;
6142          else
6143             l_level_type := 2;
6144          end if;
6145 --  populate mctcd
6146          if (i_hook = 0) then  -- if no hook is used then pouplate mctcd
6147             if l_temp_element_cost(l_index_counter) <> 0 then -- if element cost is not 0 then insert into MCTCD
6148                l_stmt_num := 20;
6149                insert into mtl_cst_txn_cost_details(
6150                             TRANSACTION_ID,
6151                             ORGANIZATION_ID,
6152                             COST_ELEMENT_ID,
6153                             LEVEL_TYPE,
6154                             LAST_UPDATE_DATE,
6155                             LAST_UPDATED_BY,
6156                             CREATION_DATE,
6157                             CREATED_BY,
6158                             LAST_UPDATE_LOGIN,
6159                             REQUEST_ID,
6160                             PROGRAM_APPLICATION_ID,
6161                             PROGRAM_ID,
6162                             PROGRAM_UPDATE_DATE,
6163                             INVENTORY_ITEM_ID,
6164                             TRANSACTION_COST)
6165                values(
6166                             i_txn_id,
6167                             i_org_id,
6168                             decode(mod(l_index_counter,5),0,5,mod(l_index_counter,5)),
6169                             l_level_type,
6170                             sysdate,
6171                             i_user_id,
6172                             sysdate,
6173                             i_user_id,
6174                             i_login_id,
6175                             i_req_id,
6176                             i_prg_appl_id,
6177                             i_prg_id,
6178                             sysdate,
6179                             i_item_id,
6180                             l_temp_element_cost(l_index_counter));
6181             end if;
6182              if l_index_counter = 5 then
6183                  l_count :=0;
6184                  Select count(*) into l_count
6185                  from mtl_cst_txn_cost_details
6186                  where transaction_id = i_txn_id;
6187 
6188                  if (l_count = 0) then
6189                     for i in 1..5 loop
6190                       if (l_cost_element(i) <> 0) then
6191                        /* Insert int MCTCD only if cost element exists in MCACD with zero transaction cost */
6192                         insert into mtl_cst_txn_cost_details(
6193                                TRANSACTION_ID,
6194                                ORGANIZATION_ID,
6195                                COST_ELEMENT_ID,
6196                                LEVEL_TYPE,
6197                                LAST_UPDATE_DATE,
6198                                LAST_UPDATED_BY,
6199                                CREATION_DATE,
6200                                CREATED_BY,
6201                                LAST_UPDATE_LOGIN,
6202                                REQUEST_ID,
6203                                PROGRAM_APPLICATION_ID,
6204                                PROGRAM_ID,
6205                                PROGRAM_UPDATE_DATE,
6206                                INVENTORY_ITEM_ID,
6207                                TRANSACTION_COST)
6208                         values(
6209                                i_txn_id,
6210                                i_org_id,
6211                                l_cost_element(i),
6212                                l_level_type,
6213                                sysdate,
6214                                i_user_id,
6215                                sysdate,
6216                                i_user_id,
6217                                i_login_id,
6218                                i_req_id,
6219                                i_prg_appl_id,
6220                                i_prg_id,
6221                                sysdate,
6222                                i_item_id,
6223                                0);
6224                        End if;
6225                     End loop;
6226                  End if;
6227               End if;
6228 
6229          else -- if hook is used
6230             l_stmt_num := 30;
6231             if l_temp_element_cost(l_index_counter) <> 0 then -- if element cost <>0 then insert update MCACD
6232                update mtl_cst_actual_cost_details mcacd
6233                   set mcacd.actual_cost = l_temp_element_cost(l_index_counter)
6234                   where mcacd.transaction_id = i_txn_id
6235                   and mcacd.cost_element_id = decode(mod(l_index_counter,5),0,5,mod(l_index_counter,5))
6236                   and mcacd.level_type = l_level_type
6237                   and mcacd.layer_id = i_to_layer;
6238             else -- if the element cost == 0 then we need to delete MCACD.
6239                delete from mtl_cst_actual_cost_details mcacd
6240                 where mcacd.transaction_id = i_txn_id
6241                 and mcacd.cost_element_id = decode(mod(l_index_counter,5),0,5,mod(l_index_counter,5))
6242                 and mcacd.level_type = l_level_type
6243                 and mcacd.layer_id = i_to_layer;
6244             end if;
6245 
6246          end if; -- end checking hook
6247       end loop;  -- end for looping 10 elements
6248   IF g_debug = 'Y' THEN
6249     fnd_file.put_line(fnd_file.log, 'Borrow_Cost >>>');
6250   END IF;
6251   EXCEPTION
6252     when others then
6253       rollback;
6254       o_err_num := SQLCODE;
6255       o_err_msg := 'CSTPAVCP.borrow_cost (' || to_char(l_stmt_num) ||
6256                    '): '
6257                    || substr(SQLERRM, 1,200);
6258 
6259 
6260 END borrow_cost;
6261 
6262 
6263 PROCEDURE store_bp_variance(
6264   I_TXN_ID              IN        NUMBER,
6265   I_FROM_LAYER_ID       IN        NUMBER,
6266   I_TO_LAYER_ID         IN      NUMBER,
6267   O_Err_Num     OUT NOCOPY        NUMBER,
6268   O_Err_Code    OUT NOCOPY        VARCHAR2,
6269   O_Err_Msg     OUT NOCOPY        VARCHAR2
6270 )IS
6271   l_err_num             NUMBER;
6272   l_err_code            VARCHAR2(240);
6273   l_err_msg             VARCHAR2(240);
6274   l_stmt_num            NUMBER;
6275   L_CUR_COST            NUMBER;
6276   L_BORROWED_COST       NUMBER;
6277   L_VARIANCE            NUMBER;
6278 
6279 -- the store_bp_variance procedure figure out the
6280 -- variance between the borrowed cost and payback cost
6281 -- by checking the from layer and the to layer
6282 -- from MCACD and store the variance
6283 -- into the from layer's MCACD.
6284 
6285 BEGIN
6286   -- initialize local variables
6287   l_err_num := 0;
6288   l_err_code := '';
6289   l_err_msg := '';
6290 
6291   IF g_debug = 'Y' THEN
6292     fnd_file.put_line(fnd_file.log, 'Store_BP_Variance <<<');
6293   END IF;
6294 
6295 
6296 
6297    for l_level_type in 1..2 loop
6298       for l_ce in 1..5 loop
6299          l_stmt_num := 10;
6300          select max(mcacd.actual_cost)
6301            into l_cur_cost
6302            from mtl_cst_actual_cost_details mcacd
6303            where mcacd.level_type = l_level_type
6304            and mcacd.cost_element_id = l_ce
6305            and mcacd.transaction_id = i_txn_id
6306            and mcacd.layer_id = i_from_layer_id;
6307          l_stmt_num := 20;
6308          select max(mcacd.actual_cost)
6309            into l_borrowed_cost
6310            from mtl_cst_actual_cost_details mcacd
6311            where mcacd.level_type = l_level_type
6312            and mcacd.cost_element_id = l_ce
6313            and mcacd.transaction_id = i_txn_id
6314            and mcacd.layer_id = i_to_layer_id;
6315 
6316             l_variance := nvl(l_cur_cost,0) - nvl(l_borrowed_cost,0);
6317 
6318 -- update the variance_amount in MCACD for the from layer.
6319          l_stmt_num := 30;
6320          update mtl_cst_actual_cost_details mcacd
6321             set mcacd.payback_variance_amount = l_variance
6322             where mcacd.transaction_id = i_txn_id
6323             and mcacd.cost_element_id = l_ce
6324             and mcacd.level_type = l_level_type
6325             and mcacd.layer_id = i_from_layer_id;
6326 
6327       end loop; -- end cost element
6328    end loop; -- end level_type loop
6329   IF g_debug = 'Y' THEN
6330     fnd_file.put_line(fnd_file.log, 'Store_BP_Variance >>>');
6331   END IF;
6332   EXCEPTION
6333     when others then
6334       rollback;
6335       o_err_num := SQLCODE;
6336       o_err_msg := 'CSTPAVCP.store_bp_variance (' || to_char(l_stmt_num) ||
6337                    '): '
6338                    || substr(SQLERRM, 1,200);
6339 
6340 END store_bp_variance;
6341 
6342 PROCEDURE interorg_elemental_detail(
6343   i_txn_id              IN NUMBER,
6344   i_compute_txn_cost    IN NUMBER,
6345   i_cost_type_id        IN NUMBER,
6346   i_from_layer_id       IN NUMBER,
6347   i_item_id             IN NUMBER,
6348   i_txn_update_id       IN NUMBER,
6349   i_from_org            IN NUMBER,
6350   i_to_org              IN NUMBER,
6351   i_snd_qty             IN NUMBER,
6352   i_txfr_cost           IN NUMBER,
6353   i_trans_cost          IN NUMBER,
6354   i_conv_rate           IN NUMBER,
6355   i_um_rate             IN NUMBER,
6356   i_user_id             IN NUMBER,
6357   i_login_id            IN NUMBER,
6358   i_req_id              IN NUMBER,
6359   i_prg_appl_id         IN NUMBER,
6360   i_prg_id              IN NUMBER,
6361   i_hook_used           IN NUMBER := 0,
6362   o_err_num             OUT NOCOPY NUMBER,
6363   o_err_code            OUT NOCOPY VARCHAR2,
6364   o_err_msg             OUT NOCOPY VARCHAR2)
6365 IS
6366   l_err_num     NUMBER;
6367   l_err_code    VARCHAR2(240);
6368   l_err_msg     VARCHAR2(240);
6369   l_stmt_num    NUMBER;
6370   process_error EXCEPTION;
6371 
6372   l_movh_cnt    NUMBER;
6373   l_rcv_movh    NUMBER;
6374   l_rcv_qty     NUMBER;
6375   l_trp_trf     NUMBER;
6376   l_from_cost_org  NUMBER; /* bugfix 3048258 */
6377 BEGIN
6378 
6379   IF g_debug = 'Y' THEN
6380     fnd_file.put_line(fnd_file.log, '>>>>Inside Interorg_Elemental_Detail');
6381   END IF;
6382   -- Insert detail elemental cost into mctcd.
6383   -- Based on the from_org :
6384   -- * If from_org is a standard org (l_compute_txn_cost=1),
6385   --   insert detail cost from cicd
6386   -- * If from_org is an avg org (l_compute_txn_cost=2),
6387   --   insert detail cost from clcd
6388   -- Need to convert the cost into the receiving org cost in receiving org
6389   -- currenct and UOM.
6390   -- Suppose that : * This level material in from org is 12 USD with UOM of DZ.
6391   --                * Receiving org is in SGD and UOM of EA
6392   --                * i_conv_rate = 2 (from USD to SGD),
6393   --                * i_um_rate = 12 (from DZ to EA).
6394   --                * In the mctcd of receiving org, we insert :
6395   --                  this level material cost as : 12 * 2 / 12 = 2 SGD/EA
6396   if (i_compute_txn_cost = 1) then
6397     l_stmt_num := 10;
6398 
6399   IF g_debug = 'Y' THEN
6400     fnd_file.put_line(fnd_file.log, '>>>>From organization is a standard org');
6401   END IF;
6402 
6403     /* Added for bugfix 3048258 */
6404     select cost_organization_id
6405       into l_from_cost_org
6406       from mtl_parameters
6407      where organization_id = i_from_org;
6408 
6409     insert into mtl_cst_txn_cost_details (
6410       transaction_id,
6411       organization_id,
6412       cost_element_id,
6413       level_type,
6414       last_update_date,
6415       last_updated_by,
6416       creation_date,
6417       created_by,
6418       last_update_login,
6419       request_id,
6420       program_application_id,
6421       program_id,
6422       program_update_date,
6423       inventory_item_id,
6424       transaction_cost,
6425       new_average_cost,
6426       percentage_change,
6427       value_change)
6428     select
6429       i_txn_update_id,
6430       i_to_org,
6431       cost_element_id,
6432       level_type,
6433       sysdate,
6434       i_user_id,
6435       sysdate,
6436       i_user_id,
6437       i_login_id,
6438       i_req_id,
6439       i_prg_appl_id,
6440       i_prg_id,
6441       sysdate,
6442       i_item_id,
6443       sum(item_cost)*i_conv_rate/i_um_rate,
6444       0,
6445       0,
6446       0
6447     from cst_item_cost_details cicd
6448     where cicd.cost_type_id = i_cost_type_id
6449       and cicd.inventory_item_id = i_item_id
6450       /* and cicd.organization_id = i_from_org : bugfix 3048258 */
6451       and cicd.organization_id = l_from_cost_org
6452     group by cicd.cost_element_id,cicd.level_type;
6453 
6454   else
6455 
6456     l_stmt_num := 20;
6457         IF (i_hook_used = 0) THEN
6458                 insert into mtl_cst_txn_cost_details (
6459                 transaction_id,
6460                 organization_id,
6461                 cost_element_id,
6462                 level_type,
6463                 last_update_date,
6464                 last_updated_by,
6465                 creation_date,
6466                 created_by,
6467                 last_update_login,
6468                 request_id,
6469                 program_application_id,
6470                 program_id,
6471                 program_update_date,
6472                 inventory_item_id,
6473                 transaction_cost,
6474                 new_average_cost,
6475                 percentage_change,
6476                 value_change)
6477                 select
6478                 i_txn_update_id,
6479                 i_to_org,
6480                 cost_element_id,
6481                 level_type,
6482                 sysdate,
6483                 i_user_id,
6484                 sysdate,
6485                 i_user_id,
6486                 i_login_id,
6487                 i_req_id,
6488                 i_prg_appl_id,
6489                 i_prg_id,
6490                 sysdate,
6491                 i_item_id,
6492                 clcd.item_cost*i_conv_rate/i_um_rate,
6493                 0,
6494                 0,
6495                 0
6496                 from cst_layer_cost_details clcd
6497                 where clcd.layer_id = i_from_layer_id;
6498         ELSE
6499                 IF g_debug = 'Y' THEN
6500                         fnd_file.put_line(fnd_file.log, '>>>>Hook has been used, inserting in MCTCD from MCACD');
6501                 END IF;
6502                 insert into mtl_cst_txn_cost_details (
6503                 transaction_id,
6504                 organization_id,
6505                 cost_element_id,
6506                 level_type,
6507                 last_update_date,
6508                 last_updated_by,
6509                 creation_date,
6510                 created_by,
6511                 last_update_login,
6512                 request_id,
6513                 program_application_id,
6514                 program_id,
6515                 program_update_date,
6516                 inventory_item_id,
6517                 transaction_cost,
6518                 new_average_cost,
6519                 percentage_change,
6520                 value_change)
6521                 select
6522                 i_txn_update_id,
6523                 i_to_org,
6524                 cost_element_id,
6525                 level_type,
6526                 sysdate,
6527                 i_user_id,
6528                 sysdate,
6529                 i_user_id,
6530                 i_login_id,
6531                 i_req_id,
6532                 i_prg_appl_id,
6533                 i_prg_id,
6534                 sysdate,
6535                 i_item_id,
6536                 mcacd.actual_cost*i_conv_rate/i_um_rate,
6537                 0,
6538                 0,
6539                 0
6540                 from mtl_cst_actual_cost_details mcacd
6541                 where mcacd.layer_id = i_from_layer_id
6542                 and mcacd.transaction_id = i_txn_id;
6543         END IF;
6544 
6545   end if;
6546 
6547 --bug 4210943 - insert a dummy mctcd record for the transaction if there is no cost defined for the item in the sending org
6548   if SQL%ROWCOUNT = 0 then
6549         l_stmt_num := 25;
6550         insert into mtl_cst_txn_cost_details (
6551               transaction_id,
6552               organization_id,
6553               cost_element_id,
6554               level_type,
6555               last_update_date,
6556               last_updated_by,
6557               creation_date,
6558               created_by,
6559               last_update_login,
6560               request_id,
6561               program_application_id,
6562               program_id,
6563               program_update_date,
6564               inventory_item_id,
6565               transaction_cost,
6566               new_average_cost,
6567               percentage_change,
6568               value_change)
6569           values (
6570               i_txn_update_id,
6571               i_to_org,
6572               1,
6573               1,
6574               sysdate,
6575               i_user_id,
6576               sysdate,
6577               i_user_id,
6578               i_login_id,
6579               i_req_id,
6580               i_prg_appl_id,
6581               i_prg_id,
6582               sysdate,
6583               i_item_id,
6584               0,
6585               0,
6586               0,
6587               0);
6588   end if;
6589 
6590   l_stmt_num := 30;
6591   -- Find out if there is already exist this level material overhead in mctcd.
6592   select count(*)
6593   into l_movh_cnt
6594   from mtl_cst_txn_cost_details mctcd
6595   where mctcd.transaction_id = i_txn_update_id
6596     and mctcd.organization_id = i_to_org
6597     and mctcd.inventory_item_id = i_item_id
6598     and mctcd.level_type = 1
6599     and mctcd.cost_element_id = 2;
6600 
6601   if (l_movh_cnt > 0) then
6602     l_stmt_num := 40;
6603     select NVL(mctcd.transaction_cost,0)
6604     into l_rcv_movh
6605     from mtl_cst_txn_cost_details mctcd
6606     where mctcd.transaction_id = i_txn_update_id
6607       and mctcd.organization_id = i_to_org
6608       and mctcd.inventory_item_id = i_item_id
6609       and mctcd.level_type = 1
6610       and mctcd.cost_element_id = 2;
6611   else
6612     l_rcv_movh := 0;
6613   end if;
6614 
6615   -- Convert the i_snd_qty in the receiving org UOM
6616   l_rcv_qty := abs(i_snd_qty) * i_um_rate;
6617 
6618     -- The transportation and transfer cost is a total cost in sending currency.
6619     -- Thus we need to convert it to recv currency.
6620   /* change for bug 2827548 - currency conversion moved outside of this function */
6621   l_trp_trf := (i_txfr_cost+i_trans_cost);
6622 
6623   -- Add in the trp and trf cost as the this level material overhead
6624   l_rcv_movh := (l_rcv_movh*l_rcv_qty + l_trp_trf)/l_rcv_qty;
6625 
6626   -- The new material overhead (l_rcv_movh) includes :
6627   -- * This level material overhead of the sending org item cost,
6628   -- * Transportation and transfer cost
6629   -- The new material overhead cost has been converted into recv org currency
6630   -- and UOM.
6631   -- If there already exist movh in mctcd, then update mctcd with new movhd
6632   -- value. Otherwise insert the new movhd into mctcd
6633   if (l_movh_cnt > 0) then
6634     l_stmt_num := 50;
6635     update mtl_cst_txn_cost_details mctcd
6636     set mctcd.transaction_cost = l_rcv_movh
6637     where mctcd.transaction_id = i_txn_update_id
6638       and mctcd.organization_id = i_to_org
6639       and mctcd.inventory_item_id = i_item_id
6640       and mctcd.level_type = 1
6641       and mctcd.cost_element_id = 2;
6642   elsif (l_rcv_movh > 0) then
6643     l_stmt_num := 60;
6644     insert into mtl_cst_txn_cost_details (
6645       transaction_id,
6646       organization_id,
6647       cost_element_id,
6648       level_type,
6649       last_update_date,
6650       last_updated_by,
6651       creation_date,
6652       created_by,
6653       last_update_login,
6654       request_id,
6655       program_application_id,
6656       program_id,
6657       program_update_date,
6658       inventory_item_id,
6659       transaction_cost,
6660       new_average_cost,
6661       percentage_change,
6662       value_change)
6663     values (
6664       i_txn_update_id,
6665       i_to_org,
6666       2,
6667       1,
6668       sysdate,
6669       i_user_id,
6670       sysdate,
6671       i_user_id,
6672       i_login_id,
6673       i_req_id,
6674       i_prg_appl_id,
6675       i_prg_id,
6676       sysdate,
6677       i_item_id,
6678       l_rcv_movh,
6679       0,
6680       0,
6681       0);
6682   end if;
6683 
6684   IF g_debug = 'Y' THEN
6685     fnd_file.put_line(fnd_file.log, 'Interorg_Elemental_Detail >>>');
6686   END IF;
6687   EXCEPTION
6688     when process_error then
6689       o_err_num := l_err_num;
6690       o_err_code := l_err_code;
6691       o_err_msg := l_err_msg;
6692     when others then
6693       rollback;
6694       o_err_num := SQLCODE;
6695       o_err_msg := 'CSTPAVCP.interorg_elemental_detail (' || to_char(l_stmt_num)
6696                    || '): ' || substr(SQLERRM, 1,200);
6697 
6698 
6699 END interorg_elemental_detail;
6700 
6701 --------------------------------------------------------------------------
6702 -- PROCEDURE                                                              --
6703 --   Cost_Acct_Events                                                     --
6704 --                                                                        --
6705 --                                                                        --
6706 -- DESCRIPTION                                                            --
6707 --   This API costs logical events that are created as part of Global     --
6708 --   Procurement or Drop Shipment Transactions. These events are known by --
6709 --   non-null parent_id.                                                  --
6710 --   The consigned price update transcation, introduced as part of        --
6711 --   Retroactive Pricing Project is also cost processed using this API.   --
6712 --   This transaction does not have a parent_id.                          --
6713 --                                                                        --
6714 --   This API is common between all cost methods to process Accounting    --
6715 --   Events and the Retroactive Price Update transaction.                 --
6716 
6717 --   It is called from inltcp.lpc for Std. Costing and from actual and    --
6718 --   layer cost workers for Average Costing and FIDO/LIFO orgs            --
6719 --   respectively.                                                        --
6720 -- PURPOSE:                                                               --
6721 --   Oracle Applications Rel 11i.10                                       --
6722 --                                                                        --
6723 --                                                                        --
6724 -- HISTORY:                                                               --
6725 --    06/22/03     Anju G       Created                                   --
6726 ----------------------------------------------------------------------------
6727 
6728 PROCEDURE Cost_Acct_Events (
6729                      p_api_version      IN  NUMBER,
6730                      /*p_init_msg_list    IN  VARCHAR2 := FND_API.G_FALSE,*/
6731                      p_commit           IN  VARCHAR2 := FND_API.G_FALSE,
6732                      p_validation_level IN  NUMBER   := FND_API.G_VALID_LEVEL_FULL,
6733                      p_debug            IN  VARCHAR2 ,
6734 
6735                      p_org_id           IN  NUMBER,
6736                      p_txn_id           IN  NUMBER,
6737                      p_parent_id        IN  NUMBER,
6738 
6739                      p_user_id          IN  NUMBER,
6740                      p_request_id       IN  NUMBER,
6741                      p_prog_id          IN  NUMBER,
6742                      p_prog_app_id      IN  NUMBER,
6743                      p_login_id         IN  NUMBER,
6744 
6745                      x_err_num          OUT NOCOPY VARCHAR2,
6746                      x_err_code         OUT NOCOPY VARCHAR2,
6747                      x_err_msg          OUT NOCOPY VARCHAR2) IS
6748 
6749  l_api_name    CONSTANT       VARCHAR2(30) := 'Cost_Acct_Events';
6750  l_api_version CONSTANT       NUMBER       := 1.0;
6751 
6752  l_msg_count                 NUMBER := 0;
6753  l_msg_data                  VARCHAR2(8000);
6754 
6755  l_exp_item                  NUMBER   := 0; --0 = asset item
6756  l_exp_flag                  NUMBER   := 0;
6757  l_parent_organization_id    NUMBER   := NULL;
6758  l_parent_transaction_type   NUMBER;
6759  l_log_in_phy                NUMBER   := 0;
6760  l_mctcd_count               NUMBER   := 0;
6761 
6762  l_stmt_num                  NUMBER   := 0;
6763  l_api_message               VARCHAR2(10000);
6764  l_layer_id                  NUMBER   := -1;
6765  l_error_num                 NUMBER   := 0;
6766  l_err_code                  VARCHAR2(240);
6767  l_err_msg                   VARCHAR2(240);
6768 
6769  l_trx_info                CST_XLA_PVT.t_xla_inv_trx_info;
6770  l_return_status           varchar2(1);
6771 
6772 
6773  CURSOR c_mmt_txns IS
6774     SELECT mmt.TRANSACTION_ID "TRANSACTION_ID",
6775            mmt.PRIMARY_QUANTITY "PRIMARY_QUANTITY",
6776            mmt.TRANSACTION_TYPE_ID "TRANSACTION_TYPE_ID",
6777            mmt.TRANSACTION_ACTION_ID "TRANSACTION_ACTION_ID",
6778            mmt.TRANSACTION_SOURCE_TYPE_ID "TRANSACTION_SOURCE_TYPE_ID",
6779            mmt.ORGANIZATION_ID "ORGANIZATION_ID",
6780            mmt.TRANSFER_ORGANIZATION_ID "TRANSFER_ORGANIZATION_ID",
6781            mmt.TRANSACTION_DATE "TRANSACTION_DATE",
6782            mmt.INVENTORY_ITEM_ID "INVENTORY_ITEM_ID",
6783            mmt.SUBINVENTORY_CODE "SUBINVENTORY_CODE",
6784            NVL(mmt.TRANSFER_COST_GROUP_ID,-1) "TRANSFER_COST_GROUP_ID",
6785            NVL(mmt.COST_GROUP_ID,mp.DEFAULT_COST_GROUP_ID) "COST_GROUP_ID",
6786            mmt.COSTED_FLAG "COSTED_FLAG",
6787            mmt.ACCT_PERIOD_ID "ACCT_PERIOD_ID",
6788            NVL(mmt.PARENT_TRANSACTION_ID, mmt.transaction_id) "PARENT_ID",
6789            mmt.transaction_quantity "TRANSACTION_QUANTITY",
6790            NVL(mmt.LOGICAL_TRX_TYPE_CODE, -1) "DROP_SHIP_FLAG",
6791            NVL(mmt.logical_transaction, 3) "LOGICAL_TRANSACTION",
6792            mp.primary_cost_method "PRIMARY_COST_METHOD",
6793            mp.cost_organization_id "COST_ORGANIZATION_ID",
6794            NVL(mmt.DISTRIBUTION_ACCOUNT_ID, -1) "DISTRIBUTION_ACCOUNT_ID",
6795            mp.primary_cost_method "COST_TYPE_ID", /* For use as cost_type_id */
6796            NVL(mp.AVG_RATES_COST_TYPE_ID, -1) "AVG_RATES_COST_TYPE_ID",
6797            decode(msi.INVENTORY_ASSET_FLAG,'Y',0,1) "EXP_ITEM"
6798     FROM   mtl_material_transactions mmt,
6799            mtl_parameters mp,
6800            mtl_system_items_b msi
6801     WHERE  mmt.organization_id = mp.organization_id
6802     AND    mmt.inventory_item_id = msi.inventory_item_id
6803     AND    mmt.organization_id = msi.organization_id
6804     AND    (( p_parent_id is not null and
6805                     mmt.parent_transaction_id = p_parent_id)
6806             or (p_parent_id is null and p_txn_id is not null and
6807                 mmt.transaction_id = p_txn_id))
6808     ORDER BY mmt.transaction_id;
6809 
6810     BEGIN
6811     IF g_debug = 'Y' THEN
6812       fnd_file.put_line(fnd_file.log, 'Cost_Acct_Events <<<');
6813     END IF;
6814 
6815     -------------------------------------------------------------------------
6816     -- Establish savepoint
6817     -------------------------------------------------------------------------
6818 
6819     SAVEPOINT Cost_Acct_Events;
6820 
6821     -------------------------------------------------------------------------
6822     -- standard call to check for call compatibility
6823     -------------------------------------------------------------------------
6824     IF NOT fnd_api.compatible_api_call (
6825                               l_api_version,
6826                               p_api_version,
6827                               l_api_name,
6828                               G_PKG_NAME ) then
6829 
6830          RAISE fnd_api.g_exc_unexpected_error;
6831 
6832     END IF;
6833 
6834     -------------------------------------------------------------------------
6835     -- initialize api return status to success
6836     -------------------------------------------------------------------------
6837     x_err_num := 0;
6838 
6839     l_stmt_num := 10;
6840 
6841     -------------------------------------------------------------------------
6842     -- parent_id or txn_id should be non-null
6843     -------------------------------------------------------------------------
6844 
6845     if (p_parent_id is NULL and p_txn_id is NULL) then
6846         x_err_msg := 'Parent and Transaction Id are both null';
6847 
6848         RAISE FND_API.g_exc_error;
6849 
6850     end if;
6851 
6852     -------------------------------------------------------------------------
6853     -- Open cursor to get all transactions to be cost processed
6854     -------------------------------------------------------------------------
6855 
6856     FOR c_mmt_txn_rec IN c_mmt_txns LOOP
6857       l_layer_id := -1; -- Initialize layer ID
6858 
6859       l_stmt_num := 15;
6860     -------------------------------------------------------------------------
6861     -- Validate record details so far
6862     -------------------------------------------------------------------------
6863 
6864       if (c_mmt_txn_rec.distribution_account_id is NULL) then
6865         l_err_msg := 'No Account exists for txn: ' || c_mmt_txn_rec.transaction_id;
6866         RAISE FND_API.g_exc_error;
6867       end if;
6868 
6869       /* If a physical transaction, then it should be the parent */
6870 
6871       if (c_mmt_txn_rec.logical_transaction <> 1 and c_mmt_txn_rec.transaction_type_id <> 20 and
6872           nvl(c_mmt_txn_rec.parent_id, -1) <> c_mmt_txn_rec.transaction_id) then
6873         l_err_msg := 'Physical Transaction' ||
6874                         c_mmt_txn_rec.transaction_id || 'should be the parent';
6875 
6876         RAISE FND_API.g_exc_error;
6877       end if;
6878 
6879 
6880     -------------------------------------------------------------------------
6881     -- Figure out if an expense item
6882     -- Figure out if expense subinventory
6883     -------------------------------------------------------------------------
6884       l_stmt_num := 17;
6885       SELECT decode(INVENTORY_ASSET_FLAG,'Y',0,1)
6886         INTO   l_exp_item
6887       FROM   MTL_SYSTEM_ITEMS
6888       WHERE  INVENTORY_ITEM_ID = c_mmt_txn_rec.inventory_item_id
6889       AND    ORGANIZATION_ID = c_mmt_txn_rec.organization_id;
6890 
6891       if (c_mmt_txn_rec.subinventory_code is null) then
6892         l_exp_flag := l_exp_item;
6893         l_stmt_num := 20;
6894       else
6895         l_stmt_num := 25;
6896         SELECT decode(l_exp_item,1,1,decode(ASSET_INVENTORY,1,0,1))
6897         INTO   l_exp_flag
6898         FROM   MTL_SECONDARY_INVENTORIES
6899         WHERE  SECONDARY_INVENTORY_NAME = c_mmt_txn_rec.subinventory_code
6900         AND    ORGANIZATION_ID = c_mmt_txn_rec.organization_id;
6901       end if;
6902 
6903       l_stmt_num := 30;
6904 
6905     -------------------------------------------------------------------------
6906     -- Determine parent organization
6907     -- Determine type of parent
6908     -- Determine if this is a logical transaction in the physical organization
6909     -------------------------------------------------------------------------
6910       if (p_parent_id = c_mmt_txn_rec.transaction_id OR c_mmt_txn_rec.transaction_type_id = 20) then
6911         l_parent_organization_id := c_mmt_txn_rec.organization_id;
6912         if (c_mmt_txn_rec.logical_transaction <> 1) then
6913           l_parent_transaction_type := 1; -- physical transaction
6914         end if;
6915       else
6916         select organization_id, decode(nvl(logical_transaction, 2), 1, 0, 1)
6917         into l_parent_organization_id, l_parent_transaction_type
6918         from mtl_material_transactions
6919         where transaction_id = p_parent_id;
6920       end if;
6921 
6922       if (c_mmt_txn_rec.organization_id = l_parent_organization_id and
6923         c_mmt_txn_rec.logical_transaction = 1 and
6924         l_parent_transaction_type = 1) then
6925         l_log_in_phy := 1;
6926       else
6927         l_log_in_phy := 0;
6928       end if;
6929 
6930       if (g_debug = 'Y') then
6931         fnd_file.put_line (fnd_file.log, 'Parent transaction Type (1-physical, 2-logical):' || l_parent_transaction_type);
6932         fnd_file.put_line (fnd_file.log, 'Logical transaction in physical org (0-no 1=yes):' || l_log_in_phy );
6933       end if;
6934 
6935       l_stmt_num := 35;
6936 
6937     -------------------------------------------------------------------------
6938     --Populate MCACD
6939     --If MCTCD exists use that
6940     --If it is a logical transaction in the physical org (this case is possible
6941     --only for shipment flows) then call procedure compute_mcacd_costs to
6942     --populate mcacd
6943     --Ensure that MCACD is not created for SO Issue and RMA OF EXPENSE ITEMS!????
6944     -------------------------------------------------------------------------
6945 
6946     if (c_mmt_txn_rec.logical_transaction = 1 OR c_mmt_txn_rec.transaction_type_id = 20) then
6947       select count(*)
6948       into l_mctcd_count
6949       from mtl_cst_txn_cost_details
6950       where transaction_id = c_mmt_txn_rec.transaction_id;
6951 
6952       if (l_mctcd_count = 0) then
6953         if (c_mmt_txn_rec.transaction_type_id = 20) then
6954            --Retroactive Price Update
6955           l_err_msg := 'No details in MCTCD: ' || c_mmt_txn_rec.transaction_id;
6956           RAISE FND_API.g_exc_error;
6957         else
6958           if (l_log_in_phy = 1) then
6959              /* This is a logical transaction in the parent physical organization -
6960                 that is the Logical Intercompany Shipment in the org where the Physical
6961                 Sales Order Issue was performed */
6962             Compute_MCACD_Costs(
6963                      p_api_version      => 1.0,
6964                      p_org_id   =>   c_mmt_txn_rec.organization_id,
6965                      p_txn_id   =>  c_mmt_txn_rec.transaction_id ,
6966                      p_parent_txn_id    => p_parent_id,
6967                      p_cost_method  =>   c_mmt_txn_rec.primary_cost_method,
6968                      p_cost_org_id  =>  c_mmt_txn_rec.cost_organization_id,
6969                      p_cost_type_id  =>   c_mmt_txn_rec.cost_type_id,
6970                      p_item_id    =>       c_mmt_txn_rec.inventory_item_id,
6971                      p_txn_action_id   =>  c_mmt_txn_rec.transaction_action_id ,
6972                      p_exp_item =>  l_exp_item,
6973                      p_exp_flag   =>  l_exp_flag,
6974                      p_cost_group_id    =>  c_mmt_txn_rec.cost_group_id,
6975                      p_rates_cost_type =>  c_mmt_txn_rec.avg_rates_cost_type_id,
6976                      p_txn_qty    =>   c_mmt_txn_rec.transaction_quantity,
6977                      p_txn_src_type => c_mmt_txn_rec.transaction_source_type_id,
6978                      p_user_id    => p_user_id,
6979                      p_request_id  =>  p_request_id ,
6980                      p_prog_id  =>   p_prog_id  ,
6981                      p_prog_app_id  =>   p_prog_app_id ,
6982                      p_login_id   =>  p_login_id  ,
6983                      x_layer_id    => l_layer_id ,
6984                      x_err_num    =>   l_error_num,
6985                      x_err_code => l_err_code,
6986                      x_err_msg   =>   l_err_msg);
6987 
6988             if (l_error_num <> 0) then
6989               raise fnd_api.g_exc_error;
6990             end if;
6991           end if;
6992         end if;
6993       else
6994         l_stmt_num := 40;
6995         /* figure out layer_id */
6996         if (c_mmt_txn_rec.primary_cost_method <> 1) then
6997           l_layer_id := CSTPACLM.layer_id(c_mmt_txn_rec.organization_id,
6998                                        c_mmt_txn_rec.inventory_item_id,
6999                                        c_mmt_txn_rec.cost_group_id,
7000                                        l_error_num, l_err_code, l_err_msg);
7001           -- check error
7002           if (l_error_num <> 0) then
7003             raise fnd_api.g_exc_error;
7004           end if;
7005 
7006           -- create a layer
7007           if (l_layer_id = 0) then
7008               l_layer_id := CSTPACLM.create_layer(c_mmt_txn_rec.organization_id,
7009                                                   c_mmt_txn_rec.inventory_item_id,
7010                                                   c_mmt_txn_rec.cost_group_id, p_user_id,
7011                                                   p_request_id, p_prog_id,
7012                                                   p_prog_app_id,
7013                                                   c_mmt_txn_rec.transaction_id,
7014                                                   l_error_num, l_err_code, l_err_msg);
7015               -- check error
7016               if (l_layer_id = 0) then
7017                     raise fnd_api.g_exc_error;
7018               end if;
7019             end if;
7020           end if;
7021 
7022           if (g_debug = 'Y') then
7023             fnd_file.put_line (fnd_file.log, 'Layer id: ' || l_layer_id);
7024             fnd_file.put_line (fnd_file.log, 'Transaction id: ' || c_mmt_txn_rec.transaction_id);
7025           end if;
7026           l_stmt_num := 41;
7027 
7028 
7029           insert into mtl_cst_actual_cost_details (
7030                              transaction_id,
7031                              organization_id,
7032                              layer_id,
7033                              cost_element_id,
7034                              level_type,
7035                              transaction_action_id,
7036                              last_update_date,
7037                              last_updated_by,
7038                              creation_date,
7039                              created_by,
7040                              last_update_login,
7041                              request_id,
7042                              program_application_id,
7043                              program_id,
7044                              program_update_date,
7045                              inventory_item_id,
7046                              actual_cost,
7047                              prior_cost,
7048                              new_cost,
7049                              insertion_flag,
7050                              variance_amount,
7051                              user_entered)
7052                              select
7053                              c_mmt_txn_rec.transaction_id,
7054                              c_mmt_txn_rec.organization_id,
7055                              l_layer_id,
7056                              1,
7057                              1,
7058                              c_mmt_txn_rec.transaction_action_id,
7059                              sysdate,
7060                              p_user_id,
7061                              sysdate,
7062                              p_user_id,
7063                              p_login_id,
7064                              p_request_id,
7065                              p_prog_app_id,
7066                              p_prog_id,
7067                              sysdate,
7068                              c_mmt_txn_rec.inventory_item_id,
7069                              decode(c_mmt_txn_rec.transaction_type_id, 20, ctcd.value_change,ctcd.transaction_cost),
7070                              NULL,
7071                              NULL,
7072                              'N',
7073                              0,
7074                              'N'
7075           FROM mtl_cst_txn_cost_details ctcd
7076           WHERE transaction_id = c_mmt_txn_rec.transaction_id;
7077 
7078           if (g_debug = 'Y') then
7079                 fnd_file.put_line (fnd_file.log, 'Inserted in mcacd:' || sql%rowcount);
7080           end if;
7081 
7082           /* Update MMT */
7083 
7084           l_stmt_num := 42;
7085 
7086           Update mtl_material_transactions mmt
7087             set (last_update_date,
7088                        last_updated_by,
7089                        last_update_login,
7090                        request_id,
7091                        program_application_id,
7092                        program_id,
7093                        program_update_date,
7094                        actual_cost,
7095                        variance_amount) =
7096             ( select sysdate,
7097                        p_user_id,
7098                        p_login_id,
7099                        p_request_id,
7100                        p_prog_app_id,
7101                        p_prog_id,
7102                        sysdate,
7103                  sum(nvl(actual_cost,0)),
7104                        sum(nvl(variance_amount,0))
7105              from mtl_cst_actual_cost_details cacd
7106              where cacd.transaction_id = c_mmt_txn_rec.transaction_id)
7107              where mmt.transaction_id = c_mmt_txn_rec.transaction_id;
7108 
7109       end if; /* mctcd count = 0 */
7110    -------------------------------------------------------------------------
7111     -- Call the Distribution Processor
7112     -- It will not be called for physical parent transactions!!
7113     -------------------------------------------------------------------------
7114       l_stmt_num := 45;
7115       CSTPACDP.cost_txn(c_mmt_txn_rec.organization_id,
7116                     c_mmt_txn_rec.transaction_id,
7117                     l_layer_id,
7118                     0, --fob point
7119                     l_exp_item,
7120                     0, --citw_flag,
7121                     0, --flow_schedule,
7122                     p_user_id,
7123                     p_login_id,
7124                     p_request_id,
7125                     p_prog_app_id,
7126                     p_prog_id,
7127                     0, --tprice_option,
7128                     0, --txf_price,
7129                     l_error_num,
7130                     l_err_code,
7131                     l_err_msg);
7132                   l_stmt_num := 50;
7133 
7134 
7135       if (l_error_num <> 0 ) then
7136         if (g_debug = 'Y') then
7137           fnd_file.put_line (fnd_file.log, 'Error Calling cost_txn');
7138         end if;
7139         raise fnd_api.g_exc_error;
7140       end if;
7141 
7142     end if;  /* c_mmt_txn_rec.logical_transaction = 1 OR c_mmt_txn_rec.transaction_type_id = 20 */
7143 
7144     l_stmt_num := 50;
7145 
7146     /* Create the event in SLA */
7147     l_trx_info.TRANSACTION_ID       := c_mmt_txn_rec.transaction_id;
7148     l_trx_info.TRANSACTION_DATE     := c_mmt_txn_rec.transaction_date;
7149     l_trx_info.TXN_ACTION_ID        := c_mmt_txn_rec.transaction_action_id;
7150     l_trx_info.TXN_ORGANIZATION_ID  := c_mmt_txn_rec.organization_id;
7151     l_trx_info.TXN_SRC_TYPE_ID      := c_mmt_txn_rec.transaction_source_type_id;
7152     l_trx_info.TP                   := 'N';
7153 
7154 
7155 
7156    l_stmt_num := 60;
7157     CST_XLA_PVT.Create_INVXLAEvent (
7158       p_api_version       => 1.0,
7159       p_init_msg_list     => FND_API.G_FALSE,
7160       p_commit            => FND_API.G_FALSE,
7161       p_validation_level  => FND_API.G_VALID_LEVEL_FULL,
7162       x_return_status     => l_return_status,
7163       x_msg_count         => l_msg_count,
7164       x_msg_data          => l_msg_data,
7165       p_trx_info          => l_trx_info
7166     );
7167     IF l_return_status <> 'S' THEN
7168       l_error_num := -1;
7169       l_err_code := 'Error raising SLA Event for transaction: '||to_char(c_mmt_txn_rec.transaction_id);
7170       RAISE FND_API.g_exc_unexpected_error;
7171     END IF;
7172 
7173  END LOOP;
7174 
7175 
7176 
7177   /* Update Costed Flag */
7178   l_stmt_num := 70;
7179   -- Change to PL/SQL Logic for the performance Bug 4773025
7180     if (p_parent_id is not null) then
7181   update mtl_material_transactions
7182   set costed_flag = NULL
7183   WHERE parent_transaction_id = p_parent_id;
7184    else
7185   update mtl_material_transactions
7186   set costed_flag = NULL
7187   WHERE transaction_id = p_txn_id ;
7188   end if;
7189 
7190 
7191  IF g_debug = 'Y' THEN
7192    fnd_file.put_line(fnd_file.log, 'Cost_Acct_Events >>>');
7193  END IF;
7194 
7195  EXCEPTION
7196  when fnd_api.g_exc_error then
7197  ROLLBACK ;
7198  x_err_num := -1;
7199  x_err_code := l_err_code;
7200  x_err_msg := 'CSTPAVCP.COST_ACCT_EVENTS:' || '(' || l_stmt_num || '):' ||
7201                l_err_msg || ':' ||  substr(SQLERRM,1,200);
7202 
7203 /* Modified update statement for performance reasons. See bug#3585779*/
7204 if (p_parent_id is null) then
7205 update mtl_material_transactions
7206 set costed_flag =  'E',
7207 error_code = x_err_code,
7208 error_explanation = x_err_msg
7209  where  (p_txn_id is not null
7210          and transaction_id = p_txn_id);
7211 
7212 elsif (p_parent_id is not null) then
7213     /* Changed to PL/SQL Logic for performance Bug 4773025 */
7214     if(p_txn_id is not null) then
7215     update mtl_material_transactions
7216     set costed_flag = decode(transaction_id, p_parent_id, 'E', 'N'),
7217     error_code = x_err_code,
7218     error_explanation = x_err_msg
7219     where parent_transaction_id  = p_parent_id or
7220     (transaction_id = p_parent_id and parent_transaction_id is null) or
7221     (transaction_id = p_txn_id);
7222     else
7223     update mtl_material_transactions
7224     set costed_flag = decode(transaction_id, p_parent_id, 'E', 'N'),
7225     error_code = x_err_code,
7226     error_explanation = x_err_msg
7227     where parent_transaction_id  = p_parent_id or
7228     (transaction_id = p_parent_id and parent_transaction_id is null);
7229     end if;
7230 end if;
7231 
7232  when others then
7233  ROLLBACK ;
7234  x_err_num := -1;
7235  x_err_code := l_err_code;
7236  x_err_msg := 'CSTPAVCP.COST_ACCT_EVENTS:' || '(' || l_stmt_num || '):' ||
7237                 substr(SQLERRM,1,200);
7238 
7239 /* Modified update statement for performance reasons. See bug#3585779*/
7240 if (p_parent_id is null) then
7241 update mtl_material_transactions
7242 set costed_flag =  'E',
7243 error_code = x_err_code,
7244 error_explanation = x_err_msg,
7245 request_id = p_request_id
7246  where  (p_txn_id is not null
7247          and transaction_id = p_txn_id);
7248 
7249 elsif (p_parent_id is not null) then
7250    /* Changed to PL/SQL Logic for performance Bug 4773025 */
7251    if (p_txn_id is not null) then
7252    update mtl_material_transactions
7253    set costed_flag = decode(transaction_id, p_parent_id, 'E', 'N'),
7254    error_code = x_err_code,
7255    error_explanation = x_err_msg,
7256    request_id = p_request_id
7257    where parent_transaction_id  = p_parent_id or
7258    (transaction_id = p_parent_id and parent_transaction_id is null) or
7259    (transaction_id = p_txn_id);
7260    else
7261    update mtl_material_transactions
7262    set costed_flag = decode(transaction_id, p_parent_id, 'E', 'N'),
7263    error_code = x_err_code,
7264    error_explanation = x_err_msg,
7265    request_id = p_request_id
7266    where parent_transaction_id  = p_parent_id or
7267    (transaction_id = p_parent_id and parent_transaction_id is null);
7268    end if;
7269 end if;
7270 
7271  END Cost_Acct_Events;
7272 
7273 
7274 
7275 --------------------------------------------------------------------------
7276 -- PROCEDURE                                                              --
7277 --   Compute_MCACD_Costs                                                  --
7278 --                                                                        --
7279 --                                                                        --
7280 -- DESCRIPTION                                                            --
7281 --   This procedure determines the costs of logical transactions in       --
7282 --   physical organizations.                                              --
7283 --   The costs are determined as follows:                                 --
7284 --   Standard Costing org: Standard cost of item                          --
7285 --   Average Costing org: actual cost of item                             --
7286 --   FIFO/FIFO org: From MCLACD of parent transaction                     --
7287 --                                                                        --
7288 --   This procedure should be called only for logical transactions in the --
7289 --   physical event owing organization - essentially orgs where physical  --
7290 --   SO Issue or RMAs are done.                                           --
7291 --                                                                        --
7292 -- PURPOSE:                                                               --
7293 --   Oracle Applications Rel 11i.10                                       --
7294 --                                                                        --
7295 --                                                                        --
7296 -- HISTORY:                                                               --
7297 --    06/22/03     Anju G       Created                                   --
7298 --    08/07/07  vjavli Bug 6328273 fix: Logical I/C Sales Issue avoid     --
7299 --                     zero by checking for shared costing and fetch      --
7300 --                     item cost from parent organization if the current  --
7301 --                     organization is shared costing organization        --
7302 ----------------------------------------------------------------------------
7303 
7304 PROCEDURE Compute_MCACD_Costs(
7305                      p_api_version      IN  NUMBER,
7306                      p_init_msg_list    IN  VARCHAR2 := FND_API.G_FALSE,
7307                      p_commit           IN  VARCHAR2 := FND_API.G_FALSE,
7308                      p_validation_level IN  NUMBER   := FND_API.G_VALID_LEVEL_FULL,
7309 
7310                      p_org_id           IN  NUMBER,
7311                      p_txn_id           IN  NUMBER,
7312                      p_parent_txn_id    IN  NUMBER,
7313                      p_cost_method      IN  NUMBER,
7314                      p_cost_org_id      IN  NUMBER,
7315                      p_cost_type_id     IN  NUMBER,
7316                      p_item_id          IN  NUMBER,
7317                      p_txn_action_id    IN  NUMBER,
7318                      p_exp_item         IN  NUMBER,
7319                      p_exp_flag         IN  NUMBER,
7320                      p_cost_group_id    IN  NUMBER,
7321                      p_rates_cost_type  IN  NUMBER,
7322                      p_txn_qty          IN  NUMBER,
7323                      p_txn_src_type     IN  NUMBER,
7324 
7325                      p_user_id          IN  NUMBER,
7326                      p_request_id       IN  NUMBER,
7327                      p_prog_id          IN  NUMBER,
7328                      p_prog_app_id      IN  NUMBER,
7329                      p_login_id         IN  NUMBER,
7330 
7331 
7332                      x_layer_id         IN OUT NOCOPY NUMBER,
7333                      x_err_num          OUT NOCOPY VARCHAR2,
7334                      x_err_code         OUT NOCOPY VARCHAR2,
7335                      x_err_msg          OUT NOCOPY VARCHAR2) IS
7336 
7337 
7338 l_stmt_num           NUMBER;
7339 l_cost_hook          NUMBER := 0;
7340 l_layer_id           NUMBER := -1;
7341 l_count              NUMBER;
7342 l_new_cost           NUMBER;
7343 
7344 
7345  l_error_num          NUMBER   := 0;
7346  l_err_code           VARCHAR2(240);
7347  l_err_msg            VARCHAR2(240);
7348 
7349 
7350 BEGIN
7351 
7352  IF g_debug = 'Y' THEN
7353    fnd_file.put_line(fnd_file.log, 'Compute_MCACD_Costs <<<');
7354  END IF;
7355 
7356  l_err_code := '';
7357  l_err_msg  := '';
7358 
7359     -------------------------------------------------------------------------
7360     -- Initialize message list if p_init_msg_list is set to TRUE
7361     -------------------------------------------------------------------------
7362 
7363     IF FND_API.to_Boolean(p_init_msg_list) THEN
7364         FND_MSG_PUB.initialize;
7365     END IF;
7366 
7367     -------------------------------------------------------------------------
7368     -- initialize api return status to success
7369     -------------------------------------------------------------------------
7370     l_error_num  := 0;
7371 
7372     l_layer_id := x_layer_id;
7373 
7374     l_stmt_num := 10;
7375 
7376     -------------------------------------------------------------------------
7377     -- Standard Costing Organizations
7378     -------------------------------------------------------------------------
7379 
7380     -- -----------------------------------------------------------------------------
7381     -- Bug 6328273 fix: Check for shared costing organization
7382     -- if p_org_id is equal to p_cost_org_id then it is not a shared std costing org
7383     -- if p_org_id is not equal to p_cost_org_id then it is a shared std costing org
7384     -- p_cost_method should be equal to 1 in both the cases
7385     -- -----------------------------------------------------------------------------
7386     if (p_cost_method = 1 AND p_org_id = p_cost_org_id) then
7387 
7388      l_stmt_num := 20;
7389        select count(*)
7390        into l_count
7391        from cst_item_cost_details
7392        where inventory_item_id = p_item_id
7393        and organization_id = p_org_id
7394        and cost_type_id = 1;
7395 
7396        if (l_count = 0) then
7397        /* Insert into MCACD using 0 cost for This Level Material */
7398 
7399           insert into mtl_cst_actual_cost_details (
7400           transaction_id,
7401           organization_id,
7402           layer_id,
7403           cost_element_id,
7404           level_type,
7405           transaction_action_id,
7406           last_update_date,
7407           last_updated_by,
7408           creation_date,
7409           created_by,
7410           last_update_login,
7411           request_id,
7412           program_application_id,
7413           program_id,
7414           program_update_date,
7415           inventory_item_id,
7416           actual_cost,
7417           insertion_flag,
7418           variance_amount,
7419           user_entered)
7420           values ( p_txn_id,
7421           p_org_id,
7422           -1,
7423           1,
7424           1,
7425           p_txn_action_id,
7426           sysdate,
7427           p_user_id,
7428           sysdate,
7429           p_user_id,
7430           p_login_id,
7431           p_request_id,
7432           p_prog_app_id,
7433           p_prog_id,
7434           sysdate,
7435           p_item_id,
7436           0,
7437           'N',
7438           0,
7439           'N');
7440 
7441      else
7442      /* Insert into MCACD cost details from CICD */
7443       l_stmt_num := 30;
7444            insert into mtl_cst_actual_cost_details (
7445            transaction_id,
7446            organization_id,
7447            layer_id,
7448            cost_element_id,
7449            level_type,
7450            transaction_action_id,
7451            last_update_date,
7452            last_updated_by,
7453            creation_date,
7454            created_by,
7455            last_update_login,
7456            request_id,
7457            program_application_id,
7458            program_id,
7459            program_update_date,
7460            inventory_item_id,
7461            actual_cost,
7462            insertion_flag,
7463            variance_amount,
7464            user_entered)
7465            select p_txn_id,
7466            p_org_id,
7467            -1,
7468            cicd.cost_element_id,
7469            cicd.level_type,
7470            p_txn_action_id,
7471            sysdate,
7472            p_user_id,
7473            sysdate,
7474            p_user_id,
7475            p_login_id,
7476            p_request_id,
7477            p_prog_app_id,
7478            p_prog_id,
7479            sysdate,
7480            p_item_id,
7481            nvl(sum(cicd.item_cost),0),
7482            'N',
7483            0,
7484            'N'
7485            from cst_item_cost_details cicd
7486            where organization_id = p_org_id
7487            and inventory_item_id = p_item_id
7488            and cost_type_id = 1
7489            group by cost_element_id, level_type;
7490 
7491        end if;
7492 
7493     -- ---------------------------------------------------------------
7494     -- Bug 6328273 fix: check for shared standard costing organization
7495     -- In the current organization, no recs can be found in CICD
7496     -- Get item cost from parent organization
7497     -- --------------------------------------------------------------
7498     elsif (p_cost_method = 1 AND p_org_id <> p_cost_org_id) then
7499      l_stmt_num := 34;
7500        select count(*)
7501        into l_count
7502        from cst_item_cost_details
7503        where inventory_item_id = p_item_id
7504        and organization_id = p_cost_org_id
7505        and cost_type_id = 1;
7506 
7507        if (l_count = 0) then
7508        /* Insert into MCACD using 0 cost for This Level Material */
7509 
7510           insert into mtl_cst_actual_cost_details (
7511           transaction_id,
7512           organization_id,
7513           layer_id,
7514           cost_element_id,
7515           level_type,
7516           transaction_action_id,
7517           last_update_date,
7518           last_updated_by,
7519           creation_date,
7520           created_by,
7521           last_update_login,
7522           request_id,
7523           program_application_id,
7524           program_id,
7525           program_update_date,
7526           inventory_item_id,
7527           actual_cost,
7528           insertion_flag,
7529           variance_amount,
7530           user_entered)
7531           values ( p_txn_id,
7532           p_org_id,
7533           -1,
7534           1,
7535           1,
7536           p_txn_action_id,
7537           sysdate,
7538           p_user_id,
7539           sysdate,
7540           p_user_id,
7541           p_login_id,
7542           p_request_id,
7543           p_prog_app_id,
7544           p_prog_id,
7545           sysdate,
7546           p_item_id,
7547           0,
7548           'N',
7549           0,
7550           'N');
7551 
7552      else
7553      /* Insert into MCACD cost details from CICD */
7554       l_stmt_num := 38;
7555            insert into mtl_cst_actual_cost_details (
7556            transaction_id,
7557            organization_id,
7558            layer_id,
7559            cost_element_id,
7560            level_type,
7561            transaction_action_id,
7562            last_update_date,
7563            last_updated_by,
7564            creation_date,
7565            created_by,
7566            last_update_login,
7567            request_id,
7568            program_application_id,
7569            program_id,
7570            program_update_date,
7571            inventory_item_id,
7572            actual_cost,
7573            insertion_flag,
7574            variance_amount,
7575            user_entered)
7576            select p_txn_id,
7577            p_org_id,
7578            -1,
7579            cicd.cost_element_id,
7580            cicd.level_type,
7581            p_txn_action_id,
7582            sysdate,
7583            p_user_id,
7584            sysdate,
7585            p_user_id,
7586            p_login_id,
7587            p_request_id,
7588            p_prog_app_id,
7589            p_prog_id,
7590            sysdate,
7591            p_item_id,
7592            nvl(sum(cicd.item_cost),0),
7593            'N',
7594            0,
7595            'N'
7596            from cst_item_cost_details cicd
7597            where organization_id = p_cost_org_id
7598            and inventory_item_id = p_item_id
7599            and cost_type_id = 1
7600            group by cost_element_id, level_type;
7601 
7602        end if;
7603 
7604    else /* Average or FIFO/LIFO organization */
7605     -------------------------------------------------------------------------
7606     -- Create layers against the physical transaction
7607     -------------------------------------------------------------------------
7608 
7609       l_stmt_num := 40;
7610 
7611       l_layer_id := CSTPACLM.layer_id(p_org_id,
7612                                       p_item_id,
7613                                       p_cost_group_id,
7614                                       l_error_num, l_err_code, l_err_msg);
7615        -- check error
7616        if (l_error_num <> 0) then
7617              raise fnd_api.g_exc_error;
7618        end if;
7619 
7620        -- create a layer
7621        if (l_layer_id = 0) then
7622               l_layer_id := CSTPACLM.create_layer(p_org_id,
7623                                                   p_item_id,
7624                                                   p_cost_group_id, p_user_id,
7625                                                   p_request_id, p_prog_id,
7626                                                   p_prog_app_id,
7627                                                   p_parent_txn_id,
7628                                                   l_error_num, l_err_code, l_err_msg);
7629                 -- check error
7630                 if (l_layer_id = 0) then
7631                     raise fnd_api.g_exc_error;
7632                 end if;
7633         end if;
7634 
7635 
7636     l_stmt_num := 50;
7637 
7638     -------------------------------------------------------------------------
7639     -- Call cost hook for asset items
7640     -------------------------------------------------------------------------
7641 
7642      if(p_exp_item = 0 ) then
7643 
7644         l_cost_hook := CSTPACHK.actual_cost_hook(p_org_id,
7645                                                  p_txn_id,
7646                                                  l_layer_id,
7647                                                  p_cost_type_id,
7648                                                  p_cost_method,
7649                                                  p_user_id,
7650                                                  p_login_id,
7651                                                  p_request_id,
7652                                                  p_prog_app_id,
7653                                                  p_prog_id,
7654                                                  l_error_num,
7655                                                  l_err_code,
7656                                                  l_err_msg);
7657     IF (l_cost_hook = 1) THEN
7658                 IF g_debug = 'Y' THEN
7659                     fnd_file.put_line(fnd_file.log, '>>>>Hook has been used. Calling CSTPAVCP.validate_actual_cost_hook');
7660                 END IF;
7661 
7662                 CSTPAVCP.validate_actual_cost_hook(i_txn_id     =>        p_txn_id,
7663                                                    i_org_id     =>      p_org_id,
7664                                                    i_layer_id   =>      l_layer_id,
7665                                                    i_req_id     =>      p_request_id,
7666                                                    i_prg_appl_id=>      p_prog_app_id,
7667                                                    i_prg_id     =>      p_prog_id,
7668                                                    o_err_num    =>      l_error_num,
7669                                                    o_err_code   =>      l_err_code,
7670                                                    o_err_msg    =>      l_err_msg);
7671     END IF;
7672         if (l_error_num <> 0) then
7673           raise fnd_api.g_exc_error;
7674         end if;
7675      end if;
7676 
7677     -------------------------------------------------------------------------
7678     -- Average Costing org
7679     -------------------------------------------------------------------------
7680      l_stmt_num := 60;
7681 
7682      if (p_cost_method = 2) then
7683 
7684         if (l_cost_hook = 0) then
7685              l_new_cost := compute_actual_cost( p_org_id,
7686                                 p_txn_id,
7687                                 l_layer_id,
7688                                 p_cost_type_id,
7689                                 p_rates_cost_type,
7690                                 p_rates_cost_type,  -----CHECK THIS!
7691                                 p_item_id,
7692                                 p_txn_qty,
7693                                 p_txn_action_id,
7694                                 p_txn_src_type,
7695                                 0,
7696                                 p_exp_flag,
7697                                 p_user_id,
7698                                 p_login_id,
7699                                 p_request_id,
7700                                 p_prog_app_id,
7701                                 p_prog_id,
7702                                 l_error_num,
7703                                 l_err_code,
7704                                 l_err_msg);
7705               if (l_error_num <> 0) then
7706                       raise fnd_api.g_exc_error;
7707               end if;
7708 
7709          else
7710             l_new_cost := 1;
7711 
7712          end if;
7713 
7714          l_stmt_num := 70;
7715 
7716          if (l_new_cost = 1) then
7717              /* Reaverage Costs */
7718                  calc_average_cost(
7719                                 p_org_id,
7720                                 p_txn_id,
7721                                 l_layer_id,
7722                                 p_cost_type_id,
7723                                 p_item_id,
7724                                 p_txn_qty,
7725                                 p_txn_action_id,
7726                                 0,
7727                                 p_user_id,
7728                                 p_login_id,
7729                                 p_request_id,
7730                                 p_prog_app_id,
7731                                 p_prog_id,
7732                                 l_error_num,
7733                                 l_err_code,
7734                                 l_err_msg);
7735 
7736                   if (l_error_num <> 0) then
7737                         raise fnd_api.g_exc_error;
7738                   end if;
7739          else
7740 
7741          l_stmt_num := 80;
7742         /* use current costs */
7743                   current_average_cost(
7744                                 p_org_id,
7745                                 p_txn_id,
7746                                 l_layer_id,
7747                                 p_cost_type_id,
7748                                 p_item_id,
7749                                 p_txn_qty,
7750                                 p_txn_action_id,
7751                                 p_exp_flag,
7752                                 0,--update mmt flag
7753                                 0,
7754                                 p_user_id,
7755                                 p_login_id,
7756                                 p_request_id,
7757                                 p_prog_app_id,
7758                                 p_prog_id,
7759                                 l_error_num,
7760                                 l_err_code,
7761                                 l_err_msg);
7762 
7763                   if (l_error_num <> 0) then
7764                          raise fnd_api.g_exc_error;
7765                   end if;
7766        end if;
7767 
7768      elsif (p_cost_method in (5,6)) then
7769      l_stmt_num := 90;
7770        /* FIFO/LIFO cost method */
7771 
7772     -------------------------------------------------------------------------
7773     -- FIFO/LIFO Costing organizations
7774     -------------------------------------------------------------------------
7775 
7776            l_new_cost := CSTPLENG.compute_layer_actual_cost(
7777                                      p_org_id,
7778                                      p_cost_method,
7779                                      p_txn_id,
7780                                      l_layer_id,
7781                                      l_cost_hook,
7782                                      p_cost_type_id,
7783                                      p_rates_cost_type,
7784                                      P_rates_cost_type,
7785                                      p_item_id,
7786                                      p_txn_qty,
7787                                      p_txn_action_id,
7788                                      p_txn_src_type,
7789                                      NULL,
7790                                      p_exp_flag,
7791                                      p_user_id,
7792                                      p_login_id,
7793                                      p_request_id,
7794                                      p_prog_app_id,
7795                                      p_prog_id,
7796                                      l_error_num,
7797                                      l_err_code,
7798                                      l_err_msg);
7799 
7800             if (l_error_num <> 0) then
7801                 raise fnd_api.g_exc_error;
7802             end if;
7803 
7804             l_stmt_num := 50;
7805 
7806             CSTPLENG.calc_layer_average_cost(p_org_id,
7807                                                 p_txn_id,
7808                                                 l_layer_id,
7809                                                 p_cost_type_id,
7810                                                 p_item_id,
7811                                                 p_txn_qty,
7812                                                 p_txn_action_id,
7813                                                 l_cost_hook,
7814                                                 0,
7815                                                 0,
7816                                                 p_user_id,
7817                                                 p_login_id,
7818                                                 p_request_id,
7819                                                 p_prog_app_id,
7820                                                 p_prog_id,
7821                                                 l_error_num,
7822                                                 l_err_code,
7823                                                 l_err_msg);
7824 
7825 
7826              if (l_error_num <> 0) then
7827                     raise fnd_api.g_exc_error;
7828              end if;
7829     end if;
7830 
7831     l_stmt_num := 100;
7832 
7833     -------------------------------------------------------------------------
7834     -- Need to update the parent physical transaction im MMT.
7835     -- update prior_cost, ew_cost, variance_amount
7836     -- use the MMT of logical transacion to update corresponding parent.
7837     -------------------------------------------------------------------------
7838 
7839     Update mtl_material_transactions mmt
7840     set (last_update_date,
7841          last_updated_by,
7842          last_update_login,
7843          request_id,
7844          program_application_id,
7845          program_id,
7846          program_update_date,
7847          actual_cost,
7848          prior_cost,
7849          new_cost,
7850          variance_amount,
7851          prior_costed_quantity,
7852          quantity_adjusted) =
7853     (select sysdate,
7854             p_user_id,
7855             p_login_id,
7856             p_request_id,
7857             p_prog_app_id,
7858             p_prog_id,
7859             sysdate,
7860             mmt2.actual_cost,
7861             mmt2.prior_cost,
7862             mmt2.new_cost,
7863             mmt2.variance_amount,
7864             mmt2.prior_costed_quantity,
7865             mmt2.quantity_adjusted
7866       from mtl_material_transactions mmt2
7867       where mmt2.transaction_id = p_txn_id
7868       and mmt2.organization_id = p_org_id)
7869     where mmt.transaction_id = p_parent_txn_id;
7870 
7871 
7872  end if;
7873 
7874     x_layer_id := l_layer_id ;
7875 
7876 
7877  IF g_debug = 'Y' THEN
7878    fnd_file.put_line(fnd_file.log, 'Compute_MCACD_Costs >>>');
7879  END IF;
7880 
7881 EXCEPTION
7882 
7883 when fnd_api.g_exc_error then
7884  x_err_num := -1;
7885  x_err_code := l_err_code;
7886  x_err_msg := 'CSTPAVCP.COMPUTE_MCACD_COSTS:' || '(' || l_stmt_num || '):' ||
7887                l_err_msg;
7888 
7889 
7890  when others then
7891  x_err_num := -1;
7892  x_err_code := l_err_code;
7893  x_err_msg := 'CSTPAVCP.COMPUTE_MCACD_COSTS:' || '(' || l_stmt_num || '):' ||
7894                l_err_msg;
7895 
7896 END Compute_MCACD_Costs;
7897 
7898 /* Bug 2665290 */
7899 /*========================================================================
7900 -- PROCEDURE
7901 --    payback_variance
7902 --
7903 -- DESCRIPTION
7904 -- This procedure will be called for all Payback transactions across the
7905 -- same cost group.
7906 -- This  procedure will identify the cost of all borrow transactions
7907 -- related to the specified payback transactions, compute the average cost
7908 -- calculate the variance and update payback_variance_amount column of MCACD.
7909 --
7910 
7911 -- HISTORY
7912 --    08/20/03     Anju Gupta          Creation
7913 
7914 =========================================================================*/
7915 
7916 
7917 /* Borrow Payback Variance Enhancements */
7918 PROCEDURE payback_variance(
7919   I_ORG_ID      IN      NUMBER,
7920   I_TXN_ID      IN      NUMBER,
7921   I_FROM_LAYER  IN      NUMBER,
7922   I_USER_ID     IN      NUMBER,
7923   I_LOGIN_ID    IN      NUMBER,
7924   I_REQ_ID      IN      NUMBER,
7925   I_PRG_APPL_ID IN      NUMBER,
7926   I_PRG_ID      IN      NUMBER,
7927   O_Err_Num     OUT NOCOPY      NUMBER,
7928   O_Err_Code    OUT NOCOPY      VARCHAR2,
7929   O_Err_Msg     OUT NOCOPY      VARCHAR2)
7930 IS
7931 
7932 cursor c_payback_txn(c_cur_txn_id number) is
7933        select pbp.borrow_transaction_id,
7934               pbp.payback_quantity
7935          from pjm_borrow_paybacks pbp
7936          where pbp.payback_transaction_id = c_cur_txn_id;
7937 
7938 -- this cursor is to find out all the mcacd data
7939 -- for a specific transaction_id
7940 cursor c_mcacd_data (c_transaction_id number) is
7941      select mcacd.transaction_id,
7942             mcacd.cost_element_id,
7943             mcacd.level_type,
7944             mcacd.inventory_item_id,
7945             mcacd.actual_cost,
7946             mcacd.prior_cost,
7947             mcacd.new_cost,
7948             mcacd.layer_id
7949        from mtl_cst_actual_cost_details mcacd
7950        where mcacd.transaction_id = c_transaction_id
7951        and mcacd.layer_id = i_from_layer;
7952 
7953   type t_cst_element is table of number
7954         index by binary_integer;
7955 
7956   l_temp_element_cost t_cst_element;
7957   l_level_type          NUMBER;
7958   l_total_bp_qty        NUMBER;
7959   l_err_num             NUMBER;
7960   l_err_code            VARCHAR2(240);
7961   l_err_msg             VARCHAR2(240);
7962   l_stmt_num            NUMBER;
7963   l_variance     NUMBER;
7964   l_cur_cost     NUMBER;
7965   l_borrowed_Cost  NUMBER;
7966 
7967 BEGIN
7968   -- initialize local variables
7969   l_err_num := 0;
7970   l_err_code := '';
7971   l_err_msg := '';
7972 
7973   l_stmt_num := 10;
7974  IF g_debug = 'Y' THEN
7975    fnd_file.put_line(fnd_file.log, 'Payback_Variance <<<');
7976  END IF;
7977 
7978 -- initialize array with 0
7979 
7980    for l_index_counter in 1..10 loop
7981       l_temp_element_cost(l_index_counter):=0;
7982    end loop;
7983 
7984    l_stmt_num := 10;
7985 
7986 -- loop through all the payaback txn to find the borrowing cost
7987 -- from MCACD and sum it up.
7988    l_total_bp_qty := 0;
7989       for c_payback_rec in c_payback_txn(i_txn_id) loop
7990          for c_mcacd_rec in c_mcacd_data(c_payback_rec.borrow_transaction_id) LOOP
7991             if c_mcacd_rec.level_type =1 then
7992                l_temp_element_cost(c_mcacd_rec.cost_element_id):=
7993                l_temp_element_cost(c_mcacd_rec.cost_element_id) +
7994                c_mcacd_rec.actual_cost * abs(c_payback_rec.payback_quantity);
7995             elsif c_mcacd_rec.level_type = 2 then
7996                l_temp_element_cost(c_mcacd_rec.cost_element_id + 5):=
7997                l_temp_element_cost(c_mcacd_rec.cost_element_id + 5) +
7998                c_mcacd_rec.actual_cost * abs(c_payback_rec.payback_quantity);
7999             end if;
8000          END LOOP; -- end looping c_mcacd_rec
8001          l_total_bp_qty := l_total_bp_qty + abs(c_payback_rec.payback_quantity);
8002       END LOOP; -- end looping c_payback_rec
8003 
8004       l_stmt_num := 20;
8005 
8006 -- do a division here to find out the average cost
8007       for l_index_counter in 1..10 loop
8008          l_temp_element_cost(l_index_counter):=l_temp_element_cost(l_index_counter) / l_total_bp_qty;
8009       end loop;
8010 
8011       l_stmt_num := 30;
8012 
8013   for l_index_counter in 1..10 loop
8014         l_stmt_num := 40;
8015 
8016         if (l_index_counter < 6) then
8017            l_level_type :=1;
8018         else
8019            l_level_type :=2;
8020         end if;
8021 
8022          select max(mcacd.actual_cost)
8023            into l_cur_cost
8024            from mtl_cst_actual_cost_details mcacd
8025            where mcacd.level_type = l_level_type
8026            and mcacd.cost_element_id = decode(mod(l_index_counter,5),0,5,mod(l_index_counter,5))
8027            and mcacd.transaction_id = i_txn_id
8028            and mcacd.layer_id = i_from_layer;
8029 
8030            l_stmt_num := 20;
8031 
8032            select   l_temp_element_cost(l_index_counter)
8033            into l_borrowed_cost
8034            from dual;
8035 
8036           l_variance := nvl(l_cur_cost,0) - nvl(l_borrowed_cost,0);
8037 
8038           update mtl_cst_actual_cost_details mcacd
8039           set mcacd.payback_variance_amount = l_variance
8040           where mcacd.transaction_id = i_txn_id
8041           and mcacd.cost_element_id = decode(mod(l_index_counter,5),0,5,mod(l_index_counter,5))
8042           and mcacd.level_type = l_level_type
8043           and mcacd.layer_id = i_from_layer;
8044   end loop;
8045 
8046  IF g_debug = 'Y' THEN
8047    fnd_file.put_line(fnd_file.log, 'Payback_Variance >>>');
8048  END IF;
8049   EXCEPTION
8050     when others then
8051       rollback;
8052       o_err_num := SQLCODE;
8053       o_err_msg := 'CSTPAVCP.payback_variance (' || to_char(l_stmt_num) ||
8054                    '): '
8055                    || substr(SQLERRM, 1,200);
8056 
8057 
8058 END payback_variance;
8059 --------------------------------------------------------------------------
8060 -- Procedure:
8061 -- Cost_LogicalSOReceipt
8062 --
8063 -- Description:
8064 -- Procedure to cost Logical Receipt Transaction that is created in the
8065 -- Receiving Organization when there is a Internal Order Issue
8066 -- transaction to an Expense destination.
8067 -- This is called by the Cost workers of all cost methods to
8068 -- insert the transaction details into MCACD which is later used
8069 -- to create distributions and do cost collection if projects are
8070 -- enabled.
8071 --
8072 -- Created:
8073 -- 11i.10                 Vinit
8074 ---------------------------------------------------------------------------
8075 
8076 PROCEDURE Cost_LogicalSOReceipt (
8077             p_parent_txn_id  IN NUMBER,
8078             p_user_id        IN NUMBER,
8079             p_request_id     IN NUMBER,
8080             p_prog_id        IN NUMBER,
8081             p_prog_app_id    IN NUMBER,
8082             p_login_id       IN NUMBER,
8083 
8084             x_err_num        OUT NOCOPY NUMBER,
8085             x_err_code       OUT NOCOPY VARCHAR2,
8086             x_err_msg        OUT NOCOPY VARCHAR2
8087             ) IS
8088 
8089 l_actual_cost           NUMBER;
8090 l_layer_id              NUMBER;
8091 l_cost_method           NUMBER;
8092 l_logical_txn_id        NUMBER;
8093 l_logical_org_id        NUMBER;
8094 l_parent_org_id         NUMBER;
8095 l_logical_cost_group_id NUMBER;
8096 l_item_id               NUMBER;
8097 l_stmt_num              NUMBER;
8098 
8099 l_primary_quantity      NUMBER;
8100 l_txn_date              DATE;
8101 l_txn_src_id            NUMBER;
8102 l_txn_src_typ_id        NUMBER;
8103 l_txn_typ_id            NUMBER;
8104 l_txn_act_id            NUMBER;
8105 l_alt_curr              VARCHAR2(15);
8106 l_pri_curr              VARCHAR2(15);
8107 l_curr_conv_rate        NUMBER;
8108 l_curr_conv_date        DATE;
8109 l_curr_conv_type        VARCHAR2(30);
8110 l_debit_account         NUMBER;
8111 l_credit_account        NUMBER;
8112 l_set_of_books_id       NUMBER;
8113 l_ou_id                 NUMBER;
8114 l_encumbrance_flag FINANCIALS_SYSTEM_PARAMS_ALL.PURCH_ENCUMBRANCE_FLAG%TYPE;
8115 
8116 l_enc_amount            NUMBER;
8117 l_enc_account           NUMBER;
8118 l_credit_line_type      NUMBER;
8119 l_return_status         VARCHAR2(1);
8120 l_return_message       VARCHAR2(1000);
8121 
8122 l_conversion_rate       NUMBER;
8123 l_conversion_type       VARCHAR2(30);
8124 l_sending_curr          VARCHAR2(15);
8125 
8126 l_exp_item              MTL_SYSTEM_ITEMS.INVENTORY_ASSET_FLAG%TYPE;
8127 l_exp_flag              VARCHAR2(1);
8128 l_subinventory_code     MTL_MATERIAL_TRANSACTIONS.SUBINVENTORY_CODE%TYPE;
8129 
8130 
8131 l_err_num               NUMBER;
8132 l_err_code              VARCHAR2(240);
8133 l_err_msg               VARCHAR2(240);
8134 
8135 /* FP Bug 6607845 fix */
8136 l_dr_acct_line_type     NUMBER;
8137 l_cr_acct_line_type     NUMBER;
8138 l_db_account            NUMBER;
8139 l_subinv_code           VARCHAR2(10);
8140 l_exp_sub               NUMBER;
8141 
8142 
8143 INSERT_ACCT_ERROR       EXCEPTION;
8144 INSERT_MCACD_ERROR      EXCEPTION;
8145 NO_CURR_CONV_RATE_FOUND EXCEPTION;
8146 COST_HOOK_ACCOUNT_ERROR EXCEPTION;
8147 
8148 -- Cursor to get expense or not expense sub inventory
8149 CURSOR c_exp_sub(c_subinventory_code  VARCHAR2
8150                 ,c_organization_id    NUMBER
8151                 )
8152 IS
8153 SELECT
8154   DECODE(asset_inventory,1,0,1)
8155 FROM mtl_secondary_inventories
8156 WHERE secondary_inventory_name = c_subinventory_code
8157   AND organization_id = c_organization_id;
8158 
8159 
8160 --
8161 -- Start INVCONV umoogala
8162 -- Bug 5349860: Internal Order issues to exp can also happen between
8163 -- process and discrete orgs. If the receiving org is process org,
8164 -- then do not do any accounting as it will be taken care by OPM.
8165 --
8166 l_parent_org_process_flag  VARCHAR2(1);
8167 l_logical_org_process_flag VARCHAR2(1);
8168 l_pd_xfer_ind              VARCHAR2(1);
8169 l_transfer_price           NUMBER;
8170 l_trx_info                 CST_XLA_PVT.t_xla_inv_trx_info; /* For SLA Event Creation */
8171 l_msg_count                NUMBER;
8172 l_msg_data                 VARCHAR2(8000);
8173 
8174 BEGIN
8175   IF g_debug = 'Y' THEN
8176     FND_FILE.PUT_LINE(FND_FILE.LOG, 'CSTPAVCP.Cost_LogicalSOReceipt <<<');
8177   END IF;
8178 
8179   -- Initialize Error Variables
8180   x_err_num  := 0;
8181 
8182   -- Get the Parent and Child transaction information from MMT
8183 
8184   l_stmt_num := 10;
8185 
8186   --
8187   -- Start INVCONV umoogala
8188   -- Bug 5349860: Internal Order issues to exp can also happen between
8189   -- process and discrete orgs. If the receiving org is process org,
8190   -- then do not do any accounting as it will be taken care by OPM.
8191   --
8192   SELECT
8193     mmt.inventory_item_id,
8194     mmt.subinventory_code,
8195     mmt.transfer_transaction_id,
8196     mmt.organization_id,
8197     mp.process_enabled_flag,
8198     mmt.transfer_organization_id,
8199     mpx.process_enabled_flag
8200   INTO
8201     l_item_id,
8202     l_subinventory_code,
8203     l_logical_txn_id,
8204     l_parent_org_id,
8205     l_parent_org_process_flag,
8206     l_logical_org_id,
8207     l_logical_org_process_flag
8208   FROM
8209     mtl_material_transactions mmt, mtl_parameters mpx, mtl_parameters mp
8210   WHERE
8211       mmt.transaction_id  = p_parent_txn_id
8212   AND mpx.organization_id = mmt.transfer_organization_id
8213   AND mp.organization_id  = mmt.organization_id
8214   ;
8215 
8216   --
8217   -- Start INVCONV umoogala
8218   -- Bug 5349860: Internal Order issues to exp can also happen between
8219   -- process and discrete orgs. If the receiving org is process org,
8220   -- then do not do any accounting as it will be taken care by OPM.
8221   --
8222   IF l_logical_org_process_flag <> l_parent_org_process_flag
8223   THEN
8224     l_pd_xfer_ind := 'Y';
8225   ELSE
8226     l_pd_xfer_ind := 'N';
8227   END IF;
8228 
8229   IF l_logical_org_process_flag = 'Y'
8230   THEN
8231     IF g_debug = 'Y' THEN
8232       FND_FILE.PUT_LINE(FND_FILE.LOG, 'Receiving Org is Process Org. So, no accounting ' ||
8233                                       ' for receiving transaction.');
8234       FND_FILE.PUT_LINE(FND_FILE.LOG, 'CSTPAVCP.Cost_LogicalSOReceipt >>>');
8235     END IF;
8236     RETURN;
8237   ELSIF l_pd_xfer_ind = 'Y'
8238   THEN
8239     IF g_debug = 'Y' THEN
8240       FND_FILE.PUT_LINE(FND_FILE.LOG, 'Process/Discrete xfer: Receiving Org is Discrete Org.');
8241     END IF;
8242   END IF;
8243   -- End bug 5349860
8244 
8245   -- If the transfer transaction is not populated, the transaction
8246   -- was created prior to 11.5.10 and not costed before the upgrade
8247   -- For these transactions, exit out the procedure. These will
8248   -- be costed in a manner similar to before the upgrade.
8249 
8250   IF l_logical_txn_id IS NULL THEN
8251     FND_FILE.PUT_LINE(FND_FILE.LOG, 'Logical Receipt Transaction not seeded');
8252     FND_FILE.PUT_LINE(FND_FILE.LOG, 'Pre-upgrade transaction');
8253     IF g_debug = 'Y' THEN
8254       FND_FILE.PUT_LINE(FND_FILE.LOG, 'CSTPAVCP.Cost_LogicalSOReceipt >>>');
8255     END IF;
8256     RETURN;
8257   END IF;
8258 
8259   l_stmt_num := 12;
8260   SELECT INVENTORY_ASSET_FLAG
8261   INTO   l_exp_item
8262   FROM   MTL_SYSTEM_ITEMS
8263   WHERE  INVENTORY_ITEM_ID = l_item_id
8264   AND    ORGANIZATION_ID   = l_parent_org_id;
8265 
8266   if ( ( l_subinventory_code is null ) or
8267        ( l_exp_item = 'N' ) ) then
8268     l_exp_flag := 'Y';
8269   else
8270     l_stmt_num := 14;
8271     SELECT decode(ASSET_INVENTORY, 1, 'N', 'Y')
8272     INTO   l_exp_flag
8273     FROM   MTL_SECONDARY_INVENTORIES
8274     WHERE  SECONDARY_INVENTORY_NAME = l_subinventory_code
8275     AND    ORGANIZATION_ID          = l_parent_org_id;
8276   end if;
8277 
8278 
8279   /* If this is an expense item or an asset item
8280      issued from an expense sub in the sending org,
8281      the logical transaction is not accounted. Set
8282      the costed_flag and return */
8283   --
8284   -- Bug 5349860: umoogala
8285   -- For process/discrete xfer, we've to book exp and payables with transfer price.
8286   --
8287   IF l_pd_xfer_ind = 'N' AND -- Bug 5349860: umoogala
8288      l_exp_flag = 'Y' THEN
8289     l_stmt_num := 16;
8290     UPDATE
8291       MTL_MATERIAL_TRANSACTIONS
8292     SET
8293       COSTED_FLAG            = NULL,
8294       LAST_UPDATE_DATE       = sysdate,
8295       LAST_UPDATED_BY        = p_user_id,
8296       LAST_UPDATE_LOGIN      = p_login_id,
8297       REQUEST_ID             = p_request_id,
8298       PROGRAM_APPLICATION_ID = p_prog_app_id,
8299       PROGRAM_ID             = p_prog_id
8300     WHERE
8301       TRANSACTION_ID = l_logical_txn_id;
8302     IF g_debug = 'Y' THEN
8303       FND_FILE.PUT_LINE(FND_FILE.LOG, 'CSTPAVCP.Cost_LogicalSOReceipt >>>');
8304     END IF;
8305     RETURN;
8306 
8307   END IF;
8308 
8309   l_stmt_num := 20;
8310 
8311   -- Get Logical transaction details
8312   SELECT
8313     PRIMARY_QUANTITY,
8314     TRANSACTION_DATE,
8315     TRANSACTION_SOURCE_ID,
8316     TRANSACTION_SOURCE_TYPE_ID,
8317     TRANSACTION_TYPE_ID,
8318     TRANSACTION_ACTION_ID,
8319     CURRENCY_CODE,
8320     CURRENCY_CONVERSION_RATE,
8321     CURRENCY_CONVERSION_DATE,
8322     CURRENCY_CONVERSION_TYPE,
8323     DISTRIBUTION_ACCOUNT_ID,
8324     COST_GROUP_ID,
8325     TRANSFER_PRICE  -- Bug 5349860: umoogala
8326   INTO
8327     l_primary_quantity,
8328     l_txn_date,
8329     l_txn_src_id,
8330     l_txn_src_typ_id,
8331     l_txn_typ_id,
8332     l_txn_act_id,
8333     l_alt_curr,
8334     l_curr_conv_rate,
8335     l_curr_conv_date,
8336     l_curr_conv_type,
8337     l_debit_account,
8338     l_logical_cost_group_id,
8339     l_transfer_price  -- Bug 5349860: umoogala
8340   FROM
8341     MTL_MATERIAL_TRANSACTIONS
8342   WHERE
8343     TRANSACTION_ID = l_logical_txn_id;
8344 
8345   IF ( g_debug = 'Y' ) THEN
8346     FND_FILE.PUT_LINE(FND_FILE.LOG, 'Logical Receipt Txn: '||to_char(l_logical_txn_id));
8347     FND_FILE.PUT_LINE(FND_FILE.LOG, 'Receipt Org: '||to_char(l_logical_org_id));
8348     FND_FILE.PUT_LINE(FND_FILE.LOG, 'Receipt Cost Group: '||to_char(l_logical_cost_group_id));
8349   END IF;
8350 
8351 -- Get Expense subinventory information
8352   -- 1 for expense; 0 for not expense
8353   OPEN c_exp_sub(l_subinv_code
8354                 ,l_logical_org_id
8355                 );
8356 
8357   FETCH c_exp_sub
8358    INTO l_exp_sub;
8359 
8360   CLOSE c_exp_sub;
8361 
8362   IF ( g_debug = 'Y' ) THEN
8363     FND_FILE.PUT_LINE(FND_FILE.LOG, 'Expense Subinventory: '||to_char(l_exp_sub));
8364   END IF;
8365 
8366 
8367     -- ===================================================================
8368     -- Call costing extension hook get_account_id for debit account
8369     -- i_acct_line_type is 2 account
8370     -- 1 for debit; -1 for credit
8371     -- 1 for sending org; 2 for receiving org
8372     -- 1 for expnese; 0 for not expense
8373     -- return values
8374     --  > 0  User selected account number
8375     --   -1  Use the default account for distribution
8376     --    0  Error
8377     -- ===================================================================
8378     l_dr_acct_line_type := 2;
8379     /*ADDED VARIABLE i_cost_group_id FOR BUG8881927 */
8380 
8381     l_db_account := CSTPACHK.get_account_id
8382                     (i_org_id               => l_logical_org_id
8383                     ,i_txn_id               => l_logical_txn_id
8384                     ,i_debit_credit         => 1
8385                     ,i_acct_line_type       => l_dr_acct_line_type
8386                     ,i_cost_element_id      => 1
8387                     ,i_resource_id          => NULL
8388                     ,i_subinv               => l_subinv_code
8389                     ,i_exp                  => l_exp_sub
8390                     ,i_snd_rcv_org          => 2
8391                     ,o_err_num              => l_err_num
8392                     ,o_err_code             => l_err_code
8393                     ,o_err_msg              => l_err_msg
8394                     ,i_cost_group_id        => NULL
8395                     );
8396 
8397     IF l_db_account = 0 THEN
8398       RAISE COST_HOOK_ACCOUNT_ERROR;
8399     END IF;
8400 
8401     IF l_db_account > 0  THEN
8402     -- costing extension hook is enabled
8403       l_debit_account := l_db_account;
8404     END IF;
8405 
8406     IF ( g_debug = 'Y' ) THEN
8407       FND_FILE.PUT_LINE(FND_FILE.LOG, 'Debit Account: '||to_char(l_debit_account));
8408       FND_FILE.PUT_LINE(FND_FILE.LOG, 'Account Line Type: '||to_char(l_dr_acct_line_type));
8409     END IF;
8410 
8411 
8412   l_stmt_num := 30;
8413 
8414   SELECT
8415     PRIMARY_COST_METHOD
8416   INTO
8417     l_cost_method
8418   FROM
8419     MTL_PARAMETERS
8420   WHERE
8421     organization_id = l_logical_org_id;
8422 
8423 
8424   -- For non-Standard Orgs, Get layer information
8425   -- For Standard Costing Orgs, we use '-1' as the layer id in MCACD
8426 
8427   IF l_cost_method <> 1 THEN
8428     l_stmt_num := 40;
8429 
8430     l_layer_id := CSTPACLM.layer_id ( l_logical_org_id,
8431                                       l_item_id,
8432                                       l_logical_cost_group_id,
8433                                       l_err_num,
8434                                       l_err_code,
8435                                       l_err_msg );
8436     if (l_err_num <> 0) then
8437       raise fnd_api.g_exc_error;
8438     end if;
8439 
8440     -- Create a layer, if necessary
8441     if (l_layer_id = 0) then
8442       l_stmt_num := 50;
8443       l_layer_id := CSTPACLM.create_layer ( l_logical_org_id,
8444                                             l_item_id,
8445                                             l_logical_cost_group_id,
8446                                             p_user_id,
8447                                             p_request_id,
8448                                             p_prog_id,
8449                                             p_prog_app_id,
8450                                             l_logical_txn_id,
8451                                             l_err_num,
8452                                             l_err_code,
8453                                             l_err_msg );
8454       if (l_err_num <> 0) then
8455         raise fnd_api.g_exc_error;
8456       end if;
8457     end if;
8458   ELSE
8459     l_layer_id := -1;
8460   END IF;
8461 
8462   IF g_debug = 'Y' THEN
8463     FND_FILE.PUT_LINE(FND_FILE.LOG, 'Layer_ID: '||to_char(l_layer_id));
8464   END IF;
8465 
8466   -- Get Cost from parent transaction's MCACD.
8467   -- This is in parent org's primary currency
8468 
8469   l_stmt_num := 60;
8470   --
8471   -- Bug 5349860: umoogala
8472   -- For Process/Discrete xfer use transfer price, which is already in base currency.
8473   --
8474   IF l_pd_xfer_ind = 'N'
8475   THEN
8476     SELECT SUM(ACTUAL_COST)
8477     INTO   l_actual_cost
8478     FROM   MTL_CST_ACTUAL_COST_DETAILS
8479     WHERE  transaction_id = p_parent_txn_id;
8480   ELSE
8481     l_actual_cost := l_transfer_price;
8482   END IF;
8483 
8484   -- Get Primary Currency of Logixal Orgn
8485   l_stmt_num := 70;
8486 
8487   SELECT CURRENCY_CODE,
8488          SET_OF_BOOKS_ID,
8489          OPERATING_UNIT
8490   INTO   l_pri_curr,
8491          l_set_of_books_id,
8492          l_ou_id
8493   FROM   CST_ORGANIZATION_DEFINITIONS
8494   WHERE  ORGANIZATION_ID = l_logical_org_id;
8495 
8496   --------------------------------------------------------------------
8497   -- Internal Order Issue to Expense could be to the same organization
8498   -- In this case, the same debit and credit accounts are used for
8499   -- the receipt. I.E., If the organizations are same:
8500   -- Issue: Cr Inventory
8501   --          Dr Charge
8502   -- Receipt (This Txn): Cr Charge
8503   --                       Dr Charge
8504   -- Looks funny but it is a valid business practice to have such a
8505   -- scenario. The main part is in the cost collection of the receipt
8506   -- if it is project enabled
8507   --------------------------------------------------------------------
8508 
8509   IF l_parent_org_id <> l_logical_org_id THEN
8510     -- Do the currency conversions and obtain the converted amount
8511     -- Obtain the credit account from Interorg parameters
8512 
8513     --
8514     -- Bug 5349860: umoogala
8515     -- For process/discrete xfer, don't need to do any currency conversion
8516     -- as transfer price is already converted to receiving orgs base currency.
8517     --
8518     IF l_pd_xfer_ind = 'N'
8519     THEN
8520 
8521       -- Get Currency of Sending Organization
8522       l_stmt_num := 80;
8523 
8524       SELECT CURRENCY_CODE
8525       INTO   l_sending_curr
8526       FROM   CST_ORGANIZATION_DEFINITIONS
8527       WHERE  ORGANIZATION_ID = l_parent_org_id;
8528 
8529 
8530       -- Get the Conversion Type from the profile
8531       FND_PROFILE.get('CURRENCY_CONVERSION_TYPE', l_conversion_type);
8532 
8533       IF g_debug = 'Y' THEN
8534         fnd_file.put_line(fnd_file.log, 'Currency Conversion Type: '|| l_conversion_type);
8535       END IF;
8536 
8537       l_conversion_rate := GL_Currency_Api.Get_Rate(l_set_of_books_id,
8538                                                    l_sending_curr,
8539                                                    l_txn_date,
8540                                                    l_conversion_type);
8541 
8542       IF l_conversion_rate IS NULL THEN
8543         FND_FILE.put_line(FND_FILE.log, 'Currency Conversion Rate not defined: ');
8544         FND_FILE.put_line(FND_FILE.log, 'Currency From: '||l_sending_curr);
8545         FND_FILE.put_line(FND_FILE.log, 'Date: '||to_char(l_txn_date, 'DD-MON-YYYY'));
8546         FND_FILE.put_line(FND_FILE.log, 'Conversion Type: '||l_conversion_type);
8547         FND_FILE.put_line(FND_FILE.log, 'Please define the rate and resubmit transaction');
8548         RAISE NO_CURR_CONV_RATE_FOUND;
8549       END IF;
8550 
8551       l_actual_cost := l_actual_cost * l_conversion_rate;
8552     END IF;
8553 
8554    l_stmt_num := 85;
8555     -- ===================================================================
8556     -- Call costing extension hook get_account_id for credit account
8557     -- i_acct_line_type is 9 interorg payable account
8558     -- 1 for debit; -1 for credit
8559     -- 1 for expense; 0 for not expense
8560     -- 1 for sending org; 2 for receiving org
8561     -- ===================================================================
8562     l_cr_acct_line_type := 9;
8563     /*ADDED VARIABLE i_cost_group_id FOR BUG8881927 */
8564     l_credit_account := CSTPACHK.get_account_id
8565                         (i_org_id               => l_logical_org_id
8566                         ,i_txn_id               => l_logical_txn_id
8567                         ,i_debit_credit         => -1
8568                         ,i_acct_line_type       => l_cr_acct_line_type
8569                         ,i_cost_element_id      => 1
8570                         ,i_resource_id          => NULL
8571                         ,i_subinv               => l_subinv_code
8572                         ,i_exp                  => l_exp_sub
8573                         ,i_snd_rcv_org          => 2
8574                         ,o_err_num              => l_err_num
8575                         ,o_err_code             => l_err_code
8576                         ,o_err_msg              => l_err_msg
8577                         ,i_cost_group_id         => NULL);
8578 
8579     IF l_credit_account = 0 THEN
8580     -- costing hook extension error
8581       RAISE COST_HOOK_ACCOUNT_ERROR;
8582     END IF;
8583 
8584     IF g_debug = 'Y' THEN
8585       FND_FILE.PUT_LINE(FND_FILE.LOG, 'Credit Account: '||to_char(l_credit_account));
8586       FND_FILE.PUT_LINE(FND_FILE.LOG, 'Account Line Type: '||to_char(l_cr_acct_line_type));
8587     END IF;
8588 
8589       IF l_credit_account = -1 THEN
8590       -- default account behavior
8591 
8592         -- Get the Interorg payables account for this Interorg relationship
8593         l_stmt_num := 90;
8594 
8595         SELECT
8596           INTERORG_PAYABLES_ACCOUNT
8597         INTO
8598           l_credit_account
8599         FROM
8600           MTL_INTERORG_PARAMETERS
8601         WHERE
8602           FROM_ORGANIZATION_ID = l_parent_org_id
8603         AND TO_ORGANIZATION_ID = l_logical_org_id;
8604 
8605 
8606       END IF; -- costing hook disabled
8607 
8608     ELSE -- Same Organizations
8609       l_credit_account := l_debit_account;
8610       l_cr_acct_line_type := 2; -- Account
8611 
8612     END IF;
8613 
8614   IF g_debug = 'Y' THEN
8615     FND_FILE.PUT_LINE(FND_FILE.LOG, 'Actual_Cost or transfer price for process/discrete xfer: '||to_char(l_actual_cost));
8616     FND_FILE.PUT_LINE(FND_FILE.LOG, 'Credit_account: '||to_char(l_credit_account));
8617     FND_FILE.PUT_LINE(FND_FILE.LOG, 'Debit_account: '||to_char(l_debit_account));
8618   END IF;
8619 
8620   -- Insert Logical Transaction details into MCACD
8621 
8622   l_stmt_num := 100;
8623 
8624   BEGIN
8625     INSERT INTO MTL_CST_ACTUAL_COST_DETAILS (
8626       transaction_id,
8627       organization_id,
8628       layer_id,
8629       cost_element_id,
8630       level_type,
8631       transaction_action_id,
8632       last_update_date,
8633       last_updated_by,
8634       creation_date,
8635       created_by,
8636       last_update_login,
8637       request_id,
8638       program_application_id,
8639       program_id,
8640       program_update_date,
8641       inventory_item_id,
8642       actual_cost,
8643       insertion_flag,
8644       variance_amount,
8645       user_entered )
8646     VALUES (
8647       l_logical_txn_id,
8648       l_logical_org_id,
8649       l_layer_id,
8650       1, -- All Costs into MTL
8651       1, -- Level: TL
8652       decode(l_pd_xfer_ind, 'Y', 17, 1), -- Bug 5349860: umoogala
8653       sysdate,
8654       p_user_id,
8655       sysdate,
8656       p_user_id,
8657       p_login_id,
8658       p_request_id,
8659       p_prog_app_id,
8660       p_prog_id,
8661       sysdate,
8662       l_item_id,
8663       l_actual_cost,
8664       'N',
8665       0,
8666       'N');
8667   EXCEPTION
8668     WHEN OTHERS THEN
8669       RAISE INSERT_MCACD_ERROR;
8670   END;
8671   -- Create Accounting Entries for the Logical Transaction
8672   -- Insert Debit Entry
8673   l_stmt_num := 110;
8674 
8675   IF g_debug = 'Y' THEN
8676     FND_FILE.PUT_LINE(FND_FILE.LOG, 'Dr Exp Account with ' || l_actual_cost * l_primary_quantity || ' ' || l_pri_curr);
8677   END IF;
8678 
8679   CSTPACDP.INSERT_ACCOUNT(
8680              l_logical_org_id,
8681              l_logical_txn_id,
8682              l_item_id,
8683              l_actual_cost * l_primary_quantity,
8684              l_primary_quantity,
8685              l_debit_account,
8686              l_set_of_books_id,
8687              l_dr_acct_line_type,  -- Accounting_Line_Type
8688              1,                    -- Cost_Element
8689              NULL,                 -- Resource_Id
8690              l_txn_date,
8691              l_txn_src_id,
8692              l_txn_src_typ_id,
8693              l_pri_curr,
8694              l_alt_curr,
8695              l_curr_conv_date,
8696              l_curr_conv_rate,
8697              l_curr_conv_type,
8698              1,
8699              p_user_id,
8700              p_login_id,
8701              p_request_id,
8702              p_prog_app_id,
8703              p_prog_id,
8704              l_err_num,
8705              l_err_code,
8706              l_err_msg );
8707 
8708   IF l_err_num <> 0 THEN
8709     RAISE INSERT_ACCT_ERROR;
8710   END IF;
8711 
8712   -- Insert Credit Entry
8713   l_stmt_num := 120;
8714 
8715   IF g_debug = 'Y' THEN
8716     FND_FILE.PUT_LINE(FND_FILE.LOG, 'Cr Payables Account with ' || -1 * l_actual_cost * l_primary_quantity || ' ' || l_pri_curr);
8717   END IF;
8718 
8719   CSTPACDP.INSERT_ACCOUNT(
8720              l_logical_org_id,
8721              l_logical_txn_id,
8722              l_item_id,
8723              -1 * l_actual_cost * l_primary_quantity,
8724              -1 * l_primary_quantity,
8725              l_credit_account,
8726              l_set_of_books_id,
8727              l_cr_acct_line_type,  -- Accounting_Line_Type
8728              1,                    -- Cost_Element
8729              NULL,                 -- Resource_Id
8730              l_txn_date,
8731              l_txn_src_id,
8732              l_txn_src_typ_id,
8733              l_pri_curr,
8734              l_alt_curr,
8735              l_curr_conv_date,
8736              l_curr_conv_rate,
8737              l_curr_conv_type,
8738              1,               -- Actual_Flag
8739              p_user_id,
8740              p_login_id,
8741              p_request_id,
8742              p_prog_app_id,
8743              p_prog_id,
8744              l_err_num,
8745              l_err_code,
8746              l_err_msg );
8747 
8748   IF l_err_num <> 0 THEN
8749     RAISE INSERT_ACCT_ERROR;
8750   END IF;
8751 
8752 
8753   l_stmt_num := 130;
8754 
8755   /* Compute Encumbrance Amount and create the reversal entry,
8756      if applicable */
8757   SELECT nvl(req_encumbrance_flag,'N') /*nvl(purch_encumbrance_flag, 'N')Bug 6469694*/
8758   INTO   l_encumbrance_flag
8759   FROM   FINANCIALS_SYSTEM_PARAMS_ALL
8760   WHERE  set_of_books_id = l_set_of_books_id
8761   AND    ( ( l_ou_id is not NULL AND org_id = l_ou_id ) OR
8762            ( l_ou_id is null ) );
8763 
8764   IF l_encumbrance_flag = 'Y' THEN
8765 
8766     l_stmt_num := 140;
8767     CompEncumbrance_IntOrdersExp (
8768       p_api_version         => 1.0,
8769       p_transaction_id      => l_logical_txn_id,
8770       x_encumbrance_amount  => l_enc_amount,
8771       x_encumbrance_account => l_enc_account,
8772       x_return_status       => l_return_status,
8773       x_return_message      => l_return_message );
8774     IF l_return_status <> FND_API.G_RET_STS_SUCCESS THEN
8775       RAISE FND_API.G_EXC_UNEXPECTED_ERROR;
8776     END IF;
8777     IF ( l_enc_amount <> 0 AND l_enc_account is not null ) THEN
8778       l_stmt_num := 150;
8779       CSTPACDP.ENCUMBRANCE_ACCOUNT(
8780              l_logical_org_id,
8781              l_logical_txn_id,
8782              l_item_id,
8783              -1 * l_enc_amount,
8784              l_primary_quantity,
8785              l_enc_account,
8786              l_set_of_books_id,
8787              l_txn_date,
8788              l_txn_src_id,
8789              l_txn_src_typ_id,
8790              l_pri_curr,
8791              l_alt_curr,
8792              l_curr_conv_date,
8793              l_curr_conv_rate,
8794              l_curr_conv_type,
8795              p_user_id,
8796              p_login_id,
8797              p_request_id,
8798              p_prog_app_id,
8799              p_prog_id,
8800              l_err_num,
8801              l_err_code,
8802              l_err_msg );
8803 
8804 
8805       IF l_err_num <> 0 THEN
8806         RAISE INSERT_ACCT_ERROR;
8807       END IF;
8808     END IF; /* l_enc_amount <> 0 ... */
8809   END IF;   /* l_encumbrance_flag = 'Y' */
8810 
8811   -- Update MMT
8812   l_stmt_num := 160;
8813   UPDATE
8814     MTL_MATERIAL_TRANSACTIONS
8815   SET
8816     COSTED_FLAG            = NULL,
8817     transaction_group_id   = NULL,
8818     ENCUMBRANCE_AMOUNT     = l_enc_amount,
8819     ENCUMBRANCE_ACCOUNT    = l_enc_account,
8820     LAST_UPDATE_DATE       = sysdate,
8821     LAST_UPDATED_BY        = p_user_id,
8822     LAST_UPDATE_LOGIN      = p_login_id,
8823     REQUEST_ID             = p_request_id,
8824     PROGRAM_APPLICATION_ID = p_prog_app_id,
8825     PROGRAM_ID             = p_prog_id
8826   WHERE
8827     TRANSACTION_ID = l_logical_txn_id;
8828 
8829 
8830   IF g_debug = 'Y' THEN
8831     FND_FILE.PUT_LINE(FND_FILE.LOG, 'Creating XLA Event');
8832   END IF;
8833 
8834   --
8835   -- Bug 5349860: Process/Discrete Xfer
8836   -- Creating event for rct txn of Internal order issue to expense
8837   --
8838 
8839   /* Create Events in SLA */
8840   l_trx_info.TRANSACTION_ID       := l_logical_txn_id;
8841   l_trx_info.TXN_ACTION_ID        := 17;  -- Logical Expense Requisition Receipt
8842   l_trx_info.TXN_ORGANIZATION_ID  := l_logical_org_id;
8843   l_trx_info.TXN_SRC_TYPE_ID      := 7;   -- Internal requisition
8844   l_trx_info.TXFR_ORGANIZATION_ID := l_parent_org_id;
8845   l_trx_info.FOB_POINT            := NULL;
8846   l_trx_info.TRANSACTION_DATE     := l_txn_date;
8847   l_trx_info.PRIMARY_QUANTITY     := l_primary_quantity;
8848 
8849 --{BUG#6611359 encumbrance flag
8850   l_trx_info.ENCUMBRANCE_FLAG  := l_encumbrance_flag;
8851 --}
8852 
8853   IF l_pd_xfer_ind = 'Y'
8854   THEN
8855     l_trx_info.TP := 'Y';
8856   ELSE
8857     l_trx_info.TP := 'N';
8858   END IF;
8859 
8860   l_trx_info.attribute := NULL;
8861 
8862   l_stmt_num := 170;
8863 
8864   CST_XLA_PVT.Create_INVXLAEvent (
8865         p_api_version       => 1.0,
8866         p_init_msg_list     => FND_API.G_FALSE,
8867         p_commit            => FND_API.G_FALSE,
8868         p_validation_level  => FND_API.G_VALID_LEVEL_FULL,
8869         x_return_status     => l_return_status,
8870         x_msg_count         => l_msg_count,
8871         x_msg_data          => l_msg_data,
8872         p_trx_info          => l_trx_info
8873       );
8874 
8875   IF l_return_status <> 'S' THEN
8876     x_err_num  := -1;
8877     x_err_code := 'Error raising SLA Event for transaction: '||to_char(l_trx_info.TRANSACTION_ID);
8878     x_err_msg  := 'CSTPAVCP.Cost_LogicalSOReceipt:('||l_stmt_num||'): '||x_err_code || '. Error Msg: ' || l_msg_data;
8879 
8880     IF g_debug = 'Y' THEN
8881       FND_FILE.PUT_LINE(FND_FILE.LOG, 'CSTPAVCP.Cost_LogicalSOReceipt >>>');
8882     END IF;
8883 
8884     RAISE FND_API.g_exc_unexpected_error;
8885   END IF;
8886   /* End bug 5349860 */
8887 
8888   IF g_debug = 'Y' THEN
8889     FND_FILE.PUT_LINE(FND_FILE.LOG, 'CSTPAVCP.Cost_LogicalSOReceipt >>>');
8890   END IF;
8891 
8892 
8893 EXCEPTION
8894   WHEN NO_CURR_CONV_RATE_FOUND THEN
8895     x_err_num := -1;
8896     x_err_code := 'Currency Conversion Rate not defined';
8897     x_err_msg := x_err_code;
8898   WHEN INSERT_MCACD_ERROR THEN
8899     x_err_num := -1;
8900     x_err_code := 'CSTPAVCP.Cost_LogicalSOReceipt( '||to_char(l_stmt_num)||' ): '||'Error Inserting into MCACD: '||SQLERRM;
8901     x_err_msg := x_err_code;
8902     FND_FILE.PUT_LINE(FND_FILE.LOG, x_err_code);
8903   WHEN INSERT_ACCT_ERROR THEN
8904     x_err_num := -1;
8905     x_err_code := 'CSTPAVCP.Cost_LogicalSOReceipt( '||to_char(l_stmt_num)||' ): '||'Error in Insert_Account: ';
8906     x_err_msg := x_err_code;
8907     FND_FILE.PUT_LINE(FND_FILE.LOG, x_err_code);
8908 
8909   WHEN COST_HOOK_ACCOUNT_ERROR THEN
8910     x_err_num  := l_err_num;
8911     x_err_code := 'CSTPAVCP.Cost_LogicalSOReceipt' || l_err_code || 'Error in cost hook get_account_id' ;
8912     x_err_msg  := l_err_msg;
8913     FND_FILE.PUT_LINE(FND_FILE.LOG, x_err_code);
8914     FND_FILE.PUT_LINE(FND_FILE.LOG, x_err_msg);
8915 
8916   WHEN FND_API.g_exc_unexpected_error THEN
8917     rollback;
8918     UPDATE mtl_material_transactions
8919     SET    costed_flag = 'E',
8920            error_code = substrb(x_err_code,1,240),
8921            error_explanation = substrb(x_err_msg,1,240),
8922            request_id = p_request_id,
8923            program_application_id = p_prog_app_id,
8924            program_id = p_prog_id,
8925            program_update_date = sysdate
8926     WHERE  transaction_id = l_trx_info.TRANSACTION_ID;
8927     commit;
8928 
8929   WHEN OTHERS THEN
8930     x_err_num := -1;
8931     x_err_code := 'CSTPAVCP.Cost_LogicalSOReceipt( '||to_char(l_stmt_num)||' ): ';
8932     x_err_msg := x_err_code;
8933     FND_FILE.PUT_LINE(FND_FILE.LOG, x_err_code);
8934 
8935 END Cost_LogicalSOReceipt;
8936 
8937 /* ===========================================================
8938    OPM INVCONV umoogala/sschinch
8939    This procedure computes cost for a logical receipt in
8940    receiving organizations for a process discrete transfer
8941    ===========================================================*/
8942 
8943 PROCEDURE Cost_Logical_itr_receipt(
8944   I_ORG_ID      IN        NUMBER,
8945   I_TXN_ID      IN         NUMBER,
8946   I_LAYER_ID    IN        NUMBER,
8947   I_COST_TYPE   IN        NUMBER,
8948   I_ITEM_ID     IN        NUMBER,
8949   I_TXN_ACTION_ID IN    NUMBER,
8950   I_TXN_ORG_ID  IN        NUMBER,
8951   I_TXFR_ORG_ID  IN     NUMBER,
8952   I_COST_GRP_ID IN      NUMBER,
8953   I_TXFR_COST_GRP IN    NUMBER,
8954   I_FOB_POINT   IN        NUMBER,
8955   I_USER_ID     IN        NUMBER,
8956   I_LOGIN_ID    IN        NUMBER,
8957   I_REQ_ID      IN        NUMBER,
8958   I_PRG_APPL_ID IN      NUMBER,
8959   I_PRG_ID      IN        NUMBER,
8960   I_TPRICE_OPTION  IN   NUMBER,
8961   I_TXF_PRICE      IN   NUMBER,
8962   O_TXN_QTY     IN OUT NOCOPY        NUMBER,
8963   O_INTERORG_REC IN OUT NOCOPY  NUMBER,
8964   O_NO_UPDATE_MMT IN OUT NOCOPY NUMBER,
8965   O_EXP_FLAG    IN OUT NOCOPY        NUMBER,
8966   O_Err_Num     OUT NOCOPY        NUMBER,
8967   O_Err_Code    OUT NOCOPY        VARCHAR2,
8968   O_Err_Msg     OUT NOCOPY        VARCHAR2
8969 ) IS
8970   l_err_num     NUMBER;
8971   l_err_code    VARCHAR2(240);
8972   l_err_msg     VARCHAR2(240);
8973   l_stmt_num    NUMBER;
8974   process_error EXCEPTION;
8975   l_txn_update_id NUMBER;
8976   l_compute_txn_cost NUMBER;
8977   l_from_org    NUMBER;
8978   l_to_org      NUMBER;
8979   l_from_cost_grp NUMBER;
8980   l_to_cost_grp NUMBER;
8981   l_cost_type_id NUMBER;
8982   l_snd_txn_cost        NUMBER;
8983   l_rcv_txn_cost        NUMBER;
8984   l_new_txn_cost        NUMBER;
8985   l_txn_cost    NUMBER;
8986   l_txfr_cost   NUMBER;
8987   l_trans_cost  NUMBER;
8988   l_std_from_org        NUMBER;
8989   l_std_to_org          NUMBER;
8990   l_std_org             NUMBER;
8991   l_std_cost_org        NUMBER;
8992   l_std_exp             NUMBER;
8993   l_update_std          NUMBER;
8994   l_snd_sob_id          NUMBER;
8995   l_snd_curr            VARCHAR2(10);
8996   l_rcv_sob_id          NUMBER;
8997   l_rcv_curr            VARCHAR2(10);
8998   l_curr_type           VARCHAR2(30);
8999   l_conv_rate           NUMBER;
9000   l_conv_date           DATE;
9001   l_snd_uom             VARCHAR2(3);
9002   l_rcv_uom             VARCHAR2(3);
9003   l_snd_qty             NUMBER;
9004   l_count               NUMBER;
9005 -- item cost history stuff
9006   l_transfer_layer_id   NUMBER;
9007   l_transfer_layer_qty  NUMBER;
9008   l_which_org           NUMBER;
9009   l_which_cst_grp       NUMBER;
9010 -- item cost history stuff
9011 -- elemental visibility
9012   l_movh                NUMBER;
9013   l_movh_cost           NUMBER;
9014   l_rec_movh_cost       NUMBER;
9015   l_mctcd_ovhd          NUMBER;
9016   l_from_layer_id       NUMBER;
9017   l_elemental_visible   varchar2(1);
9018 -- elemental visibility
9019   l_um_rate             NUMBER;
9020   l_return_status       VARCHAR2(1);
9021   l_msg_count           NUMBER;
9022   l_msg_data            VARCHAR2(240);
9023   l_earn_moh            NUMBER;
9024   moh_rules_error       EXCEPTION;
9025 
9026   l_to_std_exp                  NUMBER;
9027   l_txfr_std_exp                NUMBER;
9028 
9029 BEGIN
9030   -- initialize local variables
9031   l_err_num := 0;
9032   l_err_code := '';
9033   l_err_msg := '';
9034   l_update_std := 0;
9035   l_snd_qty := o_txn_qty;
9036   l_std_exp := 0;
9037 
9038   IF g_debug = 'Y' THEN
9039     fnd_file.put_line(fnd_file.log, 'Cost_Logical_itr_receipt <<<');
9040     fnd_file.put_line(fnd_file.log, '- Process/Discrete Transfer -');
9041   END IF;
9042 
9043   l_earn_moh := 1;
9044   l_return_status := fnd_api.g_ret_sts_success;
9045   l_msg_count := 0;
9046 
9047   l_txfr_std_exp := 0;
9048   l_to_std_exp := 0;
9049   l_elemental_visible := 'N';
9050 
9051 
9052   -- l_from_org := i_txfr_org_id;
9053   -- l_to_org := i_txn_org_id;
9054   -- l_from_cost_grp := i_txfr_cost_grp;
9055   -- l_to_cost_grp := i_cost_grp_id;
9056 
9057   -- Figure the from and to org for this transaction.
9058   l_stmt_num := 5;
9059   if (i_txn_action_id IN (21,22)) then
9060     l_from_org := i_txn_org_id;
9061     l_to_org := i_txfr_org_id;
9062     l_from_cost_grp := i_cost_grp_id;
9063     l_to_cost_grp := i_txfr_cost_grp;
9064   elsif (i_txn_action_id = 12) then
9065     l_from_org := i_txfr_org_id;
9066     l_to_org := i_txn_org_id;
9067     l_from_cost_grp := i_txfr_cost_grp;
9068     l_to_cost_grp := i_cost_grp_id;
9069   elsif (i_txn_action_id =3 and o_txn_qty <0) then
9070     l_from_org := i_txn_org_id;
9071     l_to_org := i_txfr_org_id;
9072     l_from_cost_grp := i_cost_grp_id;
9073     l_to_cost_grp := i_txfr_cost_grp;
9074   elsif (i_txn_action_id = 1) then  -- Bug 5349860: internal order issue to expense destination
9075     l_from_org := i_txn_org_id;
9076     l_to_org := i_txfr_org_id;
9077     l_from_cost_grp := i_cost_grp_id;
9078     l_to_cost_grp := i_txfr_cost_grp;
9079   else
9080     l_from_org := i_txfr_org_id;
9081     l_to_org := i_txn_org_id;
9082     l_from_cost_grp := i_txfr_cost_grp;
9083     l_to_cost_grp := i_cost_grp_id;
9084   end if;
9085 
9086 
9087   --
9088   -- Bug 5021305/5677953
9089   -- The following are considered interorg receipt transactions.
9090   -- These are transactions where ownership changes and the current org
9091   -- is the receiving org.
9092   -- This flag is being used in compute_actual_cost before calling
9093   -- apply_material_ovhd.
9094   if ((i_txn_action_id = 3 and l_snd_qty > 0) OR
9095       (i_txn_action_id = 15) OR
9096       (i_txn_action_id = 12 and i_fob_point = 2))
9097   then
9098     o_interorg_rec := 1;
9099   else
9100     o_interorg_rec := 0;
9101   end if;
9102 
9103 
9104   -- item cost history stuff
9105   --
9106   -- For p-d xfers, in Avg Cost processor Org will always be Average Costin Org.
9107   -- Shipment to Std Orgs are being processed by Std Cost processor.
9108   --
9109   -- if (l_std_to_org = 0) then
9110   -- receiving org is average
9111   l_which_org := l_to_org;
9112   l_which_cst_grp := i_cost_grp_id;
9113   -- end if;
9114 
9115   if i_txn_action_id <> 1 and  -- Bug 5349860: exculding IO Issue to Exp Destination
9116      i_org_id = l_which_org then
9117       l_stmt_num := 10;
9118       UPDATE mtl_material_transactions mmt
9119       SET TRANSFER_PRIOR_COSTED_QUANTITY =
9120       (SELECT
9121               layer_quantity
9122       FROM      cst_quantity_layers cql
9123       WHERE     cql.organization_id = l_which_org
9124       AND       cql.inventory_item_id = i_item_id
9125       AND       cql.cost_group_id = l_which_cst_grp)
9126       WHERE mmt.transaction_id = i_txn_id
9127       AND EXISTS (
9128                       SELECT 'X'
9129                       FROM cst_quantity_layers cql
9130                       WHERE cql.organization_id = l_which_org
9131                       AND   cql.inventory_item_id = i_item_id
9132                       AND   cql.cost_group_id = l_which_cst_grp);
9133 
9134       IF SQL%ROWCOUNT = 0 THEN
9135         l_stmt_num := 20;
9136         update mtl_material_transactions mmt
9137                set TRANSFER_PRIOR_COSTED_QUANTITY = 0
9138         where  mmt.transaction_id = i_txn_id;
9139       END IF;
9140   end if;
9141   -- End of item cost history
9142 
9143    --
9144    -- Got rid of big chunck of code for standard costing org.
9145    -- For p-d xfers, in Avg Cost processor Org will always be Average Costin Org.
9146    -- Shipment to Std Orgs are being processed by Std Cost processor.
9147    --
9148 
9149    --
9150    -- Bug 5349860: transportation_cost should be zero for
9151    -- internal order issues to expense destination.
9152    --
9153    l_stmt_num := 30;
9154    IF i_txn_action_id <> 1
9155    THEN
9156    SELECT nvl(transportation_cost,0)
9157      INTO l_trans_cost
9158      FROM mtl_material_transactions
9159     WHERE transaction_id = i_txn_id;
9160    ELSE
9161      l_trans_cost := 0;
9162    END IF;
9163 
9164    --
9165    -- No need for any UOM or currency conversion as it is already done
9166    -- while creating MMT row for this logical transactions.
9167    -- For details refer to: INV_LOGICAL_TRANSACTIONS_PUB.create_opm_disc_logical_trx
9168    --
9169    IF g_debug = 'Y' THEN
9170      fnd_file.put_line(fnd_file.log, 'TxnOrg: ' || i_txn_org_id || ' Item: ' || i_item_id);
9171      fnd_file.put_line(fnd_file.log, 'fromOrg: ' || l_from_org || ' toOrg: ' || l_to_org);
9172      fnd_file.put_line(fnd_file.log, 'fromCG: ' || l_from_cost_grp || ' toCG: ' || l_to_cost_grp);
9173      fnd_file.put_line(fnd_file.log, 'Transaction Action: ' || i_txn_action_id);
9174      fnd_file.put_line(fnd_file.log, 'Transfer price options: ' || i_tprice_option ||
9175                 ' Transfer Price: ' || i_txf_price ||
9176                 ' Trp Cost: ' || l_trans_cost || ' Qty: ' || l_snd_qty);
9177    END IF;
9178 
9179    -- Bug 5450648: Should not add freight here since this is rcv_txn_cost is used to
9180    -- reaverage the cost.
9181    --
9182    -- Bug 5400992: Incorrect fix was done for the above bug 5450648.
9183    -- Following is the correct fix. Freight should be used in average costing only in case
9184    -- of FOB Shipment.
9185    --
9186    if ((i_txn_action_id = 12 and i_fob_point = 2) or (i_txn_action_id = 3 and o_txn_qty > 0)) then
9187      l_rcv_txn_cost := ((i_txf_price * abs(l_snd_qty)) ) / abs(l_snd_qty);
9188    else
9189      l_rcv_txn_cost := ((i_txf_price * abs(l_snd_qty)) + l_trans_cost) / abs(l_snd_qty);
9190    end if;
9191 
9192   if ((i_txn_action_id in (21,22)) OR
9193       (i_txn_action_id = 3 and l_snd_qty < 0))
9194   then
9195 
9196      l_stmt_num := 40;
9197      select item_cost, layer_id
9198        into l_snd_txn_cost, l_from_layer_id
9199        from cst_quantity_layers
9200       where organization_id = l_from_org
9201         and inventory_item_id = i_item_id
9202         and cost_group_id = l_from_cost_grp;
9203 
9204       l_new_txn_cost := (l_snd_txn_cost * abs(l_snd_qty)  + l_trans_cost) / abs(l_snd_qty);
9205 
9206       IF g_debug = 'Y' THEN
9207         fnd_file.put_line(fnd_file.log, 'Updating trx: ' || i_txn_id || ' with trxCost: ' || l_new_txn_cost);
9208       END IF;
9209 
9210       l_stmt_num := 50;
9211       Update mtl_material_transactions
9212       Set transaction_cost = l_new_txn_cost
9213       where transaction_id = i_txn_id;
9214 
9215   elsif (i_txn_action_id = 12 AND i_fob_point = 1)
9216   then
9217 
9218       IF g_debug = 'Y' THEN
9219         fnd_file.put_line(fnd_file.log, 'Updating trx: ' || i_txn_id || ' with trxCost: ' || l_rcv_txn_cost);
9220       END IF;
9221 
9222       l_stmt_num := 70;
9223       Update mtl_material_transactions
9224       Set transaction_cost = l_rcv_txn_cost
9225       where transaction_id = i_txn_id;
9226 
9227   elsif ((i_txn_action_id = 15) OR
9228          (i_txn_action_id = 3 and l_snd_qty > 0) OR
9229          (i_txn_action_id = 12 AND i_fob_point = 2))
9230   then
9231 
9232     IF g_debug = 'Y' THEN
9233       fnd_file.put_line(fnd_file.log, 'inserting to MCTCD for txn: ' || i_txn_id || '. trxCost: ' || l_rcv_txn_cost);
9234     END IF;
9235 
9236    l_stmt_num := 80;
9237    insert into mtl_cst_txn_cost_details (
9238               transaction_id,
9239               organization_id,
9240               cost_element_id,
9241               level_type,
9242               last_update_date,
9243               last_updated_by,
9244               creation_date,
9245               created_by,
9246               last_update_login,
9247               request_id,
9248               program_application_id,
9249               program_id,
9250               program_update_date,
9251               inventory_item_id,
9252               transaction_cost,
9253               new_average_cost,
9254               percentage_change,
9255               value_change)
9256           values (i_txn_id,
9257               l_to_org,
9258               1,
9259               1,
9260               sysdate,
9261               i_user_id,
9262               sysdate,
9263               i_user_id,
9264               i_login_id,
9265               i_req_id,
9266               i_prg_appl_id,
9267               i_prg_id,
9268               sysdate,
9269               i_item_id,
9270               l_rcv_txn_cost,
9271               0,
9272               0,
9273               0);
9274 
9275     l_stmt_num := 90;
9276     -- Update the transaction cost column if appropriate.
9277     Update mtl_material_transactions
9278     Set transaction_cost = l_rcv_txn_cost
9279     where transaction_id = i_txn_id;
9280 
9281   -- Bug 5349860: Internal Order issues to exp can also happen between
9282   ELSIF (i_txn_action_id = 1)
9283   THEN
9284 
9285     NULL;
9286     /*
9287      * Bug 5631478: unique constraint violation because of this insert.
9288      * Same insert is being done in compute_actual_cost procedure
9289      *
9290     IF g_debug = 'Y' THEN
9291       fnd_file.put_line(fnd_file.log, 'inserting to MCACD for IO Issue to exp txn');
9292     END IF;
9293 
9294     insert into mtl_cst_actual_cost_details(
9295     transaction_id,
9296     organization_id,
9297     layer_id,
9298     cost_element_id,
9299     level_type,
9300     transaction_action_id,
9301     last_update_date,
9302     last_updated_by,
9303     creation_date,
9304     created_by,
9305     last_update_login,
9306     request_id,
9307     program_application_id,
9308     program_id,
9309     program_update_date,
9310     inventory_item_id,
9311     actual_cost,
9312     prior_cost,
9313     new_cost,
9314     insertion_flag,
9315     variance_amount,
9316     user_entered)
9317     select
9318     i_txn_id,
9319     i_org_id,
9320     i_layer_id,
9321     clcd.cost_element_id,
9322     clcd.level_type,
9323     i_txn_action_id,
9324     sysdate,
9325     i_user_id,
9326     sysdate,
9327     i_user_id,
9328     i_login_id,
9329     i_req_id,
9330     i_prg_appl_id,
9331     i_prg_id,
9332     sysdate,
9333     i_item_id,
9334     clcd.item_cost,
9335     clcd.item_cost,
9336     clcd.item_cost,
9337     'N',
9338     0,
9339     'N'
9340     from cst_layer_cost_details clcd
9341     where layer_id = i_layer_id;
9342     */
9343 
9344   END IF;
9345 
9346   IF g_debug = 'Y' THEN
9347     fnd_file.put_line(fnd_file.log, 'Cost Logical Intransit Receipt >>>');
9348   END IF;
9349 
9350   EXCEPTION
9351     when others then
9352       rollback;
9353       o_err_num := SQLCODE;
9354       o_err_msg := 'CSTPAVCP.Logical_itr_receipt(' || to_char(l_stmt_num) ||
9355                    '): ' || substr(SQLERRM, 1,200);
9356 
9357 END Cost_Logical_itr_receipt;
9358 
9359 PROCEDURE CompEncumbrance_IntOrdersExp (
9360             p_api_version     IN NUMBER,
9361             p_transaction_id  IN MTL_MATERIAL_TRANSACTIONS.TRANSACTION_ID%TYPE,
9362             p_req_line_id     IN PO_REQUISITION_LINES_ALL.REQUISITION_LINE_ID%TYPE,
9363             p_item_id         IN MTL_SYSTEM_ITEMS.INVENTORY_ITEM_ID%TYPE,
9364             p_organization_id IN MTL_PARAMETERS.ORGANIZATION_ID%TYPE,
9365             p_primary_qty     IN MTL_MATERIAL_TRANSACTIONS.PRIMARY_QUANTITY%TYPE,
9366             p_total_primary_qty   IN NUMBER,
9367             x_encumbrance_amount  OUT NOCOPY NUMBER,
9368             x_encumbrance_account OUT NOCOPY NUMBER,
9369             x_return_status       OUT NOCOPY VARCHAR,
9370             x_return_message      OUT NOCOPY VARCHAR2
9371  ) IS
9372 
9373 l_doc_line_qty           PO_REQUISITION_LINES_ALL.QUANTITY%TYPE;
9374 l_doc_unit_price         PO_REQUISITION_LINES_ALL.UNIT_PRICE%TYPE;
9375 l_unit_price             PO_REQUISITION_LINES_ALL.UNIT_PRICE%TYPE;
9376 l_conversion_rate        NUMBER;
9377 l_primary_uom_code       MTL_UNITS_OF_MEASURE.UOM_CODE%TYPE;
9378 l_doc_uom_code           MTL_UNITS_OF_MEASURE.UOM_CODE%TYPE;
9379 l_uom_rate               NUMBER;
9380 l_doc_primary_qty        NUMBER;
9381 l_doc_rcv_qty            NUMBER;
9382 
9383 l_stmt_num               NUMBER;
9384 l_api_name               VARCHAR2(100) := 'CompEncumbrance_IntOrdersExp';
9385 l_api_version            NUMBER := 1.0;
9386 /* Bug 6405593*/
9387 l_hook_used                  NUMBER;
9388 l_non_recoverable_tax        NUMBER;
9389 l_loc_non_recoverable_tax    NUMBER;
9390 l_loc_recoverable_tax        NUMBER;
9391 l_Err_Num                    NUMBER;
9392 l_Err_Code                   NUMBER;
9393 process_error                EXCEPTION;
9394 /* Bug 6405593*/
9395 
9396 BEGIN
9397 
9398   x_return_status := FND_API.G_RET_STS_SUCCESS;
9399 
9400   if g_debug = 'Y' then
9401     fnd_file.put_line(fnd_file.log, 'CompEncumbrance_IntOrdersExp << ');
9402   end if;
9403 
9404   l_stmt_num := 5;
9405 
9406   IF NOT FND_API.Compatible_API_Call (
9407                                        l_api_version,
9408                                        p_api_version,
9409                                        l_api_name,
9410                                        G_PKG_NAME ) THEN
9411     RAISE FND_API.G_EXC_UNEXPECTED_ERROR;
9412   END IF;
9413 
9414 
9415 
9416 
9417   /* 1. Get the budget_account, quantity ordered, and UOM from the Req */
9418   l_stmt_num := 10;
9419   SELECT um.uom_code,
9420          rl.quantity,
9421          rl.unit_price,
9422          rd.budget_account_id,
9423          nvl(rd.nonrecoverable_tax,0) /* Bug 6405593 */
9424   INTO   l_doc_uom_code,
9425          l_doc_line_qty,
9426          l_unit_price,
9427          x_encumbrance_account,
9428          l_non_recoverable_tax  /* Bug 6405593 */
9429   FROM   po_req_distributions_all rd,
9430          po_requisition_lines_all rl,
9431          mtl_units_of_measure um
9432   WHERE  rd.requisition_line_id   = p_req_line_id
9433   and    rd.requisition_line_id   = rl.requisition_line_id
9434   and    rl.UNIT_MEAS_LOOKUP_CODE = um.unit_of_measure;
9435 
9436   if g_debug = 'Y' then
9437     fnd_file.put_line(fnd_file.log, 'Unit Price: '||l_unit_price||'Encumbrance Account: '||x_encumbrance_account);
9438   end if;
9439 
9440   /* Get UOM for this item/org from MSI */
9441   l_stmt_num := 30;
9442   SELECT primary_uom_code
9443   INTO   l_primary_uom_code
9444   FROM   mtl_system_items
9445   WHERE  organization_id   = p_organization_id
9446   AND    inventory_item_id = p_item_id;
9447 
9448   if g_debug = 'Y' then
9449     fnd_file.put_line(fnd_file.log, 'Primary UOM: '||l_primary_uom_code);
9450   end if;
9451   /* Convert the total_primary_quantity into source_doc_quantity */
9452   l_stmt_num := 40;
9453   INV_Convert.INV_UM_Conversion(
9454                           from_unit       => l_primary_uom_code,
9455                           to_unit         => l_doc_uom_code,
9456                           item_id         => p_item_id,
9457                           uom_rate        => l_uom_rate );
9458   IF ( l_uom_rate = -99999) THEN
9459     x_return_message := 'Inv_Convert.inv_um_conversion() failed to get the UOM rate';
9460     x_return_status  := FND_API.G_RET_STS_ERROR;
9461     RAISE FND_API.G_EXC_ERROR;
9462   END IF;
9463 
9464   l_doc_rcv_qty     := p_total_primary_qty * l_uom_rate;
9465   l_doc_primary_qty := p_primary_qty * l_uom_rate;
9466   if g_debug = 'Y' then
9467     fnd_file.put_line(fnd_file.log, 'Document Received Quantity: '||l_doc_rcv_qty||' Document Primary Quantity: '||l_doc_primary_qty);
9468     fnd_file.put_line(fnd_file.log, 'Calling CST_Common_hooks.Get_NRtax_amount for MMT-REQ Req_line_id '||p_req_line_id);
9469   end if;
9470 
9471       /* Bug 6405593 :Added hook call to override the recoverable and Non-Recoverable
9472                       taxes for ENCUMBRANCE REVERSAL*/
9473         l_stmt_num := 45;
9474          l_hook_used := CST_Common_hooks.Get_NRtax_amount(
9475                         I_ACCT_TXN_ID        =>p_transaction_id,
9476                         I_SOURCE_DOC_TYPE    =>'REQ',
9477                         I_SOURCE_DOC_ID      =>p_req_line_id,
9478                         I_ACCT_SOURCE        =>'MMT',
9479                         I_USER_ID            =>fnd_global.user_id,
9480                         I_LOGIN_ID           =>fnd_global.login_id,
9481                         I_REQ_ID             =>fnd_global.conc_request_id,
9482                         I_PRG_APPL_ID        =>fnd_global.prog_appl_id,
9483                         I_PRG_ID             =>fnd_global.conc_program_id,
9484                         O_DOC_NR_TAX         =>l_loc_non_recoverable_tax,
9485                         O_DOC_REC_TAX        =>l_loc_recoverable_tax,
9486                         O_Err_Num            =>l_Err_Num,
9487                         O_Err_Code           =>l_Err_Code,
9488                         O_Err_Msg            =>x_return_message
9489                                    );
9490         IF l_hook_used <>0 THEN
9491 
9492          IF (l_err_num <> 0) THEN
9493               -- Error occured
9494               IF G_DEBUG = 'Y' THEN
9495                    fnd_file.put_line(fnd_file.log, 'Error getting Enc Tax in CST_Common_hooks.Get_NRtax_amount at statement :'||l_stmt_num);
9496                    fnd_file.put_line(fnd_file.log, 'Error Code :  '||l_err_code||' Error Message : '||x_return_message);
9497               END IF;
9498               RAISE process_error;
9499             END IF;
9500 
9501 
9502         IF G_DEBUG = 'Y' THEN
9503            fnd_file.put_line(fnd_file.log,'Hook Used  CST_Common_hooks.Get_NRtax_amount :'|| l_hook_used ||
9504                              ' l_loc_recoverable_tax : '||l_loc_recoverable_tax||
9505                              ' l_loc_non_recoverable_tax : '||l_loc_non_recoverable_tax);
9506         END IF;
9507 
9508         l_non_recoverable_tax:=nvl(l_non_recoverable_tax,0)+nvl(l_loc_non_recoverable_tax,0);
9509 
9510        END IF;
9511       /* Bug 6405593 :Added hook call to override the recoverable and Non-Recoverable
9512                       taxes for ENCUMBRANCE_REVERSAL event */
9513 
9514   /* The Requisition is always in the funtional currency */
9515   /* No need of currency conversion */
9516   /* Commented for Bug 6405593 */
9517 /*  IF ( l_doc_rcv_qty  >= l_doc_line_qty ) THEN
9518     x_encumbrance_amount := 0;
9519   ELSIF ( l_doc_rcv_qty + l_doc_primary_qty ) >= l_doc_line_qty THEN
9520     x_encumbrance_amount :=  l_unit_price *
9521                              ( l_doc_line_qty - l_doc_rcv_qty );
9522   ELSE
9523     x_encumbrance_amount :=  l_unit_price * l_doc_primary_qty;
9524   END IF; */
9525 
9526   /* Commented for Bug 6405593 */
9527 
9528   /* Added for Bug 6405593 */
9529   IF ( l_doc_rcv_qty  >= l_doc_line_qty ) THEN
9530     x_encumbrance_amount := 0;
9531   ELSIF ( l_doc_rcv_qty + l_doc_primary_qty ) >= l_doc_line_qty THEN
9532     x_encumbrance_amount :=  l_unit_price * ( l_doc_line_qty - l_doc_rcv_qty )
9533                             +nvl(l_non_recoverable_tax,0)*( l_doc_line_qty - l_doc_rcv_qty )/l_doc_line_qty;
9534   ELSE
9535     x_encumbrance_amount :=  l_unit_price * l_doc_primary_qty
9536                             +nvl(l_non_recoverable_tax,0)*(l_doc_primary_qty/l_doc_line_qty);
9537   END IF;
9538   /* Added for Bug 6405593 */
9539 
9540   if g_debug = 'Y' then
9541     fnd_file.put_line(fnd_file.log, 'Encumbrance Amount: '||x_encumbrance_amount);
9542     fnd_file.put_line(fnd_file.log, 'CompEncumbrance_IntOrdersExp >>');
9543   end if;
9544 
9545 EXCEPTION
9546   WHEN FND_API.G_EXC_ERROR THEN
9547     x_return_status := fnd_api.g_ret_sts_error;
9548   WHEN FND_API.G_EXC_UNEXPECTED_ERROR THEN
9549     x_return_status := fnd_api.g_ret_sts_unexp_error;
9550   WHEN process_error THEN
9551     x_return_status := fnd_api.g_ret_sts_unexp_error;
9552     x_return_message := 'Error in CSTPAVCP.CompEncumbrance_IntOrdersExp('||l_stmt_num||')';
9553   WHEN OTHERS THEN
9554     x_return_status := fnd_api.g_ret_sts_unexp_error;
9555     x_return_message := 'Error in CST_UTIL_PUB.CompEncumbrance_IntOrdersExp('||l_stmt_num||')';
9556 
9557 END CompEncumbrance_IntOrdersExp;
9558 
9559 PROCEDURE CompEncumbrance_IntOrdersExp (
9560             p_api_version     IN NUMBER,
9561             p_transaction_id  IN MTL_MATERIAL_TRANSACTIONS.TRANSACTION_ID%TYPE,
9562             x_encumbrance_amount  OUT NOCOPY NUMBER,
9563             x_encumbrance_account OUT NOCOPY NUMBER,
9564             x_return_status       OUT NOCOPY VARCHAR,
9565             x_return_message      OUT NOCOPY VARCHAR2
9566  ) IS
9567 
9568 l_total_primary_qty      NUMBER;
9569 l_primary_qty            MTL_MATERIAL_TRANSACTIONS.PRIMARY_QUANTITY%TYPE;
9570 l_organization_id        MTL_MATERIAL_TRANSACTIONS.ORGANIZATION_ID%TYPE;
9571 l_trx_source_line_id     MTL_MATERIAL_TRANSACTIONS.TRX_SOURCE_LINE_ID%TYPE;
9572 l_req_line_id            PO_REQUISITION_LINES_ALL.REQUISITION_LINE_ID%TYPE;
9573 l_item_id                MTL_MATERIAL_TRANSACTIONS.INVENTORY_ITEM_ID%TYPE;
9574 l_txn_action_id          MTL_MATERIAL_TRANSACTIONS.TRANSACTION_ACTION_ID%TYPE;
9575 l_txn_src_type_id
9576 MTL_MATERIAL_TRANSACTIONS.TRANSACTION_SOURCE_TYPE_ID%TYPE;
9577 l_rcv_txn_id             MTL_MATERIAL_TRANSACTIONS.RCV_TRANSACTION_ID%TYPE;
9578 l_txn_type_id            MTL_MATERIAL_TRANSACTIONS.TRANSACTION_TYPE_ID%TYPE;
9579 
9580 
9581 l_stmt_num               NUMBER;
9582 l_api_name               VARCHAR2(100) := 'CompEncumbrance_IntOrdersExp';
9583 l_api_version            NUMBER := 1.0;
9584 
9585 BEGIN
9586 
9587   x_return_status := FND_API.G_RET_STS_SUCCESS;
9588 
9589   if g_debug = 'Y' then
9590     fnd_file.put_line(fnd_file.log, 'CompEncumbrance_IntOrdersExp (T) <<');
9591   end if;
9592   l_stmt_num := 5;
9593 
9594   IF NOT FND_API.Compatible_API_Call (
9595                                        l_api_version,
9596                                        p_api_version,
9597                                        l_api_name,
9598                                        G_PKG_NAME ) THEN
9599     RAISE FND_API.G_EXC_UNEXPECTED_ERROR;
9600   END IF;
9601 
9602   l_stmt_num := 10;
9603 
9604   SELECT
9605     mmt.trx_source_line_id,
9606     mmt.primary_quantity,
9607     mmt.organization_id,
9608     mmt.inventory_item_id,
9609     mmt.transaction_action_id,
9610     mmt.transaction_source_type_id,
9611     mmt.transaction_type_id,
9612     mmt.rcv_transaction_id
9613   INTO
9614     l_trx_source_line_id,
9615     l_primary_qty,
9616     l_organization_id,
9617     l_item_id,
9618     l_txn_action_id,
9619     l_txn_src_type_id,
9620     l_txn_type_id,
9621     l_rcv_txn_id
9622   FROM
9623     MTL_MATERIAL_TRANSACTIONS mmt
9624   WHERE
9625     transaction_id = p_transaction_id;
9626 
9627   /* Get total received (and costed) quantity */
9628 
9629   l_stmt_num := 20;
9630   SELECT sum(primary_quantity)
9631   INTO   l_total_primary_qty
9632   from   mtl_material_transactions
9633   where  transaction_action_id      = l_txn_action_id
9634   and    transaction_source_type_id = l_txn_src_type_id
9635   and    transaction_type_id        = l_txn_type_id
9636   and    trx_source_line_id         = l_trx_source_line_id
9637   and    costed_flag IS NULL ;
9638 
9639   if g_debug = 'Y' then
9640     fnd_file.put_line(fnd_file.log, 'Total Received Primary Qty: '||l_total_primary_qty);
9641   end if;
9642 
9643   /* Get Requisition Line ID */
9644   /* For Internal Order Requisition Receipt, this is the MMT.TRX_SOURCE_LINE_ID
9645      Using above information, find the requisition_line_id */
9646   l_stmt_num := 25;
9647 
9648   IF ( l_txn_action_id       = 17
9649        AND l_txn_src_type_id = 7
9650        AND l_txn_type_id     = 27 ) THEN
9651     l_req_line_id := l_trx_source_line_id;
9652   ELSE
9653 
9654     /*
9655      * Internal Order Intransit Shipment (62, 21, 8),
9656      * Int Req Direct Org Xfr (95, 3, 7),
9657      * Int Order Direct Ship (54, 3, 8): TRX_SOURCE_LINE_ID = OE_ORDER_LINE_ID.LINE_ID
9658      * For Internal Req Intr Rcpt (61, 12, 7) and its adjustment (72, 29, 7):
9659      * TRANSACTION_SOURCE_ID = REQUISITION_HEADER_ID, also RCV_TRANSACTION_ID is populated
9660      * which provides the requisition_line_id from RCV_TRANSACTIONS  */
9661     IF ( ( l_txn_action_id   = 3
9662        AND l_txn_src_type_id = 7 ) OR
9663         ( l_txn_action_id    = 3
9664        AND l_txn_src_type_id = 8 ) OR
9665         ( l_txn_action_id           = 21
9666        AND l_txn_src_type_id = 8) ) THEN
9667       l_stmt_num := 27;
9668       SELECT
9669         oel.SOURCE_DOCUMENT_LINE_ID
9670       INTO
9671         l_req_line_id
9672       FROM
9673         OE_ORDER_LINES_ALL oel,
9674         cst_acct_info_v caiv
9675       WHERE
9676           oel.LINE_ID          = l_trx_source_line_id
9677       and oel.org_id           = caiv.operating_unit
9678       and caiv.organization_id = l_organization_id;
9679 
9680     ELSIF ( ( l_txn_action_id = 12
9681        AND l_txn_src_type_id  = 7) OR
9682             ( l_txn_action_id = 29
9683        AND l_txn_src_type_id  = 7 ) ) THEN
9684        SELECT
9685          REQUISITION_LINE_ID
9686        INTO
9687          l_req_line_id
9688        FROM
9689          RCV_TRANSACTIONS
9690        WHERE
9691          TRANSACTION_ID = l_rcv_txn_id;
9692     ELSE
9693       RETURN;
9694     END IF;
9695   END IF;
9696   if g_debug = 'Y' then
9697     fnd_file.put_line(fnd_file.log, 'Requisition Line ID: '||l_req_line_id);
9698   end if;
9699 
9700   l_primary_qty := abs(l_primary_qty);
9701   l_total_primary_qty := abs(l_total_primary_qty);
9702 
9703   if g_debug = 'Y' then
9704     fnd_file.put_line(fnd_file.log, 'Total Received Primary Qty: '||l_total_primary_qty);
9705   end if;
9706   l_stmt_num := 30;
9707   CompEncumbrance_IntOrdersExp (
9708             p_api_version         => 1.0,
9709             p_transaction_id      => p_transaction_id,
9710             p_req_line_id         => l_req_line_id,
9711             p_item_id             => l_item_id,
9712             p_organization_id     => l_organization_id,
9713             p_primary_qty         => l_primary_qty,
9714             p_total_primary_qty   => l_total_primary_qty,
9715 
9716             x_encumbrance_amount  => x_encumbrance_amount,
9717             x_encumbrance_account => x_encumbrance_account,
9718             x_return_status       => x_return_status,
9719             x_return_message      => x_return_message
9720   );
9721   if g_debug = 'Y' then
9722     fnd_file.put_line(fnd_file.log, 'CompEncumbrance_IntOrdersExp (T) >>');
9723   end if;
9724 
9725 EXCEPTION
9726   WHEN FND_API.G_EXC_UNEXPECTED_ERROR THEN
9727     x_return_status := fnd_api.g_ret_sts_unexp_error;
9728     x_return_message := 'Error in CST_UTIL_PUB.CompEncumbrance_IntOrdersExp('||l_stmt_num||')';
9729   WHEN OTHERS THEN
9730     x_return_status := fnd_api.g_ret_sts_unexp_error;
9731     x_return_message := 'Error in CST_UTIL_PUB.CompEncumbrance_IntOrdersExp('||l_stmt_num||')';
9732 
9733 
9734 END CompEncumbrance_IntOrdersExp;
9735 
9736 /*===========================================================================
9737 |  Procedure:   validate_actual_cost_hook                                    |
9738 |  Author:      Ivan Pineda                                                  |
9739 |  Date:        November 29, 2008                                            |
9740 |  Description: This procedure will be called  after  the  actual_cost_hook  |
9741 |               client extension has been called to validate the data .  We  |
9742 |               will raise two different errors. If the hook is called  and  |
9743 |               there is no data in MCACD for that transaction then we will  |
9744 |               raise exception no_mcacd_for_hook. If the data inserted  in  |
9745 |               MCACD has the insertion flag as 'Y' and there  are  details  |
9746 |               in CLCD we will raise exception insertion_flag_in_mcacd      |
9747 |                                                                            |
9748 |  Parameters:  i_txn_id: Transaction id                                     |
9749 |               i_org_id: Organization id                                    |
9750 |               i_layer_id: Layer id                                         |
9751 |                                                                            |
9752 |                                                                            |
9753 |===========================================================================*/
9754 PROCEDURE validate_actual_cost_hook(
9755 i_txn_id IN NUMBER,
9756 i_org_id IN NUMBER,
9757 i_layer_id IN NUMBER,
9758 i_req_id IN NUMBER,
9759 i_prg_appl_id IN NUMBER,
9760 i_prg_id IN NUMBER,
9761 O_err_num OUT NOCOPY NUMBER,
9762 O_err_code OUT NOCOPY VARCHAR2,
9763 O_err_msg OUT NOCOPY VARCHAR2
9764 ) IS
9765 l_err_num NUMBER;
9766 l_err_code VARCHAR2(240);
9767 l_err_msg VARCHAR2(240);
9768 l_stmt_num NUMBER;
9769 l_test_mcacd NUMBER:=0;
9770 l_test_clcd NUMBER:=0;
9771 insertion_flag_in_mcacd EXCEPTION;
9772 BEGIN
9773 
9774 /* Verify if the hook was called, see if it has been used and check if there is data in MCACD*/
9775 SELECT  COUNT(*)
9776 INTO    l_test_mcacd
9777 FROM    MTL_CST_ACTUAL_COST_DETAILS MCACD
9778 WHERE   TRANSACTION_ID = i_txn_id
9779 AND     LAYER_ID = i_layer_id
9780 AND     ORGANIZATION_ID = i_org_id;
9781 
9782 IF (l_test_mcacd = 0) THEN
9783         raise no_data_found;
9784 END IF;
9785 
9786 /* There shouldn't be details in CLCD if the insertion flag in MCACD is set as Y
9787    for that cost element, it will suffice that one of the cost element violates
9788    this condition to error out                                                 */
9789 SELECT  Count(*)
9790 INTO    l_test_clcd
9791 FROM    MTL_CST_ACTUAL_COST_DETAILS MCACD
9792 WHERE   MCACD.transaction_id = i_txn_id
9793 AND     MCACD.organization_id = i_org_id
9794 AND     MCACD.layer_id = i_layer_id
9795 AND     Nvl(MCACD.insertion_flag,'N')='Y'
9796 AND     EXISTS (SELECT 'X'
9797                FROM CST_LAYER_COST_DETAILS CLCD
9798                WHERE MCACD.layer_id = CLCD.layer_id
9799                AND   MCACD.cost_element_id = CLCD.cost_element_id
9800                AND   MCACD.level_type = CLCD.level_type);
9801 
9802 
9803 IF g_debug = 'Y' THEN
9804         fnd_file.put_line(fnd_file.log, '>>>i_txn_id: '||to_char(i_txn_id)||' MCACD: '||to_char(l_test_mcacd)||' Layer_id: '||to_char(i_layer_id));
9805 END IF;
9806 
9807 
9808 IF  (l_test_clcd <> 0) THEN
9809         fnd_file.put_line(fnd_file.log, 'There should not be details in CLCD if the insertion flag in MCACD is set to Y in the hook');
9810         raise insertion_flag_in_mcacd;
9811 END IF;
9812 
9813 EXCEPTION
9814 WHEN  no_data_found THEN
9815       rollback;
9816       o_err_num := 9999;
9817       o_err_code := 'CST_NO_COST_HOOK_DATA';
9818       FND_MESSAGE.set_name('BOM', 'CST_NO_COST_HOOK_DATA');
9819       o_err_msg := FND_MESSAGE.Get;
9820 
9821       UPDATE mtl_material_transactions
9822       SET    costed_flag = 'E',
9823              error_code = substrb(o_err_code,1,240),
9824              error_explanation = substrb(o_err_msg,1,240),
9825              request_id = i_req_id,
9826              program_application_id = i_prg_appl_id,
9827              program_id = i_prg_id,
9828              program_update_date = sysdate
9829       WHERE  transaction_id = i_txn_id;
9830 WHEN insertion_flag_in_mcacd THEN
9831       rollback;
9832       o_err_num := 9999;
9833       o_err_code := 'CST_CLCD_WITH_INS_FLAG';
9834       FND_MESSAGE.set_name('BOM','CST_CLCD_WITH_INS_FLAG');
9835       FND_MESSAGE.set_token('TXN_ID', i_txn_id);
9836       o_err_msg := FND_MESSAGE.Get;
9837       UPDATE mtl_material_transactions
9838       SET    costed_flag = 'E',
9839              error_code = substrb(o_err_code,1,240),
9840              error_explanation = substrb(o_err_msg,1,240),
9841              request_id = i_req_id,
9842              program_application_id = i_prg_appl_id,
9843              program_id = i_prg_id,
9844              program_update_date = sysdate
9845       WHERE  transaction_id = i_txn_id;
9846 WHEN others THEN
9847       rollback;
9848       o_err_num:=SQLCODE;
9849       o_err_msg:='CSTPAVCP.validate_actual_cost_hook('||to_char(l_stmt_num)||'):'||substr(SQLERRM,1,200);
9850       UPDATE mtl_material_transactions
9851       SET    costed_flag = 'E',
9852              error_code = substrb(o_err_code,1,240),
9853              error_explanation = substrb(o_err_msg,1,240),
9854              request_id = i_req_id,
9855              program_application_id = i_prg_appl_id,
9856              program_id = i_prg_id,
9857              program_update_date = sysdate
9858       WHERE  transaction_id = i_txn_id;
9859 END validate_actual_cost_hook;
9860 
9861 END CSTPAVCP;