DBA Data[Home] [Help]

PACKAGE BODY: APPS.CSTPAVCP

Source


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