DBA Data[Home] [Help]

PACKAGE BODY: APPS.CST_EAMCOST_PUB

Source


1 PACKAGE BODY  CST_eamCost_PUB AS
2 /* $Header: CSTPEACB.pls 120.50.12020000.5 2013/02/06 10:01:17 zazeng ship $ */
3 
4 G_PKG_NAME  CONSTANT VARCHAR2(30) := 'CST_eamCost_PUB';
5 G_LOG_LEVEL CONSTANT NUMBER       := FND_LOG.G_CURRENT_RUNTIME_LEVEL;
6 PG_DEBUG             VARCHAR2(1)  := NVL(FND_PROFILE.value('AFLOG_ENABLED'), 'N');
7 
8 PROCEDURE debug
9 ( line       IN VARCHAR2,
10   msg_prefix IN VARCHAR2  DEFAULT 'CST',
11   msg_module IN VARCHAR2  DEFAULT 'CST_EAMCOST_PUB',
12   msg_level  IN NUMBER    DEFAULT FND_LOG.LEVEL_STATEMENT)
13 IS
14   l_msg_prefix     VARCHAR2(64);
15   l_msg_level      NUMBER;
16   l_msg_module     VARCHAR2(256);
17   l_beg_end_suffix VARCHAR2(15);
18   l_org_cnt        NUMBER;
19   l_line           VARCHAR2(32767);
20 BEGIN
21   l_line       := line;
22   l_msg_prefix := msg_prefix;
23   l_msg_level  := msg_level;
24   l_msg_module := msg_module;
25   IF (INSTRB(upper(l_line), 'EXCEPTION') <> 0) THEN
26     l_msg_level  := FND_LOG.LEVEL_EXCEPTION;
27   END IF;
28   IF l_msg_level <> FND_LOG.LEVEL_EXCEPTION AND PG_DEBUG = 'N' THEN
29     RETURN;
30   END IF;
31   IF ( l_msg_level >= FND_LOG.G_CURRENT_RUNTIME_LEVEL ) THEN
32      FND_LOG.STRING(l_msg_level, l_msg_module, SUBSTRB(l_line,1,4000));
33   END IF;
34 EXCEPTION
35   WHEN OTHERS THEN RAISE;
36 END debug;
37 
38 
39 
40 FUNCTION Get_Transaction_Quantity(p_rcv_trx_id   IN NUMBER
41                                  ,p_rcv_qty      IN NUMBER)
42 RETURN NUMBER
43 IS
44   CURSOR c_item(p_rcv_trx_id IN NUMBER)
45   IS
46   SELECT msi.outside_operation_uom_type
47        , rt.primary_quantity
48        , rt.transaction_type
49     FROM mtl_system_items           msi
50        , rcv_transactions           rt
51        , po_lines_all               pl
52    WHERE rt.transaction_id       = p_rcv_trx_id
53      AND rt.po_line_id           = pl.po_line_id
54      AND msi.inventory_item_id   = pl.item_id
55      AND msi.organization_id     = rt.organization_id;
56 
57   CURSOR c_use_rate(p_rcv_trx_id IN NUMBER)
58   IS
59   SELECT wor.activity_id
60        , wor.resource_id
61        , wor.usage_rate_or_amount
62        , wor.basis_type
63        , wor.autocharge_type
64        , wor.uom_code
65        , wor.standard_rate_flag
66     FROM rcv_transactions         rt
67     ,    wip_operation_resources  wor
68    WHERE rt.transaction_id      = p_rcv_trx_id
69      AND wor.wip_entity_id      = rt.wip_entity_id
70      AND wor.organization_id    = rt.organization_id
71      AND wor.operation_seq_num  = rt.wip_operation_seq_num
72      AND wor.resource_seq_num   = rt.wip_resource_seq_num
73      AND (rt.wip_repetitive_schedule_id IS NULL
74                OR wor.repetitive_schedule_id = rt.wip_repetitive_schedule_id);
75 
76 
77    l_uom_basis        VARCHAR2(25);
78    l_po_qty           NUMBER;
79    l_transaction_type VARCHAR2(30);
80    l_not_found        VARCHAR2(1) := 'N';
81    l_rec              c_use_rate%ROWTYPE;
82    l_res              NUMBER;
83 BEGIN
84    debug('Get_Transaction_Quantity+');
85    debug('  p_rcv_trx_id :'||p_rcv_trx_id);
86    debug('  p_rcv_qty    :'||p_rcv_qty);
87 
88    IF (p_rcv_trx_id IS NULL OR p_rcv_trx_id = 0) OR
89       (p_rcv_qty    IS NULL OR p_rcv_qty    = 0)
90    THEN
91       debug('10');
92       debug('Get_Transaction_Quantity-');
93       RETURN p_rcv_qty;
94    END IF;
95    OPEN c_item(p_rcv_trx_id);
96    FETCH c_item INTO l_uom_basis
97                     ,l_po_qty
98                     ,l_transaction_type;
99    IF c_item%NOTFOUND THEN
100      debug('20');
101      l_not_found := 'Y';
102    END IF;
103    CLOSE c_item;
104    IF l_not_found = 'Y' THEN
105      debug('Get_Transaction_Quantity-');
106      RETURN p_rcv_qty;
107    END IF;
108 
109    OPEN c_use_rate(p_rcv_trx_id);
110    FETCH c_use_rate INTO l_rec;
111    IF c_use_rate%NOTFOUND THEN
112       debug('30');
113      l_not_found := 'Y';
114    END IF;
115    CLOSE c_use_rate;
116    IF l_not_found = 'Y' THEN
117       debug('Get_Transaction_Quantity-');
118      RETURN p_rcv_qty;
119    END IF;
120    -- Calculate the transaction quantity.
121    debug('  l_uom_basis :'||l_uom_basis);
122    debug('  l_rec.usage_rate_or_amount:'||l_rec.usage_rate_or_amount);
123    IF l_uom_basis = 'ASSEMBLY' THEN
124        IF (    l_rec.usage_rate_or_amount IS NOT NULL
125            AND l_rec.usage_rate_or_amount <> 0)
126        THEN
127           debug('40');
128           l_res := p_rcv_qty * l_rec.usage_rate_or_amount;
129        ELSE
130           debug('50');
131           l_res := p_rcv_qty;
132        END IF;
133    ELSIF l_uom_basis = 'RESOURCE' THEN
134       debug('60');
135       l_res := p_rcv_qty;
136    ELSE
137       debug('70');
138       debug('Get_Transaction_Quantity-');
139       RETURN p_rcv_qty;
140    END IF;
141    debug('l_res:'||l_res);
142    debug('Get_Transaction_Quantity-');
143    RETURN l_res;
144 EXCEPTION
145    WHEN OTHERS THEN
146       debug('EXCEPTION OTHERS in Get_Transaction_Quantity :'||SQLERRM);
147       RETURN p_rcv_qty;
148 END Get_Transaction_Quantity;
149 
150 
151 PROCEDURE display_rcv_rev_type
152 (p IN RCV_SeedEvents_PVT.rcv_event_rec_type,
153  l OUT NOCOPY  VARCHAR2)
154 IS
155 BEGIN
156  l := SUBSTRB(
157 ' event_type_id :'       ||p.event_type_id||
158 ',event_source :'        ||p.event_source||
159 ',rcv_transaction_id :'  ||p.rcv_transaction_id||
160 ',direct_delivery_flag :'||p.direct_delivery_flag||
161 ',inv_distribution_id :' ||p.inv_distribution_id||
162 ',transaction_date :'    ||p.transaction_date||
163 ',po_header_id :'        ||p.po_header_id||
164 ',po_release_id :'       ||p.po_release_id||
165 ',po_line_id :'          ||p.po_line_id||
166 ',po_line_location_id :' ||p.po_line_location_id||
167 ',po_distribution_id :'  ||p.po_distribution_id||
168 ',trx_flow_header_id :'  ||p.trx_flow_header_id||
169 ',set_of_books_id :'     ||p.set_of_books_id||
170 ',org_id :'              ||p.org_id||
171 ',transfer_org_id:'      ||p.transfer_org_id||
172 ',organization_id:'      ||p.organization_id||
173 ',transfer_organization_id:'||p.transfer_organization_id||
174 ',item_id :'         ||p.item_id||
175 ',unit_price :'      ||p.unit_price||
176 ',unit_nr_tax :'     ||p.unit_nr_tax||
177 ',unit_rec_tax :'    ||p.unit_rec_tax||
178 ',prior_unit_price :'||p.prior_unit_price||
179 ',prior_nr_tax:'     ||p.prior_nr_tax||
180 ',prior_rec_tax:'    ||p.prior_rec_tax||
181 ',intercompany_pricing_option:'||p.intercompany_pricing_option||
182 ',service_flag :'      ||p.service_flag||
183 ',transaction_amount :'||p.transaction_amount||
184 ',currency_code :'     ||p.currency_code||
185 ',currency_conversion_type :'||p.currency_conversion_type||
186 ',currency_conversion_rate :'||p.currency_conversion_rate||
187 ',currency_conversion_date :'||p.currency_conversion_date||
188 ',intercompany_price :'      ||p.intercompany_price||
189 ',intercompany_curr_code :'  ||p.intercompany_curr_code||
190 ',transaction_uom :'         ||p.transaction_uom||
191 ',trx_uom_code :'            ||p.trx_uom_code||
192 ',transaction_quantity :'    ||p.transaction_quantity||
193 ',primary_uom :'             ||p.primary_uom||
194 ',primary_quantity :'        ||p.primary_quantity||
195 ',source_doc_uom :'          ||p.source_doc_uom||
196 ',source_doc_quantity :'     ||p.source_doc_quantity||
197 ',destination_type_code :'   ||p.destination_type_code||
198 ',cross_ou_flag :'           ||p.cross_ou_flag||
199 ',procurement_org_flag :'    ||p.procurement_org_flag ||
200 ',ship_to_org_flag :'        ||p.ship_to_org_flag  ||
201 ',drop_ship_flag :'          ||p.drop_ship_flag    ||
202 ',debit_account_id :'        ||p.debit_account_id  ||
203 ',credit_account_id :'       ||p.credit_account_id||
204 ',intercompany_cogs_account_id :'||p.intercompany_cogs_account_id||
205 ',lcm_account_id :'          ||p.lcm_account_id ||
206 ',unit_landed_cost :'        ||p.unit_landed_cost,1,3980);
207 END;
208 
209 /* ======================================================================= */
210 -- PROCEDURE
211 -- Process__MatCost
212 --
213 -- DESCRIPTION
214 -- This API retrieves  the charges of the costed MTL_MATERIAL_TRANSACTIONS
215 -- row, then called Update_eamCost to populate the eAM tables.
216 -- This API should be called for a specific MMT transaction which has been
217 -- costed successfully.
218 --
219 -- PURPOSE
220 -- To support eAM job costing for Rel 11i.6
221 --
222 /*=========================================================================== */
223 
224 PROCEDURE Process_MatCost(
225      p_api_version               IN      NUMBER,
226      p_init_msg_list             IN      VARCHAR2 := FND_API.G_FALSE,
227      p_commit                    IN      VARCHAR2 := FND_API.G_FALSE,
228      p_validation_level          IN      VARCHAR2 := FND_API.G_VALID_LEVEL_FULL,
229      x_return_status             OUT NOCOPY     VARCHAR2,
230      x_msg_count                 OUT NOCOPY     NUMBER,
231      x_msg_data                  OUT NOCOPY     VARCHAR2,
232      p_txn_id                    IN      NUMBER,
233      p_user_id                   IN      NUMBER,
234      p_request_id                IN      NUMBER,
235      p_prog_id                   IN      NUMBER,
236      p_prog_app_id               IN      NUMBER,
237      p_login_id                  IN      NUMBER
238      ) IS
239    l_api_name    CONSTANT        VARCHAR2(30) := 'Process_MatCost';
240    l_api_version CONSTANT        NUMBER       := 1.0;
241 
242    l_return_status       VARCHAR2(1) := fnd_api.g_ret_sts_success;
243    l_msg_count           NUMBER := 0;
244    l_msg_data            VARCHAR2(8000);
245    l_stmt_num            NUMBER := 0;
246    l_api_message         VARCHAR2(1000);
247 
248    l_txn_date            VARCHAR2(21);
249    l_period_id           NUMBER;
250    l_wip_entity_id       NUMBER;
251    l_opseq_num           NUMBER;
252    l_value               NUMBER;
253    l_value_type          NUMBER := 1;  -- actual cost
254    l_txn_mode            NUMBER := 1;  -- material transaction
255    l_org_id              NUMBER;
256    l_debug               VARCHAR2(80);
257 
258   BEGIN
259 
260    --  Standard Start of API savepoint
261       SAVEPOINT Process_MatCost_PUB;
262       l_debug := fnd_profile.value('MRP_DEBUG');
263 
264 
265    -- Standard call to check for call compatibility
266       IF NOT FND_API.Compatible_API_Call (
267                         l_api_version,
268                         p_api_version,
269                         l_api_name,
270                         G_PKG_NAME ) THEN
271          RAISE FND_API.G_EXC_UNEXPECTED_ERROR;
272       END IF;
273 
274     -- Initialize message list if p_init_msg_list is set to TRUE
275        IF FND_API.to_Boolean(p_init_msg_list) THEN
276            FND_MSG_PUB.initialize;
277        END IF;
278 
279     -- Initialize API return status to success
280        x_return_status := FND_API.G_RET_STS_SUCCESS;
281 
282     -- Get MMT info
283        l_stmt_num := 10;
284        SELECT transaction_source_id,
285               operation_seq_num,
286               acct_period_id,
287               organization_id,
288               to_char(transaction_date,'YYYY/MM/DD HH24:MI:SS')
289           INTO l_wip_entity_id,
290                l_opseq_num,
291                l_period_id,
292                l_org_id,
293                l_txn_date
294           FROM mtl_material_transactions
295           WHERE transaction_id = p_txn_id;
296 
297    -- Get transaction value.
298       l_stmt_num := 20;
299       BEGIN
300 
301          SELECT SUM(NVL(base_transaction_value,0))
302          INTO l_value
303          FROM mtl_transaction_accounts
304          WHERE transaction_id = p_txn_id
305            AND accounting_line_type = 7         -- WIP valuation
306          GROUP BY transaction_id;
307       EXCEPTION /* bug fix 2077391 */
308           WHEN NO_DATA_FOUND    THEN --no distributions in MTA
309                   l_value := 0;
310       END;
311 
312       l_stmt_num := 30;
313          if (l_debug = 'Y') then
314                 fnd_file.put_line(fnd_file.log, 'calling Update_eamCost');
315          end if;
316       Update_eamCost (
317                 p_api_version                  => 1.0,
318                 x_return_status                => l_return_status,
319                 x_msg_count                    => l_msg_count,
320                 x_msg_data                     => l_msg_data,
321                 p_txn_mode                     => l_txn_mode,
322                 p_period_id                    => l_period_id,
323                 p_org_id                       => l_org_id,
324                 p_wip_entity_id                => l_wip_entity_id,
325                 p_opseq_num                    => l_opseq_num,
326                 p_value_type                   => l_value_type,
327                 p_value                        => l_value,
328                 p_user_id                      => p_user_id,
329                 p_request_id                   => p_request_id,
330                 p_prog_id                      => p_prog_id,
331                 p_prog_app_id                  => p_prog_app_id,
332                 p_login_id                     => p_login_id,
333                 p_txn_date                     => l_txn_date);
334 
335        IF l_return_status <> FND_API.g_ret_sts_success THEN
336           FND_FILE.put_line(FND_FILE.log, x_msg_data);
337           l_api_message := 'Update_eamCost returned error';
338           FND_MESSAGE.set_name('BOM','CST_API_MESSAGE');
339           FND_MESSAGE.set_token('TEXT', l_api_message);
340           FND_MSG_pub.add;
341           RAISE FND_API.g_exc_error;
342        END IF;
343 
344    --- Standard check of p_commit
345        IF FND_API.to_Boolean(p_commit) THEN
346           COMMIT WORK;
347        END IF;
348 
349     -- Standard Call to get message count and if count = 1, get message info
350     FND_MSG_PUB.Count_And_Get (
351            p_count     => x_msg_count,
352            p_data      => x_msg_data );
353 
354 
355    EXCEPTION
356       WHEN FND_API.g_exc_error THEN
357          ROLLBACK TO Process_MatCost_PUB;
358          x_return_status := FND_API.g_ret_sts_error;
359 
360       --  Get message count and data
361          FND_MSG_PUB.count_and_get
362              (  p_count => x_msg_count
363               , p_data  => x_msg_data
364               );
365 
366       WHEN FND_API.g_exc_unexpected_error THEN
367             ROLLBACK TO Process_MatCost_PUB;
368             x_return_status := FND_API.g_ret_sts_unexp_error ;
369 
370    --  Get message count and data
371         FND_MSG_PUB.count_and_get
372           (  p_count  => x_msg_count
373            , p_data   => x_msg_data
374             );
375 
376       WHEN OTHERS THEN
377          ROLLBACK TO Process_MatCost_PUB;
378          x_return_status := fnd_api.g_ret_sts_unexp_error ;
379 
380          IF fnd_msg_pub.check_msg_level(fnd_msg_pub.g_msg_lvl_unexp_error)
381             THEN
382                FND_MSG_PUB.add_exc_msg
383                  (  'CST_eamCost_PVT'
384                   , 'Process_MatCost : Statement -'||to_char(l_stmt_num)
385                  );
386          END IF;
387 
388   --  Get message count and data
389         FND_MSG_PUB.count_and_get
390           (  p_count  => x_msg_count
391            , p_data   => x_msg_data
392             );
393 
394       END Process_MatCost;
395 
396 /*=========================================================================== */
397 -- PROCEDURE
398 -- Process_ResCost
399 --
400 -- DESCRIPTION
401 -- This API processes all resources transactions in WIP_TRANSACTIONS for a
402 -- specified group id.  For each transaction, it identifies the correct
403 -- eAM cost element, department type, then populate eAM tables accordingly.
404 -- The calling program should ensure that all transactions for a
405 -- specific group id are costed successfully before calling this API.
406 --
407 -- PURPOSE
408 -- To support eAM job costing for Rel 11i.5
409 --
410 /*=========================================================================== */
411 
412 PROCEDURE Process_ResCost(
413           p_api_version               IN      NUMBER,
414           p_init_msg_list             IN      VARCHAR2 := FND_API.G_FALSE,
415           p_commit                    IN      VARCHAR2 := FND_API.G_FALSE,
416           p_validation_level          IN      VARCHAR2 := FND_API.G_VALID_LEVEL_FULL,
417           x_return_status             OUT NOCOPY     VARCHAR2,
418           x_msg_count                 OUT NOCOPY     NUMBER,
419           x_msg_data                  OUT NOCOPY     VARCHAR2,
420           p_group_id                  IN      NUMBER,
421           p_user_id                   IN      NUMBER,
422           p_request_id                IN      NUMBER,
423           p_prog_id                   IN      NUMBER,
424           p_prog_app_id               IN      NUMBER,
425           p_login_id                  IN      NUMBER
426           ) IS
427    l_api_name    CONSTANT        VARCHAR2(30) := 'Process_ResCost';
428    l_api_version CONSTANT        NUMBER       := 1.0;
429 
430    l_return_status       VARCHAR2(1) := fnd_api.g_ret_sts_success;
431    l_msg_count           NUMBER := 0;
432    l_msg_data            VARCHAR2(8000);
433    l_stmt_num            NUMBER := 0;
434    l_api_message         VARCHAR2(1000);
435 
436    l_wip_entity_id       NUMBER;
437    l_opseq_num           NUMBER;
438    l_value               NUMBER;
439    l_value_type          NUMBER := 1;  -- actual cost
440    l_txn_mode            NUMBER; -- 2=resource txn, 3=res txn with specified charge dept
441    l_period_id           NUMBER;
442    l_resource_id         NUMBER;
443    l_res_seq_num         NUMBER;
444    l_debug               VARCHAR2(80);
445 
446 
447 
448 -- Cursor to pull all WT transactions with group id = p_group_id and
449 -- eAM wip entity type.
450 
451    CURSOR l_resourcetxn_csr IS
452       SELECT wt.transaction_id,
453              wt.organization_id,
454              wt.wip_entity_id,
455              wt.acct_period_id,
456              DECODE(wt.resource_id,NULL, null,
457                                    wt.resource_id) resource_id,
458              wt.operation_seq_num,
459              wt.resource_seq_num,
460              wt.charge_department_id,
461              to_char(wt.transaction_date,'YYYY/MM/DD HH24:MI:SS') txn_date
462          FROM wip_transactions wt
463          WHERE wt.group_id = p_group_id
464            AND EXISTS
465               (SELECT 'eam jobs'
466                  FROM wip_entities we
467                  WHERE we.wip_entity_id = wt.wip_entity_id
468                    AND we.entity_type in (6,7));
469 
470   BEGIN
471 
472    --  Standard Start of API savepoint
473       SAVEPOINT Process_ResCost_PUB;
474       l_debug := fnd_profile.value('MRP_DEBUG');
475 
476 
477      if (l_debug = 'Y') THEN
478         fnd_file.put_line(fnd_file.log, 'In process_resCost');
479      end if;
480 
481 
482    -- Standard call to check for call compatibility
483       IF NOT FND_API.Compatible_API_Call (
484                         l_api_version,
485                         p_api_version,
486                         l_api_name,
487                         G_PKG_NAME ) THEN
488          RAISE FND_API.G_EXC_UNEXPECTED_ERROR;
489       END IF;
490 
491     -- Initialize message list if p_init_msg_list is set to TRUE
492        IF FND_API.to_Boolean(p_init_msg_list) THEN
493            FND_MSG_PUB.initialize;
494        END IF;
495 
496     -- Initialize API return status to success
497        x_return_status := FND_API.G_RET_STS_SUCCESS;
498 
499     -- Loop thru cursor to process the fetched resource transactions
500        FOR l_resourcetxn_rec IN l_resourcetxn_csr LOOP
501           l_stmt_num := 40;
502              SELECT SUM(NVL(wta.base_transaction_value,0))
503                 INTO l_value
504              FROM wip_transaction_accounts wta
505              WHERE transaction_id = l_resourcetxn_rec.transaction_id
506              AND accounting_line_type = 7;
507 
508    /*  dle 7/20 ---------------------------------------------------------
509       Add logic to check for user-entered charge dept.  If yes, populate
510       p_res_seq_num with it.  The sole purpose to pass resource seq num
511       to update_eamcost is for Get_MaintCostCat to determine the owning
512       dept.  Since we have the charge dept, there is no need for
513       Update_EamCost to call Get_MaintCostCat later on.  So it is safe to
514       use p_res_seq_num for charge dept id
515    */
516           IF l_resourcetxn_rec.charge_department_id <> 0 THEN
517              l_txn_mode := 3;   -- resource txn w/ specified charge dept
518              l_res_seq_num := l_resourcetxn_rec.charge_department_id;
519           ELSE
520              l_txn_mode := 2;   -- resource txn w/o specified charge dept
521              l_res_seq_num := l_resourcetxn_rec.resource_seq_num;
522           END IF;
523 
524        if (l_debug = 'Y') THEN
525         fnd_file.put_line(fnd_file.log, 'l_txn_mode: ' || to_char(l_txn_mode));
526      end if;
527 
528           l_stmt_num := 50;
529           Update_eamCost (
530                 p_api_version              => 1.0,
531                 x_return_status            => l_return_status,
532                 x_msg_count                => l_msg_count,
533                 x_msg_data                 => l_msg_data,
534                 p_txn_mode                 => l_txn_mode,
535                 p_period_id                => l_resourcetxn_rec.acct_period_id,
536                 p_org_id                   => l_resourcetxn_rec.organization_id,
537                 p_wip_entity_id            => l_resourcetxn_rec.wip_entity_id,
538                 p_opseq_num                => l_resourcetxn_rec.operation_seq_num,
539                 p_resource_id              => l_resourcetxn_rec.resource_id,
540                 p_res_seq_num              => l_res_seq_num,
541                 p_value_type               => l_value_type,
542                 p_value                    => l_value,
543                 p_user_id                  => p_user_id,
544                 p_request_id               => p_request_id,
545                 p_prog_id                  => p_prog_id,
546                 p_prog_app_id              => p_prog_app_id,
547                 p_login_id                 => p_login_id,
548                 p_txn_date                 => l_resourcetxn_rec.txn_date);
549 
550           IF l_return_status <> FND_API.g_ret_sts_success THEN
551              FND_FILE.put_line(FND_FILE.log, x_msg_data);
552              l_api_message := 'Update_eamCost returned error';
553              FND_MESSAGE.set_name('BOM','CST_API_MESSAGE');
554              FND_MESSAGE.set_token('TEXT', l_api_message);
555              FND_MSG_pub.add;
556              RAISE FND_API.g_exc_error;
557           END IF;
558 
559       END LOOP;
560 
561    --- Standard check of p_commit
562        IF FND_API.to_Boolean(p_commit) THEN
563           COMMIT WORK;
564        END IF;
565 
566     -- Standard Call to get message count and if count = 1, get message info
567     FND_MSG_PUB.Count_And_Get (
568            p_count     => x_msg_count,
569            p_data      => x_msg_data );
570 
571 
572    EXCEPTION
573       WHEN FND_API.g_exc_error THEN
574          ROLLBACK TO Process_ResCost_PUB;
575          x_return_status := FND_API.g_ret_sts_error;
576 
577       --  Get message count and data
578          FND_MSG_PUB.count_and_get
579              (  p_count => x_msg_count
580               , p_data  => x_msg_data
581               );
582 
583       WHEN FND_API.g_exc_unexpected_error THEN
584             ROLLBACK TO Process_ResCost_PUB;
585             x_return_status := FND_API.g_ret_sts_unexp_error ;
586 
587    --  Get message count and data
588         FND_MSG_PUB.count_and_get
589           (  p_count  => x_msg_count
590            , p_data   => x_msg_data
591             );
592 
593       WHEN OTHERS THEN
594          ROLLBACK TO Process_ResCost_PUB;
595          x_return_status := fnd_api.g_ret_sts_unexp_error ;
596 
597          IF fnd_msg_pub.check_msg_level(fnd_msg_pub.g_msg_lvl_unexp_error)
598             THEN
599                FND_MSG_PUB.add_exc_msg
600                  (  'CST_eamCost_PVT'
601                   , 'Process_ResCost : Statement -'||to_char(l_stmt_num)
602                  );
603          END IF;
604 
605   --  Get message count and data
606         FND_MSG_PUB.count_and_get
607           (  p_count  => x_msg_count
608            , p_data   => x_msg_data
609             );
610    END Process_ResCost;
611 
612 
613 /* ================================================================================= */
614 -- PROCEDURE
615 --   Update_eamCost
616 --
617 -- DESCRIPTION
618 --   This API insert or updates WIP_EAM_PERIOD_BALANCES and CST_EAM_ASSET_PER_BALANCES
619 --   with the amount passed by the calling program.
620 --
621 -- PURPOSE:
622 --    Support eAM job costing in Oracle Applications Rel 11i
623 --
624 -- PARAMETERS:
625 --   p_txn_mode:  indicates if it is a material cost (inventory items or direct
626 --                item) or resource cost.  Values:
627 --                      1 = material transaction
628 --                      2 = resource transaction
629 --                      3 = resource txn with user-specified charge department
630 --   p_wip_entity_id:  current job for which the charge is incurred
631 --   p_resource_id:  if it is a resource transaction (p_txn_mode = 2),
632 --                   a resource id must be passed by the calling program
633 --                   Do not pass param for material or dept-based overhead.
634 --   p_res_seq_num:  if it is a resource transaction (p_txn_mode = 2),
635 --                   the operation resource seq num must be passed.
636 --                   If p_txn_mode = 3, it is the charge department id.
637 --                   Do not pass param for material or dept-based overhead.
638 --   p_value_type: 1 = actual cost
639 --                 2 = estimated cost
640 --   p_period_id:  period id of an open period.  If the cost is for a future period
641 --                 pass the period set name and period name instead.  DO NOT pass
642 --                 period id 0, error will occur if there is no period id 0
643 --   p_period_set_name and p_period_name:  parameters to be passed instead of
644 --                 period id for a future period.
645 --
646 --   ACTUAL COSTS:
647 --   For a material transaction (inventory item) or receiving transaction
648 --   (direct item), it identifies the dept type of the using department.
649 --   For a resource transaction, it identifies the eAM cost element based
650 --   on the resource type, and the dept type of the owning department.
651 --
652 --   ESTIMATED COSTS:
653 --   The eAM cost estimating process will call this API to populate
654 --   WIP_EAM_PERIOD_BALANCES and CST_EAM_ASSET_PER_BALANCES with the estimated
655 --   cost values.  If it is a re-estimate, the calling program should back out the
656 --   old estimates from both WIP_EAM_PERIOD_BALANCES and CST_EAM_ASSET_PER_BALANCES
657 --   before calling this API and passing the new estimates to avoid duplication.
658 /* =============================================================================== */
659 
660 PROCEDURE Update_eamCost (
661           p_api_version                   IN      NUMBER,
662           p_init_msg_list                 IN      VARCHAR2 := FND_API.G_FALSE,
663           p_commit                        IN      VARCHAR2 := FND_API.G_FALSE,
664           p_validation_level              IN      VARCHAR2 := FND_API.G_VALID_LEVEL_FULL,
665           x_return_status                 OUT NOCOPY     VARCHAR2,
666           x_msg_count                     OUT NOCOPY     NUMBER,
667           x_msg_data                      OUT NOCOPY     VARCHAR2,
668           p_txn_mode                      IN      NUMBER, -- 1=material, 2=resource, 4=direct item
669           p_period_id                     IN      NUMBER := null,
670           p_period_set_name               IN      VARCHAR2 := null,
671           p_period_name                   IN      VARCHAR2 := null,
672           p_org_id                        IN      NUMBER,
673           p_wip_entity_id                 IN      NUMBER,
674           p_opseq_num                     IN      NUMBER, -- routing operation sequence
675           p_resource_id                   IN      NUMBER := null,
676           p_res_seq_num                   IN      NUMBER := null,
677           p_value_type                    IN      NUMBER, -- 1=actual, 2=estimated
678           p_value                         IN      NUMBER,
679           p_user_id                       IN      NUMBER,
680           p_request_id                    IN      NUMBER,
681           p_prog_id                       IN      NUMBER,
682           p_prog_app_id                   IN      NUMBER,
683           p_login_id                      IN      NUMBER,
684           p_txn_date                      IN           VARCHAR2,
685           p_txn_id                          IN          NUMBER DEFAULT -1 -- Direct Item Acct Enh (Patchset J)
686           ) IS
687 
688    l_api_name    CONSTANT        VARCHAR2(30) := 'Update_eamCost';
689    l_api_version CONSTANT        NUMBER       := 1.0;
690 
691    l_return_status           VARCHAR2(1) := fnd_api.g_ret_sts_success;
692    l_msg_count               NUMBER := 0;
693    l_msg_data                VARCHAR2(8000);
694    l_stmt_num                NUMBER := 0;
695    l_api_message             VARCHAR2(1000);
696 
697    l_wip_entity_type         NUMBER;
698    l_resource_type           NUMBER := 0;
699    l_maint_cost_category     NUMBER;
700    l_asset_group_id          NUMBER;
701    l_asset_number            VARCHAR2(30);
702    l_eam_cost_element        NUMBER;
703    l_dept_id                 NUMBER;
704    l_owning_dept_id          NUMBER;
705    l_mnt_obj_id              NUMBER;
706    l_debug                   VARCHAR2(80);
707    l_po_header_id            NUMBER;
708    l_po_line_id              NUMBER;
709    l_category_id             NUMBER;
710    l_approved_date           DATE;
711    l_check_category          NUMBER;/*BUG 8835299*/
712 
713    BEGIN
714 
715    --  Standard Start of API savepoint
716       SAVEPOINT Update_eamCost_PUB;
717       l_debug := fnd_profile.value('MRP_DEBUG');
718 
719       if (l_debug = 'Y') then
720       fnd_file.put_line(fnd_file.log, 'In Update_eamCost');
721       end if;
722 
723    -- Standard call to check for call compatibility
724       IF NOT FND_API.Compatible_API_Call (
725                         l_api_version,
726                         p_api_version,
727                         l_api_name,
728                         G_PKG_NAME ) THEN
729          RAISE FND_API.G_EXC_UNEXPECTED_ERROR;
730       END IF;
731 
732     -- Initialize message list if p_init_msg_list is set to TRUE
733        IF FND_API.to_Boolean(p_init_msg_list) THEN
734            FND_MSG_PUB.initialize;
735        END IF;
736 
737     -- Initialize API return status to success
738        x_return_status := FND_API.G_RET_STS_SUCCESS;
739 
740        IF (p_txn_mode not in (1,2,3,4) OR
741            p_value_type not in (1,2) OR
742            (p_resource_id is not null AND
743             p_res_seq_num is null) OR
744            (p_period_id is null AND
745             (p_period_set_name is null or
746             p_period_name is null))) THEN
747              FND_MESSAGE.set_name('BOM', 'CST_INVALID_PARAMS');
748              FND_MESSAGE.set_token('JOB', p_wip_entity_id);
749              FND_MSG_PUB.ADD;
750              RAISE FND_API.g_exc_error;
751        END IF;
752 
753     FND_FILE.PUT_LINE(FND_FILE.LOG, 'Processing job '
754                                      || to_char(p_wip_entity_id));
755 
756 
757    -- Process only job with eAM wip entity type
758       l_stmt_num := 60;
759 
760       SELECT we.entity_type
761          INTO l_wip_entity_type
762       FROM wip_entities we
763       WHERE we.wip_entity_id = p_wip_entity_id;
764 
765       IF l_wip_entity_type not in (6,7) THEN
766          l_api_message := 'Job is not eAM job.';
767          l_api_message := l_api_message ||'Job id: '|| TO_CHAR(p_wip_entity_id);
768          FND_MESSAGE.set_name('BOM', 'CST_API_MESSAGE');
769          FND_MESSAGE.set_token('TEXT', l_api_message);
770          FND_MSG_PUB.ADD;
771          RAISE fnd_api.g_exc_error;
772       END IF;
773 
774      l_stmt_num := 62;
775      -- Get charge asset using API
776      get_charge_asset (
777           p_api_version             =>  1.0,
778           p_wip_entity_id           =>  p_wip_entity_id,
779           x_inventory_item_id       =>  l_asset_group_id,
780           x_serial_number           =>  l_asset_number,
781           x_maintenance_object_id   =>  l_mnt_obj_id,
782           x_return_status           =>  l_return_status,
783           x_msg_count               =>  l_msg_count,
784           x_msg_data                =>  l_msg_data);
785 
786       IF (l_return_status <> FND_API.G_RET_STS_SUCCESS) then
787          FND_MESSAGE.set_token('TEXT', l_api_message);
788          FND_MSG_PUB.ADD;
789          RAISE fnd_api.g_exc_error;
790       END IF;
791 
792    ------------------------------------------------------------
793    -- Get eam cost element
794    ------------------------------------------------------------
795       l_stmt_num := 70;
796 
797       /* p_txn_mode = for Direct Item Txns; Direct Item Acct Enh (Patchset J) */
798       if p_txn_mode = 4 then
799         get_CostEle_for_DirectItem (
800           p_api_version                =>        1.0,
801           p_init_msg_list        =>        p_init_msg_list,
802           p_commit                =>        p_commit,
803           p_validation_level        =>        p_validation_level,
804           x_return_status        =>        l_return_status,
805           x_msg_count                =>        l_msg_count,
806           x_msg_data                =>        l_msg_data,
807           p_txn_id                =>        p_txn_id,
808           p_mnt_or_mfg                =>        1,
809           x_cost_element_id        =>        l_eam_cost_element
810           );
811 
812         if (l_return_status <> fnd_api.g_ret_sts_success) then
813           FND_FILE.put_line(FND_FILE.log, x_msg_data);
814           l_api_message := 'get_CostElement_for_DirectItem returned unexpected error';
815           FND_MESSAGE.set_name('BOM','CST_API_MESSAGE');
816           FND_MESSAGE.set_token('TEXT', l_api_message);
817           FND_MSG_pub.add;
818           raise fnd_api.g_exc_unexpected_error;
819         end if;
820 
821         if (l_debug = 'Y') then
822           FND_FILE.PUT_LINE(FND_FILE.LOG,'eam_cost_element_id: '|| to_char(l_eam_cost_element));
823         end if;
824 
825       else /* p_txn_mode in (1,2,3) */
826         l_eam_cost_element := Get_eamCostElement(p_txn_mode,p_org_id,p_resource_id);
827 
828         IF l_eam_cost_element = 0 THEN
829           l_api_message := 'Get_eamCostElement returned error';
830           FND_MESSAGE.set_name('BOM','CST_API_MESSAGE');
831           FND_MESSAGE.set_token('TEXT', l_api_message);
832           FND_MSG_pub.add;
833           RAISE FND_API.g_exc_error;
834         END IF;
835       end if; /* p_txn_mode */
836 
837    --------------------------------------------------------------
838    -- Get maintenance cost category and departments
839    --------------------------------------------------------------
840       IF p_txn_mode = 3  THEN
841          l_owning_dept_id := p_res_seq_num;
842 
843          l_stmt_num := 72;
844 
845         SELECT decode(maint_cost_category,NULL,0,1)
846          INTO l_check_category
847         FROM bom_departments
848         WHERE department_id = l_owning_dept_id;
849 
850        IF(l_debug = 'Y')THEN
851            fnd_file.put_line(fnd_file.log, 'l_check_category'||l_check_category);
852        END IF;
853 
854        IF(l_check_category=1) THEN
855 
856          SELECT maint_cost_category
857             INTO l_maint_cost_category
858          FROM bom_departments
859          WHERE department_id = l_owning_dept_id;
860 
861        ELSE
862  	 SELECT def_maint_cost_category
863  	 INTO l_maint_cost_category
864  	 FROM wip_eam_parameters
865  	 WHERE organization_id = p_org_id;
866 
867        END IF;
868 
869          l_stmt_num := 73;
870          SELECT department_id
871            INTO l_dept_id
872          FROM wip_operations
873          WHERE wip_entity_id = p_wip_entity_id
874            AND operation_seq_num = p_opseq_num
875            AND organization_id = p_org_id;
876 
877       ELSE
878          l_stmt_num := 80;
879          l_return_status := FND_API.G_RET_STS_SUCCESS;
880 
881       if (l_debug = 'Y') then
882       fnd_file.put_line(fnd_file.log, 'Getting maint Cost_category');
883       end if;
884 
885         Get_MaintCostCat(
886             p_txn_mode,
887             p_wip_entity_id    => p_wip_entity_id,
888             p_opseq_num        => p_opseq_num,
889             p_resource_id      => p_resource_id,
890             p_res_seq_num      => p_res_seq_num,
891             x_return_status    => l_return_status,
892             x_operation_dept   => l_dept_id,
893             x_owning_dept      => l_owning_dept_id,
894             x_maint_cost_cat   => l_maint_cost_category);
895 
896          IF l_return_status <> FND_API.g_ret_sts_success THEN
897              FND_FILE.put_line(FND_FILE.log, x_msg_data);
898              l_api_message := 'Get_MaintCostCat returned error';
899              FND_MESSAGE.set_name('BOM','CST_API_MESSAGE');
900              FND_MESSAGE.set_token('TEXT', l_api_message);
901              FND_MSG_pub.add;
902              RAISE FND_API.g_exc_error;
903          END IF;
904 
905       END IF;    -- end checking p_txn_mode
906 
907        if (l_debug = 'Y') then
908         fnd_file.put_line(fnd_file.log, 'Calling insertUpdate_EamPerBal');
909       end if;
910 
911    -- Insert/update WIP_EAM_PERIOD_BALANCES
912       l_stmt_num := 120;
913       InsertUpdate_eamPerBal(
914           p_api_version                   => 1.0,
915           x_return_status                 => l_return_status,
916           x_msg_count                     => l_msg_count,
917           x_msg_data                      => l_msg_data,
918           p_period_id                     => p_period_id,
919           p_period_set_name               => p_period_set_name,
920           p_period_name                   => p_period_name,
921           p_org_id                        => p_org_id,
922           p_wip_entity_id                 => p_wip_entity_id,
923           p_owning_dept_id                => l_owning_dept_id,
924           p_dept_id                       => l_dept_id,
925           p_maint_cost_cat                => l_maint_cost_category,
926           p_opseq_num                     => p_opseq_num,
927           p_eam_cost_element              => l_eam_cost_element,
928           p_asset_group_id                => l_asset_group_id,
929           p_asset_number                  => l_asset_number,
930           p_value_type                    => p_value_type,
931           p_value                         => p_value,
932           p_user_id                       => p_user_id,
933           p_request_id                    => p_request_id,
934           p_prog_id                       => p_prog_id,
935           p_prog_app_id                   => p_prog_app_id,
936           p_login_id                      => p_login_id,
937           p_txn_date                      => p_txn_date);
938 
939        IF l_return_status <> FND_API.g_ret_sts_success THEN
940           FND_FILE.put_line(FND_FILE.log, x_msg_data);
941           l_api_message := 'InsertUpdate_eamPerBal returned error';
942           FND_MESSAGE.set_name('BOM','CST_API_MESSAGE');
943           FND_MESSAGE.set_token('TEXT', l_api_message);
944           FND_MSG_pub.add;
945           RAISE FND_API.g_exc_error;
946        END IF;
947 
948    --- Standard check of p_commit
949        IF FND_API.to_Boolean(p_commit) THEN
950           COMMIT WORK;
951        END IF;
952 
953     -- Standard Call to get message count and if count = 1, get message info
954     FND_MSG_PUB.Count_And_Get (
955            p_count     => x_msg_count,
956            p_data      => x_msg_data );
957 
958 
959    EXCEPTION
960       WHEN FND_API.g_exc_error THEN
961           FND_FILE.PUT_LINE(fnd_file.log,'1 exception ' || SQLERRM );
962          ROLLBACK TO Update_eamCost_PUB;
963          x_return_status := FND_API.g_ret_sts_error;
964 
965       --  Get message count and data
966          FND_MSG_PUB.count_and_get
967              (  p_count => x_msg_count
968               , p_data  => x_msg_data
969               );
970 
971       WHEN FND_API.g_exc_unexpected_error THEN
972              FND_FILE.PUT_LINE(fnd_file.log,'1 exception ' || SQLERRM );
973             ROLLBACK TO Update_eamCost_PUB;
974             x_return_status := FND_API.g_ret_sts_unexp_error ;
975 
976    --  Get message count and data
977         FND_MSG_PUB.count_and_get
978           (  p_count  => x_msg_count
979            , p_data   => x_msg_data
980             );
981 
982       WHEN OTHERS THEN
983         fnd_file.put_line(fnd_file.log, 'Exception in Update_eamcost'|| SQLERRM);
984          ROLLBACK TO Update_eamCost_PUB;
985          x_return_status := fnd_api.g_ret_sts_unexp_error ;
986 
987          IF fnd_msg_pub.check_msg_level(fnd_msg_pub.g_msg_lvl_unexp_error)
988             THEN
989                FND_MSG_PUB.add_exc_msg
990                  (  'CST_eamCost_PUB'
991                   , 'Update_eamCost : Statement -'||to_char(l_stmt_num)
992                  );
993          END IF;
994 
995   --  Get message count and data
996         FND_MSG_PUB.count_and_get
997           (  p_count  => x_msg_count
998            , p_data   => x_msg_data
999             );
1000 END Update_eamCost;
1001 
1002 /* ========================================================================= */
1003 -- PROCEDURE
1004 -- InsertUpdate_eamPerBal
1005 --
1006 -- DESCRIPTION
1007 -- This procedure inserts or updates a row in wip_eam_period_balances table,
1008 -- according to the parameters passed by the calling program.
1009 -- Subsequently, it also inserts or update the related row in
1010 -- cst_eam_asset_per_balances.
1011 --
1012 -- PURPOSE
1013 -- Oracle Application Rel 11i.5
1014 -- eAM Job Costing support
1015 --
1016 -- PARAMETERS
1017 --        p_period_id
1018 --        p_period_set_name  : for an open period, passing period id,
1019 --                             instead of set name and period name,
1020 --                             would be sufficient
1021 --        p_period_name
1022 --        p_org_id
1023 --        p_wip_entity_id
1024 --        p_dept_id          : department assigned to operation
1025 --        p_owning_id        : department owning resource
1026 --        p_maint_cost_dat   : department tyoe of cost incurred
1027 --        p_opseq_num        : routing op seq
1028 --        p_eam_cost_element : eam cost element id
1029 --        p_asset_group_id   : inventory item id
1030 --        p_asset_number     : serial number of asset item
1031 --        p_value_type       : 1= actual cost, 2=system estimated cost
1032 --        p_value            : cost amount
1033 --
1034 -- HISTORY
1035 --    04/02/01      Dieu-Thuong Le         Initial creation
1036 --
1037 ------------------------------------------------------------------------------
1038 
1039 PROCEDURE InsertUpdate_eamPerBal (
1040           p_api_version                   IN      NUMBER,
1041           p_init_msg_list                 IN      VARCHAR2 := FND_API.G_FALSE,
1042           p_commit                        IN      VARCHAR2 := FND_API.G_FALSE,
1043           p_validation_level              IN      VARCHAR2 := FND_API.G_VALID_LEVEL_FULL,
1044           x_return_status                 OUT NOCOPY     VARCHAR2,
1045           x_msg_count                     OUT NOCOPY     NUMBER,
1046           x_msg_data                      OUT NOCOPY     VARCHAR2,
1047           p_period_id                     IN      NUMBER := null,
1048           p_period_set_name               IN      VARCHAR2 := null,
1049           p_period_name                   IN      VARCHAR2 := null,
1050           p_org_id                        IN      NUMBER,
1051           p_wip_entity_id                 IN      NUMBER,
1052           p_owning_dept_id                IN      NUMBER,
1053           p_dept_id                       IN      NUMBER,
1054           p_maint_cost_cat                IN      NUMBER,
1055           p_opseq_num                     IN      NUMBER,
1056           p_eam_cost_element              IN      NUMBER,
1057           p_asset_group_id                IN      NUMBER,
1058           p_asset_number                  IN      VARCHAR2,
1059           p_value_type                    IN      NUMBER,
1060           p_value                         IN      NUMBER,
1061           p_user_id                       IN      NUMBER,
1062           p_request_id                    IN      NUMBER,
1063           p_prog_id                       IN      NUMBER,
1064           p_prog_app_id                   IN      NUMBER,
1065           p_login_id                      IN      NUMBER,
1066           p_txn_date                      IN          VARCHAR2
1067           ) IS
1068 
1069    l_api_name    CONSTANT        VARCHAR2(30) := 'InsertUpdate_eamPerBal';
1070    l_api_version CONSTANT        NUMBER       := 1.0;
1071 
1072    l_return_status       VARCHAR2(1) := fnd_api.g_ret_sts_success;
1073    l_msg_count           NUMBER := 0;
1074    l_msg_data            VARCHAR2(8000);
1075    l_stmt_num            NUMBER := 0;
1076    l_api_message         VARCHAR2(1000);
1077 
1078    l_wepb_row_exists     NUMBER := 0;
1079    l_ceapb_row_exists    NUMBER := 0;
1080    l_statement           VARCHAR2(2000) := NULL;
1081    l_column              VARCHAR2(80) := NULL;
1082    l_col_type            NUMBER;
1083 
1084    l_period_id           NUMBER;
1085    l_period_set_name     VARCHAR2(15);
1086    l_period_name         VARCHAR2(15);
1087    l_period_start_date   DATE;
1088    open_period           BOOLEAN := TRUE;
1089 
1090    l_route_asset         VARCHAR2(1) := 'N';
1091    l_asset_count         NUMBER := 0;
1092    l_alloc_amount        NUMBER := 0;
1093 
1094    l_count               NUMBER := 0;
1095    l_debug               VARCHAR2(80);
1096 
1097    l_maint_obj_id        NUMBER;
1098    l_maint_obj_type      NUMBER;
1099 
1100 /* Changed the following cursor to pick the member asset information from
1101    EAM_WORK_ORDER_ROUTE table instead of MTL_EAM_NETWORK_ASSETS
1102    for eAM Requirements Project- R12  */
1103 
1104     /* Bug 5315176 - Added the union clause below as EWOR table is
1105        not populated if the work order is in draft status */
1106      CURSOR c_network_assets (p_wip_entity_id NUMBER) IS
1107      select cii.instance_id,cii.inventory_item_id,cii.serial_number
1108      from csi_item_instances cii,
1109           eam_work_order_route ewor
1110      where ewor.wip_entity_id=p_wip_entity_id
1111      and cii.instance_id=ewor.instance_id
1112      union
1113      select mena.maintenance_object_id,cii.inventory_item_id,cii2.serial_number
1114      from csi_item_instances cii,
1115           mtl_eam_network_assets mena,
1116           mtl_parameters mp,
1117           csi_item_instances cii2
1118      where cii.instance_number = p_asset_number
1119      and mena.network_object_id = cii.instance_id
1120      and cii2.instance_id = mena.maintenance_object_id
1121      and cii.inventory_item_id = p_asset_group_id
1122      and mp.maint_organization_id = p_org_id
1123      and cii.last_vld_organization_id = mp.organization_id
1124      and nvl(mena.start_date_active, sysdate) <= sysdate
1125      and nvl(mena.end_date_active, sysdate) >= sysdate
1126      and maintenance_object_type =3;
1127 
1128    BEGIN
1129 
1130 
1131    --  Standard Start of API savepoint
1132       SAVEPOINT InsertUpdate_eamPerBal_PUB;
1133       l_debug := fnd_profile.value('MRP_DEBUG');
1134 
1135      if (l_debug = 'Y') then
1136         FND_FILE.PUT_LINE(fnd_file.log,'In InsertUpdate_eamPerBal');
1137         FND_FILE.PUT_LINE(fnd_file.log,'p_asset_group_id: ' || to_char( p_asset_group_id ));
1138      end if;
1139 
1140    -- Standard call to check for call compatibility
1141       IF NOT FND_API.Compatible_API_Call (
1142                         l_api_version,
1143                         p_api_version,
1144                         l_api_name,
1145                         G_PKG_NAME ) THEN
1146          RAISE FND_API.G_EXC_UNEXPECTED_ERROR;
1147       END IF;
1148 
1149     -- Initialize message list if p_init_msg_list is set to TRUE
1150        IF FND_API.to_Boolean(p_init_msg_list) THEN
1151            FND_MSG_PUB.initialize;
1152        END IF;
1153 
1154     -- Initialize API return status to success
1155        x_return_status := FND_API.G_RET_STS_SUCCESS;
1156 
1157     -------------------------------------------------------------
1158     -- Get period id if period set name and period name is passed
1159     -- and vice versa
1160     -------------------------------------------------------------
1161     -- Calling program must pass period id or period set and period name.
1162 
1163        IF (p_period_id is null OR
1164            p_period_id = 0 ) AND
1165           (p_period_set_name is null OR
1166            p_period_name is null)  THEN
1167              l_api_message := 'Must pass period id, or period set name and period name. ';
1168              l_api_message := 'Job id: ' || TO_CHAR(p_wip_entity_id);
1169              FND_MESSAGE.set_name('BOM', 'CST_API_MESSAGE');
1170              FND_MESSAGE.set_token('TEXT', l_api_message);
1171              FND_MSG_PUB.ADD;
1172              RAISE FND_API.g_exc_error;
1173        END IF;
1174 
1175     -- Get data from org_acct_periods if it is an open period.
1176        BEGIN
1177              l_stmt_num := 300;
1178              SELECT acct_period_id,
1179                     period_set_name,
1180                     period_name,
1181                     period_start_date
1182                 INTO
1183                     l_period_id,
1184                     l_period_set_name,
1185                     l_period_name,
1186                     l_period_start_date
1187              FROM org_acct_periods
1188              WHERE organization_id = p_org_id  AND
1189                    (acct_period_id = p_period_id OR
1190                    (period_set_name = p_period_set_name AND
1191                     period_name = p_period_name));
1192        EXCEPTION
1193              WHEN no_data_found THEN     -- no open period
1194                   open_period := FALSE;
1195        END;
1196 
1197     -- Get data from gl_periods if it is a future period.
1198        IF NOT open_period  THEN
1199           l_stmt_num := 130;
1200          /* Bug 2113001 */
1201           l_period_set_name := p_period_set_name;
1202           l_period_name := p_period_name;
1203              SELECT 0,
1204                  period_set_name,
1205                  period_name,
1206                  start_date
1207               INTO
1208                  l_period_id,
1209                  l_period_set_name,
1210                  l_period_name,
1211                  l_period_start_date
1212           FROM gl_periods
1213           WHERE period_set_name = l_period_set_name AND
1214                 period_name = l_period_name;
1215        END IF;
1216 
1217     ---------------------------------------------------------------
1218     -- Identify column to update value.
1219     ---------------------------------------------------------------
1220 
1221        IF p_value_type = 1 THEN                   -- actual_cost
1222           IF p_eam_cost_element = 1  THEN               -- equiptment
1223              l_column := 'actual_eqp_cost';
1224              l_col_type := 11;
1225           ELSIF  p_eam_cost_element = 2  THEN           -- labor
1226              l_column := 'actual_lab_cost';
1227              l_col_type := 12;
1228           ELSE
1229              l_column := 'actual_mat_cost';             -- material
1230              l_col_type := 13;
1231           END IF;
1232        ELSE                                        -- system estimated
1233           IF p_eam_cost_element = 1  THEN                 -- equiptment
1234              l_column := 'system_estimated_eqp_cost';
1235              l_col_type := 21;
1236           ELSIF  p_eam_cost_element = 2  THEN             -- labor
1237              l_column := 'system_estimated_lab_cost';
1238              l_col_type := 22;
1239           ELSE
1240              l_column := 'system_estimated_mat_cost';     -- material
1241              l_col_type := 23;
1242           END IF;
1243        END IF;
1244 
1245     /* -----------------------------------------------------------
1246      Insert/update WIP_EAM_PERIOD_BALANCES
1247      ------------------------------------------------------------- */
1248 
1249        l_stmt_num := 140;
1250        /* Bug 5315176 - Added nvl as operations are stamped in Requirements
1251           only when the work order is released */
1252        SELECT count(*)
1253           INTO l_count
1254           FROM wip_eam_period_balances
1255        WHERE period_set_name = l_period_set_name        AND
1256             period_name = l_period_name                 AND
1257             /* Bug 2113001 */
1258             acct_period_id = l_period_id               AND
1259             organization_id = p_org_id                  AND
1260             wip_entity_id = p_wip_entity_id             AND
1261             maint_cost_category = p_maint_cost_cat      AND
1262             owning_dept_id = p_owning_dept_id           AND
1263             nvl(operations_dept_id,-99) = nvl(p_dept_id,-99)  AND
1264             operation_seq_num = p_opseq_num;
1265 
1266        IF l_count <> 0 THEN
1267           l_stmt_num := 150;
1268        /* Bug 2545791: Change statement to use bind variables. */
1269        /* Bug 2935692: Change statement to use bind variables even in SET clause. */
1270        /* Bug 5315176 - Added nvl as operations are stamped in Requirements
1271           only when the work order is released */
1272           l_statement := 'UPDATE wip_eam_period_balances SET '
1273                         || l_column || '='
1274                         || 'nvl('|| l_column || ',0) + nvl(:p_value,0)'
1275                         || ', last_update_date = sysdate'
1276                         || ', last_updated_by = :p_user_id'
1277                         || ', last_update_login = :p_login_id'
1278                         || ' WHERE period_set_name = :l_period_set_name'
1279                         || ' AND period_name = :l_period_name'
1280                         || ' AND organization_id = :p_org_id'
1281                         || ' AND wip_entity_id = :p_wip_entity_id'
1282                         || ' AND maint_cost_category = :p_maint_cost_cat'
1283                         || ' AND owning_dept_id = :p_owning_dept_id'
1284                         || ' AND nvl(operations_dept_id,-99) = nvl(:p_dept_id,-99)'
1285                         || ' AND operation_seq_num = :p_opseq_num';
1286 
1287 
1288 
1289 /*Bug 4205566 - Ignore row with acct_period_id = 0 when updating actual costs*/
1290          IF p_value_type = 1 THEN
1291             l_statement := l_statement
1292                            || ' AND acct_period_id <> 0';
1293          END IF;
1294 
1295          EXECUTE IMMEDIATE l_statement USING p_value,
1296                            p_user_id, p_login_id, l_period_set_name,
1297                            l_period_name, p_org_id, p_wip_entity_id,
1298                            p_maint_cost_cat, p_owning_dept_id,
1299                            p_dept_id, p_opseq_num ;
1300 
1301        ELSE
1302           l_stmt_num := 160;
1303 
1304           if (l_debug = 'Y') then
1305          FND_FILE.PUT_LINE(fnd_file.log,'Inserting wip_eam_period_balances....');
1306          FND_FILE.PUT_LINE(fnd_file.log,'period_Setname: '|| l_period_set_name );
1307          FND_FILE.PUT_LINE(fnd_file.log,'period_name: '||l_period_name );
1308          FND_FILE.PUT_LINE(fnd_file.log,'acct_period_id: '||to_char( l_period_id) );
1309          FND_FILE.PUT_LINE(fnd_file.log,'owning_dept_id: '||to_char(p_owning_dept_id) );
1310          FND_FILE.PUT_LINE(fnd_file.log,'op dept_id: '||to_char(p_dept_id ));
1311          FND_FILE.PUT_LINE(fnd_file.log,'op_seq_num: '||to_char(p_opseq_num) );
1312          FND_FILE.PUT_LINE(fnd_file.log,'COST_category: '|| to_char( p_maint_cost_cat) );
1313          FND_FILE.PUT_LINE(fnd_file.log,'asset group id: '|| to_char( p_asset_group_id) );
1314          end if;
1315 
1316 
1317           INSERT INTO wip_eam_period_balances (
1318              period_set_name,
1319              period_name,
1320              acct_period_id,
1321              wip_entity_id,
1322              organization_id,
1323              owning_dept_id,
1324              operations_dept_id,
1325              operation_seq_num,
1326              maint_cost_category,
1327              actual_mat_cost,
1328              actual_lab_cost,
1329              actual_eqp_cost,
1330              system_estimated_mat_cost,
1331              system_estimated_lab_cost,
1332              system_estimated_eqp_cost,
1333              manual_estimated_mat_cost,
1334              manual_estimated_lab_cost,
1335              manual_estimated_eqp_cost,
1336              period_start_date,
1337              last_update_date,
1338              last_updated_by,
1339              creation_date,
1340              created_by,
1341              last_update_login,
1342              request_id,
1343              program_application_id,
1344              program_id
1345              )
1346        VALUES (
1347              l_period_set_name,
1348              l_period_name,
1349              l_period_id,
1350              p_wip_entity_id,
1351              p_org_id,
1352              p_owning_dept_id,
1353              p_dept_id,
1354              p_opseq_num,
1355              p_maint_cost_cat,
1356              DECODE(l_col_type, 13, NVL(p_value,0),0),  -- actual mat
1357              DECODE(l_col_type, 12, NVL(p_value,0),0),  -- actual lab
1358              DECODE(l_col_type, 11, NVL(p_value,0),0),  -- actual eqp
1359              DECODE(l_col_type, 23, NVL(p_value,0),0),  -- sys est
1360              DECODE(l_col_type, 22, NVL(p_value,0),0),  -- sys est
1361              DECODE(l_col_type, 21, NVL(p_value,0),0),  -- sys est
1362              0,
1363              0,
1364              0,
1365              l_period_start_date,
1366              sysdate,
1367              p_user_id,
1368              sysdate,
1369              p_user_id,
1370              p_login_id,
1371              p_request_id,
1372              p_prog_app_id,
1373              p_prog_id
1374              );
1375          if (l_debug = 'Y') then
1376            fnd_file.put_line(fnd_file.log, 'Inserted into wepb');
1377          end if;
1378 
1379       END IF;   -- end checking job balance row
1380 
1381           -- ------------------------------------------------------
1382           --  Get Maintenance_Object_Id and Maintenance_Object_Type
1383           --  for this asset (eAM Requirements Project - R12)
1384           -- -------------------------------------------------------
1385              SELECT maintenance_object_id, maintenance_object_type
1386              INTO l_maint_obj_id, l_maint_obj_type
1387              FROM WIP_DISCRETE_JOBS
1388              WHERE wip_entity_id = p_wip_entity_id
1389              AND organization_id = p_org_id;
1390 
1391 
1392      ------------------------------------------------------------
1393      --   Check for Route Asset
1394      ------------------------------------------------------------
1395      l_stmt_num := 162;
1396 
1397     /* Changes to refer CII instead of MSN as Network_Asset_Flag is
1398        no longer stored in MSN (Changes for eaM Requirements Project - R12) */
1399 
1400     If( l_maint_obj_type = 3) then
1401       BEGIN
1402          select network_asset_flag
1403          into l_route_asset
1404          from CSI_Item_Instances
1405          where instance_id = l_maint_obj_id;
1406       EXCEPTION /* bug fix 2716439 */
1407          WHEN NO_DATA_FOUND    THEN --no distributions in MTA
1408                 l_route_asset := 'N';
1409       END;
1410     Else
1411        l_route_asset := 'N';
1412     End if;
1413 
1414 
1415      ---------------------------------------
1416      --  Check for Asset route
1417      ---------------------------------------
1418      if (l_route_asset = 'Y') then
1419        fnd_file.put_line(fnd_file.log,'txn date: ' || p_txn_date);
1420 
1421        l_stmt_num := 164;
1422 
1423    /* Pick up the member asset route information from EAM_WORK_ORDER_ROUTE
1424       instead of MTL_EAM_NETWORK_ASSETS (Changes for eaM Requirements
1425       Project - R12) */
1426 
1427        select count(*)
1428        into l_asset_count
1429        from EAM_WORK_ORDER_ROUTE
1430        where wip_entity_id=p_wip_entity_id;
1431 
1432       /* Bug 5315176 - Added the following statement as EWOR table might not
1433          be populated if the Work order is in Draft status */
1434          If l_asset_count =0 then
1435           select count(*)
1436           into l_asset_count
1437           from mtl_eam_network_assets mena,
1438                csi_item_instances cii,
1439                mtl_parameters mp
1440           where cii.instance_number = p_asset_number
1441           and mena.network_object_id = cii.instance_id
1442           and cii.inventory_item_id = p_asset_group_id
1443           and mp.maint_organization_id = p_org_id
1444           and cii.last_vld_organization_id = mp.organization_id
1445           and nvl(mena.start_date_active, sysdate) <= sysdate
1446           and nvl(mena.end_date_active, sysdate) >= sysdate
1447           and maintenance_object_type =3;
1448         end if;
1449 
1450      end if;
1451 
1452      -------------------------------------------------------------------
1453      --  Update actual and estimated costs by member asset.
1454      -------------------------------------------------------------------
1455      l_stmt_num := 165;
1456      if (l_asset_count > 0) then
1457 
1458        l_stmt_num := 166;
1459 
1460        l_alloc_amount := p_value/l_asset_count;
1461 
1462 
1463        l_stmt_num := 167;
1464        for route_Assets in c_network_assets(p_wip_entity_id)
1465         LOOP
1466 
1467           ------------------------------------------------
1468           --   insert into asset period balances
1469           ------------------------------------------------
1470 
1471 
1472           InsertUpdate_assetPerBal (
1473                 p_api_version           => 1.0,
1474                 x_return_status         => l_return_status,
1475                 x_msg_count             => l_msg_count,
1476                 x_msg_data              => l_msg_data,
1477                 p_period_id             => l_period_id,
1478                 p_period_set_name       => l_period_set_name,
1479                 p_period_name           => l_period_name,
1480                 p_org_id                => p_org_id,
1481                 p_maint_cost_cat        => p_maint_cost_cat,
1482                 p_asset_group_id        => route_assets.inventory_item_id,
1483                 p_asset_number          => route_assets.serial_number,
1484                 p_value                 => l_alloc_amount,
1485                 p_column                => l_column,
1486                 p_col_type              => l_col_type,
1487                 p_period_start_date     => l_period_start_date,
1488                 p_user_id               => p_user_id,
1489                 p_request_id            => p_request_id,
1490                 p_prog_id               => p_prog_id,
1491                 p_prog_app_id           => p_prog_app_id,
1492                 p_login_id              => p_login_id,
1493                 p_maint_obj_type        => 3.0,
1494                 p_maint_obj_id          => route_assets.instance_id
1495           );
1496 
1497 
1498           --BUG#5985039 FP BUG#5984909
1499           -- If return status is not success, raise error
1500           IF l_return_status <> FND_API.g_ret_sts_success THEN
1501               l_api_message := 'InsertUpdate_assetPerBal error';
1502               FND_MSG_PUB.add_exc_msg
1503                  (  'CST_eamCost_PUB',
1504                     'InsertUpdate_eamPerBal('||to_char(l_stmt_num) || ')', l_api_message);
1505               RAISE FND_API.g_exc_error;
1506           END IF;
1507 
1508         END LOOP;
1509 
1510      else
1511 
1512         InsertUpdate_assetPerBal (
1513                 p_api_version           => 1.0,
1514                 x_return_status         => l_return_status,
1515                 x_msg_count             => l_msg_count,
1516                 x_msg_data              => l_msg_data,
1517                 p_period_id             => l_period_id,
1518                 p_period_set_name       => l_period_set_name,
1519                 p_period_name           => l_period_name,
1520                 p_org_id                => p_org_id,
1521                 p_maint_cost_cat        => p_maint_cost_cat,
1522                 p_asset_group_id        => p_asset_group_id,
1523                 p_asset_number          => p_asset_number,
1524                 p_value                 => p_value,
1525                 p_column                => l_column,
1526                 p_col_type              => l_col_type,
1527                 p_period_start_date     => l_period_start_date,
1528                 p_user_id               => p_user_id,
1529                 p_request_id            => p_request_id,
1530                 p_prog_id               => p_prog_id,
1531                 p_prog_app_id           => p_prog_app_id,
1532                 p_login_id              => p_login_id,
1533                 p_maint_obj_id          => l_maint_obj_id,
1534                 p_maint_obj_type        => l_maint_obj_type
1535           );
1536 
1537           --BUG#5985039 - FPBUG 5984909
1538           -- If return status is not success, raise error
1539           IF l_return_status <> FND_API.g_ret_sts_success THEN
1540               l_api_message := 'InsertUpdate_assetPerBal error';
1541               FND_MSG_PUB.add_exc_msg
1542                  (  'CST_eamCost_PUB',
1543                     'InsertUpdate_eamPerBal('||to_char(l_stmt_num) || ')', l_api_message);
1544               RAISE FND_API.g_exc_error;
1545           END IF;
1546 
1547 
1548 
1549      end if;
1550 
1551       if (l_debug = 'Y') then
1552       FND_FILE.PUT_LINE(fnd_file.log,'inserted into cst_eam_asset_per_balances' );
1553       end if;
1554 
1555       -- Standard check of p_commit
1556           IF FND_API.to_Boolean(p_commit) THEN
1557              COMMIT WORK;
1558           END IF;
1559 
1560     -- Standard Call to get message count and if count = 1, get message info
1561     FND_MSG_PUB.Count_And_Get (
1562            p_count     => x_msg_count,
1563            p_data      => x_msg_data );
1564 
1565    EXCEPTION
1566 
1567       WHEN FND_API.g_exc_error THEN
1568           FND_FILE.PUT_LINE(fnd_file.log,' exception' || SQLERRM );
1569          ROLLBACK TO InsertUpdate_eamPerBal_PUB;
1570          x_return_status := FND_API.g_ret_sts_error;
1571 
1572       --  Get message count and data
1573          FND_MSG_PUB.count_and_get
1574              (  p_count => x_msg_count
1575               , p_data  => x_msg_data
1576               );
1577 
1578       WHEN FND_API.g_exc_unexpected_error THEN
1579              FND_FILE.PUT_LINE(fnd_file.log,' exception' || SQLERRM );
1580             ROLLBACK TO InsertUpdate_eamPerBal_PUB;
1581             x_return_status := FND_API.g_ret_sts_unexp_error ;
1582 
1583       --  Get message count and data
1584         FND_MSG_PUB.count_and_get
1585           (  p_count  => x_msg_count
1586            , p_data   => x_msg_data
1587             );
1588 
1589       WHEN OTHERS THEN
1590           FND_FILE.PUT_LINE(fnd_file.log,'exception' || SQLERRM );
1591          ROLLBACK TO InsertUpdate_eamPerBal_PUB;
1592          x_return_status := fnd_api.g_ret_sts_unexp_error ;
1593 
1594          IF fnd_msg_pub.check_msg_level(fnd_msg_pub.g_msg_lvl_unexp_error)
1595             THEN
1596                FND_MSG_PUB.add_exc_msg
1597                  (  'CST_eamCost_PUB',
1598                     'InsertUpdate_eamPerBal : Statement -'||to_char(l_stmt_num)
1599                  );
1600          END IF;
1601 
1602       --  Get message count and data
1603            FND_MSG_PUB.count_and_get
1604              (  p_count  => x_msg_count
1605               , p_data   => x_msg_data
1606              );
1607    END InsertUpdate_eamPerBal;
1608 
1609 /* ========================================================================= */
1610 -- PROCEDURE
1611 -- InsertUpdate_assetPerBal
1612 --
1613 -- DESCRIPTION
1614 --
1615 -- PURPOSE
1616 -- Oracle Application Rel 11i.5
1617 -- eAM Job Costing support
1618 --
1619 -- PARAMETERS
1620 --        p_period_id
1621 --        p_period_set_name  : for an open period, passing period id,
1622 --                             instead of set name and period name,
1623 --                             would be sufficient
1624 --        p_period_name
1625 --        p_org_id
1626 --        p_maint_cost_dat   : department tyoe of cost incurred
1627 --        p_eam_cost_element : eam cost element id
1628 --        p_asset_group_id   : inventory item id
1629 --        p_asset_number     : serial number of asset item
1630 --        p_value_type       : 1= actual cost, 2=system estimated cost
1631 --        p_value            : cost amount
1632 --        p_maint_obj_id     : CII.instance_id (added for
1633 --                             eAM Requirements Project-R12)
1634 --        p_maint_obj_type   : 3 for serialized asset or serialized
1635 --                             rebuildable item
1636 --                             2 for non-serialized rebuildable item
1637 --
1638 -- HISTORY
1639 --    03/27/05      Anjali R   Added p_maint_obj_id and p_maint_obj_type parameters
1640 --                             for eAM Requirements Project - R12.
1641 --                             CST_EAM_ASSET_PER_BALANCES table will now
1642 --                             store corresponding IB Instance_id for each
1643 --                             serialized asset or serialized rebuildable.
1644 --                             For non-serialized rebuildable item, it will
1645 --                             store MSI.inventory_item_id.
1646 --    09/18/02      Anitha     Initial creation
1647 --
1648 ------------------------------------------------------------------------------
1649 
1650 PROCEDURE InsertUpdate_assetPerBal (
1651           p_api_version                   IN      NUMBER,
1652           p_init_msg_list                 IN      VARCHAR2 := FND_API.G_FALSE,
1653           p_commit                        IN      VARCHAR2 := FND_API.G_FALSE,
1654           p_validation_level              IN      VARCHAR2 := FND_API.G_VALID_LEVEL_FULL,
1655           x_return_status                 OUT NOCOPY     VARCHAR2,
1656           x_msg_count                     OUT NOCOPY     NUMBER,
1657           x_msg_data                      OUT NOCOPY     VARCHAR2,
1658           p_period_id                     IN      NUMBER := null,
1659           p_period_set_name               IN      VARCHAR2 := null,
1660           p_period_name                   IN      VARCHAR2 := null,
1661           p_org_id                        IN      NUMBER,
1662           p_maint_cost_cat                IN      NUMBER,
1663           p_asset_group_id                IN      NUMBER,
1664           p_asset_number                  IN      VARCHAR2,
1665           p_value                         IN      NUMBER,
1666           p_column                        IN      VARCHAR2,
1667           p_col_type                      IN      NUMBER,
1668           p_period_start_date             IN      DATE,
1669           p_maint_obj_id                  IN          NUMBER,
1670           p_maint_obj_type                IN      NUMBER,
1671           p_user_id                       IN      NUMBER,
1672           p_request_id                    IN      NUMBER,
1673           p_prog_id                       IN      NUMBER,
1674           p_prog_app_id                   IN      NUMBER,
1675           p_login_id                      IN      NUMBER
1676           ) IS
1677 
1678       l_api_name     CONSTANT  VARCHAR2(30) := 'InsertUpdate_assetPerBal';
1679       l_api_version  CONSTANT  NUMBER := 1.0;
1680 
1681       l_return_status     VARCHAR2(1) := fnd_api.g_ret_sts_success;
1682       l_msg_count         NUMBER := 0;
1683       l_msg_data          VARCHAR2(8000);
1684       l_api_message       VARCHAR2(1000);
1685 
1686       l_period_id           NUMBER;
1687       l_period_set_name     VARCHAR2(15);
1688       l_period_name         VARCHAR2(15);
1689       l_period_start_date   DATE;
1690       l_statement           VARCHAR2(2000) := NULL;
1691 
1692       l_stmt_num          NUMBER := 10;
1693       l_count             NUMBER := 0;
1694 
1695       l_debug            VARCHAR2(1);
1696 
1697   BEGIN
1698          --  Standard Start of API savepoint
1699       SAVEPOINT InsertUpdate_assetPerBal_PUB;
1700       l_debug := fnd_profile.value('MRP_DEBUG');
1701 
1702      if (l_debug = 'Y') then
1703         FND_FILE.PUT_LINE(fnd_file.log,'In InsertUpdate_assetPerBal');
1704         FND_FILE.PUT_LINE(fnd_file.log,'p_asset_group_id: ' || to_char( p_asset_group_id ));
1705      end if;
1706 
1707    -- Standard call to check for call compatibility
1708       IF NOT FND_API.Compatible_API_Call (
1709                         l_api_version,
1710                         p_api_version,
1711                         l_api_name,
1712                         G_PKG_NAME ) THEN
1713          RAISE FND_API.G_EXC_UNEXPECTED_ERROR;
1714       END IF;
1715 
1716     -- Initialize message list if p_init_msg_list is set to TRUE
1717        IF FND_API.to_Boolean(p_init_msg_list) THEN
1718            FND_MSG_PUB.initialize;
1719        END IF;
1720 
1721     -- Initialize API return status to success
1722        x_return_status := FND_API.G_RET_STS_SUCCESS;
1723 
1724       l_count := 0;
1725 
1726       SELECT count(*)
1727          INTO l_count
1728          FROM cst_eam_asset_per_balances
1729       WHERE period_set_name = p_period_set_name     AND
1730             period_name = p_period_name             AND
1731             organization_id = p_org_id              AND
1732             inventory_item_id = p_asset_group_id    AND
1733             serial_number = p_asset_number          AND
1734             maint_cost_category = p_maint_cost_cat;
1735 
1736       IF l_count > 0 THEN
1737          l_stmt_num := 180;
1738       /* Bug 2545791: Using bind variables to construct statement */
1739       /* Bug 2935692: Change statement to use bind variables even in SET clause. */
1740 
1741       l_statement := 'UPDATE cst_eam_asset_per_balances SET '
1742                         || p_column || '='
1743                         || 'nvl('|| p_column || ',0) + nvl(:p_value,0)'
1744                         || ', last_update_date = sysdate'
1745                         || ', last_updated_by = :p_user_id'
1746                         || ' WHERE period_set_name = :p_period_set_name'
1747                         || ' AND period_name = :p_period_name'
1748                         || ' AND organization_id = :p_org_id'
1749                         || ' AND inventory_item_id = :p_asset_group_id'
1750                         || ' AND serial_number = :p_asset_number'
1751                         || ' AND maint_cost_category = :p_maint_cost_cat';
1752 
1753      EXECUTE IMMEDIATE l_statement USING p_value, p_user_id, p_period_set_name,
1754                       p_period_name, p_org_id, p_asset_group_id, p_asset_number,
1755                       p_maint_cost_cat ;
1756 
1757       ELSE
1758           l_stmt_num := 190;
1759           INSERT INTO cst_eam_asset_per_balances (
1760              period_set_name,
1761              period_name,
1762              acct_period_id,
1763              organization_id,
1764              inventory_item_id,
1765              serial_number,
1766              maint_cost_category,
1767              actual_mat_cost,
1768              actual_lab_cost,
1769              actual_eqp_cost,
1770              system_estimated_mat_cost,
1771              system_estimated_lab_cost,
1772              system_estimated_eqp_cost,
1773              manual_estimated_mat_cost,
1774              manual_estimated_lab_cost,
1775              manual_estimated_eqp_cost,
1776              period_start_date,
1777              last_update_date,
1778              last_updated_by,
1779              creation_date,
1780              created_by,
1781              request_id,
1782              program_application_id,
1783              maintenance_object_type,
1784              maintenance_object_id
1785              )
1786          VALUES (
1787              p_period_set_name,
1788              p_period_name,
1789              p_period_id,
1790              p_org_id,
1791              p_asset_group_id,
1792              p_asset_number,
1793              p_maint_cost_cat,
1794              DECODE(p_col_type, 13, NVL(p_value,0),0),  -- actual mat
1795              DECODE(p_col_type, 12, NVL(p_value,0),0),  -- actual lab
1796              DECODE(p_col_type, 11, NVL(p_value,0),0),  -- actual eqp
1797              DECODE(p_col_type, 23, NVL(p_value,0),0),  -- sys est
1798              DECODE(p_col_type, 22, NVL(p_value,0),0),  -- sys est
1799              DECODE(p_col_type, 21, NVL(p_value,0),0),  -- sys est
1800              0,    -- manual estimated (not implemented yet)
1801              0,
1802              0,
1803              p_period_start_date,
1804              sysdate,
1805              p_user_id,
1806              sysdate,
1807              p_user_id,
1808              p_request_id,
1809              p_prog_app_id,
1810              p_maint_obj_type,
1811              p_maint_obj_id
1812              );
1813       END IF;        -- end checking asset balance rowcount
1814 
1815 
1816       -- Standard check of p_commit
1817           IF FND_API.to_Boolean(p_commit) THEN
1818              COMMIT WORK;
1819           END IF;
1820 
1821     -- Standard Call to get message count and if count = 1, get message info
1822     FND_MSG_PUB.Count_And_Get (
1823            p_count     => x_msg_count,
1824            p_data      => x_msg_data );
1825 
1826    EXCEPTION
1827 
1828       WHEN FND_API.g_exc_error THEN
1829           FND_FILE.PUT_LINE(fnd_file.log,' exception' || SQLERRM );
1830          ROLLBACK TO InsertUpdate_assetPerBal_PUB;
1831          x_return_status := FND_API.g_ret_sts_error;
1832       --  Get message count and data
1833          FND_MSG_PUB.count_and_get
1834              (  p_count => x_msg_count
1835               , p_data  => x_msg_data
1836               );
1837 
1838       WHEN FND_API.g_exc_unexpected_error THEN
1839              FND_FILE.PUT_LINE(fnd_file.log,' exception' || SQLERRM );
1840             ROLLBACK TO InsertUpdate_assetPerBal_PUB;
1841             x_return_status := FND_API.g_ret_sts_unexp_error ;
1842 
1843       --  Get message count and data
1844         FND_MSG_PUB.count_and_get
1845           (  p_count  => x_msg_count
1846            , p_data   => x_msg_data
1847             );
1848 
1849       WHEN OTHERS THEN
1850           FND_FILE.PUT_LINE(fnd_file.log,'exception' || SQLERRM );
1851          ROLLBACK TO InsertUpdate_assetPerBal_PUB;
1852          x_return_status := fnd_api.g_ret_sts_unexp_error ;
1853 
1854          IF fnd_msg_pub.check_msg_level(fnd_msg_pub.g_msg_lvl_unexp_error)
1855             THEN
1856                FND_MSG_PUB.add_exc_msg
1857                  (  'CST_eamCost_PUB',
1858                     'InsertUpdate_assetPerBal : Statement -'||to_char(l_stmt_num)
1859                  );
1860          END IF;
1861 
1862       --  Get message count and data
1863            FND_MSG_PUB.count_and_get
1864              (  p_count  => x_msg_count
1865               , p_data   => x_msg_data
1866              );
1867    END InsertUpdate_assetPerBal;
1868 
1869 
1870 /* ============================================================== */
1871 -- FUNCTION
1872 -- Get_eamCostElement()
1873 --
1874 -- DESCRIPTION
1875 -- Function to return the correct eAM cost element, based on
1876 -- the transaction mode and the resource id of a transaction.
1877 --
1878 -- PARAMETERS
1879 -- p_txn_mode (1=material, 2=resource)
1880 -- p_org_id
1881 -- p_resource_id (optional; to be passed only for a resource tranx)
1882 --
1883 /* ================================================================= */
1884 
1885 FUNCTION Get_eamCostElement(
1886           p_txn_mode             IN  NUMBER,
1887           p_org_id               IN  NUMBER,
1888           p_resource_id          IN  NUMBER := null)
1889    RETURN number  IS
1890 
1891    l_eam_cost_element          NUMBER;
1892    l_resource_type             NUMBER;
1893    l_stmt_num                  NUMBER;
1894    l_debug                     VARCHAR2(80);
1895 
1896    BEGIN
1897    -------------------------------------------------------------------
1898    -- Determine eAM cost element.
1899    --   1 (equipment) ==> resource type 1 'machine'
1900    --   2 (labor)     ==> resource type 2 'person'
1901    --   3 (material)  ==> inventory or direct item
1902    --   For other resource types, use the default eAM cost element
1903    --   from eAM parameters
1904    --------------------------------------------------------------------
1905 
1906      l_debug := fnd_profile.value('MRP_DEBUG');
1907 
1908      if (l_debug = 'Y') THEN
1909        fnd_file.put_line(fnd_file.log, 'In Get_eamCostElement');
1910      end if;
1911 
1912 
1913       IF p_txn_mode = 1 THEN    -- material
1914          l_eam_cost_element := 3;
1915       ELSE                     -- resource
1916          IF p_resource_id is not null THEN
1917             l_stmt_num := 200;
1918             SELECT resource_type
1919                INTO l_resource_type
1920             FROM bom_resources
1921             WHERE organization_id = p_org_id
1922               AND resource_id = p_resource_id;
1923          END IF;      -- end checking resource id
1924 
1925          IF l_resource_type in (1,2) THEN
1926             l_eam_cost_element := l_resource_type;
1927          ELSE
1928             l_stmt_num := 210;
1929             SELECT def_eam_cost_element_id
1930                into l_eam_cost_element
1931             FROM wip_eam_parameters
1932             WHERE organization_id = p_org_id;
1933          END IF;      -- end checking resource type
1934       END IF;         -- end checking txn mode
1935 
1936      if (l_debug = 'Y') THEN
1937        fnd_file.put_line(fnd_file.log, 'l_eam_cost_element: '|| to_char(l_eam_cost_element));
1938         fnd_file.put_line(fnd_file.log, 'resource id: '|| to_char(p_resource_id));
1939      end if;
1940 
1941       RETURN l_eam_cost_element;
1942 
1943    EXCEPTION
1944       WHEN OTHERS THEN
1945          FND_FILE.PUT_LINE(FND_FILE.LOG,'Get_eamCostElement - statement '
1946                            || l_stmt_num || ': '
1947                            || substr(SQLERRM,1,200));
1948 
1949          IF fnd_msg_pub.check_msg_level(fnd_msg_pub.g_msg_lvl_unexp_error)
1950             THEN
1951                FND_MSG_PUB.add_exc_msg
1952                  (  'CST_eamCost_PUB'
1953                   , '.Get_eamCostElement : Statement -'||to_char(l_stmt_num)
1954                  );
1955          END IF;
1956 
1957          RETURN 0;
1958 
1959 END Get_eamCostElement;
1960 
1961 /* ==================================================================== */
1962 -- PROCEDURE
1963 -- Get_MaintCostCat
1964 --
1965 -- DESCRIPTION
1966 --
1967 -- This procedure identifies the using, owning departments and the
1968 -- related maint. cost cat for a resource or overhead charge based
1969 -- on the transaction mode, wip entity id, routing operation, and
1970 -- resource id.
1971 -- Resource id and resource seq num are optional.  They should be
1972 -- passed only for resource charges.  If they are not passed, this
1973 -- procedure will assume it is a dept based (move based) overhead
1974 -- charges.
1975 --
1976 -- IMPORTANT: Call this procedure ONLY if there is no user-entered CHARGE
1977 -- DEPARTMENT ID.  There is no need to try and figure out the owning
1978 -- department.  User-entered charge department is the overriding
1979 -- owning department.
1980 --
1981 -- HISTORY
1982 -- 4/02/01       Dieu-Thuong Le          Initial creation
1983 --
1984 /* ==================================================================== */
1985 
1986 PROCEDURE Get_MaintCostCat(
1987           p_txn_mode           IN       NUMBER,
1988           p_wip_entity_id      IN       NUMBER,
1989           p_opseq_num          IN       NUMBER,
1990           p_resource_id        IN       NUMBER := null,
1991           p_res_seq_num        IN       NUMBER := null,
1992           x_return_status      OUT NOCOPY      VARCHAR2,
1993           x_operation_dept     OUT NOCOPY      NUMBER,
1994           x_owning_dept        OUT NOCOPY      NUMBER,
1995           x_maint_cost_cat     OUT NOCOPY      NUMBER
1996           ) IS
1997 
1998           l_owning_dept_id               NUMBER;
1999           l_dept_id                      NUMBER;
2000           l_maint_cost_category          NUMBER;
2001           l_stmt_num                     NUMBER;
2002           l_entity_type                  NUMBER;
2003           l_organization_id              NUMBER;
2004           l_ops_exists                   NUMBER := 0;
2005 
2006    BEGIN
2007    -----------------------------------------------------------------------
2008    -- Material and dept-based overhead
2009    --       Owning dept is the same than operation dept.
2010    --
2011    -- Resource and resource-based overhead
2012    --       Operation dept = wor.department_id, if null then get
2013    --                        wo.department_id
2014    --       (Note: wor.department id exists and can be different than
2015    --              wo.department id only for corner cases, such as
2016    --              phantom operation.)
2017    --       Owning dept = identify from bdr.share_from_dept_id
2018    --
2019    -- Department maintenance cost category.
2020    --       Identify from bom_departments.  If null for owning dept, get it
2021    --       for wip_discrete_jobs.owning_department_id.  If there is still
2022    --       no maintenance cost cat, get the default cost cat from
2023    --       wip_eam_parameters.
2024    --
2025    -- (anjgupta) If no operation dept is identified(eg if there is no routing)
2026    --  use the Work order owning dept for costing
2027 
2028    ------------------------------------------------------------------------
2029 -- Initialize return status to success.
2030       x_return_status := FND_API.G_RET_STS_SUCCESS;
2031 
2032 -- Get organization id, just in case we need to get default cost
2033 -- category from wip_eam_parameters later on.
2034       l_stmt_num := 215;
2035       SELECT entity_type,
2036              organization_id
2037       INTO   l_entity_type,
2038              l_organization_id
2039       FROM   wip_entities we
2040       WHERE  we.wip_entity_id = p_wip_entity_id;
2041 
2042 -- Check for existence of operation.  If a job has a bill but no routing,
2043 -- component requirements will not have a department associated to it.
2044 -- In this case, the default cost category should be used.
2045 
2046       l_stmt_num := 220;
2047       SELECT count(*)
2048          INTO l_ops_exists
2049       FROM wip_operations
2050       WHERE wip_entity_id = p_wip_entity_id
2051         AND operation_seq_num = p_opseq_num;
2052 
2053       IF (p_txn_mode = 1) OR  -- material or dept ovhd or direct item txns
2054          (p_txn_mode = 2 AND p_resource_id is null) OR
2055          (p_txn_mode = 4) THEN
2056 
2057          l_stmt_num := 225;
2058          IF l_ops_exists <> 0 THEN     -- have operation
2059             l_stmt_num := 230;
2060             SELECT bd.department_id
2061                INTO l_dept_id
2062             FROM bom_departments bd,
2063                  wip_operations wo
2064             WHERE bd.department_id = wo.department_id
2065               AND wo.wip_entity_id = p_wip_entity_id
2066               AND wo.operation_seq_num = p_opseq_num;
2067          END IF;     -- end checking operation
2068 
2069          /* For material and dept-based overhead,
2070             owning dept is the same than using dept */
2071          l_owning_dept_id := l_dept_id;
2072 
2073       ELSE  -- resource
2074          l_stmt_num := 240;
2075          SELECT bdr.department_id,
2076                 DECODE(bdr.share_from_dept_id,null,bdr.department_id,
2077                        bdr.share_from_dept_id)
2078                 INTO l_dept_id, l_owning_dept_id
2079          FROM wip_operation_resources wor,
2080               wip_operations wo,
2081               bom_department_resources bdr
2082          WHERE bdr.department_id =
2083                    decode(wor.department_id,null,
2084                           wo.department_id, wor.department_id)
2085            AND bdr.resource_id = wor.resource_id
2086            AND wor.wip_entity_id = p_wip_entity_id
2087            AND wor.operation_seq_num = p_opseq_num
2088            AND wor.resource_seq_num = p_res_seq_num
2089            AND wo.wip_entity_id = wor.wip_entity_id
2090            AND wo.operation_seq_num = wor.operation_seq_num;
2091 
2092       END IF;    -- end checking material/ovhd
2093 
2094       -- If no dept is identified, get the job's owning dept.
2095       -- If Job does not have owning dept, get default cost category
2096 
2097       IF l_owning_dept_id is NULL THEN
2098            l_stmt_num := 250;
2099            /* get job's owning department  */
2100            SELECT owning_department
2101               INTO l_owning_dept_id
2102            FROM wip_discrete_jobs
2103            WHERE wip_entity_id = p_wip_entity_id;
2104       END IF;
2105 
2106       -- Bug 2158026 - if the operation dept is null, then use the
2107       --               work order owning dept for costing purposes
2108       IF l_dept_id IS NULL THEN
2109            l_stmt_num := 251;
2110            l_dept_id := l_owning_dept_id;
2111       END IF;
2112 
2113       IF l_entity_type = 1 THEN /* added by sgosain for future use */
2114          l_stmt_num := 260;
2115          l_maint_cost_category := 1;
2116        ELSE
2117             IF l_owning_dept_id is NOT NULL THEN        -- have department
2118                 l_stmt_num := 270;
2119                 SELECT maint_cost_category
2120                 INTO l_maint_cost_category
2121                 FROM bom_departments
2122                 WHERE department_id = l_owning_dept_id;
2123 
2124             END IF;   -- end checking dept
2125       END IF;     -- end checking wip_entity_type
2126 
2127       /* Bug 1988507- If l_maint_cost_category is null
2128          get default maint_cost_category */
2129        IF l_maint_cost_category IS NULL THEN
2130            l_stmt_num := 280;
2131             SELECT def_maint_cost_category
2132                INTO l_maint_cost_category
2133             FROM wip_eam_parameters
2134             WHERE organization_id = l_organization_id;
2135        END IF;
2136 
2137       x_owning_dept := l_owning_dept_id;
2138       x_operation_dept := l_dept_id;
2139       x_maint_cost_cat := l_maint_cost_category;
2140 
2141 /*
2142 DBMS_OUTPUT.PUT_LINE('l_owning_dept_id: ' || l_owning_dept_id);
2143 DBMS_OUTPUT.PUT_LINE('l_dept_id: ' || l_dept_id);
2144 DBMS_OUTPUT.PUT_LINE('l_maint_cost_category: ' || l_maint_cost_category);
2145 */
2146 
2147    EXCEPTION
2148       WHEN OTHERS THEN
2149          FND_FILE.PUT_LINE(FND_FILE.LOG,'Get_MaintCostCat - statement '
2150                            || l_stmt_num || ': '
2151                            || substr(SQLERRM,1,200));
2152          x_return_status := FND_API.g_ret_sts_unexp_error ;
2153 
2154          IF fnd_msg_pub.check_msg_level(fnd_msg_pub.g_msg_lvl_unexp_error)
2155             THEN
2156                FND_MSG_PUB.add_exc_msg
2157                  (  'CST_eamCost_PUB'
2158                   , '.Get_MaintCostCat. : Statement -'||to_char(l_stmt_num)
2159                  );
2160          END IF;
2161 
2162 END Get_MaintCostCat;
2163 
2164 /* =====================================================================  */
2165 -- PROCEDURE                                                              --
2166 --   Delete_eamPerBal                                                     --
2167 -- DESCRIPTION                                                            --
2168 --   This API removes the cost of a specific type, such as system         --
2169 --   or manual estimates from wip_eam_per_balances and delete the rows    --
2170 --   if all the costs are zeros.  It also update the corresponding amount --
2171 --   It also update the corresponding amount in                           --
2172 --   cst_eam_asset_per_balances.                                          --
2173 --   NOTE:  This process is at the wip entity level.                      --
2174 --                                                                        --
2175 --   p_type = 1  (system estimates)                                       --
2176 --            2 (manual estimates)                                        --
2177 -- PURPOSE:                                                               --
2178 --   Oracle Applications Rel 11i.6                                        --
2179 -- HISTORY:                                                               --
2180 --                                                                        --
2181 --    05/02/01      Dieu-thuong Le   Initial creation                     --
2182 /* ======================================================================= */
2183 
2184 PROCEDURE Delete_eamPerBal (
2185           p_api_version         IN       NUMBER,
2186           p_init_msg_list       IN       VARCHAR2 := FND_API.G_FALSE,
2187           p_commit              IN       VARCHAR2 := FND_API.G_FALSE,
2188           p_validation_level    IN       VARCHAR2 := FND_API.G_VALID_LEVEL_FULL,
2189           x_return_status       OUT NOCOPY      VARCHAR2,
2190           x_msg_count           OUT NOCOPY      NUMBER,
2191           x_msg_data            OUT NOCOPY      VARCHAR2,
2192           p_entity_id_tab       IN  CSTPECEP.wip_entity_id_type,
2193           p_org_id              IN       NUMBER,
2194           p_type                IN       NUMBER :=1
2195           )  IS
2196 
2197    l_api_name    CONSTANT       VARCHAR2(30) := 'Delete_eamPerBal';
2198    l_api_version CONSTANT       NUMBER       := 1.0;
2199 
2200    l_return_status       VARCHAR2(1) := fnd_api.g_ret_sts_success;
2201    l_msg_count           NUMBER := 0;
2202    l_msg_data            VARCHAR2(8000);
2203    l_stmt_num            NUMBER := 0;
2204    l_api_message         VARCHAR2(1000);
2205 
2206    l_asset_count         NUMBER := 0;
2207    l_maint_obj_id        NUMBER;
2208    l_act_mat_cost        NUMBER;
2209    l_act_lab_cost        NUMBER;
2210    l_act_eqp_cost        NUMBER;
2211    l_sys_mat_est         NUMBER;
2212    l_sys_lab_est         NUMBER;
2213    l_sys_eqp_est         NUMBER;
2214    l_man_mat_est         NUMBER;
2215    l_man_lab_est         NUMBER;
2216    l_man_eqp_est         NUMBER;
2217 
2218    l_txn_date            VARCHAR2(21) := to_char(sysdate,'YYYY/MM/DD HH24:MI:SS');
2219 
2220    /* Added for Bug 5315176 */
2221    l_inventory_item_id   NUMBER;
2222    l_asset_number        VARCHAR2(30);
2223    l_route_asset         VARCHAR2(1);
2224    l_maint_obj_type      NUMBER;
2225 
2226    CURSOR v_est_csr(c_org_id NUMBER,
2227                                c_wip_entity_id NUMBER) IS
2228       SELECT period_set_name,
2229              period_name,
2230              maint_cost_category,
2231              sum(NVL(system_estimated_mat_cost,0)) sys_mat,
2232              sum(NVL(system_estimated_lab_cost,0)) sys_lab,
2233              sum(NVL(system_estimated_eqp_cost,0)) sys_eqp,
2234              sum(NVL(manual_estimated_mat_cost,0)) man_mat,
2235              sum(NVL(manual_estimated_lab_cost,0)) man_lab,
2236              sum(NVL(manual_estimated_eqp_cost,0)) man_eqp
2237          FROM wip_eam_period_balances
2238       WHERE wip_entity_id = c_wip_entity_id AND
2239             organization_id = c_org_id
2240       GROUP BY period_set_name,
2241                period_name,
2242                maint_cost_category;
2243 
2244    BEGIN
2245 
2246    --  Standard Start of API savepoint
2247       SAVEPOINT Delete_eamPerBal_PUB;
2248 
2249    -- Standard call to check for call compatibility
2250       IF NOT FND_API.Compatible_API_Call (
2251                         l_api_version,
2252                         p_api_version,
2253                         l_api_name,
2254                         G_PKG_NAME ) THEN
2255          RAISE FND_API.G_EXC_UNEXPECTED_ERROR;
2256       END IF;
2257 
2258     -- Initialize message list if p_init_msg_list is set to TRUE
2259        IF FND_API.to_Boolean(p_init_msg_list) THEN
2260            FND_MSG_PUB.initialize;
2261        END IF;
2262 
2263     -- Initialize API return status to success
2264        x_return_status := FND_API.G_RET_STS_SUCCESS;
2265 
2266   -- Since passing parameter is a PL/SQL table, check if it has any element.
2267     -- Then proceed. First loop thru all and update, then bulk delete
2268     IF p_entity_id_tab.COUNT > 0 THEN
2269 
2270      FOR l_index IN p_entity_id_tab.FIRST..p_entity_id_tab.LAST LOOP
2271 
2272     -- Get asset group and asset number of job
2273        l_stmt_num := 300;
2274        SELECT maintenance_object_id,
2275               maintenance_object_type,
2276               asset_group_id,
2277               asset_number
2278        INTO l_maint_obj_id,
2279             l_maint_obj_type,
2280             l_inventory_item_id,
2281             l_asset_number
2282        FROM wip_discrete_jobs
2283        WHERE organization_id = p_org_id AND
2284              wip_entity_id = p_entity_id_tab(l_index);
2285 
2286     -- Check if the work order is for a route asset
2287     -- Delete asset cost from member assets if the above is true
2288 
2289     /* Refer EAM_WORK_ORDER_ROUTE table instead of MTL_EAM_NETWORK_ASSETS
2290        table. (Changes for eAM Requirements Project - R12) */
2291     l_stmt_num := 310;
2292 
2293     /* Bug 5315176 - Added the following check to determine if the asset
2294        for which work order is being estimated is an asset route  */
2295     If( l_maint_obj_type = 3) then
2296       BEGIN
2297          select network_asset_flag
2298          into l_route_asset
2299          from CSI_Item_Instances
2300          where instance_id = l_maint_obj_id;
2301       EXCEPTION
2302          WHEN NO_DATA_FOUND    THEN
2303                 l_route_asset := 'N';
2304       END;
2305     Else
2306        l_route_asset := 'N';
2307     End if;
2308 
2309     l_stmt_num := 312;
2310 
2311     If l_route_asset = 'Y' then
2312       select count(*)
2313       into l_asset_count
2314       from EAM_WORK_ORDER_ROUTE ewor
2315       where ewor.wip_entity_id = p_entity_id_tab(l_index);
2316 
2317    /* Bug 5315176 - Added the following statement as EWOR table is not
2318       populated for Work Orders in Draft status */
2319       If l_asset_count =0 then
2320        select count(*)
2321        into l_asset_count
2322        from mtl_eam_network_assets mena,
2323             csi_item_instances cii,
2324             mtl_parameters mp
2325        where cii.instance_number = l_asset_number
2326        and mena.network_object_id = cii.instance_id
2327        and cii.inventory_item_id = l_inventory_item_id
2328        and mp.maint_organization_id = p_org_id
2329        and cii.last_vld_organization_id = mp.organization_id
2330        and nvl(mena.start_date_active, sysdate) <= sysdate
2331        and nvl(mena.end_date_active, sysdate) >= sysdate
2332        and maintenance_object_type =3;
2333       end if;
2334     End if;
2335    -----------------------------------------------------
2336    -- Update cst_eam_asset_per_balances first before
2337    -- deleting wip_eam_period_balances
2338    -- If the asset on the work order is a route asset,
2339    -- then adjust asset value for the members
2340    ------------------------------------------------------
2341 
2342    if (l_asset_count > 0) then
2343       FOR v_est_rec IN v_est_csr(p_org_id,
2344                           p_entity_id_tab(l_index)) LOOP
2345 
2346          IF (p_type = 1) AND            -- update sys est
2347             ( v_est_rec.sys_mat <> 0 OR
2348               v_est_rec.sys_lab <> 0 OR
2349               v_est_rec.sys_eqp <> 0)   THEN
2350               l_stmt_num := 312;
2351               UPDATE cst_eam_asset_per_balances
2352               SET system_estimated_mat_cost =
2353                     system_estimated_mat_cost
2354                   - (v_est_rec.sys_mat/l_asset_count),
2355                  system_estimated_lab_cost =
2356                     system_estimated_lab_cost
2357                   - (v_est_rec.sys_lab/l_asset_count),
2358                  system_estimated_eqp_cost =
2359                     system_estimated_eqp_cost
2360                   - (v_est_rec.sys_eqp/l_asset_count)
2361               WHERE period_set_name = v_est_rec.period_set_name AND
2362                     period_name = v_est_rec.period_name AND
2363                     maintenance_object_id in
2364                        (select ewor.instance_id
2365                         from eam_work_order_route ewor
2366                         where ewor.wip_entity_id = p_entity_id_tab(l_index)
2367                         union    /* Added the union clause for Bug 5315176 */
2368                         select mena.maintenance_object_id
2369                         from mtl_eam_network_assets mena,
2370                              csi_item_instances cii,
2371                              mtl_parameters mp
2372                         where cii.instance_number = l_asset_number
2373                         and mena.network_object_id = cii.instance_id
2374                         and cii.inventory_item_id = l_inventory_item_id
2375                         and mp.maint_organization_id = p_org_id
2376                         and cii.last_vld_organization_id = mp.organization_id
2377                         and nvl(mena.start_date_active, sysdate) <= sysdate
2378                         and nvl(mena.end_date_active, sysdate) >= sysdate
2379                         and maintenance_object_type =3
2380                         )
2381                     AND organization_id = p_org_id
2382                     AND maint_cost_category = v_est_rec.maint_cost_category;
2383 
2384            ----------------------------------------------------------------
2385            -- Delete ceapb rows with zeros in ALL value columns
2386            ----------------------------------------------------------------
2387            DELETE from cst_eam_asset_per_balances
2388            WHERE actual_mat_cost = 0 AND
2389            NVL(actual_lab_cost,0) = 0 AND
2390            NVL(actual_eqp_cost,0) = 0 AND
2391            NVL(system_estimated_mat_cost,0) = 0 AND
2392            NVL(system_estimated_lab_cost,0) = 0 AND
2393            NVL(system_estimated_eqp_cost,0) = 0 AND
2394            NVL(manual_estimated_mat_cost,0) = 0 AND
2395            NVL(manual_estimated_lab_cost,0) = 0 AND
2396            NVL(manual_estimated_eqp_cost,0) = 0 AND
2397            period_set_name = v_est_rec.period_set_name AND
2398            period_name = v_est_rec.period_name AND
2399            maintenance_object_id in
2400               (select ewor.instance_id
2401                from eam_work_order_route ewor
2402                where ewor.wip_entity_id = p_entity_id_tab(l_index)
2403                union    /* Added the union clause for Bug 5315176 */
2404                select mena.maintenance_object_id
2405                from mtl_eam_network_assets mena,
2406                     csi_item_instances cii,
2407                     mtl_parameters mp
2408                where cii.instance_number = l_asset_number
2409                and mena.network_object_id = cii.instance_id
2410                and cii.inventory_item_id = l_inventory_item_id
2411                and mp.maint_organization_id = p_org_id
2412                and cii.last_vld_organization_id = mp.organization_id
2413                and nvl(mena.start_date_active, sysdate) <= sysdate
2414                and nvl(mena.end_date_active, sysdate) >= sysdate
2415                and maintenance_object_type =3
2416                )
2417            AND organization_id = p_org_id
2418            AND maint_cost_category = v_est_rec.maint_cost_category;
2419 
2420              ELSIF (p_type = 2) AND           -- update manual est
2421               (v_est_rec.man_mat <> 0 OR
2422                v_est_rec.man_lab <> 0 OR
2423                v_est_rec.man_eqp <> 0)    THEN
2424               l_stmt_num := 314;
2425               UPDATE cst_eam_asset_per_balances
2426               SET manual_estimated_mat_cost =
2427                     manual_estimated_mat_cost
2428                   - (v_est_rec.man_mat/l_asset_count),
2429                  manual_estimated_lab_cost =
2430                     manual_estimated_lab_cost
2431                   - (v_est_rec.man_lab/l_asset_count),
2432                  manual_estimated_eqp_cost =
2433                     manual_estimated_eqp_cost
2434                   - (v_est_rec.man_eqp/l_asset_count)
2435               WHERE period_set_name = v_est_rec.period_set_name AND
2436                     period_name = v_est_rec.period_name AND
2437                     maintenance_object_id in
2438                        (select ewor.instance_id
2439                         from eam_work_order_route ewor
2440                         where ewor.wip_entity_id = p_entity_id_tab(l_index)
2441                         union    /* Added the union clause for Bug 5315176 */
2442                         select mena.maintenance_object_id
2443                         from mtl_eam_network_assets mena,
2444                              csi_item_instances cii,
2445                              mtl_parameters mp
2446                         where cii.instance_number = l_asset_number
2447                         and mena.network_object_id = cii.instance_id
2448                         and cii.inventory_item_id = l_inventory_item_id
2449                         and mp.maint_organization_id = p_org_id
2450                         and cii.last_vld_organization_id = mp.organization_id
2451                         and nvl(mena.start_date_active, sysdate) <= sysdate
2452                         and nvl(mena.end_date_active, sysdate) >= sysdate
2453                         and maintenance_object_type =3
2454                     )
2455                     AND organization_id = p_org_id AND
2456                     maint_cost_category = v_est_rec.maint_cost_category;
2457 
2458                ----------------------------------------------------------------
2459                -- Delete ceapb rows with zeros in ALL value columns
2460                ----------------------------------------------------------------
2461                DELETE from cst_eam_asset_per_balances
2462                WHERE actual_mat_cost = 0 AND
2463                NVL(actual_lab_cost,0) = 0 AND
2464                NVL(actual_eqp_cost,0) = 0 AND
2465                NVL(system_estimated_mat_cost,0) = 0 AND
2466                NVL(system_estimated_lab_cost,0) = 0 AND
2467                NVL(system_estimated_eqp_cost,0) = 0 AND
2468                NVL(manual_estimated_mat_cost,0) = 0 AND
2469                NVL(manual_estimated_lab_cost,0) = 0 AND
2470                NVL(manual_estimated_eqp_cost,0) = 0 AND
2471                period_set_name = v_est_rec.period_set_name AND
2472                period_name = v_est_rec.period_name AND
2473                maintenance_object_id in
2474                   (select ewor.instance_id
2475                    from eam_work_order_route ewor
2476                    where ewor.wip_entity_id = p_entity_id_tab(l_index)
2477                    union    /* Added the union clause for Bug 5315176 */
2478                    select mena.maintenance_object_id
2479                    from mtl_eam_network_assets mena,
2480                         csi_item_instances cii,
2481                         mtl_parameters mp
2482                    where cii.instance_number = l_asset_number
2483                    and mena.network_object_id = cii.instance_id
2484                    and cii.inventory_item_id = l_inventory_item_id
2485                    and mp.maint_organization_id = p_org_id
2486                    and cii.last_vld_organization_id = mp.organization_id
2487                    and nvl(mena.start_date_active, sysdate) <= sysdate
2488                    and nvl(mena.end_date_active, sysdate) >= sysdate
2489                    and maintenance_object_type =3
2490                )
2491                AND organization_id = p_org_id AND
2492                maint_cost_category = v_est_rec.maint_cost_category;
2493 
2494              END IF;  --end checking p_value
2495           END LOOP;
2496 
2497      ELSE -- for assets which do not have an asset route
2498 
2499       FOR v_est_rec IN v_est_csr(p_org_id,
2500                           p_entity_id_tab(l_index)) LOOP
2501 
2502          IF (p_type = 1) AND            -- update sys est
2503             ( v_est_rec.sys_mat <> 0 OR
2504               v_est_rec.sys_lab <> 0 OR
2505               v_est_rec.sys_eqp <> 0)   THEN
2506               l_stmt_num := 316;
2507               UPDATE cst_eam_asset_per_balances
2508               SET system_estimated_mat_cost =
2509                     system_estimated_mat_cost
2510                   - v_est_rec.sys_mat,
2511                  system_estimated_lab_cost =
2512                     system_estimated_lab_cost
2513                   - v_est_rec.sys_lab,
2514                  system_estimated_eqp_cost =
2515                     system_estimated_eqp_cost
2516                   - v_est_rec.sys_eqp
2517               WHERE period_set_name = v_est_rec.period_set_name AND
2518                     period_name = v_est_rec.period_name AND
2519                     maintenance_object_id = l_maint_obj_id AND
2520                     maint_cost_category = v_est_rec.maint_cost_category;
2521 
2522          ELSIF (p_type = 2) AND           -- update manual est
2523               (v_est_rec.man_mat <> 0 OR
2524                v_est_rec.man_lab <> 0 OR
2525                v_est_rec.man_eqp <> 0)    THEN
2526               l_stmt_num := 320;
2527               UPDATE cst_eam_asset_per_balances
2528               SET manual_estimated_mat_cost =
2529                     manual_estimated_mat_cost
2530                   - v_est_rec.man_mat,
2531                  manual_estimated_lab_cost =
2532                     manual_estimated_lab_cost
2533                   - v_est_rec.man_lab,
2534                  manual_estimated_eqp_cost =
2535                     manual_estimated_eqp_cost
2536                   - v_est_rec.man_eqp
2537               WHERE period_set_name = v_est_rec.period_set_name AND
2538                     period_name = v_est_rec.period_name AND
2539                     maintenance_object_id = l_maint_obj_id AND
2540                     organization_id = p_org_id AND
2541                     maint_cost_category = v_est_rec.maint_cost_category;
2542          END IF;        -- end checking p_value
2543       END LOOP;
2544      END IF; -- check for asset route
2545 
2546     END LOOP; -- End loop for p_entity_id_tab
2547 
2548 
2549      l_stmt_num := 325;
2550     ----------------------------------------------------------------
2551     -- Delete ceapb rows with zeros in ALL value columns
2552     ----------------------------------------------------------------
2553      DELETE from cst_eam_asset_per_balances
2554      WHERE actual_mat_cost = 0 AND
2555            NVL(actual_lab_cost,0) = 0 AND
2556            NVL(actual_eqp_cost,0) = 0 AND
2557            NVL(system_estimated_mat_cost,0) = 0 AND
2558            NVL(system_estimated_lab_cost,0) = 0 AND
2559            NVL(system_estimated_eqp_cost,0) = 0 AND
2560            NVL(manual_estimated_mat_cost,0) = 0 AND
2561            NVL(manual_estimated_lab_cost,0) = 0 AND
2562            NVL(manual_estimated_eqp_cost,0) = 0 AND
2563            maintenance_object_id = l_maint_obj_id AND
2564            organization_id = p_org_id;
2565 
2566    -------------------------------------------------------------
2567    -- Update wepb estimates to zeros
2568    -------------------------------------------------------------
2569      l_stmt_num := 330;
2570      FORALL l_index IN p_entity_id_tab.FIRST..p_entity_id_tab.LAST
2571 
2572       UPDATE wip_eam_period_balances
2573          SET system_estimated_mat_cost =
2574                 decode(p_type,1,0,system_estimated_mat_cost),
2575              system_estimated_lab_cost =
2576                 decode(p_type,1,0,system_estimated_lab_cost),
2577              system_estimated_eqp_cost =
2578                 decode(p_type,1,0,system_estimated_eqp_cost),
2579              manual_estimated_mat_cost =
2580                 decode(p_type,2,0,manual_estimated_mat_cost),
2581              manual_estimated_lab_cost =
2582                 decode(p_type,2,0,manual_estimated_lab_cost),
2583              manual_estimated_eqp_cost =
2584                 decode(p_type,2,0,manual_estimated_eqp_cost)
2585       WHERE wip_entity_id = p_entity_id_tab(l_index) AND
2586             organization_id = p_org_id;
2587 
2588    ----------------------------------------------------------------
2589    -- Delete wepb and ceapb rows with zeros in ALL value columns
2590    ----------------------------------------------------------------
2591       l_stmt_num := 340;
2592       FORALL l_index IN p_entity_id_tab.FIRST..p_entity_id_tab.LAST
2593         DELETE from wip_eam_period_balances
2594         WHERE actual_mat_cost = 0 AND
2595             NVL(actual_lab_cost,0) = 0 AND
2596             NVL(actual_eqp_cost,0) = 0 AND
2597             NVL(system_estimated_mat_cost,0) = 0 AND
2598             NVL(system_estimated_lab_cost,0) = 0 AND
2599             NVL(system_estimated_eqp_cost,0) = 0 AND
2600             NVL(manual_estimated_mat_cost,0) = 0 AND
2601             NVL(manual_estimated_lab_cost,0) = 0 AND
2602             NVL(manual_estimated_eqp_cost,0) = 0 AND
2603             wip_entity_id = p_entity_id_tab(l_index) AND
2604             organization_id = p_org_id;
2605 
2606           l_stmt_num := 350;
2607 
2608     END IF;
2609 
2610    EXCEPTION
2611       WHEN FND_API.g_exc_error THEN
2612          ROLLBACK TO Delete_eamPerBal_PUB;
2613          x_return_status := FND_API.g_ret_sts_error;
2614 
2615       --  Get message count and data
2616          FND_MSG_PUB.count_and_get
2617              (  p_count => x_msg_count
2618               , p_data  => x_msg_data
2619               );
2620 
2621       WHEN FND_API.g_exc_unexpected_error THEN
2622             ROLLBACK TO Delete_eamPerBal_PUB;
2623             x_return_status := FND_API.g_ret_sts_unexp_error ;
2624 
2625    --  Get message count and data
2626         FND_MSG_PUB.count_and_get
2627           (  p_count  => x_msg_count
2628            , p_data   => x_msg_data
2629             );
2630 
2631       WHEN OTHERS THEN
2632          ROLLBACK TO Delete_eamPerBal_PUB;
2633          x_return_status := fnd_api.g_ret_sts_unexp_error ;
2634 
2635          FND_FILE.PUT_LINE(FND_FILE.LOG,'Delete_eamPerBal - statement '
2636                            || l_stmt_num || ': '
2637                            || substr(SQLERRM,1,200));
2638 
2639          IF fnd_msg_pub.check_msg_level(fnd_msg_pub.g_msg_lvl_unexp_error)
2640             THEN
2641                FND_MSG_PUB.add_exc_msg
2642                  (  'CST_eamCost_PUB'
2643                   , '.Delete_eamPerBal : Statement -'||to_char(l_stmt_num)
2644                  );
2645          END IF;
2646 
2647   --  Get message count and data
2648         FND_MSG_PUB.count_and_get
2649           (  p_count  => x_msg_count
2650            , p_data   => x_msg_data
2651             );
2652 
2653    END Delete_eamPerBal;
2654 
2655 
2656 --------------------------------------------------------------------------n
2657 -- PROCEDURE                                                              --
2658 --   Compute_Job_Estimate                                                 --
2659 --                                                                        --
2660 --                                                                        --
2661 -- DESCRIPTION                                                            --
2662 --   This API Computes the estimate for a Job                             --
2663 --                                                                        --
2664 -- PURPOSE:                                                               --
2665 --   Oracle Applications Rel 11i.6                                        --
2666 --                                                                        --
2667 --                                                                        --
2668 -- HISTORY:
2669 --
2670 --    03/29/05     Anjali R      Added call to Insert_eamBalAcct() to     --
2671 --                               insert estimation details into           --
2672 --                               CST_EAM_BALANCE_BY_ACCOUNTS table, for   --
2673 --                               eAM Requirements Project - R12.          --
2674 --
2675 --    04/17/01     Hemant G       Created                                 --
2676 ----------------------------------------------------------------------------
2677 PROCEDURE Compute_Job_Estimate (
2678                             p_api_version        IN   NUMBER,
2679                             p_init_msg_list      IN   VARCHAR2
2680                                                   := FND_API.G_FALSE,
2681                             p_commit             IN   VARCHAR2
2682                                                   := FND_API.G_FALSE,
2683                             p_validation_level   IN   NUMBER
2684                                                   := FND_API.G_VALID_LEVEL_FULL,
2685                             p_debug              IN   VARCHAR2 := 'N',
2686                             p_wip_entity_id      IN   NUMBER,
2687 
2688                             p_user_id            IN   NUMBER,
2689                             p_request_id         IN   NUMBER,
2690                             p_prog_id            IN   NUMBER,
2691                             p_prog_app_id        IN   NUMBER,
2692                             p_login_id           IN   NUMBER,
2693 
2694                             x_return_status      OUT NOCOPY  VARCHAR2,
2695                             x_msg_count          OUT NOCOPY  NUMBER,
2696                             x_msg_data           OUT NOCOPY  VARCHAR2 ) IS
2697 
2698     l_api_name    CONSTANT       VARCHAR2(30) := 'Compute_Job_Estimate';
2699     l_api_version CONSTANT       NUMBER       := 1.0;
2700 
2701     l_msg_count                 NUMBER := 0;
2702     l_msg_data                  VARCHAR2(8000);
2703 
2704     l_entity_type               NUMBER := 0;
2705     l_organization_id           NUMBER := 0;
2706     l_rates_ct                  NUMBER := 0;
2707     l_lot_size                  NUMBER := 0;
2708     l_round_unit                NUMBER := 0;
2709     l_precision                 NUMBER := 0;
2710     l_ext_precision             NUMBER := 0;
2711     l_wip_project_id            NUMBER := 0;
2712     l_cost_group_id             NUMBER := 0;
2713     l_primary_cost_method       NUMBER := 0;
2714     l_acct_period_id            NUMBER := NULL;
2715     l_scheduled_completion_date DATE;
2716     l_operation_dept_id         NUMBER := 0;
2717     l_owning_dept_id            NUMBER := 0;
2718     l_maint_cost_category       NUMBER := 0;
2719     l_eam_cost_element          NUMBER := 0;
2720     l_return_status             VARCHAR2(1) := FND_API.G_RET_STS_SUCCESS;
2721     l_api_message               VARCHAR2(10000);
2722     l_stmt_num                  NUMBER;
2723     l_dept_id                   NUMBER := 0;
2724     l_period_set_name           VARCHAR2(15) := NULL;
2725     l_period_name               VARCHAR2(15) := NULL;
2726     l_dummy                     NUMBER := 0;
2727     l_asset_group_item_id               NUMBER := 0;
2728     l_asset_number              VARCHAR2(80);
2729     l_department_id             NUMBER := 0;
2730     l_sum_rbo                   NUMBER := 0;
2731     l_mnt_obj_id                NUMBER;
2732     l_trunc_le_sched_comp_date  DATE;
2733 
2734     l_acct_id                   NUMBER;
2735     l_material_account          NUMBER;
2736     l_material_overhead_account NUMBER;
2737     l_resource_account          NUMBER;
2738     l_overhead_account          NUMBER;
2739     l_osp_account               NUMBER;
2740     l_wip_acct_class            VARCHAR2(10);
2741 
2742     l_exec_flag                 NUMBER;
2743     l_index_var                 NUMBER;
2744     l_value                     NUMBER;
2745     l_account                   NUMBER;
2746     l_approved_date             DATE;
2747 
2748     CURSOR c_wor IS
2749       SELECT wor.operation_seq_num operation_seq_num,
2750              crc.resource_rate resource_rate,
2751              wor.uom_code uom,
2752              wor.usage_rate_or_amount resource_usage,
2753              decode(br.functional_currency_flag,
2754                             1, 1,
2755                             NVL(crc.resource_rate,0))
2756                    * wor.usage_rate_or_amount
2757                    * decode(wor.basis_type,
2758                              1, l_lot_size,
2759                              2, 1,
2760                             1) raw_resource_value,
2761 
2762              ROUND(decode(br.functional_currency_flag,
2763                             1, 1,
2764                             NVL(crc.resource_rate,0))
2765                    * wor.usage_rate_or_amount
2766                    * decode(wor.basis_type,
2767                              1, l_lot_size,
2768                              2, 1,
2769                             1) ,l_ext_precision) resource_value,
2770              wor.resource_id resource_id,
2771              wor.resource_seq_num resource_seq_num,
2772              wor.basis_type basis_type,
2773              wor.usage_rate_or_amount
2774                    * decode(wor.basis_type,
2775                              1, l_lot_size,
2776                              2, 1,
2777                             1) usage_rate_or_amount,
2778              wor.standard_rate_flag standard_flag,
2779              wor.department_id department_id,
2780              br.functional_currency_flag functional_currency_flag,
2781              br.cost_element_id cost_element_id,
2782              br.resource_type resource_type
2783       FROM   wip_operation_resources wor,
2784              bom_resources br,
2785              cst_resource_costs crc
2786       WHERE  wor.wip_entity_id = p_wip_entity_id
2787       AND    br.resource_id     = wor.resource_id
2788       AND    br.organization_id = wor.organization_id
2789       AND    crc.resource_id = wor.resource_id
2790       AND    crc.cost_type_id = l_rates_ct;
2791 
2792     CURSOR c_rbo (  p_resource_id   NUMBER,
2793                     p_dept_id       NUMBER,
2794                     p_org_id        NUMBER,
2795                     p_res_units     NUMBER,
2796                     p_res_value     NUMBER) IS
2797 
2798       SELECT  cdo.overhead_id ovhd_id,
2799               cdo.rate_or_amount actual_cost,
2800               cdo.basis_type basis_type,
2801               ROUND(cdo.rate_or_amount *
2802                         decode(cdo.basis_type,
2803                                 3, p_res_units,
2804                                 p_res_value), l_ext_precision) rbo_value,
2805               cdo.department_id
2806       FROM    cst_resource_overheads cro,
2807               cst_department_overheads cdo
2808       WHERE   cdo.department_id    = p_dept_id
2809       AND     cdo.organization_id  = p_org_id
2810       AND     cdo.cost_type_id     = l_rates_ct
2811       AND     cdo.basis_type IN (3,4)
2812       AND     cro.cost_type_id     = cdo.cost_type_id
2813       AND     cro.resource_id      = p_resource_id
2814       AND     cro.overhead_id      = cdo.overhead_id
2815       AND     cro.organization_id  = cdo.organization_id;
2816 
2817    /* Select the costs corresponding to each cost element. The non-zero value for each
2818       cost element will be used to estimate charges for WAC Accounts - eAM Enhancements
2819       Project R12 */
2820 
2821    CURSOR c_wro IS
2822       SELECT wro.operation_seq_num operation_seq_num,
2823              wro.department_id department_id,
2824              ROUND(SUM(NVL(wro.required_quantity,0) * -- l_lot_size *
2825                decode(msi.eam_item_type,
2826                         3,decode(wdj.issue_zero_cost_flag,'Y',0,
2827                                                           nvl(ccicv.item_cost,0)),
2828                         NVL(ccicv.item_cost,0))), l_ext_precision) mat_value,
2829              ROUND(SUM(NVL(wro.required_quantity,0) *
2830                decode(msi.eam_item_type,
2831                         3,decode(wdj.issue_zero_cost_flag,'Y',0,
2832                                                           nvl(ccicv.material_cost,0)),
2833                         NVL(ccicv.material_cost,0))), l_ext_precision) material_cost,
2834              ROUND(SUM(NVL(wro.required_quantity,0) *
2835                decode(msi.eam_item_type,
2836                         3,decode(wdj.issue_zero_cost_flag,'Y',0,
2837                                                           nvl(ccicv.material_overhead_cost,0)),
2838                         NVL(ccicv.material_overhead_cost,0))), l_ext_precision) material_overhead_cost,
2839              ROUND(SUM(NVL(wro.required_quantity,0) *
2840                decode(msi.eam_item_type,
2841                         3,decode(wdj.issue_zero_cost_flag,'Y',0,
2842                                                           nvl(ccicv.resource_cost,0)),
2843                         NVL(ccicv.resource_cost,0))), l_ext_precision) resource_cost,
2844              ROUND(SUM(NVL(wro.required_quantity,0) *
2845                decode(msi.eam_item_type,
2846                         3,decode(wdj.issue_zero_cost_flag,'Y',0,
2847                                                           nvl(ccicv.outside_processing_cost,0)),
2848                         NVL(ccicv.outside_processing_cost,0))), l_ext_precision) outside_processing_cost,
2849              ROUND(SUM(NVL(wro.required_quantity,0) *
2850                decode(msi.eam_item_type,
2851                         3,decode(wdj.issue_zero_cost_flag,'Y',0,
2852                                                           nvl(ccicv.overhead_cost,0)),
2853                         NVL(ccicv.overhead_cost,0))), l_ext_precision) overhead_cost
2854       FROM   wip_requirement_operations wro,
2855              cst_cg_item_costs_view ccicv,
2856              mtl_system_items_b msi,
2857              wip_discrete_jobs wdj
2858       WHERE  wro.wip_entity_id = p_wip_entity_id
2859              AND wdj.wip_entity_id = wro.wip_entity_id
2860              AND ccicv.inventory_item_id = wro.inventory_item_id
2861              AND ccicv.organization_id = wro.organization_id
2862              AND ccicv.cost_group_id = decode(l_primary_cost_method,1,1,
2863                                                 l_cost_group_id)
2864              AND wro.wip_supply_type IN (1,4)
2865              AND nvl(wro.released_quantity,-1) <> 0
2866              /* Non stockable items will be included in c_wrodi */
2867              AND msi.organization_id = wro.organization_id
2868              AND msi.inventory_item_id = wro.inventory_item_id
2869              AND msi.stock_enabled_flag = 'Y'
2870              AND wro.wip_entity_id = wdj.wip_entity_id    /* Bug 5230287 */
2871              AND wro.organization_id = wdj.organization_id   /* Bug 5230287 */
2872       GROUP BY wro.operation_seq_num,
2873                wro.department_id;
2874 
2875    /* Added this cursor for patchset J, to use unit price in WRO for
2876       unordered qty of non-stockable items */
2877    CURSOR c_wrodi IS
2878    SELECT
2879              wro.operation_seq_num operation_seq_num,
2880              wro.department_id department_id,
2881              ROUND(SUM(
2882                      DECODE(
2883                        SIGN(NVL(wro.required_quantity,0) - NVL(wediv.quantity_ordered,0)),
2884                        1,
2885                        NVL(wro.required_quantity,0) - NVL(wediv.quantity_ordered,0),
2886                        0
2887                      ) *
2888                      NVL(wro.unit_price,0)), l_ext_precision) mat_value,
2889                      msi.inventory_item_id item_id,
2890                      mic.category_id category_id
2891       FROM   wip_requirement_operations wro,
2892              (SELECT cedi.work_order_number,
2893                      cedi.organization_id,
2894                      cedi.task_number,
2895                      cedi.item_id,
2896                      SUM(
2897                        inv_convert.inv_um_convert(
2898                          cedi.item_id, NULL, cedi.quantity_ordered,
2899                          cedi.uom_code, msi.primary_uom_code, NULL, NULL
2900                        )
2901                        /* We convert to primary_uom because the required_quantity in
2902                           WRO is always in the primary unit of measure */
2903                      ) quantity_ordered
2904                      /* Sum is needed because there could be multiple POs/Reqs
2905                         for the same non-stockable item */
2906               FROM   cst_eam_direct_items_temp cedi,
2907                      mtl_system_items_b msi
2908               WHERE  cedi.item_id = msi.inventory_item_id
2909               AND    cedi.organization_id = msi.organization_id
2910               AND    cedi.work_order_number = p_wip_entity_id
2911               GROUP
2912               BY     cedi.work_order_number,
2913                      cedi.organization_id,
2914                      cedi.task_number,
2915                      cedi.item_id
2916              ) wediv,
2917              mtl_system_items_b msi,
2918              mtl_item_categories mic,
2919              mtl_default_category_sets mdcs
2920       WHERE  wro.wip_entity_id = p_wip_entity_id
2921       AND    wediv.work_order_number(+) = wro.wip_entity_id
2922       AND    wediv.item_id (+)= wro.inventory_item_id
2923       AND    wediv.organization_id(+) = wro.organization_id
2924       AND    wediv.task_number(+) = wro.operation_seq_num
2925       AND    wro.wip_supply_type IN (1,4)
2926       AND    msi.organization_id = wro.organization_id
2927       AND    msi.inventory_item_id = wro.inventory_item_id
2928       AND    msi.stock_enabled_flag = 'N'
2929       AND    msi.inventory_item_id = mic.inventory_item_id
2930       AND    mic.category_set_id = mdcs.category_set_id
2931       AND    mic.organization_id = wro.organization_id
2932       AND    mdcs.functional_area_id = 2
2933       GROUP  BY
2934              wro.operation_seq_num,
2935              wro.department_id,
2936              msi.inventory_item_id,
2937              mic.category_id;
2938 
2939   /* Added this cursor for patchset J, to include unordered quantity
2940       of description items */
2941    CURSOR c_wedi IS
2942       SELECT
2943              wedi.operation_seq_num operation_seq_num,
2944              wedi.department_id department_id,
2945              wedi.purchasing_category_id category_id,
2946              wedi.direct_item_sequence_id direct_item_id,
2947              ROUND(
2948                DECODE(wediv.order_type_lookup_code,
2949                 'FIXED PRICE', NVL(wedi.amount,0) * NVL(wediv.currency_rate,1) - sum( NVL(wediv.amount_delivered ,0)),
2950                 'RATE', NVL(wedi.amount,0) * NVL(wediv.currency_rate,1) - sum(NVL(wediv.amount_delivered ,0)),
2951                  DECODE(
2952                  SIGN(
2953                    NVL(wedi.required_quantity,0) -
2954                    SUM(
2955                      /* Sum is needed because there could be multiple
2956                         POs/Reqs for the same description item */
2957                      inv_convert.inv_um_convert(
2958                        NULL, NULL, NVL(wediv.quantity_ordered,0),
2959                        NVL(wediv.uom_code, wedi.uom), wedi.uom, NULL, NULL
2960                      )
2961                    )
2962                  ),
2963                  1,
2964                  (
2965                    NVL(wedi.required_quantity,0) -
2966                    SUM(
2967                      inv_convert.inv_um_convert(
2968                        NULL, NULL, NVL(wediv.quantity_ordered,0),
2969                        NVL(wediv.uom_code, wedi.uom), wedi.uom, NULL, NULL
2970                      )
2971                    )
2972                  ),
2973                  0
2974                ) * NVL(wedi.unit_price, 0) * NVL(wediv.currency_rate,1)),
2975                l_ext_precision
2976              ) wedi_value
2977       FROM   wip_eam_direct_items wedi,
2978              cst_eam_direct_items_temp wediv
2979       WHERE  wedi.wip_entity_id = p_wip_entity_id
2980       AND    wediv.work_order_number(+) = wedi.wip_entity_id
2981       AND    wediv.organization_id(+) = wedi.organization_id
2982       AND    wediv.direct_item_sequence_id(+) = wedi.direct_item_sequence_id
2983       AND    wediv.task_number(+) = wedi.operation_seq_num
2984 /*      AND    wediv.category_id(+) = wedi.purchasing_category_id   - commented for Bug 5403190 */
2985       GROUP
2986       BY     wedi.operation_seq_num,
2987              wedi.department_id,
2988              wedi.purchasing_category_id,
2989              wedi.direct_item_sequence_id,
2990              NVL(wedi.required_quantity,0),
2991              NVL(wedi.unit_price,0),
2992              NVL(wedi.amount,0),
2993              wediv.order_type_lookup_code,
2994              wediv.currency_rate;
2995 
2996    /* Bug 2283331 - Cancelled or Rejected POs/Req. should not be estimated */
2997    /* Added category_id, category_date for Direct Item Acct Enh (Patchset J) */
2998    /* The join to WEDIV in the cursor is mainly to restrict the POs/Reqs to
2999       those corresponding to the direct items */
3000 
3001    /* The following cursor is changed to pick up the amount for Service Line
3002       Types from PO/Requisition tables based on order_type_lookup_code.
3003       (for eAM Requirements Project - R12) */
3004    CURSOR c_pda IS
3005       SELECT
3006               ROUND(SUM(
3007                        decode
3008                        (
3009                          NVL(pla.order_type_lookup_code,'QUANTITY'),
3010                         'RATE',(
3011                                 (NVL(wediv.amount,0) -   NVL(pda.amount_cancelled,0))
3012                                 + PO_TAX_SV.get_tax('PO',pda.po_distribution_id)
3013                                 )
3014                                 * NVL(wediv.currency_rate,1)  ,
3015                         'FIXED PRICE',(
3016                                        (NVL(wediv.amount,0) - NVL(pda.amount_cancelled,0))
3017                                        + PO_TAX_SV.get_tax('PO',pda.po_distribution_id)
3018                                        )
3019                                        * NVL(wediv.currency_rate,1),
3020                         (
3021                          NVL(plla.price_override,0) *
3022                          (NVL(pda.quantity_ordered,0) - NVL(pda.quantity_cancelled,0))
3023                         + PO_TAX_SV.get_tax('PO',pda.po_distribution_id)
3024                         )
3025                         * NVL(wediv.currency_rate,1)
3026                    )), l_ext_precision
3027               ) pda_value,
3028               pda.wip_operation_seq_num operation_seq_num,
3029               pla.category_id category_id,
3030               nvl(pha.approved_date, pha.last_update_date) category_date,
3031               pha.type_lookup_code, /* Bug 5201970 */
3032               wediv.po_release_id   /* Bug 5201970 */
3033       FROM    po_distributions_all pda,
3034               po_line_locations_all plla,
3035               po_headers_all pha,
3036               po_lines_all pla,
3037               cst_eam_direct_items_temp wediv
3038       WHERE   wediv.work_order_number = p_wip_entity_id
3039       AND     wediv.organization_id = l_organization_id
3040       AND     wediv.task_number = pda.wip_operation_seq_num
3041       AND     wediv.category_id = pla.category_id
3042       AND     pha.po_header_id = wediv.po_header_id
3043       AND     pla.po_line_id = wediv.po_line_id
3044       AND     pda.wip_entity_id = wediv.work_order_number
3045       AND     pda.po_header_id = wediv.po_header_id
3046       AND     pda.destination_organization_id = wediv.organization_id
3047       AND     pda.po_line_id = pla.po_line_id
3048       AND     plla.line_location_id = pda.line_location_id
3049       GROUP BY pda.wip_operation_seq_num,
3050                pla.category_id,
3051                pha.approved_date,
3052                pha.last_update_date,
3053                wediv.currency_rate,
3054                pha.last_update_date,
3055                pha.type_lookup_code,
3056                wediv.po_release_id
3057       UNION
3058           SELECT
3059               ROUND(SUM(
3060                         DECODE(NVL(prla.order_type_lookup_code,'QUANTITY'),
3061                         'RATE', NVL(wediv.amount,NVL(prla.amount * nvl(wediv.currency_rate,1),0)),
3062                         'FIXED PRICE', NVL(wediv.amount,NVL(prla.amount * nvl(wediv.currency_rate,1),0)),
3063                         NVL(prla.unit_price,0) * NVL(prla.quantity,0))
3064                          * NVL(wediv.currency_rate,1)), 6) pda_value,
3065               prla.wip_operation_seq_num operation_seq_num,
3066               prla.category_id category_id,
3067               prha.last_update_date category_date,
3068               null, /* Bug 5201970 */
3069               null  /* Bug 5201970 */
3070       FROM    po_requisition_lines_all prla,
3071               po_requisition_headers_all prha,
3072               cst_eam_direct_items_temp wediv
3073       WHERE   wediv.work_order_number = p_wip_entity_id
3074       AND     wediv.organization_id = l_organization_id
3075       AND     wediv.task_number = prla.wip_operation_seq_num
3076       AND     wediv.category_id = prla.category_id
3077       AND     wediv.po_header_id IS NULL -- to ensure that we do not double count
3078       AND     prha.requisition_header_id = wediv.requisition_header_id
3079       AND     prla.destination_organization_id = wediv.organization_id
3080       AND     prla.wip_entity_id = wediv.work_order_number
3081       AND     prla.requisition_line_id = wediv.requisition_line_id
3082       GROUP BY prla.wip_operation_seq_num,
3083                prla.category_id,
3084                prha.last_update_date,
3085                wediv.currency_rate;
3086 
3087 
3088    CURSOR c_dbo IS
3089 
3090       SELECT  SUM(ROUND(NVL(cdo.rate_or_amount,0) *
3091                 decode(cdo.basis_type,
3092                              1, l_lot_size,
3093                              2, 1,
3094                             1) ,l_ext_precision)) dbo_value,
3095               cdo.department_id department_id ,
3096               wo.operation_seq_num operation_seq_num
3097 
3098       FROM    wip_operations wo,
3099               cst_department_overheads cdo
3100       WHERE   cdo.cost_type_id = l_rates_ct
3101       AND     cdo.organization_id = l_organization_id
3102       AND     cdo.department_id = wo.department_id
3103       AND     wo.wip_entity_id = p_wip_entity_id
3104       AND     cdo.rate_or_amount <> 0
3105       AND     cdo.basis_type IN (1,2)
3106       GROUP BY wo.operation_seq_num,
3107                cdo.department_id;
3108 
3109 
3110   /* Cursor added for eAM Budgeting and Forecasting Requirements (R12).
3111      The cursor returns the WIP Account that will be hit for the given
3112      job and cost element. */
3113     cursor c_acct( p_wip_entity_id NUMBER) is
3114     select  material_account,
3115             material_overhead_account,
3116             resource_account,
3117             outside_processing_account,
3118             overhead_account,
3119             class_code wip_acct_class
3120     from wip_discrete_jobs
3121     where wip_entity_id = p_wip_entity_id;
3122 
3123 
3124 l_period_start_date Date;
3125 l_mfg_cost_element_id Number;
3126 
3127 BEGIN
3128     -------------------------------------------------------------------------
3129     -- standard start of API savepoint
3130     -------------------------------------------------------------------------
3131     SAVEPOINT Compute_Job_Estimate;
3132 
3133     -------------------------------------------------------------------------
3134     -- standard call to check for call compatibility
3135     -------------------------------------------------------------------------
3136     IF NOT fnd_api.compatible_api_call (
3137                               l_api_version,
3138                               p_api_version,
3139                               l_api_name,
3140                               G_PKG_NAME ) then
3141 
3142          RAISE fnd_api.g_exc_unexpected_error;
3143 
3144     END IF;
3145 
3146     -------------------------------------------------------------------------
3147     -- Initialize message list if p_init_msg_list is set to TRUE
3148     -------------------------------------------------------------------------
3149 
3150     IF FND_API.to_Boolean(p_init_msg_list) THEN
3151         FND_MSG_PUB.initialize;
3152     END IF;
3153 
3154 
3155     -------------------------------------------------------------------------
3156     -- initialize api return status to success
3157     -------------------------------------------------------------------------
3158     x_return_status := fnd_api.g_ret_sts_success;
3159 
3160     -- assign to local variables
3161     l_stmt_num := 10;
3162 
3163     -------------------------------------------------------------------------
3164     -- Check Entity Type is eAM
3165     -------------------------------------------------------------------------
3166 
3167     SELECT  entity_type,
3168             organization_id
3169     INTO    l_entity_type,
3170             l_organization_id
3171     FROM    wip_entities we
3172     WHERE   we.wip_entity_id = p_wip_entity_id;
3173 
3174 
3175     IF (l_entity_type NOT IN (1,6)) THEN
3176 
3177       l_api_message := l_api_message|| 'Invalid WIP entity type: '
3178                       ||TO_CHAR(l_entity_type)
3179                       ||' WIP Entity: '
3180                       ||TO_CHAR(p_wip_entity_id);
3181 
3182       FND_MSG_PUB.ADD_EXC_MSG('CST_EAMCOST_PUB', 'COMPUTE_JOB_ESTIMATES('
3183                                      ||TO_CHAR(l_stmt_num)
3184                                      ||'): ', l_api_message);
3185       RAISE FND_API.g_exc_error;
3186 
3187     ELSE
3188 
3189       l_stmt_num := 15;
3190 
3191       SELECT start_quantity,
3192              NVL(project_id, -1),
3193              scheduled_completion_date
3194       INTO   l_lot_size,
3195              l_wip_project_id,
3196              l_scheduled_completion_date
3197       FROM   wip_discrete_jobs wdj
3198       WHERE  wdj.wip_entity_id = p_wip_entity_id;
3199 
3200       l_stmt_num := 16;
3201       -- Get charge asset using API
3202       get_charge_asset (
3203           p_api_version             =>  1.0,
3204           p_wip_entity_id           =>  p_wip_entity_id,
3205           x_inventory_item_id       =>  l_asset_group_item_id,
3206           x_serial_number           =>  l_asset_number,
3207           x_maintenance_object_id   =>  l_mnt_obj_id,
3208           x_return_status           =>  l_return_status,
3209           x_msg_count               =>  l_msg_count,
3210           x_msg_data                =>  l_msg_data);
3211 
3212       IF (l_return_status <> FND_API.G_RET_STS_SUCCESS) then
3213          FND_MESSAGE.set_token('TEXT', l_api_message);
3214          FND_MSG_PUB.ADD;
3215          RAISE fnd_api.g_exc_error;
3216       END IF;
3217 
3218 
3219     END IF;
3220 
3221     /* Bug #1950738. Use default cost group of organization */
3222     SELECT NVL(default_cost_group_id,-1)
3223     INTO l_cost_group_id
3224     FROM mtl_parameters
3225     WHERE organization_id = l_organization_id;
3226 
3227     IF (l_wip_project_id <> -1) THEN
3228 
3229       l_stmt_num := 20;
3230 
3231       SELECT NVL(costing_group_id,-1)
3232       INTO   l_cost_group_id
3233       FROM   pjm_project_parameters ppp
3234       WHERE  ppp.project_id = l_wip_project_id
3235       AND    ppp.organization_id = l_organization_id;
3236 
3237       IF (l_cost_group_id = -1) THEN
3238 
3239         l_api_message := 'No CG Found for Project: '
3240                         ||TO_CHAR(l_wip_project_id)
3241                         ||' Organization: '
3242                         ||TO_CHAR(l_organization_id);
3243         FND_MSG_PUB.ADD_EXC_MSG('CST_EAMCOST_PUB', 'COMPUTE_JOB_ESTIMATES('
3244                                      ||TO_CHAR(l_stmt_num)
3245                                      ||'): ', l_api_message);
3246         RAISE FND_API.g_exc_error;
3247 
3248       END IF;
3249 
3250     END IF; -- check for wip_project_id <> -1
3251 
3252 
3253     -------------------------------------------------------------------------
3254     -- Find the period in which the scheduled completion date falls
3255     -------------------------------------------------------------------------
3256 
3257     l_stmt_num := 23;
3258     l_trunc_le_sched_comp_date := INV_LE_TIMEZONE_PUB.GET_LE_DAY_FOR_INV_ORG(
3259                                     l_scheduled_completion_date,
3260                                     l_organization_id);
3261 
3262     l_stmt_num := 25;
3263 
3264     SELECT  count(*)
3265     INTO    l_dummy
3266     FROM    org_acct_periods oap
3267     WHERE   oap.organization_id = l_organization_id
3268     AND     l_trunc_le_sched_comp_date BETWEEN oap.period_start_date
3269                                        AND     oap.schedule_close_date;
3270 
3271     IF (NVL(l_dummy,0) = 1) THEN
3272 
3273       l_stmt_num := 30;
3274 
3275       SELECT  oap.acct_period_id,
3276               oap.period_set_name,
3277               oap.period_name,
3278               oap.period_start_date
3279       INTO    l_acct_period_id,
3280               l_period_set_name,
3281               l_period_name,
3282               l_period_start_date
3283       FROM    org_acct_periods oap
3284       WHERE   oap.organization_id = l_organization_id
3285       AND     l_trunc_le_sched_comp_date BETWEEN oap.period_start_date
3286                                          AND     oap.schedule_close_date;
3287 
3288     ELSE
3289 
3290       l_stmt_num := 35;
3291 
3292 /* The following query will be modified to refer to cst_organization_definitions
3293    as an impact of the HR-PROFILE option. */
3294 
3295       SELECT  gp.period_set_name,
3296               gp.period_name,
3297               gp.start_date
3298       INTO    l_period_set_name,
3299               l_period_name,
3300               l_period_start_date
3301       FROM    gl_periods gp,
3302               gl_sets_of_books gsob,
3303               /*org_organization_definitions ood */
3304               cst_organization_definitions ood
3305       WHERE   ood.organization_id = l_organization_id
3306       AND     gsob.set_of_books_id = ood.set_of_books_id
3307       AND     gp.period_set_name = gsob.period_set_name
3308       AND     gp.adjustment_period_flag = 'N'
3309       AND     gp.period_type = gsob.accounted_period_type
3310       AND     l_trunc_le_sched_comp_date BETWEEN gp.start_date
3311                                          AND     gp.end_date;
3312 
3313     END IF; -- check for l_dummy
3314 
3315     IF (l_acct_period_id IS NULL AND (l_period_set_name IS NULL OR
3316                        l_period_name IS NULL)) THEN
3317 
3318       l_stmt_num := 40;
3319 
3320       l_api_message := 'Cannot Find Period for Date: ';
3321       l_api_message := l_api_message||TO_CHAR(l_trunc_le_sched_comp_date);
3322       FND_MSG_PUB.ADD_EXC_MSG('CST_EAMCOST_PUB', 'COMPUTE_JOB_ESTIMATES('
3323                                      ||TO_CHAR(l_stmt_num)
3324                                      ||'): ', l_api_message);
3325       RAISE FND_API.g_exc_error;
3326 
3327     END IF;
3328 
3329     -------------------------------------------------------------------------
3330     -- Derive the currency extended precision for the organization
3331     -------------------------------------------------------------------------
3332     l_stmt_num := 45;
3333 
3334     CSTPUTIL.CSTPUGCI(l_organization_id,
3335                       l_round_unit,
3336                       l_precision,
3337                       l_ext_precision);
3338 
3339 
3340     -------------------------------------------------------------------------
3341     -- Derive valuation rates cost type based on organization's cost method
3342     -------------------------------------------------------------------------
3343 
3344     l_stmt_num := 50;
3345 
3346     SELECT  decode (mp.primary_cost_method,
3347                       1, mp.primary_cost_method,
3348                       NVL(mp.avg_rates_cost_type_id,-1)),
3349             mp.primary_cost_method
3350     INTO    l_rates_ct,
3351             l_primary_cost_method
3352     FROM    mtl_parameters mp
3353     WHERE   mp.organization_id = l_organization_id;
3354 
3355     IF (l_rates_ct = -1) THEN
3356 
3357         l_api_message := 'Rates Type not defined for Org: '
3358                          ||TO_CHAR(l_organization_id);
3359 
3360         FND_MSG_PUB.ADD_EXC_MSG('CST_EAMCOST_PUB', 'COMPUTE_JOB_ESTIMATES('
3361                                      ||TO_CHAR(l_stmt_num)
3362                                      ||'): ', l_api_message);
3363         RAISE FND_API.g_exc_error;
3364 
3365 
3366     END IF;
3367 
3368     IF (p_debug = 'Y') THEN
3369       l_api_message := 'Wip Entity Type: '||TO_CHAR(l_entity_type);
3370       l_api_message := l_api_message||' Rates Ct: '||TO_CHAR(l_rates_ct);
3371       l_api_message := l_api_message||' Lot Size: '||TO_CHAR(l_lot_size);
3372       l_api_message := l_api_message||' Ext Precision: '
3373                                          ||TO_CHAR(l_ext_precision);
3374       l_api_message := l_api_message||' Asset Group Id: '
3375                                          ||TO_CHAR(l_asset_group_item_id);
3376       l_api_message := l_api_message||' Asset Number: '
3377                                          ||l_asset_number;
3378       l_api_message := l_api_message||' Wip Proj Id: '
3379                                          ||TO_CHAR(l_wip_project_id);
3380       l_api_message := l_api_message||' Cg Id: '||TO_CHAR(l_cost_group_id);
3381       l_api_message := l_api_message||' Cost Method: '
3382                                          ||TO_CHAR(l_primary_cost_method);
3383       l_api_message := l_api_message||' Acct Prd Id: '
3384                                          ||TO_CHAR(l_acct_period_id);
3385       l_api_message := l_api_message||' Schd. Compl. Dt: '
3386                                          ||TO_CHAR(l_scheduled_completion_date);
3387       l_api_message := l_api_message||' TruncLE ComplDt: '
3388                                          ||TO_CHAR(l_trunc_le_sched_comp_date);
3389       l_api_message := l_api_message||' Prd Set Name: '
3390                                          ||l_period_set_name;
3391       l_api_message := l_api_message||' Prd Name: '
3392                                          ||l_period_name;
3393       FND_MESSAGE.SET_NAME ('BOM', 'CST_API_MESSAGE');
3394       FND_MESSAGE.SET_TOKEN ('TEXT', l_api_message);
3395       FND_MSG_PUB.add;
3396 
3397     END IF;
3398 
3399 
3400     open c_acct(p_wip_entity_id);
3401     fetch c_acct into
3402          l_material_account,
3403          l_material_overhead_account,
3404          l_resource_account,
3405          l_osp_account,
3406          l_overhead_account,
3407          l_wip_acct_class;
3408     close c_acct;
3409 
3410 
3411     -------------------------------------------------------------------------
3412     -- Compute Resource Costs (WOR)
3413     -------------------------------------------------------------------------
3414 
3415     l_stmt_num := 55;
3416 
3417     FOR c_wor_rec IN c_wor LOOP
3418 
3419 
3420       IF (p_debug = 'Y') THEN
3421 
3422         l_api_message :=' Op: ';
3423         l_api_message :=l_api_message||TO_CHAR(c_wor_rec.operation_seq_num);
3424         l_api_message :=l_api_message||' Department Id: ';
3425         l_api_message :=l_api_message||TO_CHAR(c_wor_rec.department_id);
3426         l_api_message :=l_api_message||' Resource Type: ';
3427         l_api_message :=l_api_message||TO_CHAR(c_wor_rec.resource_type);
3428         l_api_message :=l_api_message||' WOR,Value: '||TO_CHAR(c_wor_rec.resource_value);
3429 
3430         FND_MESSAGE.SET_NAME ('BOM', 'CST_API_MESSAGE');
3431         FND_MESSAGE.SET_TOKEN ('TEXT', l_api_message);
3432         FND_MSG_PUB.add;
3433 
3434       END IF;
3435 
3436       l_stmt_num := 60;
3437 
3438       Get_MaintCostCat(
3439          p_txn_mode         => 2 ,
3440          p_wip_entity_id    => p_wip_entity_id,
3441          p_opseq_num        => c_wor_rec.operation_seq_num,
3442          p_resource_id      => c_wor_rec.resource_id,
3443          p_res_seq_num      => c_wor_rec.resource_seq_num,
3444          x_return_status    => l_return_status,
3445          x_operation_dept   => l_operation_dept_id,
3446          x_owning_dept      => l_owning_dept_id,
3447          x_maint_cost_cat   => l_maint_cost_category);
3448 
3449       IF l_return_status <> FND_API.g_ret_sts_success THEN
3450 
3451           l_api_message := 'Get_MaintCostCat returned error';
3452           FND_MSG_PUB.ADD_EXC_MSG('CST_EAMCOST_PUB', 'COMPUTE_JOB_ESTIMATES('
3453                                      ||TO_CHAR(l_stmt_num)
3454                                      ||'): ', l_api_message);
3455           RAISE FND_API.g_exc_error;
3456 
3457       END IF;
3458 
3459       l_stmt_num := 65;
3460 
3461       l_eam_cost_element :=
3462                    Get_eamCostElement(p_txn_mode    => 2,
3463                                       p_org_id      => l_organization_id,
3464                                       p_resource_id => c_wor_rec.resource_id);
3465 
3466       IF l_eam_cost_element = 0 THEN
3467 
3468          l_api_message := 'Get_eamCostElement returned error';
3469          FND_MSG_PUB.ADD_EXC_MSG('CST_EAMCOST_PUB', 'COMPUTE_JOB_ESTIMATES('
3470                                      ||TO_CHAR(l_stmt_num)
3471                                      ||'): ', l_api_message);
3472          RAISE FND_API.g_exc_error;
3473 
3474       END IF;
3475 
3476       IF (p_debug = 'Y') THEN
3477 
3478         l_api_message :=' MCC: ';
3479         l_api_message :=l_api_message||TO_CHAR(l_maint_cost_category);
3480         l_api_message :=l_api_message||' CE: '||TO_CHAR(l_eam_cost_element);
3481         FND_MESSAGE.SET_NAME ('BOM', 'CST_API_MESSAGE');
3482         FND_MESSAGE.SET_TOKEN ('TEXT', l_api_message);
3483         FND_MSG_PUB.add;
3484 
3485       END IF;
3486 
3487       l_stmt_num := 70;
3488 
3489       InsertUpdate_eamPerBal(
3490           p_api_version                   => 1.0,
3491           x_return_status                 => l_return_status,
3492           x_msg_count                     => l_msg_count,
3493           x_msg_data                      => l_msg_data,
3494           p_period_id                     => l_acct_period_id,
3495           p_period_set_name               => l_period_set_name,
3496           p_period_name                   => l_period_name,
3497           p_org_id                        => l_organization_id,
3498           p_wip_entity_id                 => p_wip_entity_id,
3499           p_owning_dept_id                => l_owning_dept_id,
3500           p_dept_id                       => l_operation_dept_id,
3501           p_maint_cost_cat                => l_maint_cost_category,
3502           p_opseq_num                     => c_wor_rec.operation_seq_num,
3503           p_eam_cost_element              => l_eam_cost_element,
3504           p_asset_group_id                => l_asset_group_item_id,
3505           p_asset_number                  => l_asset_number,
3506           p_value_type                    => 2,
3507           p_value                         => c_wor_rec.resource_value,
3508           p_user_id                       => p_user_id,
3509           p_request_id                    => p_request_id,
3510           p_prog_id                       => p_prog_id,
3511           p_prog_app_id                   => p_prog_app_id,
3512           p_login_id                      => p_login_id);
3513 
3514       IF l_return_status <> FND_API.g_ret_sts_success THEN
3515 
3516           l_api_message := 'insertupdate_eamperbal error';
3517           FND_MSG_PUB.ADD_EXC_MSG('CST_EAMCOST_PUB', 'COMPUTE_JOB_ESTIMATES('
3518                                      ||TO_CHAR(l_stmt_num)
3519                                      ||'): ', l_api_message);
3520           RAISE FND_API.g_exc_error;
3521 
3522       END IF;
3523 
3524 
3525       IF c_wor_rec.resource_value <> 0 then
3526 
3527          l_stmt_num := 73;
3528 
3529 
3530          case(c_wor_rec.cost_element_id)
3531          when 3 then
3532                 l_acct_id := l_resource_account;
3533          when 4 then
3534                 l_acct_id := l_osp_account;
3535          else
3536                 l_acct_id := l_resource_account;
3537          end case;
3538 
3539 
3540          IF (p_debug = 'Y') THEN
3541            l_api_message :=' Calling Insert_eamBalAcct... WOR... ';
3542            l_api_message :=l_api_message|| ' p_wip_entity_id = ' || TO_CHAR(p_wip_entity_id) || ', ';
3543            l_api_message :=l_api_message|| ' mfg_cost_element_id = ' || TO_CHAR(c_wor_rec.cost_element_id) ;
3544            l_api_message :=l_api_message|| ', account_id  =  ' || TO_CHAR(l_acct_id) || ',';
3545            l_api_message :=l_api_message|| ' eam_cost_element_id = '||TO_CHAR(l_eam_cost_element);
3546            l_api_message :=l_api_message|| ' Sum WOR = ' || TO_CHAR( c_wor_rec.resource_value);
3547            FND_MESSAGE.SET_NAME ('BOM', 'CST_API_MESSAGE');
3548           FND_MESSAGE.SET_TOKEN ('TEXT', l_api_message);
3549            FND_MSG_PUB.add;
3550          END IF;
3551 
3552             Insert_eamBalAcct(
3553               p_api_version                   => 1.0,
3554               p_init_msg_list                 => FND_API.G_FALSE,
3555               p_commit                        => FND_API.G_FALSE,
3556               p_validation_level              => FND_API.G_VALID_LEVEL_FULL,
3557               x_return_status                 => l_return_status,
3558               x_msg_count                     => l_msg_count,
3559               x_msg_data                      => l_msg_data,
3560               p_period_id                     => l_acct_period_id,
3561               p_period_set_name               => l_period_set_name,
3562               p_period_name                   => l_period_name,
3563               p_org_id                        => l_organization_id,
3564               p_wip_entity_id                 => p_wip_entity_id,
3565               p_owning_dept_id                => l_owning_dept_id,
3566               p_dept_id                       => l_operation_dept_id,
3567               p_maint_cost_cat                => l_maint_cost_category,
3568               p_opseq_num                     => c_wor_rec.operation_seq_num,
3569               p_period_start_date             => l_period_start_date,
3570               p_account_ccid                  => l_acct_id,
3571               p_value                         => c_wor_rec.resource_value,
3572               p_txn_type                      => l_eam_cost_element,
3573               p_wip_acct_class                => l_wip_acct_class,
3574               p_mfg_cost_element_id           => c_wor_rec.cost_element_id,
3575               p_user_id                       => p_user_id,
3576               p_request_id                    => p_request_id,
3577               p_prog_id                       => p_prog_id,
3578               p_prog_app_id                   => p_prog_app_id,
3579               p_login_id                      => p_login_id);
3580 
3581            IF l_return_status <> FND_API.g_ret_sts_success THEN
3582 
3583               l_api_message := 'Insert_eamBalAcct error';
3584               FND_MSG_PUB.ADD_EXC_MSG('CST_EAMCOST_PUB', 'Insert_eamBalAcct('
3585                                          ||TO_CHAR(l_stmt_num)
3586                                          ||'): ', l_api_message);
3587               RAISE FND_API.g_exc_error;
3588 
3589            END IF;
3590         ELSE
3591 
3592            IF (p_debug = 'Y') THEN
3593             l_api_message :=' Sum WOR = ' || TO_CHAR( c_wor_rec.resource_value);
3594             FND_MESSAGE.SET_NAME ('BOM', 'CST_API_MESSAGE');
3595             FND_MESSAGE.SET_TOKEN ('TEXT', l_api_message);
3596             FND_MSG_PUB.add;
3597            END IF;
3598 
3599         END IF;  -- if c_wor_rec.resource_value !=0
3600 
3601       -----------------------------------------------------------------------
3602       -- Compute Resource Based Overheads Costs (WOR)
3603       -----------------------------------------------------------------------
3604 
3605       l_stmt_num := 75;
3606 
3607       /* set the sum variable that calculates the total Overhead for the resource to 0*/
3608 
3609       l_sum_rbo := 0;
3610 
3611       FOR c_rbo_rec IN c_rbo(c_wor_rec.resource_id,
3612                              l_owning_dept_id,
3613                              l_organization_id,
3614                              c_wor_rec.usage_rate_or_amount,
3615                              c_wor_rec.raw_resource_value)
3616       LOOP
3617 
3618         IF (p_debug = 'Y') THEN
3619 
3620           l_api_message :=' Op: ';
3621           l_api_message :=l_api_message||TO_CHAR(c_wor_rec.operation_seq_num);
3622           l_api_message :=l_api_message||' RBO,Value: '||TO_CHAR(c_rbo_rec.rbo_value);
3623           l_api_message :=l_api_message||' MCC: ';
3624           l_api_message :=l_api_message||TO_CHAR(l_maint_cost_category);
3625           l_api_message :=l_api_message||' CE: '||TO_CHAR(l_eam_cost_element);
3626           FND_MESSAGE.SET_NAME ('BOM', 'CST_API_MESSAGE');
3627           FND_MESSAGE.SET_TOKEN ('TEXT', l_api_message);
3628           FND_MSG_PUB.add;
3629 
3630         END IF;
3631 
3632         l_stmt_num := 80;
3633 
3634         /* sum the total resource based overheads */
3635         l_sum_rbo := l_sum_rbo + NVL(c_rbo_rec.rbo_value,0);
3636 
3637         InsertUpdate_eamPerBal(
3638             p_api_version                   => 1.0,
3639             x_return_status                 => l_return_status,
3640             x_msg_count                     => l_msg_count,
3641             x_msg_data                      => l_msg_data,
3642             p_period_id                     => l_acct_period_id,
3643             p_period_set_name               => l_period_set_name,
3644             p_period_name                   => l_period_name,
3645             p_org_id                        => l_organization_id,
3646             p_wip_entity_id                 => p_wip_entity_id,
3647             p_owning_dept_id                => l_owning_dept_id,
3648             p_dept_id                       => l_operation_dept_id,
3649             p_maint_cost_cat                => l_maint_cost_category,
3650             p_opseq_num                     => c_wor_rec.operation_seq_num,
3651             p_eam_cost_element              => l_eam_cost_element,
3652             p_asset_group_id                => l_asset_group_item_id,
3653             p_asset_number                  => l_asset_number,
3654             p_value_type                    => 2,
3655             p_value                         => c_rbo_rec.rbo_value,
3656             p_user_id                       => p_user_id,
3657             p_request_id                    => p_request_id,
3658             p_prog_id                       => p_prog_id,
3659 
3660             p_prog_app_id                   => p_prog_app_id,
3661             p_login_id                      => p_login_id);
3662 
3663         IF l_return_status <> FND_API.g_ret_sts_success THEN
3664 
3665           l_api_message := 'insertupdate_eamperbal error';
3666 
3667           FND_MSG_PUB.ADD_EXC_MSG('CST_EAMCOST_PUB', 'COMPUTE_JOB_ESTIMATES('
3668                                      ||TO_CHAR(l_stmt_num)
3669                                      ||'): ', l_api_message);
3670           RAISE FND_API.g_exc_error;
3671 
3672         END IF;
3673 
3674       END LOOP; -- c_rbo_rec
3675 
3676 
3677       l_stmt_num := 83;
3678 
3679      /* Insert Resource based overheads only if the value is greater than 0 */
3680       IF ( l_sum_rbo <> 0 ) THEN
3681 
3682        IF (p_debug = 'Y') THEN
3683 
3684             l_api_message :=' Calling Insert_eamBalAcct... RBO... ';
3685             l_api_message :=l_api_message|| ' p_wip_entity_id = ' || TO_CHAR(p_wip_entity_id) || ', ';
3686             l_api_message :=l_api_message|| ' mfg_cost_element_id = 5,' ;
3687             l_api_message :=l_api_message|| ' account_id  =  ' || TO_CHAR(l_overhead_account) || ',';
3688             l_api_message :=l_api_message|| ' eam_cost_element_id = '||TO_CHAR(l_eam_cost_element);
3689             l_api_message :=l_api_message|| ' Sum RBO = ' || TO_CHAR(l_sum_rbo);
3690             FND_MESSAGE.SET_NAME ('BOM', 'CST_API_MESSAGE');
3691             FND_MESSAGE.SET_TOKEN ('TEXT', l_api_message);
3692             FND_MSG_PUB.add;
3693        END IF;
3694 
3695         Insert_eamBalAcct(
3696          p_api_version                   => 1.0,
3697          p_init_msg_list                 => FND_API.G_FALSE,
3698          p_commit                        => FND_API.G_FALSE,
3699          p_validation_level              => FND_API.G_VALID_LEVEL_FULL,
3700          x_return_status                 => l_return_status,
3701          x_msg_count                     => l_msg_count,
3702          x_msg_data                      => l_msg_data,
3703          p_period_id                     => l_acct_period_id,
3704          p_period_set_name               => l_period_set_name,
3705          p_period_name                   => l_period_name,
3706          p_org_id                        => l_organization_id,
3707          p_wip_entity_id                 => p_wip_entity_id,
3708          p_owning_dept_id                => l_owning_dept_id,
3709          p_dept_id                       => l_operation_dept_id,
3710          p_maint_cost_cat                => l_maint_cost_category,
3711          p_opseq_num                     => c_wor_rec.operation_seq_num,
3712          p_period_start_date             => l_period_start_date,
3713          p_account_ccid                  => l_overhead_account,
3714          p_value                         => l_sum_rbo,
3715          p_txn_type                      => l_eam_cost_element,
3716          p_wip_acct_class                => l_wip_acct_class,
3717          p_mfg_cost_element_id           => 5,    /* Overhead Cost Element */
3718          p_user_id                       => p_user_id,
3719          p_request_id                    => p_request_id,
3720          p_prog_id                       => p_prog_id,
3721          p_prog_app_id                   => p_prog_app_id,
3722          p_login_id                      => p_login_id);
3723 
3724          IF l_return_status <> FND_API.g_ret_sts_success THEN
3725 
3726            l_api_message := 'Insert_eamBalAcct error';
3727            FND_MSG_PUB.ADD_EXC_MSG('CST_EAMCOST_PUB', 'Insert_eamBalAcct('
3728                                     ||TO_CHAR(l_stmt_num)
3729                                     ||'): ', l_api_message);
3730            RAISE FND_API.g_exc_error;
3731 
3732         END IF;
3733 
3734      ELSE
3735        IF (p_debug = 'Y') THEN
3736             l_api_message :=' Sum RBO = ' || TO_CHAR(l_sum_rbo);
3737             FND_MESSAGE.SET_NAME ('BOM', 'CST_API_MESSAGE');
3738             FND_MESSAGE.SET_TOKEN ('TEXT', l_api_message);
3739             FND_MSG_PUB.add;
3740        END IF;
3741      END IF;  -- if l_sum_rbo != 0
3742 
3743       /*Now ADD the value for the total resource based Overheads for this
3744       resource and the resource value and insert into CST_EAM_WO_ESTIMATE_DETAILS */
3745 
3746       l_sum_rbo := l_sum_rbo + c_wor_rec.resource_value;
3747 
3748       l_stmt_num := 85;
3749 
3750       Insert into CST_EAM_WO_ESTIMATE_DETAILS(
3751                      wip_entity_id,
3752                      organization_id,
3753                      operations_dept_id,
3754                      operations_seq_num,
3755                      maint_cost_category,
3756                      owning_dept_id,
3757                      estimated_cost,
3758                      resource_id,
3759                      resource_rate,
3760                      uom,
3761                      resource_usage,
3762                      last_update_date,
3763                      last_updated_by,
3764                      creation_date,
3765                      created_by,
3766                      last_update_login,
3767                      request_id,
3768                      program_application_id,
3769                      program_id,
3770                      program_update_date)
3771              VALUES(
3772                      p_wip_entity_id,
3773                      l_organization_id,
3774                      l_operation_dept_id,
3775                      c_wor_rec.operation_seq_num,
3776                      l_maint_cost_category,
3777                      l_owning_dept_id,
3778                      l_sum_rbo,
3779                      c_wor_rec.resource_id,
3780                      c_wor_rec.resource_rate,
3781                      c_wor_rec.uom,
3782                      c_wor_rec.resource_usage,
3783                      SYSDATE,
3784                      p_user_id,
3785                      SYSDATE,
3786                      p_user_id,
3787                      p_login_id,
3788                      p_request_id,
3789                      p_prog_app_id,
3790                      p_prog_id,
3791                      SYSDATE);
3792 
3793     END LOOP; --c_wor_rec
3794 
3795 /*
3796 
3797 Support For earning Department Based Overheads is not being provided in the first phase of
3798 eAM release. Therefore commenting out the follwing code.
3799 
3800 
3801     -------------------------------------------------------------------------
3802     -- Compute Department Based Overheads Costs
3803     -------------------------------------------------------------------------
3804 
3805     l_stmt_num := 90;
3806 
3807     FOR c_dbo_rec IN c_dbo LOOP
3808 
3809       IF (p_debug = 'Y') THEN
3810 
3811         l_api_message :=' Op: ';
3812         l_api_message :=l_api_message||TO_CHAR(c_dbo_rec.operation_seq_num);
3813         l_api_message :=l_api_message||' Department Id: ';
3814         l_api_message :=l_api_message||TO_CHAR(c_dbo_rec.department_id);
3815         l_api_message :=l_api_message||' DBO,Value: '||TO_CHAR(c_dbo_rec.dbo_value);
3816         FND_MESSAGE.SET_NAME ('BOM', 'CST_API_MESSAGE');
3817         FND_MESSAGE.SET_TOKEN ('TEXT', l_api_message);
3818         FND_MSG_PUB.add;
3819 
3820       END IF;
3821 
3822       l_stmt_num := 92;
3823 
3824       Get_MaintCostCat(
3825          p_txn_mode         => 2 ,
3826          p_wip_entity_id    => p_wip_entity_id,
3827          p_opseq_num        => c_dbo_rec.operation_seq_num,
3828          x_return_status    => l_return_status,
3829          x_operation_dept   => l_operation_dept_id,
3830          x_owning_dept      => l_owning_dept_id,
3831          x_maint_cost_cat   => l_maint_cost_category);
3832 
3833       IF l_return_status <> FND_API.g_ret_sts_success THEN
3834 
3835           l_api_message := 'Get_MaintCostCat returned error';
3836           FND_MSG_PUB.ADD_EXC_MSG('CST_EAMCOST_PUB', 'COMPUTE_JOB_ESTIMATES('
3837                                      ||TO_CHAR(l_stmt_num)
3838                                      ||'): ', l_api_message);
3839           RAISE FND_API.g_exc_error;
3840 
3841       END IF;
3842 
3843       l_stmt_num := 95;
3844 
3845       l_eam_cost_element :=
3846                    Get_eamCostElement(p_txn_mode    => 2,
3847                                       p_org_id      => l_organization_id);
3848 
3849       IF l_eam_cost_element = 0 THEN
3850 
3851          l_api_message := 'Get_eamCostElement returned error';
3852          FND_MSG_PUB.ADD_EXC_MSG('CST_EAMCOST_PUB', 'COMPUTE_JOB_ESTIMATES('
3853                                      ||TO_CHAR(l_stmt_num)
3854                                      ||'): ', l_api_message);
3855          RAISE FND_API.g_exc_error;
3856 
3857       END IF;
3858 
3859       IF (p_debug = 'Y') THEN
3860 
3861         l_api_message :=' MCC: ';
3862         l_api_message :=l_api_message||TO_CHAR(l_maint_cost_category);
3863         l_api_message :=l_api_message||' CE: '||TO_CHAR(l_eam_cost_element);
3864         FND_MESSAGE.SET_NAME ('BOM', 'CST_API_MESSAGE');
3865         FND_MESSAGE.SET_TOKEN ('TEXT', l_api_message);
3866         FND_MSG_PUB.add;
3867 
3868       END IF;
3869 
3870       l_stmt_num := 100;
3871 
3872       InsertUpdate_eamPerBal(
3873           p_api_version                   => 1.0,
3874           x_return_status                 => l_return_status,
3875           x_msg_count                     => l_msg_count,
3876           x_msg_data                      => l_msg_data,
3877           p_period_id                     => l_acct_period_id,
3878           p_period_set_name               => l_period_set_name,
3879           p_period_name                   => l_period_name,
3880           p_org_id                        => l_organization_id,
3881           p_wip_entity_id                 => p_wip_entity_id,
3882           p_owning_dept_id                => l_owning_dept_id,
3883           p_dept_id                       => l_operation_dept_id,
3884           p_maint_cost_cat                => l_maint_cost_category,
3885           p_opseq_num                     => c_dbo_rec.operation_seq_num,
3886           p_eam_cost_element              => l_eam_cost_element,
3887           p_asset_group_id                => l_asset_group_item_id,
3888           p_asset_number                  => l_asset_number,
3889           p_value_type                    => 2,
3890           p_value                         => c_dbo_rec.dbo_value,
3891           p_user_id                       => p_user_id,
3892           p_request_id                    => p_request_id,
3893           p_prog_id                       => p_prog_id,
3894           p_prog_app_id                   => p_prog_app_id,
3895           p_login_id                      => p_login_id);
3896 
3897       IF l_return_status <> FND_API.g_ret_sts_success THEN
3898 
3899           l_api_message := 'INSERTUPDATE_EAMPERBAL ERROR';
3900 
3901           FND_MSG_PUB.ADD_EXC_MSG('CST_EAMCOST_PUB', 'COMPUTE_JOB_ESTIMATES('
3902                                      ||TO_CHAR(l_stmt_num)
3903                                      ||'): ', l_api_message);
3904           RAISE FND_API.g_exc_error;
3905 
3906       END IF;
3907 
3908 
3909     --  Adding the call to Insert_eamBalAcct in case this part of the  code is
3910     --  de-commented later
3911 
3912         IF ( c_dbo_rec.dbo_value <> 0 ) THEN
3913 
3914        IF (p_debug = 'Y') THEN
3915 
3916             l_api_message :=' Calling Insert_eamBalAcct... DBO... ';
3917             l_api_message :=l_api_message|| ' p_wip_entity_id = ' || TO_CHAR(p_wip_entity_id) || ', ';
3918             l_api_message :=l_api_message|| ' mfg_cost_element_id = 5,' ;
3919             l_api_message :=l_api_message|| ' account_id  =  ' || TO_CHAR(l_overhead_account) || ',';
3920             l_api_message :=l_api_message|| ' eam_cost_element_id = '||TO_CHAR(l_eam_cost_element);
3921             l_api_message :=l_api_message|| ' Sum DBO = ' || TO_CHAR(l_sum_dbo);
3922             FND_MESSAGE.SET_NAME ('BOM', 'CST_API_MESSAGE');
3923             FND_MESSAGE.SET_TOKEN ('TEXT', l_api_message);
3924             FND_MSG_PUB.add;
3925        END IF;
3926 
3927         Insert_eamBalAcct(
3928          p_api_version                   => 1.0,
3929          p_init_msg_list                 => FND_API.G_FALSE,
3930          p_commit                        => FND_API.G_FALSE,
3931          p_validation_level              => FND_API.G_VALID_LEVEL_FULL,
3932          x_return_status                 => l_return_status,
3933          x_msg_count                     => l_msg_count,
3934          x_msg_data                      => l_msg_data,
3935          p_period_id                     => l_acct_period_id,
3936          p_period_set_name               => l_period_set_name,
3937          p_period_name                   => l_period_name,
3938          p_org_id                        => l_organization_id,
3939          p_wip_entity_id                 => p_wip_entity_id,
3940          p_owning_dept_id                => l_owning_dept_id,
3941          p_dept_id                       => l_operation_dept_id,
3942          p_maint_cost_cat                => l_maint_cost_category,
3943          p_opseq_num                     => c_dbo_rec.operation_seq_num,
3944          p_period_start_date             => l_period_start_date,
3945          p_account_ccid                  => l_overhead_account,
3946          p_value                         => c_dbo_rec.dbo_value,
3947          p_txn_type                      => l_eam_cost_element,
3948          p_wip_acct_class                => l_wip_acct_class,
3949          p_mfg_cost_element_id           => 5,    -- Overhead Cost Element
3950          p_user_id                       => p_user_id,
3951          p_request_id                    => p_request_id,
3952          p_prog_id                       => p_prog_id,
3953          p_prog_app_id                   => p_prog_app_id,
3954          p_login_id                      => p_login_id);
3955 
3956          IF l_return_status <> FND_API.g_ret_sts_success THEN
3957 
3958            l_api_message := 'Insert_eamBalAcct error';
3959            FND_MSG_PUB.ADD_EXC_MSG('CST_EAMCOST_PUB', 'Insert_eamBalAcct('
3960                                     ||TO_CHAR(l_stmt_num)
3961                                     ||'): ', l_api_message);
3962            RAISE FND_API.g_exc_error;
3963 
3964         END IF;
3965 
3966      ELSE
3967        IF (p_debug = 'Y') THEN
3968             l_api_message :=' Sum DBO = ' || TO_CHAR(l_sum_dbo);
3969             FND_MESSAGE.SET_NAME ('BOM', 'CST_API_MESSAGE');
3970             FND_MESSAGE.SET_TOKEN ('TEXT', l_api_message);
3971             FND_MSG_PUB.add;
3972        END IF;
3973 
3974     END LOOP; */
3975 
3976     -------------------------------------------------------------------------
3977     -- Compute Material Costs (WRO + WRODI)
3978     -------------------------------------------------------------------------
3979 
3980     l_stmt_num := 105;
3981 
3982 
3983     FOR c_wro_rec IN c_wro LOOP
3984 
3985       l_stmt_num := 110;
3986 
3987       IF (p_debug = 'Y') THEN
3988 
3989         l_api_message :=' Op: ';
3990         l_api_message :=l_api_message||TO_CHAR(c_wro_rec.operation_seq_num);
3991         l_api_message :=l_api_message||' Department Id: ' ;
3992         l_api_message :=l_api_message||TO_CHAR(c_wro_rec.department_id);
3993         l_api_message :=l_api_message||' WRO,Value: '||TO_CHAR(c_wro_rec.mat_value);
3994         FND_MESSAGE.SET_NAME ('BOM', 'CST_API_MESSAGE');
3995         FND_MESSAGE.SET_TOKEN ('TEXT', l_api_message);
3996         FND_MSG_PUB.add;
3997 
3998       END IF;
3999 
4000       Get_MaintCostCat(
4001          p_txn_mode         => 1 ,
4002          p_wip_entity_id    => p_wip_entity_id,
4003          p_opseq_num        => c_wro_rec.operation_seq_num,
4004          x_return_status    => l_return_status,
4005          x_operation_dept   => l_operation_dept_id,
4006          x_owning_dept      => l_owning_dept_id,
4007          x_maint_cost_cat   => l_maint_cost_category);
4008 
4009        IF l_return_status <> FND_API.g_ret_sts_success THEN
4010 
4011           l_api_message := 'Get_MaintCostCat returned error';
4012 
4013           FND_MSG_PUB.ADD_EXC_MSG('CST_EAMCOST_PUB', 'COMPUTE_JOB_ESTIMATES('
4014                                      ||TO_CHAR(l_stmt_num)
4015                                      ||'): ', l_api_message);
4016           RAISE FND_API.g_exc_error;
4017 
4018        END IF;
4019 
4020       l_stmt_num := 115;
4021 
4022       l_eam_cost_element :=
4023                    Get_eamCostElement(p_txn_mode    => 1,
4024                                       p_org_id      => l_organization_id);
4025 
4026       IF l_eam_cost_element = 0 THEN
4027 
4028          l_api_message := 'Get_eamCostElement returned error';
4029 
4030          FND_MSG_PUB.ADD_EXC_MSG('CST_EAMCOST_PUB', 'COMPUTE_JOB_ESTIMATES('
4031                                      ||TO_CHAR(l_stmt_num)
4032                                      ||'): ', l_api_message);
4033          RAISE FND_API.g_exc_error;
4034 
4035       END IF;
4036 
4037       IF (p_debug = 'Y') THEN
4038 
4039         l_api_message :=' MCC: ';
4040         l_api_message :=l_api_message||TO_CHAR(l_maint_cost_category);
4041         l_api_message :=l_api_message||' CE: '||TO_CHAR(l_eam_cost_element);
4042         FND_MESSAGE.SET_NAME ('BOM', 'CST_API_MESSAGE');
4043         FND_MESSAGE.SET_TOKEN ('TEXT', l_api_message);
4044         FND_MSG_PUB.add;
4045 
4046       END IF;
4047 
4048       l_stmt_num := 120;
4049 
4050       InsertUpdate_eamPerBal(
4051           p_api_version                   => 1.0,
4052           x_return_status                 => l_return_status,
4053           x_msg_count                     => l_msg_count,
4054           x_msg_data                      => l_msg_data,
4055           p_period_id                     => l_acct_period_id,
4056           p_period_set_name               => l_period_set_name,
4057           p_period_name                   => l_period_name,
4058           p_org_id                        => l_organization_id,
4059           p_wip_entity_id                 => p_wip_entity_id,
4060           p_owning_dept_id                => l_owning_dept_id,
4061           p_dept_id                       => c_wro_rec.department_id,
4062           p_maint_cost_cat                => l_maint_cost_category,
4063           p_opseq_num                     => c_wro_rec.operation_seq_num,
4064           p_eam_cost_element              => l_eam_cost_element,
4065           p_asset_group_id                => l_asset_group_item_id,
4066           p_asset_number                  => l_asset_number,
4067           p_value_type                    => 2,
4068           p_value                         => c_wro_rec.mat_value,
4069           p_user_id                       => p_user_id,
4070           p_request_id                    => p_request_id,
4071           p_prog_id                       => p_prog_id,
4072           p_prog_app_id                   => p_prog_app_id,
4073           p_login_id                      => p_login_id);
4074 
4075       IF l_return_status <> FND_API.g_ret_sts_success THEN
4076 
4077           l_api_message := 'insertupdate_eamperbal error';
4078 
4079           FND_MSG_PUB.ADD_EXC_MSG('CST_EAMCOST_PUB', 'COMPUTE_JOB_ESTIMATES('
4080                                      ||TO_CHAR(l_stmt_num)
4081                                      ||'): ', l_api_message);
4082           RAISE FND_API.g_exc_error;
4083 
4084       END IF;
4085 
4086 
4087       l_stmt_num := 123;
4088 
4089       /* Enter Estimation details for all the manufacturing cost elements where cost is
4090          non-zero - Eam Enhancements Project R12 */
4091 
4092       for l_index_var in 1..5 loop
4093 
4094        case (l_index_var)
4095        when 1 then
4096               If  c_wro_rec.material_cost <> 0 then
4097                  l_mfg_cost_element_id := 1;
4098                  l_account := l_material_account;
4099                  l_value := c_wro_rec.material_cost;
4100                  l_exec_flag := 1;
4101               Else
4102                  l_exec_flag := 0;
4103               End If;
4104        when 2 then
4105               If  c_wro_rec.material_overhead_cost <> 0 then
4106                  l_mfg_cost_element_id := 2;
4107                  l_account := l_material_overhead_account;
4108                  l_value := c_wro_rec.material_overhead_cost;
4109                  l_exec_flag := 1;
4110               Else
4111                  l_exec_flag := 0;
4112               End If;
4113         when 3 then
4114               If  c_wro_rec.resource_cost <> 0 then
4115                  l_mfg_cost_element_id := 3;
4116                  l_account := l_resource_account;
4117                  l_value := c_wro_rec.resource_cost;
4118                  l_exec_flag := 1;
4119               Else
4120                  l_exec_flag := 0;
4121               End If;
4122         when 4 then
4123               If c_wro_rec.outside_processing_cost <> 0 then
4124                  l_mfg_cost_element_id := 4;
4125                  l_account := l_osp_account;
4126                  l_value :=  c_wro_rec.outside_processing_cost;
4127                  l_exec_flag := 1;
4128               Else
4129                  l_exec_flag := 0;
4130               End If;
4131         when 5 then
4132               If c_wro_rec.overhead_cost <> 0 then
4133                  l_mfg_cost_element_id := 5;
4134                  l_account := l_overhead_account;
4135                  l_value :=  c_wro_rec.overhead_cost;
4136                  l_exec_flag := 1;
4137               Else
4138                  l_exec_flag := 0;
4139               End If;
4140        end case;
4141 
4142        IF (p_debug = 'Y' and l_exec_flag = 1) THEN
4143             l_api_message :=' Calling Insert_eamBalAcct... WRO... ';
4144             l_api_message :=l_api_message|| ' p_wip_entity_id = ' || TO_CHAR(p_wip_entity_id) || ', ';
4145             l_api_message :=l_api_message|| ' mfg_cost_element_id = ' || TO_CHAR(l_mfg_cost_element_id) ;
4146             l_api_message :=l_api_message|| ', account_id  =  ' || TO_CHAR(l_account) || ',';
4147             l_api_message :=l_api_message|| ' eam_cost_element_id = '||TO_CHAR(l_eam_cost_element);
4148             l_api_message :=l_api_message|| ' Sum WRO = ' || TO_CHAR(l_value);
4149             FND_MESSAGE.SET_NAME ('BOM', 'CST_API_MESSAGE');
4150             FND_MESSAGE.SET_TOKEN ('TEXT', l_api_message);
4151             FND_MSG_PUB.add;
4152        END IF;
4153 
4154      If (l_exec_flag = 1) then
4155       Insert_eamBalAcct(
4156        p_api_version                   => 1.0,
4157        p_init_msg_list                 => FND_API.G_FALSE,
4158        p_commit                        => FND_API.G_FALSE,
4159        p_validation_level              => FND_API.G_VALID_LEVEL_FULL,
4160        x_return_status                 => l_return_status,
4161        x_msg_count                     => l_msg_count,
4162        x_msg_data                      => l_msg_data,
4163        p_period_id                     => l_acct_period_id,
4164        p_period_set_name               => l_period_set_name,
4165        p_period_name                   => l_period_name,
4166        p_org_id                        => l_organization_id,
4167        p_wip_entity_id                 => p_wip_entity_id,
4168        p_owning_dept_id                => l_owning_dept_id,
4169        p_dept_id                       => l_operation_dept_id,
4170        p_maint_cost_cat                => l_maint_cost_category,
4171        p_opseq_num                     => c_wro_rec.operation_seq_num,
4172        p_period_start_date             => l_period_start_date,
4173        p_account_ccid                  => l_account,
4174        p_value                         => l_value,
4175        p_txn_type                      => l_eam_cost_element,
4176        p_wip_acct_class                => l_wip_acct_class,
4177        p_mfg_cost_element_id           => l_mfg_cost_element_id,
4178        p_user_id                       => p_user_id,
4179        p_request_id                    => p_request_id,
4180        p_prog_id                      => p_prog_id,
4181        p_prog_app_id                   => p_prog_app_id,
4182        p_login_id                      => p_login_id);
4183 
4184        IF l_return_status <> FND_API.g_ret_sts_success THEN
4185 
4186           l_api_message := 'Insert_eamBalAcct error';
4187           FND_MSG_PUB.ADD_EXC_MSG('CST_EAMCOST_PUB', 'Insert_eamBalAcct('
4188                                        ||TO_CHAR(l_stmt_num)
4189                                        ||'): ', l_api_message);
4190           RAISE FND_API.g_exc_error;
4191 
4192        END IF;
4193 
4194        IF (p_debug = 'Y') THEN
4195             l_api_message :=' Sum WRO = 0';
4196             FND_MESSAGE.SET_NAME ('BOM', 'CST_API_MESSAGE');
4197             FND_MESSAGE.SET_TOKEN ('TEXT', l_api_message);
4198             FND_MSG_PUB.add;
4199        END IF;
4200       End If;
4201       End loop;  /* End For Loop for l_index_var */
4202 
4203       /* Now start inserting the Estimation details into CST_EAM_WO_ESTIMATE_DETAILS */
4204       l_stmt_num := 125;
4205 
4206       Insert into CST_EAM_WO_ESTIMATE_DETAILS(
4207                    wip_entity_id,
4208                    organization_id,
4209                    operations_dept_id,
4210                    operations_seq_num,
4211                    maint_cost_category,
4212                    owning_dept_id,
4213                    estimated_cost,
4214                    inventory_item_id,
4215                    item_cost,
4216                    required_quantity,
4217                    last_update_date,
4218                    last_updated_by,
4219                    creation_date,
4220                    created_by,
4221                    last_update_login,
4222                    request_id,
4223                    program_application_id,
4224                    program_id,
4225                    program_update_date)
4226             SELECT p_wip_entity_id,
4227                    wro.organization_id,
4228                    l_operation_dept_id,
4229                    wro.operation_seq_num,
4230                    l_maint_cost_category,
4231                    l_owning_dept_id,
4232                    NVL(wro.required_quantity,0) *           --     lot_size * Commented for bug 5398315
4233                         decode(msi.eam_item_type,
4234                                 3,decode(wdj.issue_zero_cost_flag,'Y',0,nvl(ccicv.item_cost,0)),
4235                                 NVL(ccicv.item_cost,0)),
4236                    wro.inventory_item_id,
4237                    decode(msi.eam_item_type,
4238                         3,decode(wdj.issue_zero_cost_flag,'Y',0,ccicv.item_cost),
4239                         ccicv.item_cost),
4240                    wro.required_quantity,
4241                    SYSDATE,
4242                    p_user_id,
4243                    SYSDATE,
4244                    p_user_id,
4245                    p_login_id,
4246                    p_request_id,
4247                    p_prog_app_id,
4248                    p_prog_id,
4249                    SYSDATE
4250               FROM wip_requirement_operations wro,
4251                    cst_cg_item_costs_view ccicv,
4252                    wip_discrete_jobs wdj,
4253                    mtl_system_items_b msi
4254               WHERE wro.wip_entity_id = p_wip_entity_id
4255                    AND ccicv.inventory_item_id = wro.inventory_item_id
4256                    AND ccicv.organization_id = wro.organization_id
4257                    AND ccicv.cost_group_id = decode(l_primary_cost_method,1,1,
4258                                                               l_cost_group_id)
4259                    AND wro.wip_supply_type IN (1,4)
4260                    AND nvl(wro.released_quantity,-1) <> 0
4261                    AND wdj.wip_entity_id = wro.wip_entity_id
4262                    AND msi.inventory_item_id = wro.inventory_item_id
4263                    AND msi.organization_id = wro.organization_id
4264                    AND msi.stock_enabled_flag = 'Y'
4265                    AND wro.department_id = c_wro_rec.department_id
4266                    AND wro.operation_seq_num = c_wro_rec.operation_seq_num
4267                    AND wdj.organization_id = wro.organization_id ;/* Bug 5230287 */
4268 
4269               /* NOTE: joining to ccicv.cost_group_id of 1 for standard costing org.
4270                        for ccicv, using default cost group id for that org is not
4271                        needed in the case of standard costing. */
4272 
4273     END LOOP;
4274 
4275     l_stmt_num := 130;
4276 
4277     FOR c_wrodi_rec IN c_wrodi LOOP
4278 
4279       l_stmt_num := 140;
4280 
4281       IF (p_debug = 'Y') THEN
4282 
4283         l_api_message :=' Op: ';
4284         l_api_message :=l_api_message||TO_CHAR(c_wrodi_rec.operation_seq_num);
4285         l_api_message :=l_api_message||' Department Id: ' ;
4286         l_api_message :=l_api_message||TO_CHAR(c_wrodi_rec.department_id);
4287         l_api_message :=l_api_message||' WRO Direct Items,Value: '||TO_CHAR(c_wrodi_rec.mat_value);
4288         FND_MESSAGE.SET_NAME ('BOM', 'CST_API_MESSAGE');
4289         FND_MESSAGE.SET_TOKEN ('TEXT', l_api_message);
4290         FND_MSG_PUB.add;
4291 
4292       END IF;
4293 
4294       Get_MaintCostCat(
4295          p_txn_mode         => 1 ,
4296          p_wip_entity_id    => p_wip_entity_id,
4297          p_opseq_num        => c_wrodi_rec.operation_seq_num,
4298          x_return_status    => l_return_status,
4299          x_operation_dept   => l_operation_dept_id,
4300          x_owning_dept      => l_owning_dept_id,
4301          x_maint_cost_cat   => l_maint_cost_category);
4302 
4303        IF l_return_status <> FND_API.g_ret_sts_success THEN
4304 
4305           l_api_message := 'Get_MaintCostCat returned error';
4306 
4307           FND_MSG_PUB.ADD_EXC_MSG('CST_EAMCOST_PUB', 'COMPUTE_JOB_ESTIMATES('
4308                                      ||TO_CHAR(l_stmt_num)
4309                                      ||'): ', l_api_message);
4310           RAISE FND_API.g_exc_error;
4311 
4312        END IF;
4313 
4314       l_stmt_num := 145;
4315 
4316       BEGIN
4317         select cceea.mnt_cost_element_id,cceea.mfg_cost_element_id
4318         into   l_eam_cost_element,l_mfg_cost_element_id
4319         from   cst_cat_ele_exp_assocs cceea
4320         where  cceea.category_id = c_wrodi_rec.category_id
4321         and    NVL(cceea.end_date, SYSDATE) + 1 > SYSDATE
4322         and    cceea.start_date <= sysdate;
4323       exception
4324         when no_data_found then
4325           l_eam_cost_element := 3;
4326           l_mfg_cost_element_id := 1;
4327       end;
4328 
4329       IF (p_debug = 'Y') THEN
4330 
4331         l_api_message :=' MCC: ';
4332         l_api_message :=l_api_message||TO_CHAR(l_maint_cost_category);
4333         l_api_message :=l_api_message||' CE: '||TO_CHAR(l_eam_cost_element);
4334         FND_MESSAGE.SET_NAME ('BOM', 'CST_API_MESSAGE');
4335         FND_MESSAGE.SET_TOKEN ('TEXT', l_api_message);
4336         FND_MSG_PUB.add;
4337 
4338       END IF;
4339 
4340       l_stmt_num := 150;
4341 
4342        InsertUpdate_eamPerBal(
4343           p_api_version                   => 1.0,
4344           x_return_status                 => l_return_status,
4345           x_msg_count                     => l_msg_count,
4346           x_msg_data                      => l_msg_data,
4347           p_period_id                     => l_acct_period_id,
4348           p_period_set_name               => l_period_set_name,
4349           p_period_name                   => l_period_name,
4350           p_org_id                        => l_organization_id,
4351           p_wip_entity_id                 => p_wip_entity_id,
4352           p_owning_dept_id                => l_owning_dept_id,
4353           p_dept_id                       => c_wrodi_rec.department_id,
4354           p_maint_cost_cat                => l_maint_cost_category,
4355           p_opseq_num                     => c_wrodi_rec.operation_seq_num,
4356           p_eam_cost_element              => l_eam_cost_element,
4357           p_asset_group_id                => l_asset_group_item_id,
4358           p_asset_number                  => l_asset_number,
4359           p_value_type                    => 2,
4360           p_value                         => c_wrodi_rec.mat_value,
4361           p_user_id                       => p_user_id,
4362           p_request_id                    => p_request_id,
4363           p_prog_id                       => p_prog_id,
4364           p_prog_app_id                   => p_prog_app_id,
4365           p_login_id                      => p_login_id);
4366 
4367       IF l_return_status <> FND_API.g_ret_sts_success THEN
4368 
4369           l_api_message := 'insertupdate_eamperbal error';
4370 
4371           FND_MSG_PUB.ADD_EXC_MSG('CST_EAMCOST_PUB', 'COMPUTE_JOB_ESTIMATES('
4372                                      ||TO_CHAR(l_stmt_num)
4373                                      ||'): ', l_api_message);
4374           RAISE FND_API.g_exc_error;
4375 
4376       END IF;
4377 
4378 
4379      IF c_wrodi_rec.mat_value <> 0 THEN
4380       l_stmt_num := 153;
4381 
4382       case(l_mfg_cost_element_id)
4383       when 1 then
4384                 l_acct_id := l_material_account;
4385       when 3 then
4386                 l_acct_id := l_resource_account;
4387       when 4 then
4388                 l_acct_id := l_osp_account;
4389       when 5 then
4390                 l_acct_id := l_overhead_account;
4391       else
4392                 l_acct_id := l_material_account;
4393       end case;
4394 
4395       IF (p_debug = 'Y') THEN
4396 
4397             l_api_message :=' Calling Insert_eamBalAcct... WRODI... ';
4398             l_api_message :=l_api_message|| ' p_wip_entity_id = ' || TO_CHAR(p_wip_entity_id) || ', ';
4399             l_api_message :=l_api_message|| ' mfg_cost_element_id = ' || TO_CHAR(l_mfg_cost_element_id) || ',';
4400             l_api_message :=l_api_message|| ' account_id  =  ' || TO_CHAR(l_acct_id) || ',';
4401             l_api_message :=l_api_message|| ' eam_cost_element_id = '||TO_CHAR(l_eam_cost_element);
4402             l_api_message :=l_api_message|| ' Sum WRODI = ' || TO_CHAR(c_wrodi_rec.mat_value);
4403             FND_MESSAGE.SET_NAME ('BOM', 'CST_API_MESSAGE');
4404             FND_MESSAGE.SET_TOKEN ('TEXT', l_api_message);
4405             FND_MSG_PUB.add;
4406       END IF;
4407 
4408       Insert_eamBalAcct(
4409        p_api_version                   => 1.0,
4410        p_init_msg_list                 => FND_API.G_FALSE,
4411        p_commit                        => FND_API.G_FALSE,
4412        p_validation_level              => FND_API.G_VALID_LEVEL_FULL,
4413        x_return_status                 => l_return_status,
4414        x_msg_count                     => l_msg_count,
4415        x_msg_data                      => l_msg_data,
4416        p_period_id                     => l_acct_period_id,
4417        p_period_set_name               => l_period_set_name,
4418        p_period_name                   => l_period_name,
4419        p_org_id                        => l_organization_id,
4420        p_wip_entity_id                 => p_wip_entity_id,
4421        p_owning_dept_id                => l_owning_dept_id,
4422        p_dept_id                       => l_operation_dept_id,
4423        p_maint_cost_cat                => l_maint_cost_category,
4424        p_opseq_num                     => c_wrodi_rec.operation_seq_num,
4425        p_period_start_date             => l_period_start_date,
4426        p_account_ccid                  => l_acct_id,
4427        p_value                         => c_wrodi_rec.mat_value,
4428        p_txn_type                      => l_eam_cost_element,
4429        p_wip_acct_class                => l_wip_acct_class,
4430        p_mfg_cost_element_id           => l_mfg_cost_element_id,
4431        p_user_id                       => p_user_id,
4432        p_request_id                    => p_request_id,
4433        p_prog_id                       => p_prog_id,
4434        p_prog_app_id                   => p_prog_app_id,
4435        p_login_id                      => p_login_id);
4436 
4437        IF l_return_status <> FND_API.g_ret_sts_success THEN
4438 
4439          l_api_message := 'Insert_eamBalAcct error';
4440          FND_MSG_PUB.ADD_EXC_MSG('CST_EAMCOST_PUB', 'Insert_eamBalAcct('
4441                                    ||TO_CHAR(l_stmt_num)
4442                                    ||'): ', l_api_message);
4443          RAISE FND_API.g_exc_error;
4444 
4445        END IF;
4446 
4447       ELSE
4448        IF (p_debug = 'Y') THEN
4449             l_api_message :=' Sum WRODI = ' || TO_CHAR(c_wrodi_rec.mat_value);
4450             FND_MESSAGE.SET_NAME ('BOM', 'CST_API_MESSAGE');
4451             FND_MESSAGE.SET_TOKEN ('TEXT', l_api_message);
4452             FND_MSG_PUB.add;
4453        END IF;
4454 
4455       END IF;  -- if c_wrodi_rec.mat_value != 0
4456 
4457       /* Now start inserting the Estimation details into CST_EAM_WO_ESTIMATE_DETAILS */
4458       l_stmt_num := 155;
4459 
4460       Insert into CST_EAM_WO_ESTIMATE_DETAILS(
4461                    wip_entity_id,
4462                    organization_id,
4463                    operations_dept_id,
4464                    operations_seq_num,
4465                    maint_cost_category,
4466                    owning_dept_id,
4467                    estimated_cost,
4468                    inventory_item_id,
4469                    direct_item,
4470                    item_cost,
4471                    required_quantity,
4472                    last_update_date,
4473                    last_updated_by,
4474                    creation_date,
4475                    created_by,
4476                    last_update_login,
4477                    request_id,
4478                    program_application_id,
4479                    program_id,
4480                    program_update_date)
4481             SELECT p_wip_entity_id,
4482                    wro.organization_id,
4483                    l_operation_dept_id,
4484                    wro.operation_seq_num,
4485                    l_maint_cost_category,
4486                    l_owning_dept_id,
4487                    (NVL(wro.required_quantity,0) - NVL(wediv.quantity_ordered,0))
4488                     * NVL(wro.unit_price,0),
4489                    wro.inventory_item_id,
4490                    'Y',
4491                    NVL(wro.unit_price,0),
4492                    NVL(wro.required_quantity,0) - NVL(wediv.quantity_ordered,0),
4493                    SYSDATE,
4494                    p_user_id,
4495                    SYSDATE,
4496                    p_user_id,
4497                    p_login_id,
4498                    p_request_id,
4499                    p_prog_app_id,
4500                    p_prog_id,
4501                    SYSDATE
4502               FROM wip_requirement_operations wro,
4503                    (SELECT
4504                            cedi.work_order_number,
4505                            cedi.organization_id,
4506                            cedi.task_number,
4507                            cedi.item_id,
4508                            SUM(
4509                              inv_convert.inv_um_convert(
4510                                cedi.item_id, NULL, cedi.quantity_ordered,
4511                                cedi.uom_code, msi.primary_uom_code, NULL, NULL
4512                              )
4513                              /* We convert to primary_uom because the required_quantity in
4514                                 WRO is always in the primary unit of measure */
4515                            ) quantity_ordered
4516                            /* Sum is needed because there could be multiple POs/Reqs
4517                               for the same non-stockable item */
4518                     FROM   cst_eam_direct_items_temp cedi,
4519                            mtl_system_items_b msi
4520                     WHERE  cedi.item_id = msi.inventory_item_id
4521                     AND    cedi.organization_id = msi.organization_id
4522                     AND    cedi.work_order_number  = p_wip_entity_id
4523                     GROUP
4524                     BY     cedi.work_order_number,
4525                            cedi.organization_id,
4526                            cedi.task_number,
4527                            cedi.item_id
4528                    ) wediv,
4529                    mtl_system_items_b msi
4530               WHERE wro.wip_entity_id = p_wip_entity_id
4531               AND   wediv.work_order_number(+) = wro.wip_entity_id
4532               AND   wediv.item_id(+) = wro.inventory_item_id
4533               AND   wediv.organization_id(+) = wro.organization_id
4534               AND   wediv.task_number(+) = wro.operation_seq_num
4535               AND   wro.wip_supply_type IN (1,4)
4536               AND   msi.organization_id = wro.organization_id
4537               AND   msi.inventory_item_id = wro.inventory_item_id
4538               AND   msi.stock_enabled_flag = 'N'
4539               AND   wro.department_id = c_wrodi_rec.department_id
4540               AND   wro.operation_seq_num = c_wrodi_rec.operation_seq_num
4541               AND   wro.inventory_item_id = c_wrodi_rec.item_id
4542               AND   NVL(wro.required_quantity,0) > NVL(wediv.quantity_ordered,0);
4543 
4544     END LOOP;
4545 
4546     l_stmt_num := 158;
4547     FOR c_wedi_rec IN c_wedi LOOP
4548 
4549       l_stmt_num := 160;
4550 
4551       IF (p_debug = 'Y') THEN
4552 
4553         l_api_message :=' Op: ';
4554         l_api_message :=l_api_message||TO_CHAR(c_wedi_rec.operation_seq_num);
4555         l_api_message :=l_api_message||' Department Id: ' ;
4556         l_api_message :=l_api_message||TO_CHAR(c_wedi_rec.department_id);
4557         l_api_message :=l_api_message||' Category ID: ' ;
4558         l_api_message :=l_api_message||TO_CHAR(c_wedi_rec.category_id);
4559         l_api_message :=l_api_message||' Direct Item Sequence ID: ' ;
4560         l_api_message :=l_api_message||TO_CHAR(c_wedi_rec.direct_item_id);
4561         l_api_message :=l_api_message||' WRO Direct Items,Value: '||TO_CHAR(c_wedi_rec.wedi_value);
4562         FND_MESSAGE.SET_NAME ('BOM', 'CST_API_MESSAGE');
4563         FND_MESSAGE.SET_TOKEN ('TEXT', l_api_message);
4564         FND_MSG_PUB.add;
4565 
4566       END IF;
4567 
4568       Get_MaintCostCat(
4569          p_txn_mode         => 1 ,
4570          p_wip_entity_id    => p_wip_entity_id,
4571          p_opseq_num        => c_wedi_rec.operation_seq_num,
4572          x_return_status    => l_return_status,
4573          x_operation_dept   => l_operation_dept_id,
4574          x_owning_dept      => l_owning_dept_id,
4575          x_maint_cost_cat   => l_maint_cost_category);
4576 
4577        IF l_return_status <> FND_API.g_ret_sts_success THEN
4578 
4579           l_api_message := 'Get_MaintCostCat returned error';
4580 
4581           FND_MSG_PUB.ADD_EXC_MSG('CST_EAMCOST_PUB', 'COMPUTE_JOB_ESTIMATES('
4582                                      ||TO_CHAR(l_stmt_num)
4583                                      ||'): ', l_api_message);
4584           RAISE FND_API.g_exc_error;
4585 
4586        END IF;
4587 
4588       l_stmt_num := 165;
4589 
4590       BEGIN
4591         select cceea.mnt_cost_element_id,cceea.mfg_cost_element_id
4592         into   l_eam_cost_element,l_mfg_cost_element_id
4593         from   cst_cat_ele_exp_assocs cceea
4594         where  cceea.category_id = c_wedi_rec.category_id
4595         and    NVL(cceea.end_date, SYSDATE) + 1 > SYSDATE
4596         and    cceea.start_date <= sysdate;
4597       exception
4598         when no_data_found then
4599           l_eam_cost_element := 3;
4600           l_mfg_cost_element_id := 1;
4601       end;
4602 
4603       IF (p_debug = 'Y') THEN
4604 
4605         l_api_message :=' MCC: ';
4606         l_api_message :=l_api_message||TO_CHAR(l_maint_cost_category);
4607         l_api_message :=l_api_message||' CE: '||TO_CHAR(l_eam_cost_element);
4608         FND_MESSAGE.SET_NAME ('BOM', 'CST_API_MESSAGE');
4609         FND_MESSAGE.SET_TOKEN ('TEXT', l_api_message);
4610         FND_MSG_PUB.add;
4611 
4612       END IF;
4613 
4614       l_stmt_num := 170;
4615       InsertUpdate_eamPerBal(
4616           p_api_version                   => 1.0,
4617           x_return_status                 => l_return_status,
4618           x_msg_count                     => l_msg_count,
4619           x_msg_data                      => l_msg_data,
4620           p_period_id                     => l_acct_period_id,
4621           p_period_set_name               => l_period_set_name,
4622           p_period_name                   => l_period_name,
4623           p_org_id                        => l_organization_id,
4624           p_wip_entity_id                 => p_wip_entity_id,
4625           p_owning_dept_id                => l_owning_dept_id,
4626           p_dept_id                       => c_wedi_rec.department_id,
4627           p_maint_cost_cat                => l_maint_cost_category,
4628           p_opseq_num                     => c_wedi_rec.operation_seq_num,
4629           p_eam_cost_element              => l_eam_cost_element,
4630           p_asset_group_id                => l_asset_group_item_id,
4631           p_asset_number                  => l_asset_number,
4632           p_value_type                    => 2,
4633           p_value                         => c_wedi_rec.wedi_value,
4634           p_user_id                       => p_user_id,
4635           p_request_id                    => p_request_id,
4636           p_prog_id                       => p_prog_id,
4637           p_prog_app_id                   => p_prog_app_id,
4638           p_login_id                      => p_login_id);
4639 
4640       IF l_return_status <> FND_API.g_ret_sts_success THEN
4641 
4642           l_api_message := 'insertupdate_eamperbal error';
4643 
4644           FND_MSG_PUB.ADD_EXC_MSG('CST_EAMCOST_PUB', 'COMPUTE_JOB_ESTIMATES('
4645                                      ||TO_CHAR(l_stmt_num)
4646                                      ||'): ', l_api_message);
4647           RAISE FND_API.g_exc_error;
4648 
4649       END IF;
4650 
4651     If c_wedi_rec.wedi_value <> 0 then
4652       l_stmt_num := 173;
4653 
4654       case(l_mfg_cost_element_id)
4655       when 1 then
4656                 l_acct_id := l_material_account;
4657       when 3 then
4658                 l_acct_id := l_resource_account;
4659       when 4 then
4660                 l_acct_id := l_osp_account;
4661       when 5 then
4662                 l_acct_id := l_overhead_account;
4663       else
4664                 l_acct_id := l_material_account;
4665       end case;
4666 
4667       IF (p_debug = 'Y') THEN
4668 
4669             l_api_message :=' Calling Insert_eamBalAcct... WEDI';
4670             l_api_message :=l_api_message|| ' p_wip_entity_id = ' || TO_CHAR(p_wip_entity_id) || ', ';
4671             l_api_message :=l_api_message|| ' mfg_cost_element_id = ' || TO_CHAR( l_mfg_cost_element_id);
4672             l_api_message :=l_api_message|| ' account_id  =  ' || TO_CHAR(l_acct_id) || ',';
4673             l_api_message :=l_api_message|| ' eam_cost_element_id = '||TO_CHAR(l_eam_cost_element);
4674             l_api_message :=l_api_message|| ' Sum WEDI = ' || TO_CHAR(c_wedi_rec.wedi_value);
4675             FND_MESSAGE.SET_NAME ('BOM', 'CST_API_MESSAGE');
4676             FND_MESSAGE.SET_TOKEN ('TEXT', l_api_message);
4677             FND_MSG_PUB.add;
4678       END IF;
4679 
4680       Insert_eamBalAcct(
4681         p_api_version                   => 1.0,
4682         p_init_msg_list                 => FND_API.G_FALSE,
4683         p_commit                        => FND_API.G_FALSE,
4684         p_validation_level              => FND_API.G_VALID_LEVEL_FULL,
4685         x_return_status                 => l_return_status,
4686         x_msg_count                     => l_msg_count,
4687         x_msg_data                      => l_msg_data,
4688         p_period_id                     => l_acct_period_id,
4689         p_period_set_name               => l_period_set_name,
4690         p_period_name                   => l_period_name,
4691         p_org_id                        => l_organization_id,
4692         p_wip_entity_id                 => p_wip_entity_id,
4693         p_owning_dept_id                => l_owning_dept_id,
4694         p_dept_id                       => l_operation_dept_id,
4695         p_maint_cost_cat                => l_maint_cost_category,
4696         p_opseq_num                     => c_wedi_rec.operation_seq_num,
4697         p_period_start_date             => l_period_start_date,
4698         p_account_ccid                  => l_acct_id,
4699         p_value                         => c_wedi_rec.wedi_value,
4700         p_txn_type                      => l_eam_cost_element,
4701         p_wip_acct_class                => l_wip_acct_class,
4702         p_mfg_cost_element_id           => l_mfg_cost_element_id,
4703         p_user_id                       => p_user_id,
4704         p_request_id                    => p_request_id,
4705         p_prog_id                       => p_prog_id,
4706         p_prog_app_id                   => p_prog_app_id,
4707         p_login_id                      => p_login_id);
4708 
4709         IF l_return_status <> FND_API.g_ret_sts_success THEN
4710 
4711           l_api_message := 'Insert_eamBalAcct error';
4712           FND_MSG_PUB.ADD_EXC_MSG('CST_EAMCOST_PUB', 'Insert_eamBalAcct('
4713                                     ||TO_CHAR(l_stmt_num)
4714                                     ||'): ', l_api_message);
4715           RAISE FND_API.g_exc_error;
4716 
4717          END IF;
4718 
4719       Else
4720        IF (p_debug = 'Y') THEN
4721             l_api_message :=' Sum WEDI = ' || TO_CHAR(c_wedi_rec.wedi_value);
4722             FND_MESSAGE.SET_NAME ('BOM', 'CST_API_MESSAGE');
4723             FND_MESSAGE.SET_TOKEN ('TEXT', l_api_message);
4724             FND_MSG_PUB.add;
4725        END IF;
4726 
4727       End If; -- if c_wedi_rec.wedi_value !=0
4728 
4729       /* Now start inserting the Estimation details into CST_EAM_WO_ESTIMATE_DETAILS */
4730       l_stmt_num := 175;
4731 
4732       Insert into CST_EAM_WO_ESTIMATE_DETAILS(
4733                    wip_entity_id,
4734                    organization_id,
4735                    operations_dept_id,
4736                    operations_seq_num,
4737                    maint_cost_category,
4738                    owning_dept_id,
4739                    estimated_cost,
4740                    item_description,
4741                    direct_item,
4742                    item_cost,
4743                    required_quantity,
4744                    last_update_date,
4745                    last_updated_by,
4746                    creation_date,
4747                    created_by,
4748                    last_update_login,
4749                    request_id,
4750                    program_application_id,
4751                    program_id,
4752                    program_update_date)
4753             SELECT
4754                    p_wip_entity_id,
4755                    wedi.organization_id,
4756                    l_operation_dept_id,
4757                    wedi.operation_seq_num,
4758                    l_maint_cost_category,
4759                    l_owning_dept_id,
4760                    DECODE(cedi.order_type_lookup_code,
4761                    'FIXED PRICE',NVL(wedi.amount,0) * NVL(cedi.currency_rate,1) - sum(NVL(cedi.amount_delivered,0)),
4762                    'RATE',NVL(wedi.amount,0) * NVL(cedi.currency_rate,1) - sum(NVL(cedi.amount_delivered,0)),
4763                    (NVL(wedi.required_quantity,0) -
4764                       SUM(
4765                         /* Sum is needed because there could be multiple
4766                            POs/Reqs for the same description item */
4767                         inv_convert.inv_um_convert(
4768                           NULL, NULL, NVL(cedi.quantity_ordered,0),
4769                           NVL(cedi.uom_code, wedi.uom), wedi.uom, NULL, NULL
4770                         )
4771                       )
4772                    ) * NVL(wedi.unit_price, 0) * NVL(cedi.currency_rate,1)),
4773                    wedi.description,
4774                    'Y',
4775                    DECODE(cedi.order_type_lookup_code,
4776                           'FIXED PRICE',NVL(wedi.amount,0) * NVL(cedi.currency_rate,1),
4777                           'RATE',NVL(wedi.amount,0) * NVL(cedi.currency_rate,1),
4778                            NVL(wedi.unit_price, 0) * NVL(cedi.currency_rate,1) ),
4779                    DECODE(cedi.order_type_lookup_code,
4780                    'FIXED PRICE',NVL(wedi.amount,0) * NVL(cedi.currency_rate,1) - sum(NVL(cedi.amount_delivered,0)),
4781                    'RATE',NVL(wedi.amount,0) * NVL(cedi.currency_rate,1) - sum(NVL(cedi.amount_delivered,0)),
4782                    NVL(wedi.required_quantity,0) -
4783                      SUM(
4784                        /* Sum is needed because there could be multiple
4785                           POs/Reqs for the same description item */
4786                        inv_convert.inv_um_convert(
4787                          NULL, NULL, NVL(cedi.quantity_ordered,0),
4788                          NVL(cedi.uom_code, wedi.uom), wedi.uom, NULL, NULL
4789                        )
4790                      )),
4791                    SYSDATE,
4792                    p_user_id,
4793                    SYSDATE,
4794                    p_user_id,
4795                    p_login_id,
4796                    p_request_id,
4797                    p_prog_app_id,
4798                    p_prog_id,
4799                    SYSDATE
4800               FROM wip_eam_direct_items wedi,
4801                    cst_eam_direct_items_temp cedi
4802               WHERE wedi.wip_entity_id = p_wip_entity_id
4803               AND   cedi.work_order_number(+) = wedi.wip_entity_id
4804               AND   cedi.direct_item_sequence_id(+) = wedi.direct_item_sequence_id
4805               AND   cedi.organization_id(+) = wedi.organization_id
4806               AND   cedi.task_number(+) = wedi.operation_seq_num
4807 /*              AND   cedi.category_id(+) = wedi.purchasing_category_id  Commented for Bug 5403190 */
4808               AND   wedi.department_id = c_wedi_rec.department_id
4809               AND   wedi.operation_seq_num = c_wedi_rec.operation_seq_num
4810               AND   wedi.purchasing_category_id = c_wedi_rec.category_id
4811               AND   wedi.direct_item_sequence_id = c_wedi_rec.direct_item_id
4812               GROUP
4813               BY    wedi.operation_seq_num,
4814                     wedi.organization_id,
4815                     NVL(wedi.required_quantity,0),
4816                     NVL(wedi.unit_price, 0),
4817                     NVL(wedi.amount,0),
4818                     wedi.description,
4819                     cedi.order_type_lookup_code,
4820                     cedi.currency_rate
4821               HAVING
4822                    DECODE(cedi.order_type_lookup_code,
4823                     'FIXED PRICE',NVL(wedi.amount,0) - sum(NVL(cedi.amount_delivered,0)),
4824                     'RATE',NVL(wedi.amount,0) - sum(NVL(cedi.amount_delivered,0)),
4825                     NVL(wedi.required_quantity,0) -                       SUM(
4826                         inv_convert.inv_um_convert(
4827                           NULL, NULL, NVL(cedi.quantity_ordered,0),
4828                           NVL(cedi.uom_code, wedi.uom), wedi.uom, NULL, NULL
4829                         )
4830                       )) > 0;
4831 
4832     END LOOP;
4833 
4834     l_stmt_num := 178;
4835     FOR c_pda_rec IN c_pda LOOP
4836 
4837       l_stmt_num := 180;
4838 
4839       SELECT  department_id
4840       INTO    l_dept_id
4841       FROM    wip_operations wo
4842       WHERE   wo.wip_entity_id = p_wip_entity_id
4843       AND     wo.operation_seq_num = c_pda_rec.operation_seq_num;
4844 
4845       IF (p_debug = 'Y') THEN
4846 
4847         l_api_message :=l_api_message||' Op: ';
4848         l_api_message :=l_api_message||TO_CHAR(c_pda_rec.operation_seq_num);
4849         l_api_message :=l_api_message||' Department Id: ';
4850         l_api_message :=l_api_message||TO_CHAR(l_dept_id);
4851         l_api_message :=l_api_message||' Category ID ';
4852         l_api_message :=l_api_message||TO_CHAR(c_pda_rec.category_id);
4853         l_api_message :=l_api_message||' Category Date ';
4854         l_api_message :=l_api_message||TO_CHAR(c_pda_rec.category_date);
4855         l_api_message :=l_api_message||' PDA,Value: '||TO_CHAR(c_pda_rec.pda_value);
4856         FND_MESSAGE.SET_NAME ('BOM', 'CST_API_MESSAGE');
4857         FND_MESSAGE.SET_TOKEN ('TEXT', l_api_message);
4858         FND_MSG_PUB.add;
4859 
4860       END IF;
4861 
4862       l_stmt_num := 185;
4863 
4864       Get_MaintCostCat(
4865          p_txn_mode         => 1 ,
4866          p_wip_entity_id    => p_wip_entity_id,
4867          p_opseq_num        => c_pda_rec.operation_seq_num,
4868          x_return_status    => l_return_status,
4869          x_operation_dept   => l_operation_dept_id,
4870          x_owning_dept      => l_owning_dept_id,
4871          x_maint_cost_cat   => l_maint_cost_category);
4872 
4873       IF l_return_status <> FND_API.g_ret_sts_success THEN
4874 
4875           l_api_message := 'Get_MaintCostCat returned error';
4876 
4877           FND_MSG_PUB.ADD_EXC_MSG('CST_EAMCOST_PUB', 'COMPUTE_JOB_ESTIMATES('
4878                                      ||TO_CHAR(l_stmt_num)
4879                                      ||'): ', l_api_message);
4880           RAISE FND_API.g_exc_error;
4881 
4882       END IF;
4883 
4884         l_stmt_num :=187;
4885         If (c_pda_rec.type_lookup_code = 'BLANKET') then
4886            select approved_date
4887            into l_approved_date
4888            from po_releases_all
4889            where po_release_id = c_pda_rec.po_release_id;
4890          Else
4891            l_approved_date := c_pda_rec.category_date;
4892          End if;
4893 
4894       l_stmt_num := 190;
4895       begin
4896         select cceea.mnt_cost_element_id, cceea.mfg_cost_element_id
4897         into l_eam_cost_element, l_mfg_cost_element_id
4898         from cst_cat_ele_exp_assocs cceea
4899         where cceea.category_id = c_pda_rec.category_id
4900           and l_approved_date >= cceea.start_date
4901           and l_approved_date < (nvl(cceea.end_date, sysdate) + 1);
4902       exception
4903         when no_data_found then
4904           l_eam_cost_element := 3;
4905           l_mfg_cost_element_id :=1;
4906       end;
4907 
4908       IF (p_debug = 'Y') THEN
4909 
4910         l_api_message :=' MCC: ';
4911         l_api_message :=l_api_message||TO_CHAR(l_maint_cost_category);
4912         l_api_message :=l_api_message||' CE: '||TO_CHAR(l_eam_cost_element);
4913         FND_MESSAGE.SET_NAME ('BOM', 'CST_API_MESSAGE');
4914         FND_MESSAGE.SET_TOKEN ('TEXT', l_api_message);
4915         FND_MSG_PUB.add;
4916 
4917       END IF;
4918 
4919       l_stmt_num := 195;
4920 
4921       InsertUpdate_eamPerBal(
4922           p_api_version                   => 1.0,
4923           x_return_status                 => l_return_status,
4924           x_msg_count                     => l_msg_count,
4925           x_msg_data                      => l_msg_data,
4926           p_period_id                     => l_acct_period_id,
4927           p_period_set_name               => l_period_set_name,
4928           p_period_name                   => l_period_name,
4929           p_org_id                        => l_organization_id,
4930           p_wip_entity_id                 => p_wip_entity_id,
4931           p_owning_dept_id                => l_owning_dept_id,
4932           p_dept_id                       => l_dept_id,
4933           p_maint_cost_cat                => l_maint_cost_category,
4934           p_opseq_num                     => c_pda_rec.operation_seq_num,
4935           p_eam_cost_element              => l_eam_cost_element,
4936           p_asset_group_id                => l_asset_group_item_id,
4937           p_asset_number                  => l_asset_number,
4938           p_value_type                    => 2,
4939           p_value                         => c_pda_rec.pda_value,
4940           p_user_id                       => p_user_id,
4941           p_request_id                    => p_request_id,
4942           p_prog_id                       => p_prog_id,
4943           p_prog_app_id                   => p_prog_app_id,
4944           p_login_id                      => p_login_id);
4945 
4946       IF l_return_status <> FND_API.g_ret_sts_success THEN
4947 
4948           l_api_message := 'insertupdate_eamperbal error';
4949 
4950           FND_MSG_PUB.ADD_EXC_MSG('CST_EAMCOST_PUB', 'COMPUTE_JOB_ESTIMATES('
4951                                      ||TO_CHAR(l_stmt_num)
4952                                      ||'): ', l_api_message);
4953           RAISE FND_API.g_exc_error;
4954 
4955       END IF;
4956 
4957      If  c_pda_rec.pda_value <> 0 then
4958       l_stmt_num := 197;
4959 
4960       case(l_mfg_cost_element_id)
4961       when 1 then
4962                 l_acct_id := l_material_account;
4963       when 3 then
4964                 l_acct_id := l_resource_account;
4965       when 4 then
4966                 l_acct_id := l_osp_account;
4967       when 5 then
4968                 l_acct_id := l_overhead_account;
4969       else
4970                 l_acct_id := l_material_account;
4971       end case;
4972 
4973       IF (p_debug = 'Y') THEN
4974 
4975             l_api_message :=' Calling Insert_eamBalAcct... PDA...';
4976             l_api_message :=l_api_message|| ' p_wip_entity_id = ' || TO_CHAR(p_wip_entity_id) || ', ';
4977             l_api_message :=l_api_message|| ' mfg_cost_element_id = ' || TO_CHAR(l_mfg_cost_element_id) || ',';
4978             l_api_message :=l_api_message|| ' account_id  =  ' || TO_CHAR(l_acct_id) || ',';
4979             l_api_message :=l_api_message|| ' eam_cost_element_id = '||TO_CHAR(l_eam_cost_element);
4980             l_api_message :=l_api_message|| ' Sum PDA = ' || TO_CHAR( c_pda_rec.pda_value);
4981             FND_MESSAGE.SET_NAME ('BOM', 'CST_API_MESSAGE');
4982             FND_MESSAGE.SET_TOKEN ('TEXT', l_api_message);
4983             FND_MSG_PUB.add;
4984       END IF;
4985 
4986       Insert_eamBalAcct(
4987         p_api_version                   => 1.0,
4988         p_init_msg_list                 => FND_API.G_FALSE,
4989         p_commit                        => FND_API.G_FALSE,
4990         p_validation_level              => FND_API.G_VALID_LEVEL_FULL,
4991         x_return_status                 => l_return_status,
4992         x_msg_count                     => l_msg_count,
4993         x_msg_data                      => l_msg_data,
4994         p_period_id                     => l_acct_period_id,
4995         p_period_set_name               => l_period_set_name,
4996         p_period_name                   => l_period_name,
4997         p_org_id                        => l_organization_id,
4998         p_wip_entity_id                 => p_wip_entity_id,
4999         p_owning_dept_id                => l_owning_dept_id,
5000         p_dept_id                       => l_operation_dept_id,
5001         p_maint_cost_cat                => l_maint_cost_category,
5002         p_opseq_num                     => c_pda_rec.operation_seq_num,
5003         p_period_start_date             => l_period_start_date,
5004         p_account_ccid                  => l_acct_id,
5005         p_value                         => c_pda_rec.pda_value,
5006         p_txn_type                      => l_eam_cost_element,
5007         p_wip_acct_class                => l_wip_acct_class,
5008         p_mfg_cost_element_id           => l_mfg_cost_element_id,
5009         p_user_id                       => p_user_id,
5010         p_request_id                    => p_request_id,
5011         p_prog_id                       => p_prog_id,
5012         p_prog_app_id                   => p_prog_app_id,
5013         p_login_id                      => p_login_id);
5014 
5015         IF l_return_status <> FND_API.g_ret_sts_success THEN
5016 
5017           l_api_message := 'Insert_eamBalAcct error';
5018           FND_MSG_PUB.ADD_EXC_MSG('CST_EAMCOST_PUB', 'Insert_eamBalAcct('
5019                                    ||TO_CHAR(l_stmt_num)
5020                                    ||'): ', l_api_message);
5021           RAISE FND_API.g_exc_error;
5022 
5023         END IF;
5024        Else
5025           IF (p_debug = 'Y') THEN
5026             l_api_message :=' Sum PDA = ' || TO_CHAR( c_pda_rec.pda_value);
5027             FND_MESSAGE.SET_NAME ('BOM', 'CST_API_MESSAGE');
5028             FND_MESSAGE.SET_TOKEN ('TEXT', l_api_message);
5029             FND_MSG_PUB.add;
5030            END IF;
5031        End If; -- if  c_pda_rec.pda_value != 0
5032 
5033       l_stmt_num := 200;
5034 
5035       /* Insert quantity as NULL for Service Line types */
5036 
5037       Insert into CST_EAM_WO_ESTIMATE_DETAILS(
5038                   wip_entity_id,
5039                   organization_id,
5040                   operations_dept_id,
5041                   operations_seq_num,
5042                   maint_cost_category,
5043                   owning_dept_id,
5044                   direct_item,
5045                   estimated_cost,
5046                   required_quantity,
5047                   item_cost,
5048                   rate,
5049                   requisition_header_id,
5050                   po_header_id,
5051                   requisition_line_id,
5052                   po_distribution_id,
5053                   line_location_id,
5054                   item_description,
5055                   inventory_item_id,
5056                   req_auth_status,
5057                   po_line_cancel_flag,
5058                   req_line_cancel_flag,
5059                   last_update_date,
5060                   last_updated_by,
5061                   creation_date,
5062                   created_by,
5063                   last_update_login,
5064                   request_id,
5065                   program_application_id,
5066                   program_id,
5067                   program_update_date)
5068            SELECT  p_wip_entity_id,
5069                    l_organization_id,
5070                    l_operation_dept_id,
5071                    c_pda_rec.operation_seq_num,
5072                    l_maint_cost_category,
5073                    l_owning_dept_id,
5074                    'Y',
5075                    CST_TEMP.estimated_cost,
5076                    CST_TEMP.required_quantity,
5077                    CST_TEMP.unit_price,
5078                    CST_TEMP.rate,
5079                    CST_TEMP.requisition_header_id,
5080                    CST_TEMP.po_header_id,
5081                    CST_TEMP.requisition_line_id,
5082                    CST_TEMP.po_distribution_id,
5083                    CST_TEMP.line_location_id,
5084                    CST_TEMP.item_description,
5085                    CST_TEMP.item_id,
5086                    CST_TEMP.req_auth_status,
5087                    'N', -- enforced in the view WEDIV
5088                    'N', -- enforced in the view WEDIV
5089                    SYSDATE,
5090                    p_user_id,
5091                    SYSDATE,
5092                    p_user_id,
5093                    p_login_id,
5094                    p_request_id,
5095                    p_prog_app_id,
5096                    p_prog_id,
5097                    SYSDATE
5098            FROM    (
5099                     SELECT  decode(NVL(pla.order_type_lookup_code,'QUANTITY'),
5100                             'RATE',(
5101                                     (NVL(cedi.amount,0) -   NVL(pda.amount_cancelled,0))
5102                                     + PO_TAX_SV.get_tax('PO',pda.po_distribution_id)
5103                                     )
5104                                    * NVL(cedi.currency_rate,1),
5105                             'FIXED PRICE',(
5106                                     (NVL(cedi.amount,0) - NVL(pda.amount_cancelled,0))
5107                                      + PO_TAX_SV.get_tax('PO',pda.po_distribution_id)
5108                                     )
5109                                     * NVL(cedi.currency_rate,1),
5110                             (NVL(plla.price_override,0) *
5111                              (NVL(pda.quantity_ordered,0) - NVL(pda.quantity_cancelled,0))
5112                             + /* Tax */ PO_TAX_SV.get_tax('PO',pda.po_distribution_id)
5113                             )
5114                             * NVL(cedi.currency_rate,1))    estimated_cost,
5115                             decode(NVL(pla.order_type_lookup_code,'QUANTITY'),
5116                             'RATE',NVL(cedi.amount,0) ,
5117                             'FIXED PRICE',NVL(cedi.amount,0),
5118                              NVL(cedi.unit_price,0)) unit_price,
5119                             DECODE(pla.order_type_lookup_code,'RATE',NULL,'FIXED PRICE',NULL,
5120                                    NVL(pda.quantity_ordered,0) - NVL(pda.quantity_cancelled,0)
5121                                   ) required_quantity,
5122                             pda.rate rate,
5123                             cedi.po_header_id po_header_id,
5124                             cedi.requisition_header_id requisition_header_id,
5125                             cedi.requisition_line_id requisition_line_id,
5126                             pda.po_distribution_id po_distribution_id,
5127                             plla.line_location_id line_location_id,
5128                             pla.item_description item_description,
5129                             pla.item_id item_id,
5130                             cedi.req_authorization_status req_auth_status
5131                     FROM    po_distributions_all pda,
5132                             po_line_locations_all plla,
5133                             po_headers_all pha,
5134                             po_lines_all pla,
5135                             cst_eam_direct_items_temp cedi
5136                     WHERE   cedi.work_order_number = p_wip_entity_id
5137                     AND     cedi.organization_id = l_organization_id
5138                     AND     cedi.task_number = pda.wip_operation_seq_num
5139                     AND     cedi.category_id = pla.category_id
5140                     AND     pha.po_header_id = cedi.po_header_id
5141                     AND     pla.po_line_id = cedi.po_line_id
5142                     AND     pda.wip_entity_id = cedi.work_order_number
5143                     AND     pda.po_header_id = cedi.po_header_id
5144                     AND     pda.po_line_id = cedi.po_line_id
5145                     AND     pda.destination_organization_id = cedi.organization_id
5146                     AND     plla.line_location_id = pda.line_location_id
5147                     AND     pda.wip_operation_seq_num = c_pda_rec.operation_seq_num
5148                     AND     pla.category_id = c_pda_rec.category_id
5149                     AND     NVL(pha.approved_date, pha.last_update_date) = c_pda_rec.category_date
5150                     UNION ALL
5151                     SELECT
5152                             decode(NVL(prla.order_type_lookup_code,'QUANTITY'),
5153                             'RATE',NVL(cedi.amount,NVL(prla.amount,0) * NVL(cedi.currency_rate,1)),
5154                             'FIXED PRICE',NVL(cedi.amount, NVL(prla.amount,0)* NVL(cedi.currency_rate,1)),
5155                             NVL(prla.unit_price,0) * NVL(prla.quantity,0) )
5156                                            * NVL(cedi.currency_rate,1) estimated_cost,
5157                              decode(NVL(prla.order_type_lookup_code,'QUANTITY'),
5158                             'RATE',NVL(cedi.amount,0),
5159                             'FIXED PRICE',NVL(cedi.amount,0),
5160                              NVL(cedi.unit_price,0)) unit_price,
5161                             decode(NVL(prla.order_type_lookup_code,'QUANTITY'),
5162                                   'RATE',NULL, 'FIXED PRICE',NULL,
5163                                    prla.quantity) required_quantity,
5164                             prla.rate rate,
5165                             TO_NUMBER(NULL) po_header_id,
5166                             cedi.requisition_header_id requisition_header_id,
5167                             cedi.requisition_line_id requisition_line_id,
5168                             TO_NUMBER(NULL) po_distribution_id,
5169                             TO_NUMBER(NULL) line_location_id,
5170                             prla.item_description item_description,
5171                             prla.item_id item_id,
5172                             cedi.req_authorization_status req_auth_status
5173                     FROM    po_requisition_lines_all prla,
5174                             po_requisition_headers_all prha,
5175                             cst_eam_direct_items_temp cedi
5176                     WHERE   cedi.work_order_number = p_wip_entity_id
5177                     AND     cedi.organization_id = l_organization_id
5178                     AND     cedi.task_number = prla.wip_operation_seq_num
5179                     AND     cedi.category_id = prla.category_id
5180                     AND     cedi.po_header_id IS NULL -- to ensure that we do not double count
5181                     AND     prha.requisition_header_id = cedi.requisition_header_id
5182                     AND     prla.destination_organization_id = cedi.organization_id
5183                     AND     prla.wip_entity_id = cedi.work_order_number
5184                     AND     prla.requisition_line_id = cedi.requisition_line_id
5185                     AND     prla.wip_operation_seq_num = c_pda_rec.operation_seq_num
5186                     AND     prla.category_id = c_pda_rec.category_id
5187                     AND     prha.last_update_date = c_pda_rec.category_date
5188                     ) CST_TEMP;
5189 
5190     END LOOP;
5191 
5192     ---------------------------------------------------------------------------
5193     -- Standard check of p_commit
5194     ---------------------------------------------------------------------------
5195 
5196     IF FND_API.to_Boolean(p_commit) THEN
5197       COMMIT WORK;
5198     END IF;
5199 
5200     ---------------------------------------------------------------------------
5201     -- Standard Call to get message count and if count = 1, get message info
5202     ---------------------------------------------------------------------------
5203 
5204     FND_MSG_PUB.Count_And_Get (
5205         p_count     => x_msg_count,
5206         p_data      => x_msg_data );
5207 
5208  EXCEPTION
5209 
5210    WHEN fnd_api.g_exc_error THEN
5211       x_return_status := fnd_api.g_ret_sts_error;
5212 
5213         --  Get message count and data
5214         fnd_msg_pub.count_and_get
5215           (  p_count => x_msg_count
5216            , p_data  => x_msg_data
5217            );
5218       --
5219    WHEN fnd_api.g_exc_unexpected_error THEN
5220       x_return_status := fnd_api.g_ret_sts_unexp_error ;
5221 
5222         --  Get message count and data
5223         fnd_msg_pub.count_and_get
5224           (  p_count  => x_msg_count
5225            , p_data   => x_msg_data
5226             );
5227       --
5228    WHEN OTHERS THEN
5229       x_return_status := fnd_api.g_ret_sts_unexp_error ;
5230       --
5231       IF fnd_msg_pub.check_msg_level(fnd_msg_pub.g_msg_lvl_unexp_error)
5232         THEN
5233          fnd_msg_pub.add_exc_msg
5234            (  'CST_EamJob_PUB'
5235               , 'Compute_Job_Estimate : l_stmt_num - '||to_char(l_stmt_num)
5236               );
5237 
5238         END IF;
5239         --  Get message count and data
5240         fnd_msg_pub.count_and_get
5241           (  p_count  => x_msg_count
5242            , p_data   => x_msg_data
5243              );
5244 
5245 END Compute_Job_Estimate;
5246 
5247 
5248 -- Start of comments
5249 ----------------------------------------------------------------------------
5250 -- API name     : Rollup_Cost
5251 -- Type         : Public
5252 -- Pre-reqs     : None.
5253 -- Function     : Rollup total cost for Asset Item
5254 -- Parameters
5255 -- IN           :
5256 --                p_inventory_item_id           IN NUMBER        Required
5257 --                      inventory_item_id in csi_item_instances
5258 --                p_serial_number               IN VARCHAR2        Required
5259 --                      serial_number in csi_item_instances
5260 --                p_period_set_name             IN VARCHAR2        Required
5261 --                      period_set_name in ORG_ACCT_PERIODS_V
5262 --                p_beginning_period_name          IN VARCHAR2        Required
5263 --                      starting period name for EAM cost Rollup
5264 --                p_ending_period_name                IN VARCHAR2        Required
5265 --                      ending period name for EAM Cost Rollup
5266 --
5267 -- Version      :
5268 --
5269 -- history      :
5270 --     04/17/2001 Terence chan          Genesis
5271 ----------------------------------------------------------------------------
5272 -- End of comments
5273 
5274 PROCEDURE Rollup_Cost (
5275           p_api_version                        IN NUMBER,
5276         p_init_msg_list                        IN VARCHAR2 := FND_API.G_FALSE ,
5277         p_commit                        IN VARCHAR2 := FND_API.G_FALSE ,
5278         p_validation_level                IN NUMBER   := FND_API.G_VALID_LEVEL_FULL ,
5279         x_return_status                        OUT NOCOPY VARCHAR2 ,
5280         x_msg_count                        OUT NOCOPY NUMBER ,
5281         x_msg_data                        OUT NOCOPY VARCHAR2 ,
5282 
5283         p_inventory_item_id                   IN NUMBER ,
5284         p_serial_number                       IN VARCHAR2 ,
5285         P_period_set_name                IN VARCHAR2 ,
5286         p_beginning_period_name         IN VARCHAR2 ,
5287         p_ending_period_name                 IN VARCHAR2 ,
5288 
5289         x_group_id                            OUT NOCOPY NUMBER )
5290 
5291         IS
5292         l_api_name         CONSTANT        VARCHAR2(30) := 'Rollup_Cost';
5293         l_api_version        CONSTANT        NUMBER             := 1.0;
5294         l_api_message                        VARCHAR2(2400);
5295 
5296         l_statement                        NUMBER := 0;
5297         l_gen_object_id                 NUMBER;
5298         l_count                                NUMBER := 0;
5299         l_period_start_date                DATE;
5300         l_period_end_date                DATE;
5301 
5302         l_maintenance_object_id         NUMBER;
5303         l_org_id         NUMBER;
5304 BEGIN
5305         ---------------------------------------------
5306         --  Standard start of API savepoint
5307         ---------------------------------------------
5308         SAVEPOINT Rollup_Cost_PUB;
5309 
5310         ------------------------------------------------
5311         --  Standard call to check for API compatibility
5312         ------------------------------------------------
5313         l_statement := 10;
5314         IF not fnd_api.compatible_api_call (
5315                                   l_api_version,
5316                                   p_api_version,
5317                                   l_api_name,
5318                                   G_PKG_NAME ) then
5319            RAISE fnd_api.G_exc_unexpected_error;
5320         END IF;
5321 
5322         ------------------------------------------------------------
5323         -- Initialize message list if p_init_msg_list is set to TRUE
5324         -------------------------------------------------------------
5325         l_statement := 20;
5326         IF fnd_api.to_Boolean(p_init_msg_list) then
5327           fnd_msg_pub.initialize;
5328         END IF;
5329 
5330         -------------------------------------------------------------
5331         --  Initialize API return status to Success
5332         -------------------------------------------------------------
5333         l_statement := 30;
5334         x_return_status := fnd_api.g_ret_sts_success;
5335 
5336         ------------------------------------------------
5337         -- find out object_id from MTL_SERIAL_NUMBERS
5338         -- using inventory_item_id
5339         -- and serial number
5340         ------------------------------------------------
5341         l_statement := 40;
5342         SELECT gen_object_id, current_organization_id
5343         INTO l_gen_object_id, l_org_id
5344         FROM mtl_serial_numbers
5345         WHERE inventory_item_id = p_inventory_item_id
5346         AND serial_number         = p_serial_number;
5347 
5348         l_statement := 45;
5349         SELECT mtl_eam_asset_activities_s.nextval
5350         INTO x_group_id
5351         FROM dual;
5352 
5353         l_statement := 50;
5354 
5355         IF p_beginning_period_name IS NOT NULL THEN
5356            select
5357              y.start_date
5358            into
5359              l_period_start_date
5360            from gl_periods y,
5361                 mfg_lookups x
5362            where
5363             y.adjustment_period_flag = 'N'  and
5364             x.lookup_type(+) = 'MTL_ACCT_PERIOD_STATUS' and
5365             x.enabled_flag(+) = 'Y' and
5366             x.lookup_code (+)= 67 and
5367             y.period_name = p_beginning_period_name and
5368             y.period_set_name = p_period_set_name;
5369 
5370         ELSE
5371                 l_period_start_date := NULL;
5372         END IF;
5373 
5374         l_statement := 55;
5375 
5376         IF p_ending_period_name IS NOT NULL THEN
5377           select
5378            y.end_date
5379           into
5380            l_period_end_date
5381           from gl_periods y,
5382                mfg_lookups x
5383           where
5384            y.adjustment_period_flag = 'N' and
5385            x.lookup_type(+) = 'MTL_ACCT_PERIOD_STATUS' and
5386            x.enabled_flag(+) = 'Y' and
5387            x.lookup_code (+)= 67 and
5388            y.period_name = p_ending_period_name and
5389            y.period_set_name = p_period_set_name;
5390         ELSE
5391                 l_period_end_date := NULL;
5392         END IF;
5393 
5394         ------------------------------------------------
5395         -- Take a snapshot of hierarchy structure from
5396         -- MTL_OBJECT_GENEALOGY
5397         -- and put it into CST_EAM_HIERARCHY_SNAPSHOT
5398         -- using l_gen_object_id and all it's child
5399         ------------------------------------------------
5400 
5401         -----------------------------------------------
5402         -- Comment out l_statement := 60 and l_statement := 65
5403         -- for bug#15907393 as l_statement := 60 insert statement
5404         -- may include multiple parent record if multiple parent_object_id
5405         -- exist.
5406         --l_statement := 60;
5407         /*INSERT INTO cst_eam_hierarchy_snapshot
5408         (group_id,
5409          object_type,
5410          object_id,
5411          parent_object_type,
5412          parent_object_id,
5413          level_num,
5414          last_update_date,
5415          last_updated_by,
5416          creation_date,
5417          created_by,
5418          request_id,
5419          program_application_id,
5420          last_update_login
5421         )
5422         SELECT DISTINCT
5423          x_group_id,
5424          1, -- Asset
5425          object_id,
5426          1, -- Asset
5427          parent_object_id,
5428          level,
5429          sysdate,
5430          1,
5431          sysdate,
5432          1,
5433          NULL,
5434          NULL,
5435          NULL
5436         FROM mtl_object_genealogy
5437         START WITH object_id = l_gen_object_id */
5438         /* Bug 8792876 - AND sysdate between start_date_active and nvl(end_date_active, sysdate)*/
5439         /*AND (END_DATE_ACTIVE IS NULL OR  END_DATE_ACTIVE >=
5440                                                     NVL(l_period_start_date,END_DATE_ACTIVE)) AND
5441                                             (START_DATE_ACTIVE <=
5442                                                 NVL(l_period_end_date,START_DATE_ACTIVE))
5443         CONNECT BY parent_object_id = PRIOR object_id */
5444         /* Bug 8792876 - AND sysdate between start_date_active and nvl(end_date_active, sysdate);*/
5445         /* AND (END_DATE_ACTIVE IS NULL OR  END_DATE_ACTIVE >=
5446                                                     NVL(l_period_start_date,END_DATE_ACTIVE)) AND
5447                                             (START_DATE_ACTIVE <=
5448                                                 NVL(l_period_end_date,START_DATE_ACTIVE));  */
5449 
5450         ------------------------------------------------
5451         -- check for single asset. If it's the case
5452         -- insert one row into CST_EAM_HIERARCHY_SNAPSHOT
5453         ------------------------------------------------
5454         /*l_statement := 65;
5455         SELECT count(*)
5456         INTO l_count
5457         FROM cst_eam_hierarchy_snapshot
5458         WHERE group_id = x_group_id; */
5459 
5460         --IF (l_count = 0) THEN
5461 
5462 	      l_statement := 70;
5463 
5464         /*  AMONDAL's fix, updated by DLE    */
5465         INSERT INTO cst_eam_hierarchy_snapshot
5466         (group_id,
5467          object_type,
5468          object_id,
5469          parent_object_type,
5470          parent_object_id,
5471          level_num,
5472          last_update_date,
5473          last_updated_by,
5474          creation_date,
5475          created_by,
5476          request_id,
5477          program_application_id,
5478          last_update_login
5479         )
5480         SELECT DISTINCT
5481          x_group_id,
5482          1, -- Asset
5483          object_id,
5484          1, -- Asset
5485          parent_object_id,
5486          level,
5487          sysdate,
5488          1,
5489          sysdate,
5490          1,
5491          NULL,
5492          NULL,
5493          NULL
5494         FROM mtl_object_genealogy
5495         START WITH parent_object_id = l_gen_object_id
5496         /*Bug 15907393 - to avoid parent asset associated as original child asset's child asset*/
5497         AND object_id <> l_gen_object_id
5498         /* Bug 8792876 - AND sysdate between start_date_active and nvl(end_date_active, sysdate)*/
5499         AND (END_DATE_ACTIVE IS NULL OR  END_DATE_ACTIVE >=
5500                                                     NVL(l_period_start_date,END_DATE_ACTIVE)) AND
5501                                             (START_DATE_ACTIVE <=
5502                                                 NVL(l_period_end_date,START_DATE_ACTIVE))
5503         CONNECT BY parent_object_id = PRIOR object_id
5504         /*Bug 15907393 - to avoid parent asset associated as original child asset's child asset*/
5505         AND object_id <> l_gen_object_id
5506         /* Bug 8792876 - AND sysdate between start_date_active and nvl(end_date_active, sysdate);*/
5507         AND (END_DATE_ACTIVE IS NULL OR  END_DATE_ACTIVE >=
5508                                                     NVL(l_period_start_date,END_DATE_ACTIVE)) AND
5509                                             (START_DATE_ACTIVE <=
5510                                                 NVL(l_period_end_date,START_DATE_ACTIVE));
5511 
5512         /*  end of AMONDAL's fix   */
5513 	l_statement := 75;
5514 
5515         INSERT INTO cst_eam_hierarchy_snapshot
5516         (group_id,
5517          object_type,
5518          object_id,
5519          parent_object_type,
5520          parent_object_id,
5521          level_num,
5522          last_update_date,
5523          last_updated_by,
5524          creation_date,
5525          created_by,
5526          request_id,
5527          program_application_id,
5528          last_update_login
5529         )
5530         VALUES
5531         (x_group_id,
5532          1, -- Asset
5533          l_gen_object_id,
5534          1, -- Asset
5535         -1,
5536         1,
5537         sysdate,
5538         1,
5539         sysdate,
5540         1,
5541         NULL,
5542         NULL,
5543         NULL );
5544 
5545         --END IF;
5546 
5547         ------------------------------------------------
5548         -- Roll Up the Cost of Asset Item and all it's child
5549         -- By ACCT_PERIOD_ID
5550         -- and MAINT_COST_ELEMENT
5551         -- and ORGANIZATION_ID
5552         ------------------------------------------------
5553         /* Bug 8792876 - l_statement := 60;
5554 
5555         IF p_beginning_period_name IS NOT NULL THEN
5556            select
5557              y.start_date
5558            into
5559              l_period_start_date
5560            from gl_periods y,
5561                 mfg_lookups x
5562            where
5563             y.adjustment_period_flag = 'N'  and
5564             x.lookup_type(+) = 'MTL_ACCT_PERIOD_STATUS' and
5565             x.enabled_flag(+) = 'Y' and
5566             x.lookup_code (+)= 67 and
5567             y.period_name = p_beginning_period_name and
5568             y.period_set_name = p_period_set_name;
5569 
5570         ELSE
5571                 l_period_start_date := NULL;
5572         END IF;
5573 
5574         l_statement := 70;
5575 
5576         IF p_ending_period_name IS NOT NULL THEN
5577           select
5578            y.end_date
5579           into
5580            l_period_end_date
5581           from gl_periods y,
5582                mfg_lookups x
5583           where
5584            y.adjustment_period_flag = 'N' and
5585            x.lookup_type(+) = 'MTL_ACCT_PERIOD_STATUS' and
5586            x.enabled_flag(+) = 'Y' and
5587            x.lookup_code (+)= 67 and
5588            y.period_name = p_ending_period_name and
5589            y.period_set_name = p_period_set_name;
5590         ELSE
5591                 l_period_end_date := NULL;
5592         END IF; */
5593 
5594         -- dbms_output.put_line('p_ending_period_name :=' || p_ending_period_name);
5595         -- dbms_output.put_line('l_period_end_date :=' || l_period_end_date);
5596         -- dbms_output.put_line('p_beginning_period_name := ' || p_beginning_period_name);
5597         -- dbms_output.put_line('l_period_start_date := ' || l_period_start_date);
5598 
5599         l_statement := 80;
5600 
5601        /* Get the maintenance_object_id for the asset */
5602         select cii.instance_id
5603         into l_maintenance_object_id
5604         from csi_item_instances cii
5605         where cii.serial_number = p_serial_number
5606         and cii.inventory_item_id = p_inventory_item_id;
5607 
5608 
5609        /* Inserted maintenance_object_id and maintenance_object_type from CEAPB as
5610           part of eAM Requirements Project - R12. */
5611 
5612         INSERT INTO cst_eam_rollup_temp
5613         (group_id,
5614          period_set_name,
5615          period_name,
5616          inventory_item_id,
5617          serial_number,
5618          organization_id,
5619          acct_period_id,
5620          maint_cost_category,
5621          actual_mat_cost,
5622          actual_lab_cost,
5623          actual_eqp_cost,
5624          system_estimated_mat_cost,
5625          system_estimated_lab_cost,
5626          system_estimated_eqp_cost,
5627          manual_estimated_mat_cost,
5628          manual_estimated_lab_cost,
5629          manual_estimated_eqp_cost,
5630          period_start_date,
5631          maintenance_object_type,
5632          maintenance_object_id,
5633          last_update_date,
5634          last_updated_by,
5635          creation_date,
5636          created_by,
5637          request_id,
5638          program_application_id
5639         )
5640         SELECT
5641          x_group_id,
5642          p_period_set_name,
5643          ceapb.period_name,
5644          p_inventory_item_id,
5645          p_serial_number,
5646          ceapb.organization_id,
5647          ceapb.acct_period_id,
5648          ceapb.maint_cost_category,
5649          sum(ceapb.actual_mat_cost),
5650          sum(ceapb.actual_lab_cost),
5651          sum(ceapb.actual_eqp_cost),
5652          sum(ceapb.system_estimated_mat_cost),
5653          sum(ceapb.system_estimated_lab_cost),
5654          sum(ceapb.system_estimated_eqp_cost),
5655          sum(ceapb.manual_estimated_mat_cost),
5656          sum(ceapb.manual_estimated_lab_cost),
5657          sum(ceapb.manual_estimated_eqp_cost),
5658          ceapb.period_start_date,
5659          3,
5660          l_maintenance_object_id,
5661          sysdate,
5662          1,
5663          sysdate,
5664          1,
5665          NULL,
5666          NULL
5667         FROM cst_eam_asset_per_balances ceapb,
5668              mtl_serial_numbers msn,
5669              --Bug#16095661: Distinct group_id, object
5670              (select DISTINCT group_id, object_id
5671                         from cst_eam_hierarchy_snapshot
5672                     where group_id = x_group_id ) cehs
5673         WHERE ceapb.organization_id = l_org_id
5674         AND   ceapb.inventory_item_id = msn.inventory_item_id
5675         AND   ceapb.serial_number     = msn.serial_number
5676         AND   msn.gen_object_id       = cehs.object_id
5677         AND   cehs.group_id              = x_group_id
5678         AND   ceapb.period_set_name   = p_period_set_name
5679         AND   ceapb.period_start_date >= DECODE(l_period_start_date, NULL, ceapb.period_start_date, l_period_start_date)
5680         AND   ceapb.period_start_date <= DECODE(l_period_end_date, NULL, ceapb.period_start_date, l_period_end_date)
5681         GROUP BY
5682         ceapb.period_name,
5683         ceapb.organization_id,
5684         ceapb.acct_period_id,
5685         ceapb.maint_cost_category,
5686         ceapb.period_start_date;
5687 
5688         l_statement := 90;
5689         ---------------------------------------------------------------------------
5690         -- Check if there is anything inserted
5691         ---------------------------------------------------------------------------
5692         SELECT count(*) INTO l_count
5693         FROM cst_eam_rollup_temp
5694         WHERE group_id = x_group_id;
5695 
5696         l_statement := 100;
5697         ---------------------------------------------------------------------------
5698         -- If nothing, raise error
5699         ---------------------------------------------------------------------------
5700         IF (l_count = 0) THEN
5701            l_api_message := 'No row is inserted into CST_EAM_ROLLUP_TEMP';
5702            fnd_msg_pub.add_exc_msg
5703            ( G_PKG_NAME,
5704              l_api_name,
5705              l_api_message );
5706            RAISE fnd_api.g_exc_error;
5707         END IF;
5708 
5709         ---------------------------------------------------------------------------
5710         -- Standard check of p_commit
5711         ---------------------------------------------------------------------------
5712         l_statement := 110;
5713         IF FND_API.to_Boolean(p_commit) THEN
5714            COMMIT WORK;
5715         END IF;
5716 
5717         ---------------------------------------------------------------------------
5718         -- Standard Call to get message count and if count = 1, get message info
5719         ---------------------------------------------------------------------------
5720         l_statement := 120;
5721         fnd_msg_pub.count_and_get (p_count     => x_msg_count,
5722                                    p_data      => x_msg_data );
5723 
5724 
5725 EXCEPTION
5726         WHEN fnd_api.g_exc_error then
5727                 ROLLBACK TO Rollup_Cost_PUB;
5728                 x_return_status := fnd_api.g_ret_sts_error;
5729                 fnd_msg_pub.count_and_get ( p_count => x_msg_count,
5730                                                 p_data  => x_msg_data );
5731 
5732         WHEN fnd_api.g_exc_unexpected_error then
5733                 ROLLBACK TO Rollup_Cost_PUB;
5734                 x_return_status := fnd_api.g_ret_sts_unexp_error;
5735                 fnd_msg_pub.count_and_get ( p_count => x_msg_count,
5736                                             p_data  => x_msg_data );
5737 
5738         WHEN OTHERS THEN
5739                 ROLLBACK TO Rollup_Cost_PUB;
5740                 x_return_status := fnd_api.g_ret_sts_unexp_error ;
5741 
5742                 IF fnd_msg_pub.check_msg_level(fnd_msg_pub.g_msg_lvl_unexp_error) then
5743                    fnd_msg_pub.add_exc_msg
5744                  ( G_PKG_NAME,l_api_name || ' : Statement - ' || to_char(l_statement));
5745                 END IF;
5746 
5747                 fnd_msg_pub.count_and_get( p_count => x_msg_count,
5748                                            p_data  => x_msg_data );
5749 
5750 END Rollup_Cost;
5751 
5752 
5753 -- Start of comments
5754 ----------------------------------------------------------------------------
5755 -- API name     : Purge_Rollup_Cost
5756 -- Type         : Public
5757 -- Pre-reqs     : None.
5758 -- Function     : Rollup total cost for Asset Item
5759 -- Parameters
5760 -- IN           :
5761 --                p_group_id                IN VARCHAR2        Required
5762 --                      group_id in cst_eam_hierarchy_snapshot
5763 --                                  cst_eam_rollup_temp
5764 --
5765 -- Version      :
5766 --
5767 -- history      :
5768 --     05/09/2001 Terence chan          Genesis
5769 ----------------------------------------------------------------------------
5770 -- End of comments
5771 PROCEDURE Purge_Rollup_Cost (
5772           p_api_version                        IN NUMBER,
5773         p_init_msg_list                        IN VARCHAR2 := FND_API.G_FALSE ,
5774         p_commit                        IN VARCHAR2 := FND_API.G_FALSE ,
5775         p_validation_level                IN NUMBER   := FND_API.G_VALID_LEVEL_FULL ,
5776         x_return_status                        OUT NOCOPY VARCHAR2 ,
5777         x_msg_count                        OUT NOCOPY NUMBER ,
5778         x_msg_data                        OUT NOCOPY VARCHAR2 ,
5779 
5780         p_group_id                            IN NUMBER )
5781 
5782         IS
5783 
5784         l_api_name         CONSTANT        VARCHAR2(30) := 'Purge_Rollup_Cost';
5785         l_api_version        CONSTANT        NUMBER             := 1.0;
5786         l_api_message                        VARCHAR2(240);
5787 
5788         l_statement                        NUMBER := 0;
5789 
5790 BEGIN
5791         ---------------------------------------------
5792         --  Standard start of API savepoint
5793         ---------------------------------------------
5794         SAVEPOINT Purge_Rollup_Cost_PUB;
5795 
5796         ------------------------------------------------
5797         --  Standard call to check for API compatibility
5798         ------------------------------------------------
5799         l_statement := 10;
5800         IF not fnd_api.compatible_api_call (
5801                                   l_api_version,
5802                                   p_api_version,
5803                                   l_api_name,
5804                                   G_PKG_NAME ) then
5805            RAISE fnd_api.G_exc_unexpected_error;
5806         END IF;
5807 
5808         ------------------------------------------------------------
5809         -- Initialize message list if p_init_msg_list is set to TRUE
5810         -------------------------------------------------------------
5811         l_statement := 20;
5812         IF fnd_api.to_Boolean(p_init_msg_list) then
5813           fnd_msg_pub.initialize;
5814         END IF;
5815 
5816         -------------------------------------------------------------
5817         --  Initialize API return status to Success
5818         -------------------------------------------------------------
5819         l_statement := 30;
5820         x_return_status := fnd_api.g_ret_sts_success;
5821 
5822         -------------------------------------------------------------
5823         --  Purge cst_am_hierarchy_snapshot
5824         -------------------------------------------------------------
5825         l_statement := 40;
5826         DELETE cst_eam_hierarchy_snapshot
5827         WHERE group_id= p_group_id;
5828 
5829         -------------------------------------------------------------
5830         --  Pruge cst_eam_rollup_temp
5831         -------------------------------------------------------------
5832         l_statement := 50;
5833         DELETE cst_eam_rollup_temp
5834         WHERE group_id= p_group_id;
5835 
5836         ---------------------------------------------------------------------------
5837         -- Standard check of p_commit
5838         ---------------------------------------------------------------------------
5839         l_statement := 60;
5840         IF FND_API.to_Boolean(p_commit) THEN
5841            COMMIT WORK;
5842         END IF;
5843 
5844         ---------------------------------------------------------------------------
5845         -- Standard Call to get message count and if count = 1, get message info
5846         ---------------------------------------------------------------------------
5847         l_statement := 70;
5848         fnd_msg_pub.count_and_get (p_count     => x_msg_count,
5849                                    p_data      => x_msg_data );
5850 
5851 
5852 EXCEPTION
5853 
5854         WHEN fnd_api.g_exc_error then
5855                 ROLLBACK TO Purge_Rollup_Cost_PUB;
5856                 x_return_status := fnd_api.g_ret_sts_error;
5857                 fnd_msg_pub.count_and_get ( p_count => x_msg_count,
5858                                                 p_data  => x_msg_data );
5859 
5860         WHEN fnd_api.g_exc_unexpected_error then
5861                 ROLLBACK TO Purge_Rollup_Cost_PUB;
5862                 x_return_status := fnd_api.g_ret_sts_unexp_error;
5863                 fnd_msg_pub.count_and_get ( p_count => x_msg_count,
5864                                             p_data  => x_msg_data );
5865 
5866         WHEN OTHERS THEN
5867                 ROLLBACK TO Purge_Rollup_Cost_PUB;
5868                 x_return_status := fnd_api.g_ret_sts_unexp_error ;
5869                 IF fnd_msg_pub.check_msg_level(fnd_msg_pub.g_msg_lvl_unexp_error) then
5870                    fnd_msg_pub.add_exc_msg
5871                    ( G_PKG_NAME,l_api_name || ' : Statement - ' || to_char(l_statement));
5872                 END IF;
5873                 fnd_msg_pub.count_and_get( p_count => x_msg_count,
5874                                            p_data  => x_msg_data );
5875 
5876 END Purge_Rollup_Cost;
5877 
5878 ----------------------------------------------------------------------------
5879 -- PROCEDURE                                                              --
5880 --   check_if_direct_item                                                 --
5881 --                                                                        --
5882 -- DESCRIPTION                                                            --
5883 --   checks if this is a direct item transaction                          --
5884 --    * Organization should be EAM enabled                                --
5885 --    * Destination should be EAM job                                     --
5886 --    * Item number is null or the item should not be of type OSP         --
5887 -- PURPOSE:                                                               --
5888 --    Called by the function process_OSP_Transaction in the receiving     --
5889 --    transaction processor                                               --
5890 --                                                                        --
5891 -- HISTORY:                                                               --
5892 --    05/01/01  Anitha Dixit    Created                                   --
5893 ----------------------------------------------------------------------------
5894 
5895 PROCEDURE check_if_direct_item (
5896                 p_api_version                   IN      NUMBER,
5897                 p_init_msg_list                 IN      VARCHAR2 := FND_API.G_FALSE,
5898                 p_commit                        IN      VARCHAR2 := FND_API.G_FALSE,
5899                 p_validation_level              IN      VARCHAR2 := FND_API.G_VALID_LEVEL_FULL,
5900 
5901                 p_interface_txn_id              IN      NUMBER,
5902 
5903                 x_direct_item_flag              OUT NOCOPY     NUMBER,
5904                 x_return_status                 OUT NOCOPY     VARCHAR2,
5905                 x_msg_count                     OUT NOCOPY     NUMBER,
5906                 x_msg_data                      OUT NOCOPY     VARCHAR2
5907                 ) IS
5908 
5909   l_api_name    CONSTANT        VARCHAR2(30) := 'check_if_direct_item';
5910   l_api_version CONSTANT        NUMBER              := 1.0;
5911 
5912   l_return_status       VARCHAR2(1) := fnd_api.g_ret_sts_success;
5913   l_msg_count           NUMBER := 0;
5914   l_msg_data            VARCHAR2(8000);
5915   l_stmt_num            NUMBER := 0;
5916 
5917   l_wip_entity_id       NUMBER;
5918   l_entity_type         NUMBER;
5919   l_item_id             NUMBER;
5920   l_org_id              NUMBER;
5921   l_eam_flag            VARCHAR2(1);
5922   l_osp_item            VARCHAR2(1);
5923 
5924   l_api_message         VARCHAR2(1000);
5925   l_debug               VARCHAR2(80);
5926   l_interface_txn_id    NUMBER;
5927 
5928   BEGIN
5929 
5930     --  Standard Start of API savepoint
5931     SAVEPOINT check_if_direct_item_PUB;
5932     l_debug := fnd_profile.value('MRP_DEBUG');
5933 
5934     if (l_debug = 'Y') then
5935          FND_FILE.PUT_LINE(fnd_file.log,'Check if direct item');
5936     end if;
5937 
5938     -- Standard call to check for call compatibility
5939     IF NOT FND_API.Compatible_API_Call (
5940                         l_api_version,
5941                         p_api_version,
5942                         l_api_name,
5943                         G_PKG_NAME ) THEN
5944           RAISE FND_API.G_EXC_UNEXPECTED_ERROR;
5945     END IF;
5946 
5947     -- Initialize message list if p_init_msg_list is set to TRUE
5948     IF FND_API.to_Boolean(p_init_msg_list) THEN
5949         FND_MSG_PUB.initialize;
5950     END IF;
5951 
5952     -- Initialize API return status to success
5953     l_stmt_num := 0;
5954     x_return_status := FND_API.G_RET_STS_SUCCESS;
5955     x_direct_item_flag := 0;
5956 
5957     -- Validate IN parameters
5958     l_stmt_num := 20;
5959     IF (p_interface_txn_id IS NULL) THEN
5960          RAISE fnd_api.g_exc_error;
5961     END IF;
5962 
5963     -- Due to changes in Bug #1926731, p_interface_txn_id now contains the rcv_transaction_id
5964     -- instead of interface_transaction_id. Get the interface_transaction_id from rcv_transactions.
5965     l_stmt_num := 25;
5966 
5967     if(l_debug = 'Y') then
5968         fnd_file.put_line(fnd_file.log,'RCV transaction ID : '||p_interface_txn_id);
5969     end if;
5970 
5971     SELECT interface_transaction_id
5972     INTO l_interface_txn_id
5973     FROM rcv_transactions
5974     WHERE transaction_id = p_interface_txn_id;
5975 
5976     IF (l_interface_txn_id IS NULL) THEN
5977          RAISE fnd_api.g_exc_error;
5978     END IF;
5979 
5980     if(l_debug = 'Y') then
5981         fnd_file.put_line(fnd_file.log,'Interface Txn ID : '||l_interface_txn_id);
5982     end if;
5983 
5984     -- Obtain wip entity, organization and item ID for the receiving transaction
5985     l_stmt_num := 30;
5986     SELECT wip_entity_id,
5987            item_id,
5988            to_organization_id
5989       INTO l_wip_entity_id,
5990            l_item_id,
5991            l_org_id
5992       FROM rcv_transactions_interface
5993      WHERE interface_transaction_id = l_interface_txn_id;
5994 
5995     if (l_debug = 'Y') then
5996         fnd_file.put_line(fnd_file.log,'WE: ' || to_char(l_wip_entity_id));
5997         fnd_file.put_line(fnd_file.log,'item: ' || to_char(l_item_id));
5998         fnd_file.put_line(fnd_file.log,'to_org: ' || to_char(l_org_id));
5999     end if;
6000 
6001     -- Get EAM enabled flag for organization
6002     l_stmt_num := 40;
6003     SELECT nvl(eam_enabled_flag,'N')
6004       INTO l_eam_flag
6005       FROM mtl_parameters
6006      WHERE organization_id = l_org_id;
6007 
6008     if (l_debug = 'Y') then
6009          fnd_file.put_line(fnd_file.log,'EAM flag: ' || l_eam_flag);
6010     end if;
6011 
6012     -- Get entity type for the job
6013     l_stmt_num := 50;
6014     SELECT nvl(entity_type,-1)
6015       INTO l_entity_type
6016       FROM wip_entities
6017      WHERE wip_entity_id = l_wip_entity_id;
6018 
6019     if (l_debug = 'Y') then
6020          fnd_file.put_line(fnd_file.log,'Entity: ' || to_char(l_entity_type));
6021     end if;
6022 
6023     -- Validate organization and entity type
6024     l_stmt_num := 60;
6025     IF ((l_eam_flag <> 'Y') OR (l_entity_type NOT IN (6,7))) THEN
6026         x_direct_item_flag := 0;
6027     ELSE
6028         -- Check for Item ID
6029         l_stmt_num := 70;
6030         if (l_debug = 'Y') then
6031              fnd_file.put_line(fnd_file.log,'EAM job!');
6032         end if;
6033 
6034         IF (l_item_id IS NULL) THEN
6035              x_direct_item_flag := 1;
6036         ELSE
6037              l_stmt_num := 80;
6038              SELECT nvl(outside_operation_flag,'N')
6039                INTO l_osp_item
6040                FROM mtl_system_items_b
6041               WHERE inventory_item_id = l_item_id
6042                 AND organization_id = l_org_id;
6043 
6044              if (l_debug = 'Y') then
6045                   fnd_file.put_line(fnd_file.log,'osp flag : ' || l_osp_item);
6046              end if;
6047 
6048              IF (l_osp_item = 'N') THEN
6049                   x_direct_item_flag := 1;
6050              ELSE
6051                   x_direct_item_flag := 0;
6052              END IF; /* check if item is OSP or not */
6053         END IF;  /* check for NULL item_id */
6054     END IF; /* Organization and job are of EAM type */
6055 
6056     if (l_debug = 'Y') then
6057          fnd_file.put_line(fnd_file.log,'Direct item flag : ' || to_char(x_direct_item_flag));
6058     end if;
6059 
6060     -- Standard check of p_commit
6061     IF FND_API.to_Boolean(p_commit) THEN
6062        COMMIT WORK;
6063     END IF;
6064 
6065     -- Standard Call to get message count and if count = 1, get message info
6066     FND_MSG_PUB.Count_And_Get (
6067            p_count     => x_msg_count,
6068            p_data      => x_msg_data );
6069 
6070    -- Print messages to log file
6071 
6072 
6073     EXCEPTION
6074       WHEN fnd_api.g_exc_error THEN
6075          ROLLBACK TO check_if_direct_item_PUB;
6076          x_return_status := fnd_api.g_ret_sts_error;
6077 
6078         --  Get message count and data
6079         fnd_msg_pub.count_and_get
6080              (  p_count => x_msg_count
6081               , p_data  => x_msg_data
6082               );
6083 
6084       WHEN fnd_api.g_exc_unexpected_error THEN
6085             ROLLBACK TO check_if_direct_item_PUB;
6086             x_return_status := fnd_api.g_ret_sts_unexp_error ;
6087 
6088         --  Get message count and data
6089         fnd_msg_pub.count_and_get
6090           (  p_count  => x_msg_count
6091            , p_data   => x_msg_data
6092             );
6093       --
6094    WHEN OTHERS THEN
6095       ROLLBACK TO check_if_direct_item_PUB;
6096       x_return_status := fnd_api.g_ret_sts_unexp_error ;
6097       --
6098       IF fnd_msg_pub.check_msg_level(fnd_msg_pub.g_msg_lvl_unexp_error)
6099         THEN
6100          fnd_msg_pub.add_exc_msg
6101            (  'CST_eamCost_PUB'
6102               , 'check_if_direct_item : Statement - '|| to_char(l_stmt_num)
6103               );
6104 
6105       END IF;
6106 
6107       --  Get message count and data
6108       fnd_msg_pub.count_and_get
6109           (  p_count  => x_msg_count
6110            , p_data   => x_msg_data
6111            );
6112 END check_if_direct_item;
6113 
6114 ----------------------------------------------------------------------------
6115 -- PROCEDURE                                                              --
6116 --   process_direct_item_txn                                              --
6117 -- DESCRIPTION                                                            --
6118 --   This is the wrapper function to do direct item costing               --
6119 --    * Inserts transaction into wip_cost_txn_interface                   --
6120 -- PURPOSE:                                                               --
6121 --    API to process direct item transaction. Called from the function    --
6122 --    process_OSP_transaction in the receiving transaction processor      --
6123 -- HISTORY:                                                               --
6124 --    05/01/01          Anitha Dixit    Created                           --
6125 ----------------------------------------------------------------------------
6126 
6127 PROCEDURE process_direct_item_txn (
6128                 p_api_version                        IN        NUMBER,
6129                  p_init_msg_list                        IN        VARCHAR2 := FND_API.G_FALSE,
6130                 p_commit                        IN        VARCHAR2 := FND_API.G_FALSE,
6131                 p_validation_level                IN        VARCHAR2 := FND_API.G_VALID_LEVEL_FULL,
6132 
6133                 p_directItem_rec                IN        WIP_Transaction_PUB.Res_Rec_Type,
6134 
6135                 x_directItem_rec                IN OUT NOCOPY        WIP_Transaction_PUB.Res_Rec_Type,
6136                 x_return_status                        OUT NOCOPY        VARCHAR2,
6137                 x_msg_count                        OUT NOCOPY        NUMBER,
6138                 x_msg_data                        OUT NOCOPY        VARCHAR2
6139                 ) IS
6140 
6141   l_api_name    CONSTANT        VARCHAR2(30) := 'process_direct_item_txn';
6142   l_api_version CONSTANT        NUMBER              := 1.0;
6143 
6144   l_return_status       VARCHAR2(1) := fnd_api.g_ret_sts_success;
6145   l_msg_count           NUMBER := 0;
6146   l_msg_data            VARCHAR2(8000);
6147   l_stmt_num            NUMBER := 0;
6148 
6149   l_actual_res_rate     NUMBER;
6150   l_txn_id              NUMBER;
6151   l_project_id          NUMBER;
6152   l_task_id             NUMBER;
6153   l_op_seq_num          NUMBER;
6154   l_txn_type            VARCHAR2(240);
6155   l_wip_entity_id       NUMBER;
6156   l_txn_value           NUMBER;
6157   l_primary_qty         NUMBER;
6158   l_wip_acct            NUMBER := -1;
6159   l_dept_id             NUMBER;
6160   l_org_id              NUMBER;
6161   l_user_id             NUMBER;
6162   l_login_id            NUMBER;
6163   l_curr_rate           NUMBER;
6164 
6165   l_quantity            NUMBER;
6166   l_primary_quantity    NUMBER;
6167 
6168   l_item_id                    NUMBER;
6169   l_source_doc_unit_of_measure VARCHAR2(25);
6170   l_source_doc_uom_code        VARCHAR2(3);
6171 
6172   l_directItem_rec      WIP_Transaction_PUB.Res_Rec_Type;
6173 
6174   l_api_message         VARCHAR2(1000);
6175   l_debug               VARCHAR2(80);
6176 
6177   l_curr_code           VARCHAR2(16);
6178   l_po_txn_type         VARCHAR2(25);
6179 
6180   l_interface_txn_id    NUMBER;
6181 
6182   l_po_order_type_lookup_code VARCHAR2(20);
6183 
6184 -- Bug 9356654 WIP Encumbrance enhancement Change
6185   l_encumbrance_amount         NUMBER;
6186   l_encumbrance_quantity       NUMBER;
6187   l_encumbrance_ccid           NUMBER;
6188   l_encumbrance_type_id        NUMBER;
6189   l_enc_return_status          VARCHAR2(1);
6190   l_enc_msg_count              NUMBER;
6191   l_enc_msg_data               VARCHAR2(2000);
6192 
6193   BEGIN
6194 
6195     --  Standard Start of API savepoint
6196     SAVEPOINT process_direct_item_txn_PUB;
6197 
6198     l_debug := fnd_profile.value('MRP_DEBUG');
6199 
6200     -- Standard call to check for call compatibility
6201     IF NOT FND_API.Compatible_API_Call (
6202                         l_api_version,
6203                         p_api_version,
6204                         l_api_name,
6205                         G_PKG_NAME ) THEN
6206           RAISE FND_API.G_EXC_UNEXPECTED_ERROR;
6207     END IF;
6208 
6209     -- Initialize message list if p_init_msg_list is set to TRUE
6210     IF FND_API.to_Boolean(p_init_msg_list) THEN
6211         FND_MSG_PUB.initialize;
6212     END IF;
6213 
6214     -- Initialize API return status to success
6215     l_stmt_num := 10;
6216     x_return_status := FND_API.G_RET_STS_SUCCESS;
6217 
6218     -- Initialize direct item record
6219     l_stmt_num := 20;
6220     l_directItem_rec := p_directItem_rec;
6221 
6222     -- Due to changes in Bug #1926731, l_directItem_rec.rcv_transaction_id now contains the rcv_transaction_id
6223     -- instead of interface_transaction_id. Get the interface_transaction_id from rcv_transactions.
6224     l_stmt_num := 25;
6225 
6226    l_txn_id := l_directItem_rec.rcv_transaction_id;
6227     if(l_debug = 'Y') then
6228         fnd_file.put_line(fnd_file.log,'RCV transaction ID : '||l_txn_id);
6229     end if;
6230 
6231     /* Modified quantity to source_doc_quantity for bug 3253815. When the
6232        receipt UOM is different from the UOM on the PO, using quantity
6233        instead of the source_doc_quantity results in an incorrect actual_res_rate
6234        when it is converted to the primary_uom */
6235     SELECT interface_transaction_id, source_doc_quantity /*, primary_quantity*/
6236     INTO l_interface_txn_id, l_quantity /*, l_primary_quantity*/
6237     FROM rcv_transactions
6238    WHERE transaction_id = l_txn_id;
6239 
6240     IF (l_interface_txn_id IS NULL) THEN
6241          RAISE fnd_api.g_exc_error;
6242     END IF;
6243 
6244     -- Bug #2144236. Interface_txn_id was getting inserted into WCTI
6245     -- instead of rcv_transaction_id
6246     -- l_directItem_rec.rcv_transaction_id := l_interface_txn_id;
6247 
6248     if (l_debug = 'Y') then
6249          fnd_file.put_line(fnd_file.log,'Interface txn ID : '
6250                              || to_char(l_interface_txn_id));
6251     end if;
6252 
6253 
6254     -- Get actual resource rate
6255     l_stmt_num := 30;
6256 
6257     /* Added a check for order_type_lookup_code to consider PO Service Line
6258        Types for Direct Item Delivery to Shop Floor. Changes are for eAM
6259        Requirements Project - R12 */
6260 
6261 /*       SELECT  decode(pol.order_type_lookup_code,
6262        'RATE', rti.amount + rti.amount *
6263           PO_TAX_SV.get_tax('PO',pod.po_distribution_id)/pod.amount_ordered,
6264        'FIXED PRICE', rti.amount + rti.amount *
6265           PO_TAX_SV.get_tax('PO',pod.po_distribution_id)/pod.amount_ordered,
6266        (rti.po_unit_price +
6267           PO_TAX_SV.get_tax('PO',pod.po_distribution_id)/pod.quantity_ordered)),
6268            nvl(l_directItem_rec.currency_conversion_rate,nvl(rti.currency_conversion_rate,1)),
6269            rti.currency_code,
6270            pol.order_type_lookup_code
6271       into l_actual_res_rate,
6272            l_curr_rate,
6273            l_curr_code,
6274            l_po_order_type_lookup_code
6275       from po_distributions_all pod,
6276            rcv_transactions_interface rti,
6277            po_lines_all pol
6278      where rti.interface_transaction_id = l_interface_txn_id
6279      and  pod.po_distribution_id = rti.po_distribution_id
6280      and pol.po_header_id=pod.po_header_id
6281      and pol.po_line_id=pod.po_line_id; */
6282 
6283     -- Get rti details
6284     l_stmt_num := 30;
6285 
6286     select
6287 	   decode(pol.order_type_lookup_code,
6288               'RATE',  rti.amount
6289 			         +   rti.amount
6290 					  *  PO_TAX_SV.get_tax('PO',pod.po_distribution_id)
6291 					  /  pod.amount_ordered,
6292                'FIXED PRICE', rti.amount
6293 			         +  rti.amount
6294                       *  PO_TAX_SV.get_tax('PO',pod.po_distribution_id)
6295 					  /  pod.amount_ordered,
6296                (   rti.po_unit_price
6297                  +  PO_TAX_SV.get_tax('PO',pod.po_distribution_id)
6298 				   /pod.quantity_ordered)),
6299 	   nvl(l_directItem_rec.currency_conversion_rate,nvl(rti.currency_conversion_rate,nvl(pod.rate,1))),
6300 	   --
6301            --rti.currency_code,
6302 	   --
6303            pol.order_type_lookup_code,
6304            1,
6305            rti.last_updated_by,
6306            sysdate,
6307            l_actual_res_rate,
6308            rti.currency_code,
6309            nvl(l_directItem_rec.currency_conversion_date,rti.currency_conversion_date),
6310            --BUG introduced by the fix of bug#7355438
6311 	   -- The l_directItem_rec.currency_conversion_rate value is always null
6312 	   -- l_curr_rate
6313 	   --
6314            nvl(l_directItem_rec.currency_conversion_type,rti.currency_conversion_type),
6315            rti.last_updated_by,
6316            sysdate,
6317            rti.last_update_login,
6318            rti.wip_operation_seq_num,
6319            rti.organization_id,
6320            rti.po_header_id,
6321            rti.po_line_id,
6322            2,
6323            1,
6324            sysdate,
6325            pod.project_id,
6326            rti.reason_id,
6327            rti.comments,
6328            2,
6329            pod.task_id,
6330            rti.transaction_date,
6331            decode(pol.order_type_lookup_code, 'RATE',NULL,
6332                                                'FIXED PRICE', NULL,
6333                                                 rti.quantity),
6334            17,
6335            rti.uom_code,
6336            rti.wip_entity_id,
6337            pol.item_id,
6338            rti.source_doc_unit_of_measure
6339      into l_actual_res_rate,
6340           l_directItem_rec.currency_conversion_rate,
6341           --
6342 	  --l_curr_code,
6343           --
6344           l_po_order_type_lookup_code,
6345           l_directItem_rec.basis_type,
6346           l_directItem_rec.created_by,
6347           l_directItem_rec.creation_date,
6348           l_directItem_rec.currency_actual_rsc_rate,
6349           l_directItem_rec.currency_code,
6350           l_directItem_rec.currency_conversion_date,
6351           l_directItem_rec.currency_conversion_type,
6352           l_directItem_rec.last_updated_by,
6353           l_directItem_rec.last_update_date,
6354           l_directItem_rec.last_update_login,
6355           l_directItem_rec.operation_seq_num,
6356           l_directItem_rec.organization_id,
6357           l_directItem_rec.po_header_id,
6358           l_directItem_rec.po_line_id,
6359           l_directItem_rec.process_phase,
6360           l_directItem_rec.process_status,
6361           l_directItem_rec.program_update_date,
6362           l_directItem_rec.project_id,
6363           l_directItem_rec.reason_id,
6364           l_directItem_rec.reference,
6365           l_directItem_rec.standard_rate_flag,
6366           l_directItem_rec.task_id,
6367           l_directItem_rec.transaction_date,
6368           l_directItem_rec.transaction_quantity,
6369           l_directItem_rec.transaction_type,
6370           l_directItem_rec.transaction_uom,
6371           l_directItem_rec.wip_entity_id,
6372           l_item_id,
6373           l_source_doc_unit_of_measure
6374      from rcv_transactions  rti,
6375           po_distributions_all pod,
6376           po_lines_all pol
6377    where rti.transaction_id = l_txn_id
6378       and rti.po_distribution_id = pod.po_distribution_id
6379       and pol.po_line_id = pod.po_line_id;
6380 
6381    l_curr_rate := l_directItem_rec.currency_conversion_rate;
6382    l_curr_code := l_directItem_rec.currency_code;
6383 
6384     if (l_debug = 'Y') then
6385       fnd_file.put_line(fnd_file.log,'Actual resource rate: ' || to_char(l_actual_res_rate) ||
6386                                      'Currency Conv rate : ' ||to_char(l_curr_rate)||
6387                                      'Order Type Lookup Code : ' ||to_char( l_po_order_type_lookup_code));
6388     end if;
6389 
6390 
6391 ----------------------------------------------------------
6392 -- Bug 9356654 -WIP Encumbrance Enhancement Change 1 :To support Encumbrance for Direct items
6393 -- Calling NEW Encumbrance API to get encumbrance details for a delivery transaction id
6394 -- corresponding to Direct Item
6395 -- This API will
6396 ----------------------------------------------------------
6397 
6398     l_stmt_num := 35;
6399 
6400     Get_Encumbrance_Data(
6401      p_receiving_transaction_id  => l_txn_id ,
6402      p_api_version                => 1.0 ,
6403      x_encumbrance_amount         => l_encumbrance_amount,
6404      x_encumbrance_quantity       => l_encumbrance_quantity,
6405      x_encumbrance_ccid           => l_encumbrance_ccid,
6406      x_encumbrance_type_id        =>l_encumbrance_type_id,
6407      x_return_status              =>l_enc_return_status,
6408      x_msg_count                  =>l_enc_msg_count,
6409      x_msg_data                   =>l_enc_msg_data);
6410 
6411 
6412 	l_directItem_rec.ENCUMBRANCE_TYPE_ID  := l_encumbrance_type_id;
6413 	l_directItem_rec.ENCUMBRANCE_AMOUNT   := l_encumbrance_amount;
6414 	l_directItem_rec.ENCUMBRANCE_QUANTITY := l_encumbrance_quantity;
6415 	l_directItem_rec.ENCUMBRANCE_CCID     := l_encumbrance_ccid;
6416 
6417   -- End of the changes EAM Enc
6418 
6419 
6420 
6421 
6422     l_stmt_num := 40;
6423 
6424     if l_item_id is null then
6425 
6426 -- Get UOM code for the source document's UOM
6427 
6428      IF ( l_po_order_type_lookup_code <> 'FIXED PRICE') THEN /*ADDED FOR BUG 7668184*/
6429 
6430      SELECT uom_code
6431      INTO   l_source_doc_uom_code
6432      FROM   mtl_units_of_measure
6433      WHERE  unit_of_measure = l_source_doc_unit_of_measure;
6434 
6435      l_directItem_rec.primary_uom := l_source_doc_uom_code;
6436      l_directItem_rec.primary_quantity := l_quantity; /* populate primary_quantity as source doc quantity */
6437 
6438      END IF;
6439 
6440     else
6441 
6442     SELECT msi.primary_uom_code
6443       INTO l_directItem_rec.primary_uom
6444       from mtl_system_items_b msi
6445      where msi.inventory_item_id = l_item_id
6446        and msi.organization_id = l_directItem_rec.organization_id;
6447 
6448     l_directItem_rec.primary_quantity := inv_convert.inv_um_convert(
6449           l_item_id,
6450           NULL,
6451           l_directItem_rec.transaction_quantity, -- TRX quantity
6452           l_directItem_rec.transaction_uom,      -- TRX UOM
6453           l_directItem_rec.primary_uom,          -- PRI uom
6454           NULL,
6455           NULL);
6456 
6457     end if;
6458 
6459     /* Bug 4683371 : Removed the select statement added for Bug #1795350.
6460        The currency conversion rate should be  multiplied by the product of Unit Price * Quantity
6461        to obtain the correct transaction value. As we are not using the primary quantity here,
6462        we can defer the actual resource rate calculation till Cost Processing.   */
6463 
6464     /* Bug 2595198 - adjust actual resource rate against the primary uom quantity */
6465 
6466    /* No need to adjust quantity in case of Service Line Types
6467      - eAM Requirements Project R12 */
6468 
6469     IF ( l_po_order_type_lookup_code <> 'RATE'
6470          AND  l_po_order_type_lookup_code <> 'FIXED PRICE') THEN
6471       l_actual_res_rate := l_actual_res_rate * (l_quantity/l_directItem_rec.primary_quantity);
6472     END IF;
6473 
6474     if (l_debug = 'Y') then
6475       fnd_file.put_line(fnd_file.log,'Actual resource rate: ' || to_char(l_actual_res_rate));
6476     end if;
6477 
6478     l_directItem_rec.actual_resource_rate := l_actual_res_rate * l_curr_rate;
6479     l_directItem_rec.usage_rate_or_amount := l_actual_res_rate * l_curr_rate;
6480 
6481     -- Get rti details
6482     -- Bug 2304290: insert uom code instead of uom into l_directItem_rec
6483 
6484     /* Bug 3831013 : l_directItem_rec.primary_uom must be the base uom code of the class
6485                to which the transaction uom belongs and not the primary_unit_of_measure
6486                of rti */
6487 
6488 /*    l_stmt_num := 40;*/
6489 
6490     /* eAM  Requirements Project (R12) - Populate quantity as NULL for Service Line Types */
6491 /*    select (l_actual_res_rate * l_curr_rate),
6492            1,
6493            rti.last_updated_by,
6494            sysdate,
6495            l_actual_res_rate,
6496            rti.currency_code,
6497            nvl(l_directItem_rec.currency_conversion_date,rti.currency_conversion_date),
6498            l_curr_rate,
6499            nvl(l_directItem_rec.currency_conversion_type,rti.currency_conversion_type),
6500            rti.last_updated_by,
6501            sysdate,
6502            rti.last_update_login,
6503            rti.wip_operation_seq_num,
6504            rti.to_organization_id,
6505            rti.po_header_id,
6506            rti.po_line_id,
6507            decode(l_po_order_type_lookup_code, 'RATE',NULL,
6508                                                'FIXED PRICE', NULL,
6509                                                 rti.primary_quantity),
6510            muom.uom_code,
6511            2,
6512            1,
6513            sysdate,
6514            pod.project_id,
6515            rti.reason_id,
6516            rti.comments,
6517            2,
6518            pod.task_id,
6519            rti.transaction_date,
6520            decode(l_po_order_type_lookup_code, 'RATE',NULL,
6521                                                'FIXED PRICE', NULL,
6522                                                 rti.quantity),
6523            17,
6524            rti.uom_code,
6525            l_actual_res_rate * l_curr_rate,
6526            rti.wip_entity_id
6527      into l_directItem_rec.actual_resource_rate,
6528           l_directItem_rec.basis_type,
6529           l_directItem_rec.created_by,
6530           l_directItem_rec.creation_date,
6531           l_directItem_rec.currency_actual_rsc_rate,
6532           l_directItem_rec.currency_code,
6533           l_directItem_rec.currency_conversion_date,
6534           l_directItem_rec.currency_conversion_rate,
6535           l_directItem_rec.currency_conversion_type,
6536           l_directItem_rec.last_updated_by,
6537           l_directItem_rec.last_update_date,
6538           l_directItem_rec.last_update_login,
6539           l_directItem_rec.operation_seq_num,
6540           l_directItem_rec.organization_id,
6541           l_directItem_rec.po_header_id,
6542           l_directItem_rec.po_line_id,
6543           l_directItem_rec.primary_quantity,
6544           l_directItem_rec.primary_uom,
6545           l_directItem_rec.process_phase,
6546           l_directItem_rec.process_status,
6547           l_directItem_rec.program_update_date,
6548           l_directItem_rec.project_id,
6549           l_directItem_rec.reason_id,
6550           l_directItem_rec.reference,
6551           l_directItem_rec.standard_rate_flag,
6552           l_directItem_rec.task_id,
6553           l_directItem_rec.transaction_date,
6554           l_directItem_rec.transaction_quantity,
6555           l_directItem_rec.transaction_type,
6556           l_directItem_rec.transaction_uom,
6557           l_directItem_rec.usage_rate_or_amount,
6558           l_directItem_rec.wip_entity_id
6559      from rcv_transactions_interface rti,
6560           po_distributions_all pod,
6561           mtl_units_of_measure muom,
6562           mtl_units_of_measure puom
6563     where rti.interface_transaction_id = l_interface_txn_id
6564       and rti.po_distribution_id = pod.po_distribution_id
6565       and puom.unit_of_measure(+) = rti.unit_of_measure
6566       and muom.uom_class(+) = puom.uom_class
6567       and muom.base_uom_flag(+) = 'Y'
6568       and muom.language(+) = userenv('LANG');  */
6569 
6570     if (l_debug = 'Y') then
6571      fnd_file.put_line(fnd_file.log,'Populated direct item record for job ' || to_char(l_directItem_rec.wip_entity_id));
6572     end if;
6573 
6574 
6575     -- Obtain PO transaction type
6576     select transaction_type
6577     into l_po_txn_type
6578     from rcv_transactions_interface
6579     where interface_transaction_id = l_interface_txn_id;
6580 
6581     if (l_debug = 'Y') then
6582      fnd_file.put_line(fnd_file.log,'PO txn type is ' || l_po_txn_type);
6583    end if;
6584 
6585     -- Update sign on primary quantity
6586     l_stmt_num := 45;
6587     if ( l_po_order_type_lookup_code <> 'RATE'
6588          AND  l_po_order_type_lookup_code <> 'FIXED PRICE' AND
6589          (l_po_txn_type = 'RETURN TO RECEIVING' OR l_po_txn_type = 'RETURN TO VENDOR')) then
6590 
6591       l_directItem_rec.primary_quantity := -1 * abs(l_directItem_rec.primary_quantity);
6592       l_directItem_rec.transaction_quantity := -1 * abs(l_directItem_rec.transaction_quantity);
6593 
6594     end if;
6595     if (l_debug = 'Y') then
6596       fnd_file.put_line(fnd_file.log,'Primary quantity: ' || to_char(l_directItem_rec.primary_quantity));
6597     end if;
6598 
6599     -- Get WE details
6600     l_stmt_num := 50;
6601     select primary_item_id,
6602            wip_entity_name,
6603            entity_type
6604       into l_directItem_rec.primary_item_id,
6605            l_directItem_rec.wip_entity_name,
6606            l_directItem_rec.entity_type
6607       from wip_entities
6608      where wip_entity_id = l_directItem_rec.wip_entity_id;
6609 
6610      if (l_debug = 'Y') then
6611       fnd_file.put_line(fnd_file.log,'Job Name : ' || l_directItem_rec.wip_entity_name);
6612      end if;
6613 
6614     -- Get Department details
6615     l_stmt_num := 60;
6616     select wo.department_id,
6617            bd.department_code
6618       into l_directItem_rec.department_id,
6619            l_directitem_rec.department_code
6620       from wip_operations wo,
6621            bom_departments bd
6622      where wo.wip_entity_id = l_directItem_rec.wip_entity_id
6623        and wo.operation_seq_num = l_directItem_rec.operation_seq_num
6624        and wo.organization_id = l_directItem_rec.organization_id
6625        and bd.department_id = wo.department_id;
6626      if (l_debug = 'Y') then
6627        fnd_file.put_line(fnd_file.log,'Dept Code : ' || l_directitem_rec.department_code);
6628      end if;
6629 
6630     -- Default other attributes
6631     l_stmt_num := 70;
6632     select user_name
6633     into l_directItem_rec.created_by_name
6634     from fnd_user
6635     where user_id = l_directItem_rec.created_by;
6636     if (l_debug = 'Y') then
6637       fnd_file.put_line(fnd_file.log,'user name : ' || l_directItem_rec.created_by_name);
6638     end if;
6639 
6640     l_stmt_num := 80;
6641     select user_name
6642     into l_directItem_rec.last_updated_by_name
6643     from fnd_user
6644     where user_id = l_directItem_rec.last_updated_by;
6645     if (l_debug = 'Y') then
6646       fnd_file.put_line(fnd_file.log,'updated by ' || l_directItem_rec.last_updated_by);
6647     end if;
6648 
6649     l_stmt_num := 90;
6650     select organization_code
6651     into l_directItem_rec.organization_code
6652     from mtl_parameters
6653     where organization_id = l_directItem_rec.organization_id;
6654     if (l_debug = 'Y') then
6655       fnd_file.put_line(fnd_file.log,'organization code ' || l_directItem_rec.organization_code);
6656     end if;
6657 
6658     l_stmt_num := 100;
6659     if (l_directItem_rec.reason_id IS NOT NULL) then
6660          select reason_name
6661          into l_directItem_rec.reason_name
6662          from mtl_transaction_reasons
6663          where reason_id = l_directItem_rec.reason_id;
6664          if (l_debug = 'Y') then
6665            fnd_file.put_line(fnd_file.log,'reason name ' || l_directItem_rec.reason_name);
6666          end if;
6667     end if;
6668 
6669 
6670     -- Update out variable
6671     l_stmt_num := 110;
6672     x_directItem_rec := l_directItem_rec;
6673 
6674     -- Insert/Update rows in WEDI/WRO
6675     l_stmt_num := 120;
6676     WIP_EAM_RESOURCE_TRANSACTION.WIP_EAMRCVDIRECTITEM_HOOK(
6677       p_api_version   => 1.0,
6678       p_rcv_txn_id    => l_directItem_rec.rcv_transaction_id,
6679       p_primary_qty   => l_directItem_rec.primary_quantity,
6680       p_primary_uom   => l_directItem_rec.primary_uom,
6681       p_unit_price    => l_directItem_rec.actual_resource_rate,
6682       x_return_status => l_return_status,
6683       x_msg_count     => l_msg_count,
6684       x_msg_data      => l_msg_data
6685     );
6686 
6687     IF l_return_status <> FND_API.g_ret_sts_success THEN
6688        FND_FILE.put_line(FND_FILE.log, l_msg_data);
6689        l_api_message := 'WIP_EAM_RESOURCE_TRANSACTION.WIP_EAMRCVDIRECTITEM_HOOK returned error';
6690        FND_MESSAGE.set_name('BOM','CST_API_MESSAGE');
6691        FND_MESSAGE.set_token('TEXT', l_api_message);
6692        FND_MSG_pub.add;
6693        RAISE FND_API.g_exc_error;
6694     END IF;
6695 
6696     -- Standard check of p_commit
6697     IF FND_API.to_Boolean(p_commit) THEN
6698        COMMIT WORK;
6699     END IF;
6700 
6701     -- Standard Call to get message count and if count = 1, get message info
6702     FND_MSG_PUB.Count_And_Get (
6703            p_count     => x_msg_count,
6704            p_data      => x_msg_data );
6705 
6706    -- Print messages to log file
6707 
6708 
6709     EXCEPTION
6710       WHEN fnd_api.g_exc_error THEN
6711          ROLLBACK TO process_direct_item_txn_PUB;
6712          x_return_status := fnd_api.g_ret_sts_error;
6713 
6714         --  Get message count and data
6715         fnd_msg_pub.count_and_get
6716              (  p_count => x_msg_count
6717               , p_data  => x_msg_data
6718               );
6719 
6720       WHEN fnd_api.g_exc_unexpected_error THEN
6721             ROLLBACK TO process_direct_item_txn_PUB;
6722             x_return_status := fnd_api.g_ret_sts_unexp_error ;
6723 
6724         --  Get message count and data
6725         fnd_msg_pub.count_and_get
6726           (  p_count  => x_msg_count
6727            , p_data   => x_msg_data
6728             );
6729       --
6730    WHEN OTHERS THEN
6731       ROLLBACK TO process_direct_item_txn_PUB;
6732       x_return_status := fnd_api.g_ret_sts_unexp_error ;
6733       --
6734       IF fnd_msg_pub.check_msg_level(fnd_msg_pub.g_msg_lvl_unexp_error)
6735         THEN
6736          fnd_msg_pub.add_exc_msg
6737            (  'CST_eamCost_PUB'
6738               , 'process_direct_item_txn : Statement - '|| to_char(l_stmt_num)
6739               );
6740 
6741       END IF;
6742 
6743       --  Get message count and data
6744       fnd_msg_pub.count_and_get
6745           (  p_count  => x_msg_count
6746            , p_data   => x_msg_data
6747            );
6748 END process_direct_item_txn;
6749 
6750 
6751 ----------------------------------------------------------------------------
6752 -- PROCEDURE                                                              --
6753 --   cost_direct_item_txn                                                 --
6754 -- DESCRIPTION                                                            --
6755 --   cost a transaction record from wip_cost_txn_interface                --
6756 --    * new transaction type called Direct Shopfloor Delivery             --
6757 --    * called by cmlctw                                                  --
6758 --    * inserts debits and credits into wip_transaction_accounts          --
6759 --    * update eam asset cost and asset period balances                   --
6760 -- PURPOSE:                                                               --
6761 --   procedure that costs a direct item transaction and does              --
6762 --   accounting                                                           --
6763 -- HISTORY:                                                               --
6764 --   05/01/01           Anitha Dixit            Created                   --
6765 ----------------------------------------------------------------------------
6766 PROCEDURE cost_direct_item_txn (
6767                 p_api_version                   IN      NUMBER,
6768                 p_init_msg_list                 IN      VARCHAR2 := FND_API.G_FALSE,
6769                 p_commit                        IN      VARCHAR2 := FND_API.G_FALSE,
6770                 p_validation_level              IN      VARCHAR2 := FND_API.G_VALID_LEVEL_FULL,
6771 
6772                 p_group_id                      IN      NUMBER,
6773                 p_prg_appl_id                   IN      NUMBER,
6774                 p_prg_id                        IN      NUMBER,
6775                 p_request_id                    IN      NUMBER,
6776                 p_user_id                       IN      NUMBER,
6777                 p_login_id                      IN      NUMBER,
6778 
6779                 x_return_status                 OUT NOCOPY     VARCHAR2,
6780                 x_msg_count                     OUT NOCOPY     NUMBER,
6781                 x_msg_data                      OUT NOCOPY     VARCHAR2
6782                 ) IS
6783 
6784   l_api_name    CONSTANT        VARCHAR2(30) := 'cost_direct_item_txn';
6785   l_api_version CONSTANT        NUMBER       := 1.0;
6786 
6787   l_return_status       VARCHAR2(1) := fnd_api.g_ret_sts_success;
6788   l_msg_count           NUMBER := 0;
6789   l_msg_data            VARCHAR2(8000);
6790   l_stmt_num            NUMBER := 0;
6791 
6792   l_func_curr_code      NUMBER;
6793   l_func_mau            NUMBER;
6794   l_func_precision      NUMBER;
6795   l_txn_value           NUMBER;
6796   l_base_txn_value      NUMBER;
6797   l_wip_acct            NUMBER;
6798   l_acct_line_type      NUMBER;
6799 
6800   l_count               NUMBER := -1;
6801   l_api_message         VARCHAR2(1000);
6802   l_debug               VARCHAR2(80);
6803   l_cost_element        NUMBER := 1;
6804 
6805   l_organization_id     NUMBER;
6806 
6807   CURSOR direct_item_txn_cur IS
6808     select wcti.transaction_id,
6809            wcti.organization_id,
6810            nvl(wcti.acct_period_id,-1) acct_period_id,
6811            nvl(wcti.receiving_account_id,-1) rcv_acct_id,
6812            nvl(wcti.actual_resource_rate,0) act_res_rate,
6813            nvl(wcti.currency_actual_resource_rate, 0) curr_act_res_rate,
6814            wcti.wip_entity_id,
6815            wcti.operation_seq_num opseq_num,
6816            wcti.primary_quantity qty,
6817            wcti.source_code src_code,
6818            to_char(wcti.transaction_date,'YYYY/MM/DD HH24:MI:SS') txn_date,
6819            wcti.rcv_transaction_id,
6820            wcti.currency_code,                   /* bug 4683371 */
6821            wcti.currency_conversion_rate,        /* bug 4683371 */
6822           ----------------------------------------------------
6823           -- BUG#9356654 Added for WIP encumbrance enhancement
6824           ----------------------------------------------------
6825            wcti.encumbrance_type_id,
6826            wcti.encumbrance_amount,
6827            wcti.encumbrance_quantity,
6828            wcti.encumbrance_ccid,
6829            mp.encumbrance_reversal_flag
6830 	from wip_cost_txn_interface  wcti
6831 	,    mtl_parameters          mp
6832     where wcti.group_id = p_group_id
6833       and wcti.process_status = 2
6834 	  and wcti.organization_id = mp.organization_id;
6835 
6836 
6837   BEGIN
6838 
6839     --  Standard Start of API savepoint
6840     SAVEPOINT cost_direct_item_txn_PUB;
6841 
6842     l_debug := fnd_profile.value('MRP_DEBUG');
6843 
6844     -- Standard call to check for call compatibility
6845     IF NOT FND_API.Compatible_API_Call (
6846                         l_api_version,
6847                         p_api_version,
6848                         l_api_name,
6849                         G_PKG_NAME ) THEN
6850           RAISE FND_API.G_EXC_UNEXPECTED_ERROR;
6851     END IF;
6852 
6853     -- Initialize message list if p_init_msg_list is set to TRUE
6854     IF FND_API.to_Boolean(p_init_msg_list) THEN
6855         FND_MSG_PUB.initialize;
6856     END IF;
6857 
6858     -- Initialize API return status to success
6859     l_stmt_num := 10;
6860     x_return_status := FND_API.G_RET_STS_SUCCESS;
6861 
6862     l_stmt_num := 50;
6863     -- Loop through all direct item transactions
6864     FOR direct_item_txn_rec IN direct_item_txn_cur LOOP
6865 
6866           if (l_debug = 'Y') then
6867             fnd_file.put_line(fnd_file.log,'Transaction ID ' || to_char(direct_item_txn_rec.transaction_id));
6868           end if;
6869        /* Organization_id is the same for the entire group */
6870        l_organization_id := direct_item_txn_rec.organization_id;
6871 
6872           l_stmt_num := 60;
6873           -- Obtain transaction value and line type
6874 
6875         /* Added the select statements in the IF clause  for bug 4683371. The transaction value is
6876             first calculated and then rounded with standard precision of the functional currency*/
6877 
6878           /* Removed the select statement that fetched actual resource rate in functional
6879              currency for IPV xrf txns as actual resource rate is correctly populated in WCTI,
6880              no need to convert the value. Bug 5360723 */
6881           if (direct_item_txn_rec.src_code = 'IPV') then
6882              l_txn_value := direct_item_txn_rec.curr_act_res_rate;
6883              l_base_txn_value := direct_item_txn_rec.act_res_rate;
6884              l_acct_line_type := 2;
6885           else
6886 
6887            /* As part of eAM Reuirements Project (R12) - for PO Service Line Types,
6888               quantity column in WCTI will have NULL value */
6889              if (direct_item_txn_rec.qty is NULL) then
6890              select decode(nvl(fc.minimum_accountable_unit,0),0,
6891                            round(direct_item_txn_rec.act_res_rate,fc.precision),
6892                            round(direct_item_txn_rec.act_res_rate/fc.minimum_accountable_unit)
6893                                 *fc.minimum_accountable_unit) ,
6894                     (decode(nvl(fc.minimum_accountable_unit,0),0,
6895                            round(direct_item_txn_rec.act_res_rate,fc.precision),
6896                            round(direct_item_txn_rec.act_res_rate/fc.minimum_accountable_unit)
6897                                 *fc.minimum_accountable_unit)) / nvl(direct_item_txn_rec.currency_conversion_rate,1)
6898              into l_base_txn_value,
6899                   l_txn_value
6900              from fnd_currencies fc
6901              where currency_code = direct_item_txn_rec.currency_code;
6902 
6903              else
6904              select decode(nvl(fc.minimum_accountable_unit,0),0,
6905                             round(direct_item_txn_rec.act_res_rate * direct_item_txn_rec.qty ,fc.precision),
6906                             round(direct_item_txn_rec.act_res_rate * direct_item_txn_rec.qty /fc.minimum_accountable_unit)
6907                                           *fc.minimum_accountable_unit),
6908                     ( decode(nvl(fc.minimum_accountable_unit,0),0,
6909                             round(direct_item_txn_rec.act_res_rate * direct_item_txn_rec.qty ,fc.precision),
6910                             round(direct_item_txn_rec.act_res_rate * direct_item_txn_rec.qty /fc.minimum_accountable_unit)
6911                                           *fc.minimum_accountable_unit)) / nvl(direct_item_txn_rec.currency_conversion_rate,1)
6912                        into l_base_txn_value,
6913                             l_txn_value
6914                        from fnd_currencies fc
6915              where currency_code = direct_item_txn_rec.currency_code;
6916 
6917              end if;
6918              l_acct_line_type := 5;
6919           end if;
6920 
6921           if (l_debug = 'Y') then
6922             fnd_file.put_line(fnd_file.log,'Transaction value ' || to_char(l_txn_value));
6923             fnd_file.put_line(fnd_file.log,'Base Transaction value ' || to_char(l_base_txn_value));
6924             fnd_file.put_line(fnd_file.log,'Quantity ' || to_char(direct_item_txn_rec.qty));
6925           end if;
6926 
6927           l_stmt_num := 80;
6928           if (l_debug = 'Y') then
6929            fnd_file.put_line(fnd_file.log,'Insert RI account ' || to_char(direct_item_txn_rec.rcv_acct_id));
6930           end if;
6931 
6932           -- Insert line for receiving inspection if it's not an IPV transfer
6933           -- Insert line for account (adjusment account) if it's an IPV transfer
6934           insert_direct_item_distr (
6935                   p_api_version         =>        1.0,
6936                   p_txn_id                =>        direct_item_txn_rec.transaction_id,
6937                   p_ref_acct                =>        direct_item_txn_rec.rcv_acct_id,
6938                   p_txn_value                =>        -1 * l_txn_value,
6939                   p_base_txn_value      =>      -1 * l_base_txn_value,
6940                   p_wip_entity_id       =>        direct_item_txn_rec.wip_entity_id,
6941                   p_acct_line_type      =>        l_acct_line_type,
6942                   p_prg_appl_id         =>      p_prg_appl_id,
6943                   p_prg_id              =>      p_prg_id,
6944                   p_request_id          =>      p_request_id,
6945                   p_user_id             =>      p_user_id,
6946                   p_login_id            =>      p_login_id,
6947                   x_return_status        =>        x_return_status,
6948                   x_msg_count                =>        x_msg_count,
6949                   x_msg_data                =>        x_msg_data
6950                   ,p_enc_insert_flag        =>  direct_item_txn_rec.encumbrance_reversal_flag
6951                   );
6952 
6953            if (x_return_status <> fnd_api.g_ret_sts_success) then
6954                 raise fnd_api.g_exc_unexpected_error;
6955            end if;
6956 
6957 
6958 
6959 
6960 
6961 	   --{ Bug 9356654 WIP Encumbrance enhancement Change 2
6962 
6963 	   l_stmt_num := 85;
6964 	   IF  (    direct_item_txn_rec.encumbrance_type_id  IS NOT NULL
6965 	        AND direct_item_txn_rec.encumbrance_ccid     IS NOT NULL
6966 	        AND NVL(direct_item_txn_rec.encumbrance_amount,0) <> 0
6967 		)THEN
6968 
6969 
6970 
6971 		l_acct_line_type := 15;
6972 		insert_direct_item_distr (
6973                   p_api_version         =>   1.0,
6974                   p_txn_id              =>   direct_item_txn_rec.transaction_id,
6975                   p_ref_acct            =>   direct_item_txn_rec.encumbrance_ccid,
6976                   p_txn_value           =>   NULL, /* Will be calculated within API */
6977                   p_base_txn_value      =>   direct_item_txn_rec.encumbrance_amount, -- HYU Discussed we need to detect returns
6978                   p_wip_entity_id       =>   direct_item_txn_rec.wip_entity_id,
6979                   p_acct_line_type      =>   l_acct_line_type,
6980                   p_prg_appl_id         =>   p_prg_appl_id,
6981                   p_prg_id              =>   p_prg_id,
6982                   p_request_id          =>   p_request_id,
6983                   p_user_id             =>   p_user_id,
6984                   p_login_id            =>   p_login_id,
6985                   x_return_status       =>   x_return_status,
6986                   x_msg_count           =>   x_msg_count,
6987                   x_msg_data            =>   x_msg_data
6988                   ,p_enc_insert_flag        =>  direct_item_txn_rec.encumbrance_reversal_flag
6989                   );
6990 
6991 		IF (x_return_status <> fnd_api.g_ret_sts_success) then
6992 			raise fnd_api.g_exc_unexpected_error;
6993 		END IF;
6994 
6995 	   END IF;
6996 
6997 
6998 	   --} WIP Encumbrance enhancement ends
6999 
7000           l_stmt_num := 90;
7001           -- Obtain material account for the job
7002           get_CostEle_for_DirectItem (
7003             p_api_version        =>        1.0,
7004             p_init_msg_list        =>        p_init_msg_list,
7005             p_commit                =>        p_commit,
7006             p_validation_level        =>        p_validation_level,
7007             x_return_status        =>        l_return_status,
7008             x_msg_count                =>        l_msg_count,
7009             x_msg_data                =>        l_msg_data,
7010             p_txn_id                =>        direct_item_txn_rec.transaction_id,
7011             p_mnt_or_mfg        =>        2,
7012             x_cost_element_id        =>        l_cost_element
7013             );
7014 
7015           if (l_return_status <> fnd_api.g_ret_sts_success) then
7016             FND_FILE.put_line(FND_FILE.log, x_msg_data);
7017             l_api_message := 'get_CostEle_for_DirectItem returned unexpected error';
7018             FND_MESSAGE.set_name('BOM','CST_API_MESSAGE');
7019             FND_MESSAGE.set_token('TEXT', l_api_message);
7020             FND_MSG_pub.add;
7021             raise fnd_api.g_exc_unexpected_error;
7022           end if;
7023 
7024           if (l_debug = 'Y') then
7025             FND_FILE.PUT_LINE(FND_FILE.LOG, 'mfg cost_element_id: '|| to_char(l_cost_element));
7026           end if;
7027 
7028           select decode(l_cost_element, 1, nvl(material_account,-1),
7029                                         3, nvl(resource_account, -1),
7030                                         4, nvl(outside_processing_account, -1), -1)
7031           into l_wip_acct
7032           from wip_discrete_jobs
7033           where wip_entity_id = direct_item_txn_rec.wip_entity_id;
7034 
7035           l_stmt_num := 100;
7036           -- Insert line for WIP valuation
7037           if (l_debug = 'Y') then
7038             fnd_file.put_line(fnd_file.log,'Insert WIP material acct ' || to_char(l_wip_acct));
7039           end if;
7040 
7041 
7042           insert_direct_item_distr (
7043                   p_api_version         =>      1.0,
7044                   p_txn_id              =>      direct_item_txn_rec.transaction_id,
7045                   p_ref_acct            =>      l_wip_acct,
7046                   p_txn_value           =>      l_txn_value,
7047                   p_base_txn_value      =>      l_base_txn_value,
7048                   p_wip_entity_id       =>        direct_item_txn_rec.wip_entity_id,
7049                   p_acct_line_type      =>      7,
7050                   p_prg_appl_id         =>        p_prg_appl_id,
7051                   p_prg_id                =>        p_prg_id,
7052                   p_request_id                =>        p_request_id,
7053                   p_user_id                =>        p_user_id,
7054                   p_login_id                =>        p_login_id,
7055                   x_return_status       =>      x_return_status,
7056                   x_msg_count           =>      x_msg_count,
7057                   x_msg_data            =>      x_msg_data
7058                   ,p_enc_insert_flag        =>  direct_item_txn_rec.encumbrance_reversal_flag
7059                   );
7060 
7061            if (x_return_status <> fnd_api.g_ret_sts_success) then
7062                 raise fnd_api.g_exc_unexpected_error;
7063            end if;
7064 
7065 
7066           -- Update wip period balances , pl_material_in
7067           l_stmt_num := 110;
7068           if (l_debug = 'Y') then
7069             fnd_file.put_line(fnd_file.log,'Update wip_period_balances');
7070           end if;
7071 
7072           update_wip_period_balances (
7073                   p_api_version                =>        1.0,
7074                   p_wip_entity_id        =>        direct_item_txn_rec.wip_entity_id,
7075                   p_acct_period_id        =>        direct_item_txn_rec.acct_period_id,
7076                   p_txn_id                =>        direct_item_txn_rec.transaction_id,
7077                   p_prg_appl_id         =>      p_prg_appl_id,
7078                   p_prg_id              =>      p_prg_id,
7079                   p_request_id          =>      p_request_id,
7080                   p_user_id             =>      p_user_id,
7081                   p_login_id            =>      p_login_id,
7082                   x_return_status        =>      x_return_status,
7083                   x_msg_count                =>        x_msg_count,
7084                   x_msg_data                 =>        x_msg_data
7085                   );
7086 
7087            if (x_return_status <> fnd_api.g_ret_sts_success) then
7088                 raise fnd_api.g_exc_unexpected_error;
7089            end if;
7090 
7091           -- update wip_eam_asset_per_balances material cost
7092           l_stmt_num := 120;
7093           if (l_debug = 'Y') then
7094             fnd_file.put_line(fnd_file.log,'Update eamcost');
7095           end if;
7096 
7097             update_eamCost (
7098                 p_api_version           =>      1.0,
7099                 p_validation_level      =>      p_validation_level,
7100                 x_return_status         =>      x_return_status,
7101                 x_msg_count             =>      x_msg_count,
7102                 x_msg_data              =>      x_msg_data,
7103                 p_txn_mode              =>      4, /* Direct Item */
7104                 p_period_id             =>      direct_item_txn_rec.acct_period_id,
7105                 p_org_id                =>      direct_item_txn_rec.organization_id,
7106                 p_wip_entity_id         =>      direct_item_txn_rec.wip_entity_id,
7107                 p_opseq_num             =>      direct_item_txn_rec.opseq_num,
7108                 p_value_type            =>      1,
7109              /* Bug 2924311: the following parameter should contain the base transaction value */
7110                 p_value                 =>      l_base_txn_value,
7111                 p_user_id               =>      p_user_id,
7112                 p_request_id            =>      p_request_id,
7113                 p_prog_id               =>      p_prg_id,
7114                 p_prog_app_id           =>      p_prg_appl_id,
7115                 p_login_id              =>      p_login_id,
7116                 p_txn_date              =>        direct_item_txn_rec.txn_date,
7117                 p_txn_id                =>        direct_item_txn_rec.transaction_id
7118                 );
7119 
7120            if (x_return_status <> fnd_api.g_ret_sts_success) then
7121                 raise fnd_api.g_exc_unexpected_error;
7122            end if;
7123       END LOOP; /* for transactions */
7124 
7125       /* insert_direct_item_txn */
7126       l_stmt_num := 130;
7127       if (l_debug = 'Y') then
7128         fnd_file.put_line(fnd_file.log,'Insert direct item transaction');
7129       end if;
7130       insert_direct_item_txn (
7131                   p_api_version                =>        1.0,
7132                   p_group_id                =>        p_group_id,
7133                   p_prg_appl_id         =>      p_prg_appl_id,
7134                   p_prg_id              =>      p_prg_id,
7135                   p_request_id          =>      p_request_id,
7136                   p_user_id             =>      p_user_id,
7137                   p_login_id            =>      p_login_id,
7138                   x_return_status       =>      x_return_status,
7139                   x_msg_count           =>      x_msg_count,
7140                   x_msg_data            =>      x_msg_data
7141                   );
7142 
7143            if (x_return_status <> fnd_api.g_ret_sts_success) then
7144                 raise fnd_api.g_exc_unexpected_error;
7145            end if;
7146 
7147     l_stmt_num := 135;
7148     /* Create the Events for the transactions in the WCTI group */
7149 
7150     CST_XLA_PVT.CreateBulk_WIPXLAEvent(
7151       p_api_version      => 1.0,
7152       p_init_msg_list    => FND_API.G_FALSE,
7153       p_commit           => FND_API.G_FALSE,
7154       p_validation_level => FND_API.G_VALID_LEVEL_FULL,
7155       x_return_status    => l_return_status,
7156       x_msg_count        => x_msg_count,
7157       x_msg_data         => x_msg_data,
7158       p_wcti_group_id    => p_group_id,
7159       p_organization_id  => l_organization_id );
7160 
7161     IF l_return_status <> FND_API.G_RET_STS_SUCCESS THEN
7162       RAISE FND_API.G_EXC_UNEXPECTED_ERROR;
7163     END IF;
7164 
7165     l_stmt_num := 140;
7166     if (l_debug = 'Y') then
7167      fnd_file.put_line(fnd_file.log,'Delete from wcti');
7168     end if;
7169     delete from wip_cost_txn_interface
7170     where group_id = p_group_id
7171     and process_status = 2;
7172 
7173     -- Standard check of p_commit
7174     IF FND_API.to_Boolean(p_commit) THEN
7175        COMMIT WORK;
7176     END IF;
7177 
7178     -- Standard Call to get message count and if count = 1, get message info
7179     FND_MSG_PUB.Count_And_Get (
7180            p_count     => x_msg_count,
7181            p_data      => x_msg_data );
7182 
7183    -- Print messages to log file
7184 
7185 
7186     EXCEPTION
7187       WHEN fnd_api.g_exc_error THEN
7188          ROLLBACK TO cost_direct_item_txn_PUB;
7189          x_return_status := fnd_api.g_ret_sts_error;
7190 
7191         --  Get message count and data
7192         fnd_msg_pub.count_and_get
7193              (  p_count => x_msg_count
7194               , p_data  => x_msg_data
7195               );
7196 
7197       WHEN fnd_api.g_exc_unexpected_error THEN
7198             ROLLBACK TO cost_direct_item_txn_PUB;
7199             x_return_status := fnd_api.g_ret_sts_unexp_error ;
7200 
7201         --  Get message count and data
7202         fnd_msg_pub.count_and_get
7203           (  p_count  => x_msg_count
7204            , p_data   => x_msg_data
7205             );
7206       --
7207    WHEN OTHERS THEN
7208       ROLLBACK TO cost_direct_item_txn_PUB;
7209       x_return_status := fnd_api.g_ret_sts_unexp_error ;
7210       fnd_file.put_line(fnd_file.log,'CST_eamCost_PUB.cost_direct_item_txn: Statement(' || to_char(l_stmt_num) || '): ' || substr(SQLERRM,1,240));
7211       IF fnd_msg_pub.check_msg_level(fnd_msg_pub.g_msg_lvl_unexp_error)
7212         THEN
7213          fnd_msg_pub.add_exc_msg
7214            (  'CST_eamCost_PUB'
7215               , 'cost_direct_item_txn : Statement - '|| to_char(l_stmt_num)
7216               );
7217 
7218       END IF;
7219 
7220       --  Get message count and data
7221       fnd_msg_pub.count_and_get
7222           (  p_count  => x_msg_count
7223            , p_data   => x_msg_data
7224            );
7225 END cost_direct_item_txn;
7226 
7227 
7228 ----------------------------------------------------------------------------
7229 -- PROCEDURE                                                              --
7230 --   insert_direct_item_distr                                             --
7231 --                                                                        --
7232 -- DESCRIPTION                                                            --
7233 --   insert accounting into wip_transaction_accounts                      --
7234 --    * WIP valuation account used is material account                    --
7235 --    * Offset against Receiving Inspection account                       --
7236 --    * Accounting done at actuals (PO price + non recoverable tax)       --
7237 -- PURPOSE:                                                               --
7238 --   insert accounting into wip_transaction_accounts                      --
7239 -- HISTORY:                                                               --
7240 --   05/01/01           Anitha Dixit            Created                   --
7241 ----------------------------------------------------------------------------
7242 
7243 PROCEDURE insert_direct_item_distr (
7244                 p_api_version                        IN        NUMBER,
7245                  p_init_msg_list                        IN        VARCHAR2 := FND_API.G_FALSE,
7246                 p_commit                        IN        VARCHAR2 := FND_API.G_FALSE,
7247                 p_validation_level                IN        VARCHAR2 := FND_API.G_VALID_LEVEL_FULL,
7248 
7249                 p_txn_id                        IN         NUMBER,
7250                 p_ref_acct                        IN        NUMBER,
7251                 p_txn_value                        IN        NUMBER,
7252                 p_base_txn_value                IN      NUMBER,
7253                 p_wip_entity_id                        IN        NUMBER,
7254                 p_acct_line_type                IN        NUMBER,
7255                 p_prg_appl_id                   IN        NUMBER,
7256                 p_prg_id                        IN        NUMBER,
7257                 p_request_id                    IN        NUMBER,
7258                 p_user_id                       IN        NUMBER,
7259                 p_login_id                      IN        NUMBER,
7260 
7261                 x_return_status                        OUT NOCOPY        VARCHAR2,
7262                 x_msg_count                        OUT NOCOPY        NUMBER,
7263                 x_msg_data                        OUT NOCOPY        VARCHAR2
7264                   ,p_enc_insert_flag            IN       NUMBER DEFAULT 1
7265                 ) IS
7266 
7267   l_api_name    CONSTANT        VARCHAR2(30) := 'insert_direct_item_distr';
7268   l_api_version CONSTANT        NUMBER              := 1.0;
7269 
7270   l_return_status       VARCHAR2(1) := fnd_api.g_ret_sts_success;
7271   l_msg_count           NUMBER := 0;
7272   l_msg_data            VARCHAR2(8000);
7273   l_stmt_num            NUMBER := 0;
7274 
7275   l_currency            VARCHAR2(30);
7276   l_func_currency       VARCHAR2(30);
7277   l_org_id              NUMBER;
7278   l_txn_value           NUMBER;
7279   l_base_txn_value      NUMBER;
7280   l_cost_element        NUMBER; /* Direct Item Acct Enh Project */
7281 
7282   l_api_message         VARCHAR2(1000);
7283   l_debug               VARCHAR2(80);
7284   l_need_enc            VARCHAR2(1) := 'Y';
7285 
7286   l_same_currency       NUMBER := 1;  --Bug 9356654 WIP Encumbrance enhancement
7287   l_source_code         VARCHAR2(10);
7288 
7289   BEGIN
7290 
7291     --  Standard Start of API savepoint
7292     SAVEPOINT insert_direct_item_distr_PUB;
7293 
7294     l_debug := fnd_profile.value('MRP_DEBUG');
7295 
7296     -- Standard call to check for call compatibility
7297     IF NOT FND_API.Compatible_API_Call (
7298                         l_api_version,
7299                         p_api_version,
7300                         l_api_name,
7301                         G_PKG_NAME ) THEN
7302           RAISE FND_API.G_EXC_UNEXPECTED_ERROR;
7303     END IF;
7304 
7305     -- Initialize message list if p_init_msg_list is set to TRUE
7306     IF FND_API.to_Boolean(p_init_msg_list) THEN
7307         FND_MSG_PUB.initialize;
7308     END IF;
7309 
7310     -- Initialize API return status to success
7311     l_stmt_num := 10;
7312     x_return_status := FND_API.G_RET_STS_SUCCESS;
7313 
7314 
7315     -- Verify account
7316     l_stmt_num := 20;
7317     if (p_ref_acct = -1) then
7318           RAISE fnd_api.g_exc_error;
7319     end if;
7320 
7321     -- Get transaction details
7322     l_stmt_num := 30;
7323     select organization_id, currency_code,source_code
7324     into l_org_id,l_currency,l_source_code
7325     from wip_cost_txn_interface
7326     where transaction_id = p_txn_id;
7327 
7328     -- DBMS_OUTPUT.PUT_LINE('Currency ' || l_currency);
7329     -- Get functional currency
7330     l_stmt_num := 40;
7331 
7332    /* The following select statement will be modified to refer to
7333       cst_organization_definitions as an impact of the HR-PROFILE option. */
7334 
7335     select ood.currency_code
7336     into l_func_currency
7337     from cst_organization_definitions ood
7338     where ood.organization_id = l_org_id;
7339 
7340 
7341     -- Get txn value and base txn value
7342     l_stmt_num := 50;
7343 
7344     /* Bug 9356654 Encumbrnce enhancement for direct item */
7345     IF p_acct_line_type = 15 THEN
7346         l_base_txn_value := p_base_txn_value;
7347 	if (nvl(l_currency,l_func_currency) = l_func_currency) then
7348 	l_txn_value := null;
7349 	l_same_currency := 1;
7350 	else
7351 	 l_same_currency := 0;
7352 	end if ;
7353 
7354 
7355         --BUG#9356654 Do not insert encumbrance line if encumbrance reversal flag is unchecked
7356         IF  p_enc_insert_flag = 2 THEN
7357 	   l_need_enc := 'N';
7358            RETURN;
7359         END IF;
7360 
7361     ELSE
7362 
7363 
7364     if (nvl(l_currency,l_func_currency) = l_func_currency) then
7365          l_txn_value := null;
7366 
7367          l_stmt_num := 60;
7368          select decode(minimum_accountable_unit,null,
7369                         decode(precision, null, p_base_txn_value, round(p_base_txn_value,precision)),
7370                         0, decode(precision, null, p_base_txn_value, round(p_base_txn_value,precision)),
7371                         round(p_base_txn_value/minimum_accountable_unit) * minimum_accountable_unit)
7372          into l_base_txn_value
7373          from fnd_currencies
7374          where currency_code = l_func_currency;
7375     else
7376          l_stmt_num := 70;
7377          select decode(minimum_accountable_unit,null,
7378                         decode(precision, null, p_txn_value, round(p_txn_value,precision)),
7379                         0, decode(precision, null, p_txn_value, round(p_txn_value,precision)),
7380                         round(p_txn_value/minimum_accountable_unit) * minimum_accountable_unit)
7381          into l_txn_value
7382          from fnd_currencies
7383          where currency_code = l_currency;
7384 
7385          l_stmt_num := 90;
7386          select decode(minimum_accountable_unit,null,
7387                    decode(precision, null, p_base_txn_value, round(p_base_txn_value,precision)),
7388                    0, decode(precision, null, p_base_txn_value, round(p_base_txn_value,precision)),
7389                    round((p_base_txn_value)/minimum_accountable_unit) * minimum_accountable_unit)
7390          into l_base_txn_value
7391          from fnd_currencies
7392          where currency_code = l_func_currency;
7393     end if;
7394 
7395     END IF; /* p_acct_line_type = 15 */
7396 
7397 
7398     if (l_debug = 'Y') then
7399           fnd_file.put_line(fnd_file.log,'Txn value: ' || to_char(l_txn_value));
7400           fnd_file.put_line(fnd_file.log,'Base txn value: ' || to_char(l_base_txn_value));
7401     end if;
7402 
7403 
7404     /* Bug 9356654 WIP Encumbrance enhancement
7405     For Encumbrance line cost element id should be null
7406     */
7407     IF (p_acct_line_type <> 15) THEN
7408 
7409     l_stmt_num := 95;
7410     /* Direct Item Acct Enh (Patchset J) */
7411     get_CostEle_for_DirectItem (
7412       p_api_version             =>        1.0,
7413       p_init_msg_list           =>        p_init_msg_list,
7414       p_commit                  =>        p_commit,
7415       p_validation_level        =>        p_validation_level,
7416       x_return_status           =>        l_return_status,
7417       x_msg_count               =>        l_msg_count,
7418       x_msg_data                =>        l_msg_data,
7419       p_txn_id                  =>        p_txn_id,
7420       p_mnt_or_mfg              =>        2,
7421       x_cost_element_id         =>        l_cost_element
7422       );
7423 
7424     if (l_return_status <> fnd_api.g_ret_sts_success) then
7425       FND_FILE.put_line(FND_FILE.log, x_msg_data);
7426       l_api_message := 'get_CostEle_for_DirectItem returned unexpected error';
7427       FND_MESSAGE.set_name('BOM','CST_API_MESSAGE');
7428       FND_MESSAGE.set_token('TEXT', l_api_message);
7429       FND_MSG_pub.add;
7430       raise fnd_api.g_exc_unexpected_error;
7431     end if;
7432 
7433     if (l_debug = 'Y') then
7434       FND_FILE.PUT_LINE(FND_FILE.LOG,'mfg cost_element_id: '|| to_char(l_cost_element));
7435     end if;
7436 
7437     END IF; --p_acct_line_type <> 15
7438 
7439     -- insert into wip_transaction_accounts
7440     l_stmt_num := 100;
7441 
7442     IF ((p_acct_line_type <> 15) OR (l_need_enc = 'Y')) AND (l_source_code <> 'IPV') THEN
7443     Insert into wip_transaction_accounts (
7444                         wip_sub_ledger_id,
7445                         transaction_id,
7446                         reference_account,
7447                         last_update_date,
7448                         last_updated_by,
7449                         creation_date,
7450                         created_by,
7451                         last_update_login,
7452                         organization_id,
7453                         transaction_date,
7454                         wip_entity_id,
7455                         accounting_line_type,
7456                         transaction_value,
7457                         base_transaction_value,
7458                         primary_quantity,
7459                         rate_or_amount,
7460                         basis_type,
7461                         cost_element_id,
7462                         currency_code,
7463                         currency_conversion_date,
7464                         currency_conversion_type,
7465                         currency_conversion_rate,
7466                         request_id,
7467                         program_application_id,
7468                         program_id,
7469                         program_update_date,
7470                         encumbrance_type_id -- Bug 9356654 WIP Encumbrance enhancement Change 3
7471 						)
7472                 select        DECODE(p_acct_line_type, 15, -1,1) * CST_WIP_SUB_LEDGER_ID_S.NEXTVAL,
7473                         p_txn_id,
7474                         p_ref_acct,
7475                         sysdate,
7476                         p_user_id,
7477                         sysdate,
7478                         p_user_id,
7479                         p_login_id,
7480                         wcti.organization_id,
7481                         wcti.transaction_date,
7482                         p_wip_entity_id,
7483                         p_acct_line_type,
7484 --{BUG#9356654
7485        DECODE(p_acct_line_type,
7486 	          15,
7487               DECODE(SIGN(NVL(wcti.primary_quantity,0)),0,-1,1,-1 ,-1,1 )*
7488               DECODE(l_same_currency,
7489                      0,  -- base_currency <> txn_currency
7490                      DECODE(fc.minimum_accountable_unit,
7491                             null,
7492                             DECODE(fc.precision, null,
7493                                    ROUND(l_base_txn_value/nvl(pod.rate,1),2),
7494                                    ROUND(l_base_txn_value/nvl(pod.rate,1),fc.precision)),
7495                              0,
7496                             DECODE(fc.precision, null,
7497                                    l_base_txn_value/nvl(pod.rate,1),
7498                                    round(l_base_txn_value/nvl(pod.rate,1),fc.precision)),
7499                             ROUND((l_base_txn_value/nvl(pod.rate,1))/fc.minimum_accountable_unit) * fc.minimum_accountable_unit
7500                             ),
7501 				      l_txn_value
7502 				      ),
7503                 l_txn_value
7504 				),      -- transaction_value
7505           -- l_txn_value
7506 --}
7507    DECODE(p_acct_line_type,
7508           15,
7509           DECODE(SIGN(NVL(wcti.primary_quantity,0)),0,-1,1,-1 ,-1,1 )*l_base_txn_value,l_base_txn_value
7510           ), --base_transaction_value
7511    DECODE(p_acct_line_type,
7512           15,
7513           wcti.encumbrance_quantity,
7514           DECODE(wcti.source_code,'IPV',NULL,wcti.primary_quantity)
7515           ),  --primary_quantity
7516    DECODE(p_acct_line_type, 15,
7517           (l_base_txn_value/wcti.encumbrance_quantity),
7518           wcti.actual_resource_rate
7519           ), --rate_or_amount
7520           1,  --basis_type
7521    DECODE(p_acct_line_type, 15,NULL,l_cost_element),
7522    wcti.currency_code,
7523    DECODE(p_acct_line_type, 15,nvl(pod.rate_date,pod.creation_date),wcti.currency_conversion_date), -- conversion_date
7524    DECODE(p_acct_line_type, 15,poh.rate_type,wcti.currency_conversion_type),
7525    DECODE(p_acct_line_type, 15,nvl(pod.rate,1),wcti.currency_conversion_rate),
7526    p_request_id,
7527    p_prg_appl_id,
7528    p_prg_id,
7529    sysdate,
7530    DECODE(p_acct_line_type,15,encumbrance_type_id,NULL) --Bug 9356654 WIP Encumbrance enhancement Change 3
7531      FROM   wip_cost_txn_interface wcti,
7532 			po_distributions_all pod,
7533 			po_headers_all poh,
7534 			rcv_transactions rt,
7535 			fnd_currencies fc
7536                 WHERE  wcti.transaction_id = p_txn_id
7537 		AND	poh.po_header_id = wcti.po_header_id
7538 		AND	poh.po_header_id = pod.po_header_id
7539 		AND	poh.po_header_id = rt.po_header_id
7540 		AND	rt.po_distribution_id = pod.po_distribution_id
7541 		AND	rt.transaction_id = wcti.rcv_transaction_id
7542 		AND fc.currency_code = wcti.currency_code;
7543      END IF;
7544 
7545 l_stmt_num := 110;
7546 
7547     IF (l_source_code = 'IPV') THEN
7548     Insert into wip_transaction_accounts (
7549                         wip_sub_ledger_id,
7550                              transaction_id,
7551                         reference_account,
7552                          last_update_date,
7553                         last_updated_by,
7554                         creation_date,
7555                         created_by,
7556                         last_update_login,
7557                         organization_id,
7558                         transaction_date,
7559                         wip_entity_id,
7560                         accounting_line_type,
7561                         transaction_value,
7562                         base_transaction_value,
7563                         rate_or_amount,
7564                         basis_type,
7565                         cost_element_id,
7566                         currency_code,
7567                         currency_conversion_date,
7568                         currency_conversion_type,
7569                         currency_conversion_rate,
7570                         request_id,
7571                         program_application_id,
7572                         program_id,
7573                         program_update_date
7574 						)
7575                 select  CST_WIP_SUB_LEDGER_ID_S.NEXTVAL,
7576                         p_txn_id,
7577                         p_ref_acct,
7578                         sysdate,
7579                         p_user_id,
7580                         sysdate,
7581                         p_user_id,
7582                         p_login_id,
7583                         wcti.organization_id,
7584                         wcti.transaction_date,
7585                         p_wip_entity_id,
7586                         p_acct_line_type,
7587                         l_txn_value,
7588                         l_base_txn_value,
7589 						wcti.actual_resource_rate,
7590                         1,  --basis_type
7591                         l_cost_element,
7592                         wcti.currency_code,
7593                         wcti.currency_conversion_date, -- conversion_date
7594                         wcti.currency_conversion_type,
7595                         wcti.currency_conversion_rate,
7596                         p_request_id,
7597                         p_prg_appl_id,
7598                         p_prg_id,
7599                         sysdate
7600      FROM   wip_cost_txn_interface wcti
7601       WHERE wcti.transaction_id = p_txn_id;
7602      END IF;
7603 
7604     -- Standard check of p_commit
7605     IF FND_API.to_Boolean(p_commit) THEN
7606        COMMIT WORK;
7607     END IF;
7608 
7609     -- Standard Call to get message count and if count = 1, get message info
7610     FND_MSG_PUB.Count_And_Get (
7611            p_count     => x_msg_count,
7612            p_data      => x_msg_data );
7613 
7614    -- Print messages to log file
7615 
7616 
7617     EXCEPTION
7618       WHEN fnd_api.g_exc_error THEN
7619          ROLLBACK TO insert_direct_item_distr_PUB;
7620          x_return_status := fnd_api.g_ret_sts_error;
7621 
7622         --  Get message count and data
7623         fnd_msg_pub.count_and_get
7624              (  p_count => x_msg_count
7625               , p_data  => x_msg_data
7626               );
7627 
7628       WHEN fnd_api.g_exc_unexpected_error THEN
7629             ROLLBACK TO insert_direct_item_distr_PUB;
7630             x_return_status := fnd_api.g_ret_sts_unexp_error ;
7631 
7632         --  Get message count and data
7633         fnd_msg_pub.count_and_get
7634           (  p_count  => x_msg_count
7635            , p_data   => x_msg_data
7636             );
7637       --
7638    WHEN OTHERS THEN
7639       ROLLBACK TO insert_direct_item_distr_PUB;
7640       x_return_status := fnd_api.g_ret_sts_unexp_error ;
7641       fnd_file.put_line(fnd_file.log,'CST_eamCost_PUB.insert_direct_item_distr(' || to_char(l_stmt_num) || '): ' || substr(SQLERRM,1,240));
7642       --
7643       IF fnd_msg_pub.check_msg_level(fnd_msg_pub.g_msg_lvl_unexp_error)
7644         THEN
7645          fnd_msg_pub.add_exc_msg
7646            (  'CST_eamCost_PUB'
7647               , 'insert_direct_item_distr : Statement - '|| to_char(l_stmt_num)
7648               );
7649 
7650       END IF;
7651 
7652       --  Get message count and data
7653       fnd_msg_pub.count_and_get
7654           (  p_count  => x_msg_count
7655            , p_data   => x_msg_data
7656            );
7657 END insert_direct_item_distr;
7658 
7659 ----------------------------------------------------------------------------
7660 -- PROCEDURE                                                              --
7661 --   update_wip_period_balances                                           --
7662 -- DESCRIPTION                                                            --
7663 --   This function updates the tl_material_in in wip_period_balances      --
7664 --   for the Direct Item Shopfloor delivery transaction                   --
7665 -- PURPOSE:                                                               --
7666 --   Oracle Applications - Enterprise asset management                    --
7667 --   Beta on 11i Patchset G                                               --
7668 --   Costing Support for EAM                                              --
7669 --                                                                        --
7670 -- HISTORY:                                                               --
7671 --    07/18/01                  Anitha Dixit            Created           --
7672 ----------------------------------------------------------------------------
7673 PROCEDURE update_wip_period_balances (
7674                     p_api_version        IN   NUMBER,
7675                     p_init_msg_list      IN   VARCHAR2 := FND_API.G_FALSE,
7676                     p_commit             IN   VARCHAR2 := FND_API.G_FALSE,
7677                     p_validation_level   IN   NUMBER := FND_API.G_VALID_LEVEL_FULL,
7678 
7679                     p_wip_entity_id      IN   NUMBER,
7680                     p_acct_period_id         IN   NUMBER,
7681                     p_txn_id                 IN   NUMBER,
7682                     p_prg_appl_id        IN   NUMBER,
7683                     p_prg_id             IN   NUMBER,
7684                     p_request_id         IN   NUMBER,
7685                     p_user_id            IN   NUMBER,
7686                     p_login_id           IN   NUMBER,
7687 
7688                     x_return_status      OUT NOCOPY  VARCHAR2,
7689                     x_msg_count          OUT NOCOPY  NUMBER,
7690                     x_msg_data           OUT NOCOPY  VARCHAR2 ) IS
7691 
7692           l_api_name    CONSTANT        VARCHAR2(30) := 'update_wip_period_balances';
7693           l_api_version CONSTANT        NUMBER       := 1.0;
7694 
7695           l_api_message                 VARCHAR2(240);
7696           l_statement                   NUMBER := 0;
7697           l_txn_value                   NUMBER := 0;
7698 
7699           l_debug                       VARCHAR2(80);
7700           l_cost_element                NUMBER := 1;
7701           l_update_stmt                        VARCHAR2(2000) := NULL;
7702 
7703 BEGIN
7704       ---------------------------------------------
7705       --  Standard start of API savepoint
7706       ---------------------------------------------
7707       SAVEPOINT  update_wip_period_balances_PUB;
7708 
7709       l_debug := fnd_profile.value('MRP_DEBUG');
7710 
7711       ------------------------------------------------
7712       --  Standard call to check for API compatibility
7713       ------------------------------------------------
7714       l_statement := 10;
7715       IF not fnd_api.compatible_api_call (
7716                                   l_api_version,
7717                                   p_api_version,
7718                                   l_api_name,
7719                                   G_PKG_NAME ) then
7720             RAISE fnd_api.G_exc_unexpected_error;
7721       END IF;
7722 
7723       ------------------------------------------------------------
7724       -- Initialize message list if p_init_msg_list is set to TRUE
7725       -------------------------------------------------------------
7726       l_statement := 20;
7727       IF fnd_api.to_Boolean(p_init_msg_list) then
7728           fnd_msg_pub.initialize;
7729       end if;
7730 
7731       -------------------------------------------------------------
7732       --  Initialize API return status to Success
7733       -------------------------------------------------------------
7734       l_statement := 30;
7735       x_return_status := fnd_api.g_ret_sts_success;
7736 
7737       ----------------------------------------------------
7738       --  Validate Account Period ID
7739       ----------------------------------------------------
7740       l_statement := 40;
7741       if ((nvl(p_acct_period_id,-1) = -1) OR (p_txn_id IS NULL))  then
7742         raise fnd_api.g_exc_unexpected_error;
7743       end if;
7744 
7745       -----------------------------------
7746       --   Obtain transaction value
7747       -----------------------------------
7748       l_statement := 50;
7749       select sum(nvl(base_transaction_value,0))
7750       into l_txn_value
7751       from wip_transaction_accounts
7752       where transaction_id = p_txn_id
7753       and accounting_line_type = 7;
7754 
7755       -----------------------------------------------
7756       --  Obtain manufacturing cost element
7757       -----------------------------------------------
7758       l_statement := 55;
7759 
7760       /* Direct Item Acct Enh (Patchset J) */
7761       get_CostEle_for_DirectItem (
7762         p_api_version                =>        1.0,
7763         p_init_msg_list                =>        p_init_msg_list,
7764         p_commit                =>        p_commit,
7765         p_validation_level        =>        p_validation_level,
7766         x_return_status                =>        x_return_status,
7767         x_msg_count                =>        x_msg_count,
7768         x_msg_data                =>        x_msg_data,
7769         p_txn_id                =>        p_txn_id,
7770         p_mnt_or_mfg                =>        2,
7771         x_cost_element_id        =>        l_cost_element
7772         );
7773 
7774       if (x_return_status <> fnd_api.g_ret_sts_success) then
7775         FND_FILE.put_line(FND_FILE.log, x_msg_data);
7776         l_api_message := 'get_CostEle_for_DirectItem returned unexpected error';
7777         FND_MESSAGE.set_name('BOM','CST_API_MESSAGE');
7778         FND_MESSAGE.set_token('TEXT', l_api_message);
7779         FND_MSG_pub.add;
7780         raise fnd_api.g_exc_unexpected_error;
7781       end if;
7782 
7783       if (l_debug = 'Y') then
7784         FND_FILE.PUT_LINE(FND_FILE.LOG,'mfg cost_element: '|| to_char(l_cost_element));
7785       end if;
7786 
7787       /* Bug 4321505 - Modified the dynamic update query to remove literals
7788          in the SQL and use bind variables instead. This is to make the SQL
7789          comply with PL/SQL Standards */
7790 
7791       if l_cost_element = 1 then
7792        l_update_stmt := 'UPDATE wip_period_balances ' ||
7793         'SET pl_material_in = nvl( pl_material_in, 0) + :l_txn_value , ' ||
7794         'last_update_date = sysdate, ' ||
7795         'last_updated_by = :p_user_id, ' ||
7796         'last_update_login = :p_login_id, ' ||
7797         'request_id = :p_request_id, ' ||
7798         'program_application_id = :p_prg_appl_id, ' ||
7799         'program_id =:p_prg_id, ' ||
7800         'program_update_date = sysdate ' ||
7801         'WHERE wip_entity_id = :p_wip_entity_id ' ||
7802         ' AND acct_period_id = :p_acct_period_id ';
7803 
7804       elsif l_cost_element = 3 then
7805        l_update_stmt := 'UPDATE wip_period_balances ' ||
7806         'SET tl_resource_in = nvl( tl_resource_in, 0) + :l_txn_value , ' ||
7807         'last_update_date = sysdate, ' ||
7808         'last_updated_by = :p_user_id, ' ||
7809         'last_update_login = :p_login_id, ' ||
7810         'request_id = :p_request_id, ' ||
7811         'program_application_id = :p_prg_appl_id, ' ||
7812         'program_id =:p_prg_id, ' ||
7813         'program_update_date = sysdate ' ||
7814         'WHERE wip_entity_id = :p_wip_entity_id ' ||
7815         ' AND acct_period_id = :p_acct_period_id ';
7816 
7817       else
7818        l_update_stmt := 'UPDATE wip_period_balances ' ||
7819         'SET tl_outside_processing_in = ' ||
7820         'nvl( tl_outside_processing_in, 0)  + :l_txn_value , ' ||
7821         'last_update_date = sysdate, ' ||
7822         'last_updated_by = :p_user_id, ' ||
7823         'last_update_login = :p_login_id, ' ||
7824         'request_id = :p_request_id, ' ||
7825         'program_application_id = :p_prg_appl_id, ' ||
7826         'program_id =:p_prg_id, ' ||
7827         'program_update_date = sysdate ' ||
7828         'WHERE wip_entity_id = :p_wip_entity_id ' ||
7829         ' AND acct_period_id = :p_acct_period_id ';
7830 
7831       end if;
7832 
7833       --------------------------------------------
7834       --  Update wip_period_balances
7835       --------------------------------------
7836       l_statement := 60;
7837 
7838       EXECUTE IMMEDIATE l_update_stmt USING
7839         l_txn_value, p_user_id, p_login_id, p_request_id, p_prg_appl_id, p_prg_id,
7840         p_wip_entity_id, p_acct_period_id;
7841 
7842     -- Standard check of p_commit
7843     IF FND_API.to_Boolean(p_commit) THEN
7844        COMMIT WORK;
7845     END IF;
7846 
7847     -- Standard Call to get message count and if count = 1, get message info
7848     FND_MSG_PUB.Count_And_Get (
7849            p_count     => x_msg_count,
7850            p_data      => x_msg_data );
7851 
7852    -- Print messages to log file
7853 
7854 
7855 EXCEPTION
7856     WHEN fnd_api.g_exc_error then
7857        ROLLBACK TO update_wip_period_balances_PUB;
7858        x_return_status := fnd_api.g_ret_sts_error;
7859 
7860        fnd_msg_pub.count_and_get
7861           ( p_count => x_msg_count,
7862             p_data  => x_msg_data );
7863 
7864     WHEN fnd_api.g_exc_unexpected_error then
7865        ROLLBACK TO update_wip_period_balances_PUB;
7866        x_return_status := fnd_api.g_ret_sts_unexp_error;
7867 
7868        fnd_msg_pub.count_and_get
7869           ( p_count => x_msg_count,
7870             p_data  => x_msg_data );
7871 
7872     WHEN OTHERS THEN
7873        ROLLBACK TO update_wip_period_balances_PUB;
7874       x_return_status := fnd_api.g_ret_sts_unexp_error ;
7875       If fnd_msg_pub.check_msg_level(fnd_msg_pub.g_msg_lvl_unexp_error) then
7876            fnd_msg_pub.add_exc_msg
7877               ( 'CST_eamCost_PUB',' update_wip_period_balances : Statement - ' || to_char(l_statement));
7878       end if;
7879 
7880       fnd_msg_pub.count_and_get( p_count => x_msg_count,
7881                                  p_data  => x_msg_data );
7882   END  update_wip_period_balances;
7883 
7884 ----------------------------------------------------------------------------
7885 -- PROCEDURE                                                              --
7886 --   insert_direct_item_txn                                               --
7887 -- DESCRIPTION                                                            --
7888 --   insert a transaction record into wip_transactions                    --
7889 --    * new transaction type called Direct Shopfloor Delivery             --
7890 --    * called by cost_direct_item_txn                                    --
7891 -- PURPOSE:                                                               --
7892 --   procedure that inserts a transaction into wip_transactions and       --
7893 --   deletes the record from wip_cost_txn_interface                       --
7894 -- HISTORY:                                                               --
7895 --   05/01/01           Anitha Dixit            Created                   --
7896 ----------------------------------------------------------------------------
7897 PROCEDURE insert_direct_item_txn (
7898                 p_api_version                   IN      NUMBER,
7899                 p_init_msg_list                 IN      VARCHAR2 := FND_API.G_FALSE,
7900                 p_commit                        IN      VARCHAR2 := FND_API.G_FALSE,
7901                 p_validation_level              IN      VARCHAR2 := FND_API.G_VALID_LEVEL_FULL,
7902 
7903                 p_group_id                      IN        NUMBER,
7904                 p_prg_appl_id                   IN        NUMBER,
7905                 p_prg_id                        IN        NUMBER,
7906                 p_request_id                        IN        NUMBER,
7907                 p_user_id                        IN        NUMBER,
7908                 p_login_id                        IN        NUMBER,
7909 
7910                 x_return_status                        OUT NOCOPY        VARCHAR2,
7911                 x_msg_count                        OUT NOCOPY        NUMBER,
7912                 x_msg_data                        OUT NOCOPY        VARCHAR2
7913                 ) IS
7914 
7915   l_api_name    CONSTANT        VARCHAR2(30) := 'insert_direct_item_txn';
7916   l_api_version CONSTANT        NUMBER       := 1.0;
7917 
7918   l_return_status       VARCHAR2(1) := fnd_api.g_ret_sts_success;
7919   l_msg_count           NUMBER := 0;
7920   l_msg_data            VARCHAR2(8000);
7921   l_stmt_num            NUMBER := 0;
7922 
7923   l_api_message         VARCHAR2(1000);
7924   l_debug               VARCHAR2(80);
7925 
7926   BEGIN
7927 
7928     --  Standard Start of API savepoint
7929     SAVEPOINT insert_direct_item_txn_PUB;
7930 
7931     l_debug := fnd_profile.value('MRP_DEBUG');
7932 
7933     -- Standard call to check for call compatibility
7934     IF NOT FND_API.Compatible_API_Call (
7935                         l_api_version,
7936                         p_api_version,
7937                         l_api_name,
7938                         G_PKG_NAME ) THEN
7939           RAISE FND_API.G_EXC_UNEXPECTED_ERROR;
7940     END IF;
7941 
7942     -- Initialize message list if p_init_msg_list is set to TRUE
7943     IF FND_API.to_Boolean(p_init_msg_list) THEN
7944         FND_MSG_PUB.initialize;
7945     END IF;
7946 
7947     -- Initialize API return status to success
7948     x_return_status := FND_API.G_RET_STS_SUCCESS;
7949 
7950 
7951     -- Insert into Wip_transactions
7952     l_stmt_num := 20;
7953     if (l_debug = 'Y') then
7954      fnd_file.put_line(fnd_file.log,'Insert into WT');
7955     end if;
7956 
7957     /* Insert Currency_Actual_Resource_Rate also - Bug 2719622 */
7958 
7959     insert into wip_transactions (
7960                         transaction_id,
7961                         last_update_date,
7962                         last_updated_by,
7963                         creation_date,
7964                         created_by,
7965                         last_update_login,
7966                         organization_id,
7967                         wip_entity_id,
7968                         primary_item_id,
7969                         acct_period_id,
7970                         department_id,
7971                         transaction_type,
7972                         transaction_date,
7973                         line_id,
7974                         source_code,
7975                         source_line_id,
7976                         operation_seq_num,
7977                         standard_rate_flag,
7978                         usage_rate_or_amount,
7979                         basis_type,
7980                         transaction_quantity,
7981                         transaction_uom,
7982                         primary_quantity,
7983                         primary_uom,
7984                         actual_resource_rate,
7985                         currency_actual_resource_rate,
7986                         currency_code,
7987                         currency_conversion_date,
7988                         currency_conversion_type,
7989                         currency_conversion_rate,
7990                         reason_id,
7991                         reference,
7992                         po_header_id,
7993                         po_line_id,
7994                         rcv_transaction_id,
7995                         request_id,
7996                         program_application_id,
7997                         program_id,
7998                         pm_cost_collected,
7999                         project_id,
8000                         task_id,
8001                         /*Bug 9356654 Wip Encumbrance Enhancement */
8002                         encumbrance_type_id,
8003                         encumbrance_amount,
8004                         encumbrance_quantity,
8005                         encumbrance_ccid
8006 						 )
8007                select   wcti.transaction_id,
8008                         sysdate,
8009                         p_user_id,
8010                         sysdate,
8011                         p_user_id,
8012                         p_login_id,
8013                         wcti.organization_id,
8014                         wcti.wip_entity_id,
8015                         wcti.primary_item_id,
8016                         wcti.acct_period_id,
8017                         wcti.department_id,
8018                         17,
8019                         wcti.transaction_date,
8020                         wcti.line_id,
8021                         wcti.source_code,
8022                         wcti.source_line_id,
8023                         wcti.operation_seq_num,
8024                         wcti.standard_rate_flag,
8025                         wcti.usage_rate_or_amount,
8026                         wcti.basis_type,
8027                         decode(wcti.source_code,'IPV',NULL,wcti.transaction_quantity),
8028                         wcti.transaction_uom,
8029                         decode(wcti.source_code,'IPV',NULL,wcti.primary_quantity),
8030                         wcti.primary_uom,
8031                         wcti.actual_resource_rate,
8032                         wcti.currency_actual_resource_rate,
8033                         wcti.currency_code,
8034                         wcti.currency_conversion_date,
8035                         wcti.currency_conversion_type,
8036                         wcti.currency_conversion_rate,
8037                         wcti.reason_id,
8038                         wcti.reference,
8039                         wcti.po_header_id,
8040                         wcti.po_line_id,
8041                         wcti.rcv_transaction_id,
8042                         p_request_id,
8043                         p_prg_appl_id,
8044                         p_prg_id,
8045                         'N',
8046                         wcti.project_id,
8047                         wcti.task_id,
8048 			/*Bug 9356654 Wip Encumbrance Enhancement */
8049 			wcti.encumbrance_type_id,
8050             -- Sign logic: If delivery to SF >0
8051             --             If return from SF <0
8052             --             If correct as per sign
8053 			DECODE(SIGN(NVL(wcti.primary_quantity,0))
8054 			       ,0,1
8055 			       ,1,1
8056                    ,-1,-1)* wcti.encumbrance_amount,  -- signed encumbrance_amount
8057 			DECODE(SIGN(NVL(wcti.primary_quantity,0))
8058 			       ,0,1
8059 			       ,1,1
8060                    ,-1,-1)* wcti.encumbrance_quantity, -- signed encumbrance_quantity
8061 			wcti.encumbrance_ccid
8062                   from  wip_cost_txn_interface wcti
8063                 where   group_id = p_group_id
8064                   and   process_status = 2;
8065 
8066     -- Standard check of p_commit
8067     IF FND_API.to_Boolean(p_commit) THEN
8068        COMMIT WORK;
8069     END IF;
8070 
8071     -- Standard Call to get message count and if count = 1, get message info
8072     FND_MSG_PUB.Count_And_Get (
8073            p_count     => x_msg_count,
8074            p_data      => x_msg_data );
8075 
8076    -- Print messages to log file
8077 
8078 
8079     EXCEPTION
8080       WHEN fnd_api.g_exc_error THEN
8081          ROLLBACK TO insert_direct_item_txn_PUB;
8082          x_return_status := fnd_api.g_ret_sts_error;
8083 
8084         --  Get message count and data
8085         fnd_msg_pub.count_and_get
8086              (  p_count => x_msg_count
8087               , p_data  => x_msg_data
8088               );
8089 
8090       WHEN fnd_api.g_exc_unexpected_error THEN
8091             ROLLBACK TO insert_direct_item_txn_PUB;
8092             x_return_status := fnd_api.g_ret_sts_unexp_error ;
8093 
8094         --  Get message count and data
8095         fnd_msg_pub.count_and_get
8096           (  p_count  => x_msg_count
8097            , p_data   => x_msg_data
8098             );
8099       --
8100    WHEN OTHERS THEN
8101       ROLLBACK TO insert_direct_item_txn_PUB;
8102       x_return_status := fnd_api.g_ret_sts_unexp_error ;
8103       fnd_file.put_line(fnd_file.log,'CST_eamCost_PUB.insert_direct_item_txn: Statement(' || to_char(l_stmt_num) || '): ' || substr(SQLERRM,1,240));
8104       --
8105       IF fnd_msg_pub.check_msg_level(fnd_msg_pub.g_msg_lvl_unexp_error)
8106         THEN
8107          fnd_msg_pub.add_exc_msg
8108            (  'CST_eamCost_PUB'
8109               , 'insert_direct_item_txn : Statement - '|| to_char(l_stmt_num)
8110               );
8111 
8112       END IF;
8113 
8114       --  Get message count and data
8115       fnd_msg_pub.count_and_get
8116           (  p_count  => x_msg_count
8117            , p_data   => x_msg_data
8118            );
8119 END insert_direct_item_txn;
8120 
8121 
8122 ----------------------------------------------------------------------------
8123 -- PROCEDURE                                                              --
8124 --   get_Direct_Item_Charge_Acct                                          --
8125 --                                                                        --
8126 -- DESCRIPTION                                                            --
8127 --  This API determines returns the material account number
8128 --  given a EAM job (entity  type = 6,7)                                     --
8129 --  If the wip identity doesn't refer to an EAM job type then             --
8130 --  -1 is returned, -1 is also returned if material account is not          --
8131 --  defined for that particular wip entity.
8132 --
8133 --  This API has been moved to CST_Utility_PUB to limit dependencies for  --
8134 --  PO.  Any changes J (11.5.10) and higher made to this API should NOT be--
8135 --  made here, but at CST_Utiltiy_PUB.get_Direct_Item_Charge_Acct.
8136 --
8137 -- PURPOSE:                                                               --
8138 --   Oracle Applications Rel 11i.6                                        --
8139 --   Costing Support for EAM                                              --
8140 --   Called by PO account generator
8141 --                                                                        --
8142 --                                                                        --
8143 -- HISTORY:                                                               --
8144 --    07/18/01                  Vinit Srivastava        Created           --
8145 ----------------------------------------------------------------------------
8146 
8147 PROCEDURE get_Direct_Item_Charge_Acct (
8148                             p_api_version        IN   NUMBER,
8149                             p_init_msg_list      IN   VARCHAR2
8150                                                 := FND_API.G_FALSE,
8151                             p_commit             IN   VARCHAR2
8152                                                 := FND_API.G_FALSE,
8153                             p_validation_level   IN   NUMBER
8154                                                 := FND_API.G_VALID_LEVEL_FULL,
8155                             p_wip_entity_id      IN   NUMBER := NULL,
8156                             x_material_acct     OUT NOCOPY  NUMBER,
8157                             x_return_status      OUT NOCOPY  VARCHAR2,
8158                             x_msg_count          OUT NOCOPY  NUMBER,
8159                             x_msg_data           OUT NOCOPY  VARCHAR2 ) IS
8160 
8161           l_api_name    CONSTANT        VARCHAR2(30) := 'get_Direct_Item_Charge_Acct';
8162           l_api_version CONSTANT        NUMBER       := 1.0;
8163 
8164           l_api_message                 VARCHAR2(240);
8165           l_statement                   NUMBER := 0;
8166           l_material_account            NUMBER := -1;
8167           l_entity_type                 NUMBER;
8168 
8169 BEGIN
8170 
8171       ---------------------------------------------
8172       --  Standard start of API savepoint
8173       ---------------------------------------------
8174       SAVEPOINT  get_Direct_Item_Charge_Acct;
8175 
8176       ------------------------------------------------
8177       --  Standard call to check for API compatibility
8178       ------------------------------------------------
8179       l_statement := 10;
8180       IF not fnd_api.compatible_api_call (
8181                                   l_api_version,
8182                                   p_api_version,
8183                                   l_api_name,
8184                                   G_PKG_NAME ) then
8185             RAISE fnd_api.G_exc_unexpected_error;
8186       END IF;
8187 
8188       ------------------------------------------------------------
8189       -- Initialize message list if p_init_msg_list is set to TRUE
8190       -------------------------------------------------------------
8191       l_statement := 20;
8192       IF fnd_api.to_Boolean(p_init_msg_list) then
8193           fnd_msg_pub.initialize;
8194       end if;
8195 
8196       -------------------------------------------------------------
8197       --  Initialize API return status to Success
8198       -------------------------------------------------------------
8199       l_statement := 30;
8200       x_return_status := fnd_api.g_ret_sts_success;
8201 
8202 
8203       -------------------------------------------------
8204       --  Validate input parameters
8205       -------------------------------------------------
8206       l_statement := 40;
8207       if (p_wip_entity_id is null) then
8208             l_api_message := 'Please specify a wip entity id';
8209             FND_MESSAGE.set_name('BOM','CST_API_MESSAGE');
8210             FND_MESSAGE.set_token('TEXT', l_api_message);
8211             FND_MSG_PUB.add;
8212 
8213             RAISE fnd_api.g_exc_error;
8214       end if;
8215 
8216       ---------------------------------------------
8217       --  Verify if EAM job
8218       ---------------------------------------------
8219       l_statement := 45;
8220       select entity_type
8221       into l_entity_type
8222       from wip_entities
8223       where wip_entity_id = p_wip_entity_id;
8224 
8225       if (l_entity_type in (6,7)) then
8226       ---------------------------------------------
8227       --  Obtain material_account
8228       ---------------------------------------------
8229          l_statement := 50;
8230          select nvl(material_account,-1)
8231          into l_material_account
8232          from wip_discrete_jobs
8233          where wip_entity_id = p_wip_entity_id;
8234       end if;
8235 
8236         x_material_acct := l_material_account;
8237 
8238 EXCEPTION
8239     WHEN fnd_api.g_exc_error then
8240        x_return_status := fnd_api.g_ret_sts_error;
8241        x_material_acct := -1;
8242 
8243        fnd_msg_pub.count_and_get
8244           ( p_count => x_msg_count,
8245             p_data  => x_msg_data );
8246 
8247     WHEN fnd_api.g_exc_unexpected_error then
8248        x_return_status := fnd_api.g_ret_sts_unexp_error;
8249        x_material_acct := -1;
8250 
8251        fnd_msg_pub.count_and_get
8252           ( p_count => x_msg_count,
8253             p_data  => x_msg_data );
8254 
8255     WHEN OTHERS THEN
8256       x_return_status := fnd_api.g_ret_sts_unexp_error ;
8257       x_material_acct := -1;
8258       If fnd_msg_pub.check_msg_level(fnd_msg_pub.g_msg_lvl_unexp_error) then
8259            fnd_msg_pub.add_exc_msg
8260               ( 'CST_eamCost_PUB',' get_Direct_Item_Charge_Acct : Statement - ' || to_char(l_statement));
8261       end if;
8262 
8263       fnd_msg_pub.count_and_get( p_count => x_msg_count,
8264                                  p_data  => x_msg_data );
8265   END  get_Direct_Item_Charge_Acct;
8266 
8267 ----------------------------------------------------------------------------
8268 -- PROCEDURE                                                              --
8269 --  validate_for_reestimation                                             --
8270 --                                                                        --
8271 -- DESCRIPTION                                                            --
8272 --  validates if the re-estimation flag on the work order value summary   --
8273 --  form, can be updated                                                  --
8274 --    * Calls validate_est_status_hook. If hook is used, default          --
8275 --      validation will be overridden                                     --
8276 --    * Default Validation :                                              --
8277 --      If curr_est_status is Complete, flag can be checked to re-estimate -
8278 --      If curr_est_status is Re-estimate, flag can be unchecked to complete
8279 -- PURPOSE:                                                               --
8280 --    called by work order value summary form                             --
8281 --                                                                        --
8282 -- HISTORY:                                                               --
8283 --    08/26/01  Anitha Dixit    Created                                   --
8284 ----------------------------------------------------------------------------
8285 PROCEDURE validate_for_reestimation (
8286                 p_api_version           IN      NUMBER,
8287                 p_init_msg_list         IN      VARCHAR2 := fnd_api.g_false,
8288                 p_commit                IN      VARCHAR2 := fnd_api.g_false,
8289                 p_validation_level      IN      VARCHAR2 := fnd_api.g_valid_level_full,
8290 
8291                 p_wip_entity_id         IN      NUMBER,
8292                 p_job_status            IN      NUMBER,
8293                 p_curr_est_status       IN      NUMBER,
8294 
8295                 x_validate_flag         OUT NOCOPY     NUMBER,
8296                 x_return_status         OUT NOCOPY     VARCHAR2,
8297                 x_msg_count             OUT NOCOPY     NUMBER,
8298                 x_msg_data              OUT NOCOPY     VARCHAR2
8299                 ) IS
8300      l_api_name         CONSTANT        VARCHAR2(30) := 'validate_for_reestimation';
8301      l_api_version      CONSTANT        NUMBER       := 1.0;
8302 
8303      l_return_status    VARCHAR2(1) := fnd_api.g_ret_sts_success;
8304      l_msg_count        NUMBER := 0;
8305      l_msg_data         VARCHAR2(8000);
8306      l_stmt_num         NUMBER := 0;
8307 
8308      l_err_num          NUMBER := 0;
8309      l_err_code         VARCHAR2(240);
8310      l_err_msg          VARCHAR2(8000);
8311 
8312      l_validate_flag    NUMBER := 0;
8313      l_hook             NUMBER := 0;
8314 
8315 BEGIN
8316    -- Standard start of API savepoint
8317    SAVEPOINT validate_for_reestimation_PUB;
8318 
8319     -- Standard call to check for call compatibility
8320     IF NOT FND_API.Compatible_API_Call (
8321                         l_api_version,
8322                         p_api_version,
8323                         l_api_name,
8324                         G_PKG_NAME ) THEN
8325           RAISE FND_API.G_EXC_UNEXPECTED_ERROR;
8326     END IF;
8327 
8328     -- Initialize message list if p_init_msg_list is set to TRUE
8329     IF FND_API.to_Boolean(p_init_msg_list) THEN
8330         FND_MSG_PUB.initialize;
8331     END IF;
8332 
8333 
8334     -- Initialize API return status to success
8335     l_stmt_num := 0;
8336     x_return_status := FND_API.G_RET_STS_SUCCESS;
8337 
8338    -- Call validation hook
8339    l_stmt_num := 10;
8340    l_hook := CSTPACHK.validate_job_est_status_hook (
8341                 i_wip_entity_id         =>      p_wip_entity_id,
8342                 i_job_status            =>      p_job_status,
8343                 i_curr_est_status       =>      p_curr_est_status,
8344                 o_validate_flag         =>      l_validate_flag,
8345                 o_err_num               =>      l_err_num,
8346                 o_err_code              =>      l_err_code,
8347                 o_err_msg               =>      l_err_msg );
8348 
8349    if (l_err_num <> 0) then
8350      raise fnd_api.g_exc_unexpected_error;
8351    end if;
8352 
8353 
8354    l_stmt_num := 20;
8355    if (l_hook = 1) then
8356      x_validate_flag := l_validate_flag;
8357      return;
8358    end if;
8359 
8360    l_stmt_num := 30;
8361    /* Bug 3361378 - Pending WOs can be estimated */
8362    if (p_curr_est_status = 1 or p_curr_est_status IS null) then
8363         x_validate_flag :=1;
8364    elsif (p_curr_est_status = 2 or p_curr_est_status = 3) then
8365      x_validate_flag := 0;
8366    elsif (p_curr_est_status = 7) then
8367      if (p_job_status in (1,3,4,6, 17)) then /* bug 2186082 draft WOs can be reestimated */
8368        x_validate_flag := 1;
8369      else
8370        x_validate_flag := 0;
8371      end if;
8372    elsif (p_curr_est_status = 8 OR p_curr_est_status = 9) then
8373      x_validate_flag := 1;
8374    else
8375      x_validate_flag := 0;
8376    end if;
8377 
8378     -- Standard check of p_commit
8379     IF FND_API.to_Boolean(p_commit) THEN
8380        COMMIT WORK;
8381     END IF;
8382 
8383     -- Standard Call to get message count and if count = 1, get message info
8384     FND_MSG_PUB.Count_And_Get (
8385            p_count     => x_msg_count,
8386            p_data      => x_msg_data );
8387 
8388 EXCEPTION
8389       WHEN fnd_api.g_exc_error THEN
8390          ROLLBACK TO validate_for_reestimation_PUB;
8391          x_return_status := fnd_api.g_ret_sts_error;
8392 
8393         --  Get message count and data
8394         fnd_msg_pub.count_and_get
8395              (  p_count => x_msg_count
8396               , p_data  => x_msg_data
8397               );
8398 
8399       WHEN fnd_api.g_exc_unexpected_error THEN
8400             ROLLBACK TO validate_for_reestimation_PUB;
8401             x_return_status := fnd_api.g_ret_sts_unexp_error ;
8402 
8403         --  Get message count and data
8404         fnd_msg_pub.count_and_get
8405           (  p_count  => x_msg_count
8406            , p_data   => x_msg_data
8407             );
8408 
8409    WHEN OTHERS THEN
8410       ROLLBACK TO validate_for_reestimation_PUB;
8411       x_return_status := fnd_api.g_ret_sts_unexp_error ;
8412       --
8413       IF fnd_msg_pub.check_msg_level(fnd_msg_pub.g_msg_lvl_unexp_error)
8414         THEN
8415          fnd_msg_pub.add_exc_msg
8416            (  'CST_eamCost_PUB'
8417               , 'validate_for_reestimation : Statement - '|| to_char(l_stmt_num)
8418               );
8419 
8420       END IF;
8421 
8422       --  Get message count and data
8423       fnd_msg_pub.count_and_get
8424           (  p_count  => x_msg_count
8425            , p_data   => x_msg_data
8426            );
8427 END validate_for_reestimation;
8428 
8429 ----------------------------------------------------------------------------
8430 -- PROCEDURE                                                              --
8431 --   Redistribute_WIP_Accounts                                            --
8432 --                                                                        --
8433 --                                                                        --
8434 -- DESCRIPTION                                                            --
8435 --   This API redistributes  accounts values from the Accounting class    --
8436 --   of the route job to the accounting class of the memeber assets.      --
8437 --   It does so for the variance accounts of the corresponding WACs.      --
8438 --   This API should be called from period close(CSTPWPVR)                --
8439 --   and job close (cmlwjv)                                               --
8440 --                                                                        --
8441 -- PURPOSE:                                                               --
8442 --   Oracle Applications Rel 11i.9                                        --
8443 --                                                                        --
8444 --                                                                        --
8445 -- HISTORY:                                                               --
8446 --   11/26/02  Anitha         Modified to support close through SRS       --
8447 --                            merged accounting entry creation into       --
8448 --                            single SQL against the job close txn        --
8449 --   09/26/02  Hemant G       Created                                     --
8450 --   09/07/07  Veeresha Javli  Bug: 5767070 fix:  use round               --
8451 ----------------------------------------------------------------------------
8452 PROCEDURE Redistribute_WIP_Accounts (
8453                             p_api_version        IN   NUMBER,
8454                             p_init_msg_list      IN   VARCHAR2 := FND_API.G_FALSE,
8455                             p_commit             IN   VARCHAR2 := FND_API.G_FALSE,
8456                             p_validation_level   IN   VARCHAR2 := FND_API.G_VALID_LEVEL_FULL,
8457                             p_wcti_group_id      IN   NUMBER,
8458 
8459                             p_user_id            IN   NUMBER,
8460                             p_request_id         IN   NUMBER,
8461                             p_prog_id            IN   NUMBER,
8462                             p_prog_app_id        IN   NUMBER,
8463                             p_login_id           IN   NUMBER,
8464 
8465                             x_return_status      OUT  NOCOPY VARCHAR2,
8466                             x_msg_count          OUT  NOCOPY NUMBER,
8467                             x_msg_data           OUT  NOCOPY VARCHAR2 ) IS
8468 
8469     l_api_name    CONSTANT       VARCHAR2(30) :='Redistribute_WIP_Accounts';
8470     l_api_version CONSTANT       NUMBER       := 1.0;
8471 
8472     l_msg_count                 NUMBER := 0;
8473     l_msg_data                  VARCHAR2(8000);
8474 
8475     l_class_code                VARCHAR2(10);
8476 
8477     l_weightage_factor          NUMBER := 0;
8478     l_number_members            NUMBER := 0;
8479     l_pl_var                    NUMBER := 0;
8480     l_res_var                   NUMBER := 0;
8481     l_osp_var                   NUMBER := 0;
8482     l_ovh_var                   NUMBER := 0;
8483     l_min_acct_unit             NUMBER := 0;
8484     l_round_unit                NUMBER := 0;
8485     l_precision                 NUMBER := 0;
8486     l_ext_precision             NUMBER := 0;
8487     l_currency_code             VARCHAR2(15);
8488 
8489     l_pl_var_total              NUMBER := 0;
8490     l_res_var_total             NUMBER := 0;
8491     l_osp_var_total             NUMBER := 0;
8492     l_ovh_var_total             NUMBER := 0;
8493 
8494     l_mtl_var_acct              NUMBER;
8495     l_res_var_acct              NUMBER;
8496     l_osp_var_acct              NUMBER;
8497     l_ovh_var_acct              NUMBER;
8498 
8499     l_return_status             VARCHAR2(1) := FND_API.G_RET_STS_SUCCESS;
8500     l_api_message               VARCHAR2(10000);
8501     l_stmt_num                  NUMBER;
8502 
8503     l_dummy                     NUMBER := 0;
8504 
8505 
8506   /* Changes required in the following cursor to refer to CII
8507      instead of MSN for network Asset Flag (eAM Requirements
8508       Project - R12) */
8509 
8510     CURSOR c_route_assets(p_wcti_group_id NUMBER) IS
8511      select wcti.transaction_id,
8512             wcti.organization_id,
8513             wcti.wip_entity_id,
8514             wcti.acct_period_id,
8515             to_char(wcti.transaction_date,'YYYY/MM/DD HH24:MI:SS') txn_date,
8516             cii.inventory_item_id,
8517             cii.serial_number,
8518             wdj.class_code,
8519             wdj.primary_item_id,
8520             wdj.project_id,
8521             wdj.task_id,
8522             wdj.maintenance_object_id
8523        from wip_cost_txn_interface wcti,
8524             wip_discrete_jobs wdj,
8525             wip_entities we,
8526             csi_item_instances cii
8527       where wcti.group_id = p_wcti_group_id
8528         and wdj.wip_entity_id = wcti.wip_entity_id
8529         and we.wip_entity_id = wcti.wip_entity_id
8530         and we.entity_type in (6,7)
8531         and cii.instance_id = wdj.maintenance_object_id
8532         and wdj.maintenance_object_type = 3
8533         and cii.network_asset_flag = 'Y';
8534 
8535 
8536   /* Changes required in following cursor as current org can view assets
8537      assigned to itself and to organizations that it maintains.
8538      Also changed to pick member assets information from
8539      EAM_WORK_ORDER_ROUTE table (eAM Requirements Project - R12). */
8540 
8541      CURSOR c_ewor (p_org_id NUMBER,
8542                    p_wip_entity_id NUMBER) IS
8543      select cii.inventory_item_id,
8544             cii.serial_number,
8545             msn.gen_object_id
8546      from   csi_item_instances cii,
8547             eam_work_order_route ewor,
8548             mtl_serial_numbers msn,
8549             wip_discrete_jobs wdj
8550      where wdj.organization_id = p_org_id
8551      and ewor.wip_entity_id = p_wip_entity_id
8552      and ewor.wip_entity_id = wdj.wip_entity_id
8553      and cii.instance_id = ewor.instance_id
8554      and msn.inventory_item_id = cii.inventory_item_id
8555      and msn.serial_number = cii.serial_number;
8556 
8557 BEGIN
8558 
8559     -------------------------------------------------------------------------
8560     -- standard start of API savepoint
8561     -------------------------------------------------------------------------
8562     SAVEPOINT Redistribute_WIP_Accounts;
8563 
8564     -------------------------------------------------------------------------
8565     -- standard call to check for call compatibility
8566     -------------------------------------------------------------------------
8567     IF NOT fnd_api.compatible_api_call (
8568                               l_api_version,
8569                               p_api_version,
8570                               l_api_name,
8571                               G_PKG_NAME ) then
8572 
8573          RAISE fnd_api.g_exc_unexpected_error;
8574 
8575     END IF;
8576 
8577     -------------------------------------------------------------------------
8578     -- Initialize message list if p_init_msg_list is set to TRUE
8579     -------------------------------------------------------------------------
8580     IF FND_API.to_Boolean(p_init_msg_list) THEN
8581         FND_MSG_PUB.initialize;
8582     END IF;
8583 
8584 
8585     -------------------------------------------------------------------------
8586     -- initialize api return status to success
8587     -------------------------------------------------------------------------
8588     x_return_status := fnd_api.g_ret_sts_success;
8589 
8590     -- assign to local variables
8591     l_stmt_num := 10;
8592 
8593     SELECT DISTINCT COD.currency_code
8594     INTO   l_currency_code
8595     FROM   cst_organization_definitions COD,
8596            wip_cost_txn_interface WCTI
8597     WHERE  WCTI.group_id = p_wcti_group_id
8598     AND    WCTI.organization_id = COD.organization_id;
8599 
8600     l_stmt_num := 12;
8601     FND_CURRENCY.GET_INFO( l_currency_code, l_precision, l_ext_precision, l_min_acct_unit);
8602 
8603     if (l_min_acct_unit = 0 OR l_min_acct_unit IS NULL) then
8604        l_min_acct_unit := power(10, -1*l_precision);
8605     end if;
8606 
8607     -------------------------------------------------------------------------
8608     -- Check Entity Type is eAM and that it has a Route Asset
8609     -------------------------------------------------------------------------
8610     fnd_file.put_line(fnd_file.log,'enter-->');
8611 
8612     fnd_file.put_line(fnd_file.log,'p_wcti_group_id: ' || to_char(p_wcti_group_id));
8613 
8614     for c_route_rec in c_route_assets(p_wcti_group_id)
8615 
8616      LOOP
8617        fnd_file.put_line(fnd_file.log,'Route rec: txn:' || to_char(c_route_rec.transaction_id)
8618                            || ' Org:' || to_char(c_route_rec.organization_id)
8619                            || ' WE:' || to_char(c_route_rec.wip_entity_id)
8620                            || ' AcctPer: ' || to_char(c_route_rec.acct_period_id));
8621 
8622        l_stmt_num := 15;
8623 
8624        --------------------------------------------------------
8625        --    Initialize local variables for each wip entity ID
8626        --------------------------------------------------------
8627        l_pl_var := 0;
8628        l_res_var := 0;
8629        l_osp_var := 0;
8630        l_ovh_var := 0;
8631        l_pl_var_total := 0;
8632        l_res_var_total := 0;
8633        l_osp_var_total := 0;
8634        l_ovh_var_total := 0;
8635        l_number_members := 0;
8636 
8637        -----------------------------------------------------------------------
8638        --  Get the number of memeber assets in this network/route
8639        -----------------------------------------------------------------------
8640 
8641       /* There will be as many number of rows in EAM_WORK_ORDER_ROUTE table as
8642          there are asset members in the asset route at the time of Work Order
8643          Release. Changing reference to EWOR from MENA. (eAM Requirements
8644          Project - R12) */
8645 
8646        l_stmt_num := 20;
8647 
8648        select count(*)
8649        into l_number_members
8650        from EAM_WORK_ORDER_ROUTE ewor
8651        where ewor.wip_entity_id = c_route_rec.wip_entity_id;
8652 
8653        if (l_number_members > 0) then
8654 
8655          l_stmt_num := 25;
8656          l_weightage_factor := 1/l_number_members;
8657 
8658          l_api_message := ' Number Members: ' ||TO_CHAR(l_number_members);
8659          l_api_message := l_api_message || ' Weightage Factor: '||TO_CHAR(l_weightage_factor);
8660          FND_MESSAGE.SET_NAME ('BOM', 'CST_API_MESSAGE');
8661          FND_MESSAGE.SET_TOKEN ('TEXT', l_api_message);
8662          FND_MSG_PUB.add;
8663 
8664          -------------------------------------------------------------
8665          --  Get variance amounts pl + moh, resource , osp, overhead
8666          --------------------------------------------------------------
8667          l_stmt_num := 30;
8668          select
8669            -1* SUM(NVL(wpb.pl_material_out,0)
8670                     - NVL(wpb.pl_material_in,0)
8671                     + NVL(wpb.pl_material_var,0)
8672                     + NVL(wpb.pl_material_overhead_out,0)
8673                     - NVL(wpb.pl_material_overhead_in,0)
8674                     + NVL(wpb.pl_material_overhead_var,0)
8675                     + NVL(wpb.pl_resource_out,0)
8676                     - NVL(wpb.pl_resource_in,0)
8677                     + NVL(wpb.pl_resource_var,0)
8678                     + NVL(wpb.pl_overhead_out,0)
8679                     - NVL(wpb.pl_overhead_in,0)
8680                     + NVL(wpb.pl_overhead_var,0)
8681                     + NVL(wpb.pl_outside_processing_out,0)
8682                     - NVL(wpb.pl_outside_processing_in,0)
8683                     + NVL(wpb.pl_outside_processing_var,0)
8684                     + NVL(wpb.tl_material_out,0)
8685                     - 0
8686                     + NVL(wpb.tl_material_var,0)
8687                     + NVL(wpb.tl_material_overhead_out,0)
8688                     - 0
8689                     + NVL(wpb.tl_material_overhead_var,0)),
8690               SUM(NVL(wpb.tl_resource_in,0)
8691                     - NVL(wpb.tl_resource_out,0)
8692                     - NVL(wpb.tl_resource_var,0)),
8693               SUM(NVL(wpb.tl_outside_processing_in,0)
8694                     - NVL(wpb.tl_outside_processing_out,0)
8695                     - NVL(wpb.tl_outside_processing_var,0)),
8696               SUM(NVL(wpb.tl_overhead_in,0)
8697                     - NVL(wpb.tl_overhead_out,0)
8698                     - NVL(wpb.tl_overhead_var,0))
8699             INTO l_pl_var,
8700                  l_res_var,
8701                  l_osp_var,
8702                  l_ovh_var
8703             from wip_period_balances wpb
8704            where wpb.wip_entity_id = c_route_rec.wip_entity_id
8705              and wpb.acct_period_id <= c_route_rec.acct_period_id;
8706 
8707            l_stmt_num := 32;
8708 
8709            FOR c_ewor_rec IN c_ewor(c_route_rec.organization_id,
8710                                     c_route_rec.wip_entity_id)
8711             LOOP
8712 
8713              l_stmt_num := 35;
8714 
8715              -------------------------------------------
8716              ---  Get wip accounting class
8717              -------------------------------------------
8718              l_stmt_num := 40;
8719              WIP_EAM_UTILS.DEFAULT_ACC_CLASS(
8720                                 p_org_id          => c_route_rec.organization_id,
8721                                 p_job_type        => 1,
8722                                 p_serial_number   => c_ewor_rec.serial_number,
8723                                 p_asset_group_id  => c_ewor_rec.inventory_item_id,
8724                                 p_asset_activity_id => c_route_rec.primary_item_id,
8725                                 p_project_id      => c_route_rec.project_id,
8726                                 p_task_id         => c_route_rec.task_id,
8727                                 x_class_code      => l_class_code,
8728                                 x_return_status   => l_return_status,
8729                                 x_msg_data        => l_msg_data
8730                                 );
8731 
8732              if (l_return_status <> fnd_api.g_ret_sts_success) then
8733                   raise fnd_api.g_exc_unexpected_error;
8734              end if;
8735 
8736 
8737              l_stmt_num := 45;
8738              if (l_class_code is not null) then
8739                   select material_variance_account,
8740                          resource_variance_account,
8741                          outside_proc_variance_account,
8742                          overhead_variance_account
8743                     into l_mtl_var_acct,
8744                          l_res_var_acct,
8745                          l_osp_var_acct,
8746                          l_ovh_var_acct
8747                     from wip_accounting_classes
8748                    where class_code = l_class_code
8749                      and organization_id = c_route_rec.organization_id;
8750 
8751                ---------------------------------------------------------------------
8752                --  Dr. Member Route Accounts
8753                ---------------------------------------------------------------------
8754 
8755                l_stmt_num := 50;
8756                INSERT INTO wip_transaction_accounts
8757                    (TRANSACTION_ID,             REFERENCE_ACCOUNT,
8758                     LAST_UPDATE_DATE,           LAST_UPDATED_BY,
8759                     CREATION_DATE,              CREATED_BY,
8760                     LAST_UPDATE_LOGIN,          ORGANIZATION_ID,
8761                     TRANSACTION_DATE,           WIP_ENTITY_ID,
8762                     ACCOUNTING_LINE_TYPE,       BASE_TRANSACTION_VALUE,
8763                     CONTRA_SET_ID,              COST_ELEMENT_ID,
8764                     REQUEST_ID,                 PROGRAM_APPLICATION_ID,
8765                     PROGRAM_ID,                 PROGRAM_UPDATE_DATE)
8766 
8767                SELECT
8768                     c_route_rec.transaction_id,
8769                     decode(cce.cost_element_id,
8770                             1,l_mtl_var_acct,
8771                             3,l_res_var_acct,
8772                             4,l_osp_var_acct,
8773                             5,l_ovh_var_acct),
8774                     SYSDATE,
8775                     p_user_id,
8776                     SYSDATE,
8777                     p_user_id,
8778                     p_login_id,
8779                     c_route_rec.organization_id,
8780                     to_date(c_route_rec.txn_date,'YYYY/MM/DD HH24:MI:SS'),
8781                     c_route_rec.wip_entity_id,
8782                     8, -- accounting_line_type is WIP variance,
8783                     ROUND((decode(cce.cost_element_id,
8784                            1, l_pl_var,
8785                            3, l_res_var,
8786                            4, l_osp_var,
8787                            5, l_ovh_var) * l_weightage_factor)/l_min_acct_unit) * l_min_acct_unit,
8788                     c_ewor_rec.gen_object_id,
8789                     cce.cost_element_id,
8790                     p_request_id,
8791                     p_prog_app_id,
8792                     p_prog_id,
8793                     SYSDATE
8794                FROM cst_cost_elements cce
8795               WHERE cce.cost_element_id <> 2
8796              GROUP BY cce.cost_element_id
8797              HAVING decode(cce.cost_element_id,
8798                            1, l_pl_var,
8799                            3, l_res_var,
8800                            4, l_osp_var,
8801                            5, l_ovh_var) * l_weightage_factor <> 0;
8802 
8803                l_stmt_num := 55;
8804                l_pl_var_total := l_pl_var_total + (ROUND((l_pl_var * l_weightage_factor)/l_min_acct_unit) * l_min_acct_unit);
8805                l_res_var_total := l_res_var_total + (ROUND((l_res_var * l_weightage_factor)/l_min_acct_unit) * l_min_acct_unit);
8806                l_osp_var_total := l_osp_var_total + (ROUND((l_osp_var * l_weightage_factor)/l_min_acct_unit) * l_min_acct_unit);
8807                l_ovh_var_total := l_ovh_var_total + (ROUND((l_ovh_var * l_weightage_factor)/l_min_acct_unit) * l_min_acct_unit);
8808              end if;  -- check for class code
8809 
8810          END LOOP; -- end for member assets
8811 
8812 
8813 
8814          l_stmt_num := 60;
8815          ---------------------------------------------------------------------
8816          --  Cr. Route Accounts for the Balance
8817          ---------------------------------------------------------------------
8818 
8819 
8820          INSERT INTO wip_transaction_accounts
8821              (TRANSACTION_ID,            REFERENCE_ACCOUNT,
8822              LAST_UPDATE_DATE,           LAST_UPDATED_BY,
8823              CREATION_DATE,              CREATED_BY,
8824              LAST_UPDATE_LOGIN,          ORGANIZATION_ID,
8825              TRANSACTION_DATE,           WIP_ENTITY_ID,
8826              ACCOUNTING_LINE_TYPE,
8827              BASE_TRANSACTION_VALUE,
8828              CONTRA_SET_ID,              COST_ELEMENT_ID,
8829              REQUEST_ID,                 PROGRAM_APPLICATION_ID,
8830              PROGRAM_ID,                 PROGRAM_UPDATE_DATE)
8831         SELECT
8832             c_route_rec.transaction_id,
8833             decode(cce.cost_element_id,
8834               1, wdj.material_variance_account,
8835               3, wdj.resource_variance_account,
8836               4, wdj.outside_proc_variance_account,
8837               5, wdj.overhead_variance_account),
8838             SYSDATE,
8839             p_user_id,
8840             SYSDATE,
8841             p_user_id,
8842             p_login_id,
8843             c_route_rec.organization_id,
8844             to_date(c_route_rec.txn_date,'YYYY/MM/DD HH24:MI:SS'),
8845             c_route_rec.wip_entity_id,
8846             8,
8847             decode(cce.cost_element_id,
8848                     1,l_pl_var_total,
8849                     3,l_res_var_total,
8850                     4,l_osp_var_total,
8851                     5,l_ovh_var_total) * -1,
8852             c_route_rec.maintenance_object_id,
8853             cce.cost_element_id, -- CE
8854             p_request_id,
8855             p_prog_app_id,
8856             p_prog_id,
8857             SYSDATE
8858       FROM  cst_cost_elements cce,
8859             wip_discrete_jobs wdj
8860      where  cce.cost_element_id <> 2
8861             and wdj.wip_entity_id = c_route_rec.wip_entity_id
8862     group by cce.cost_element_id,
8863              decode(cce.cost_element_id,
8864               1, wdj.material_variance_account,
8865               3, wdj.resource_variance_account,
8866               4, wdj.outside_proc_variance_account,
8867               5, wdj.overhead_variance_account)
8868     having  decode(cce.cost_element_id,
8869                        1,l_pl_var_total,
8870                        3,l_res_var_total,
8871                        4,l_osp_var_total,
8872                        5,l_ovh_var_total) <> 0;
8873 
8874                l_stmt_num := 65;
8875                UPDATE WIP_TRANSACTION_ACCOUNTS
8876                SET    WIP_SUB_LEDGER_ID = CST_WIP_SUB_LEDGER_ID_S.NEXTVAL
8877                WHERE  TRANSACTION_ID = c_route_rec.transaction_id;
8878 
8879 
8880      end if; --check for member assets count
8881 
8882     END LOOP; --for route jobs
8883 
8884     l_stmt_num := 75;
8885     ---------------------------------------------------------------------------
8886     -- Standard check of p_commit
8887     ---------------------------------------------------------------------------
8888 
8889     IF FND_API.to_Boolean(p_commit) THEN
8890       COMMIT WORK;
8891     END IF;
8892 
8893     ---------------------------------------------------------------------------
8894     -- Standard Call to get message count and if count = 1, get message info
8895     ---------------------------------------------------------------------------
8896 
8897     FND_MSG_PUB.Count_And_Get (
8898         p_count     => x_msg_count,
8899         p_data      => x_msg_data );
8900 
8901  EXCEPTION
8902 
8903    WHEN fnd_api.g_exc_error THEN
8904       x_return_status := fnd_api.g_ret_sts_error;
8905 
8906         --  Get message count and data
8907         fnd_msg_pub.count_and_get
8908           (  p_count => x_msg_count
8909            , p_data  => x_msg_data
8910            );
8911       --
8912    WHEN fnd_api.g_exc_unexpected_error THEN
8913       x_return_status := fnd_api.g_ret_sts_unexp_error ;
8914       fnd_file.put_line(fnd_file.log,l_msg_data);
8915 
8916         --  Get message count and data
8917         fnd_msg_pub.count_and_get
8918           (  p_count  => x_msg_count
8919            , p_data   => x_msg_data
8920             );
8921       --
8922    WHEN OTHERS THEN
8923       x_return_status := fnd_api.g_ret_sts_unexp_error ;
8924       --
8925       IF fnd_msg_pub.check_msg_level(fnd_msg_pub.g_msg_lvl_unexp_error)
8926         THEN
8927          fnd_msg_pub.add_exc_msg
8928            (  'CST_EamJob_PUB'
8929               , 'Redistribute_WIP_Accounts : l_stmt_num - '
8930                          ||to_char(l_stmt_num)
8931               );
8932 
8933         END IF;
8934         --  Get message count and data
8935         fnd_msg_pub.count_and_get
8936           (  p_count  => x_msg_count
8937            , p_data   => x_msg_data
8938              );
8939 
8940 END Redistribute_WIP_Accounts;
8941 
8942 ----------------------------------------------------------------------------
8943 -- PROCEDURE                                                              --
8944 --  get_charge_asset                                                      --
8945 --                                                                        --
8946 -- DESCRIPTION                                                            --
8947 --  This API will be called instead of obtaining charge asset             --
8948 --  from wdj.asset_group_id                                               --
8949 --  It will provide support for the following                             --
8950 --   * regular asset work orders                                          --
8951 --   * rebuild work orders with parent asset                              --
8952 --   * standalone rebuild work orders                                     --
8953 --   * installed base items - future                                      --
8954 -- PURPOSE:                                                               --
8955 --   Oracle Applications 11i.9                                            --
8956 --                                                                        --
8957 -- HISTORY:                                                               --
8958 --    03/29/05  Anjali R   Modified for eAM Requirements Project - R12.   --
8959 --                         changes include reference to CSI_ITEM_INSTANCES--
8960 --                         table from MTL_EAM_NETWORK_ASSETS.             --
8961 --    11/26/02  Ray Thng   Created                                        --
8962 ----------------------------------------------------------------------------
8963   PROCEDURE get_charge_asset (
8964     p_api_version               IN         NUMBER,
8965     p_init_msg_list             IN         VARCHAR2 := FND_API.G_FALSE,
8966     p_wip_entity_id             IN         NUMBER,
8967     x_inventory_item_id         OUT NOCOPY csi_item_instances.inventory_item_id%TYPE,
8968     x_serial_number             OUT NOCOPY csi_item_instances.serial_number%TYPE,
8969     x_maintenance_object_id     OUT NOCOPY mtl_serial_numbers.gen_object_id%TYPE,
8970     x_return_status             OUT NOCOPY VARCHAR2,
8971     x_msg_count                 OUT NOCOPY NUMBER,
8972     x_msg_data                  OUT NOCOPY VARCHAR2)
8973   IS
8974     l_api_name CONSTANT         VARCHAR2(30) := 'get_asset';
8975     l_api_version CONSTANT      NUMBER       := 1.0;
8976     l_stmt_num                  NUMBER       := 0;
8977     l_return_status             VARCHAR2(1)  := fnd_api.g_ret_sts_success;
8978 
8979     l_parent_wip_entity_id      wip_discrete_jobs.parent_wip_entity_id%TYPE;
8980     l_parent_maint_object_type  wip_discrete_jobs.maintenance_object_type%TYPE;
8981     l_parent_maint_object_id    wip_discrete_jobs.maintenance_object_source%TYPE;
8982     l_parent_network_asset_flag csi_item_instances.network_asset_flag%TYPE;
8983     l_parent_inventory_item_id  csi_item_instances.inventory_item_id%TYPE;
8984     l_parent_serial_number      csi_item_instances.serial_number%TYPE;
8985     l_maint_object_type         wip_discrete_jobs.maintenance_object_type%TYPE;
8986     l_maint_object_id           wip_discrete_jobs.maintenance_object_source%TYPE;
8987     l_inventory_item_id         csi_item_instances.inventory_item_id%TYPE;
8988     l_serial_number             csi_item_instances.serial_number%TYPE;
8989   BEGIN
8990     -- Standard call to check for call compatibility
8991     IF NOT FND_API.Compatible_API_Call(l_api_version,p_api_version,l_api_name,G_PKG_NAME) THEN
8992       RAISE FND_API.G_EXC_UNEXPECTED_ERROR;
8993     END IF;
8994 
8995     -- Initialize message list if p_init_msg_list is set to TRUE
8996     IF FND_API.to_Boolean(p_init_msg_list) THEN
8997       FND_MSG_PUB.initialize;
8998     END IF;
8999 
9000     -- Initialize API return status to success
9001     l_stmt_num := 0;
9002     x_return_status := FND_API.G_RET_STS_SUCCESS;
9003 
9004 
9005     -- Retrieve information about the current work order and its parent
9006    /* Changed the following SQL statement to refer to CII
9007       instead of MSN for network Asset Flag */
9008     l_stmt_num := 10;
9009     SELECT  wdj.parent_wip_entity_id,
9010             pwdj.maintenance_object_type,
9011             pwdj.maintenance_object_id,
9012             pcii.network_asset_flag,
9013             pcii.inventory_item_id,
9014             pcii.serial_number,
9015             wdj.maintenance_object_type,
9016             wdj.maintenance_object_id,
9017             cii.inventory_item_id,
9018             cii.serial_number
9019     INTO    l_parent_wip_entity_id,
9020             l_parent_maint_object_type,
9021             l_parent_maint_object_id,
9022             l_parent_network_asset_flag,
9023             l_parent_inventory_item_id,
9024             l_parent_serial_number,
9025             l_maint_object_type,
9026             l_maint_object_id,
9027             l_inventory_item_id,
9028             l_serial_number
9029     FROM    wip_discrete_jobs wdj,
9030             wip_discrete_jobs pwdj,
9031             csi_item_instances cii,
9032             csi_item_instances pcii
9033     WHERE   wdj.wip_entity_id = p_wip_entity_id
9034     AND     cii.instance_id (+) = wdj.maintenance_object_id
9035     AND     pwdj.wip_entity_id (+) = wdj.parent_wip_entity_id
9036     AND     pcii.instance_id (+) = pwdj.maintenance_object_id;
9037 
9038    /* Also added condition below to check for Maintenance_object_type as 3
9039       as part of eAM Requirements project. For assets associated with
9040       IB instances, maintenance_object_id will store value as 3. All previous
9041       rows storing the value of 1 will be updated to 3 as part of the project */
9042     -- Set the output depending on the work order type and the network asset flag
9043     l_stmt_num := 20;
9044     -- Rebuildable Work Order with a non network asset parent
9045 
9046     IF l_parent_maint_object_type = 3 AND
9047        l_parent_network_asset_flag = 'N' THEN
9048       x_inventory_item_id := l_parent_inventory_item_id;
9049       x_serial_number := l_parent_serial_number;
9050       x_maintenance_object_id := l_parent_maint_object_id;
9051     -- Rebuildable Work Order with a network asset parent OR Asset Work Order
9052     ELSIF  l_maint_object_type = 3 AND
9053            (   l_parent_wip_entity_id IS NULL
9054            OR  l_parent_maint_object_type <> 3
9055            OR  l_parent_network_asset_flag <> 'N') THEN
9056       x_inventory_item_id := l_inventory_item_id;
9057       x_serial_number := l_serial_number;
9058       x_maintenance_object_id := l_maint_object_id;
9059     -- Other cases
9060     ELSE
9061       x_inventory_item_id := NULL;
9062       x_serial_number := NULL;
9063       x_maintenance_object_id := NULL;
9064     END IF;
9065 
9066     -- Standard Call to get message count and if count = 1, get message info
9067     l_stmt_num := 30;
9068     FND_MSG_PUB.Count_And_Get(
9069       p_count => x_msg_count,
9070       p_data  => x_msg_data);
9071 
9072   EXCEPTION
9073     WHEN fnd_api.g_exc_error THEN
9074       x_return_status := fnd_api.g_ret_sts_error;
9075 
9076       --  Get message count and data
9077       fnd_msg_pub.count_and_get(
9078         p_count => x_msg_count,
9079         p_data  => x_msg_data);
9080 
9081     WHEN fnd_api.g_exc_unexpected_error THEN
9082       x_return_status := fnd_api.g_ret_sts_unexp_error ;
9083 
9084       --  Get message count and data
9085       fnd_msg_pub.count_and_get(
9086         p_count => x_msg_count,
9087         p_data  => x_msg_data);
9088 
9089     WHEN OTHERS THEN
9090       x_return_status := fnd_api.g_ret_sts_unexp_error ;
9091 
9092       IF fnd_msg_pub.check_msg_level(fnd_msg_pub.g_msg_lvl_unexp_error) THEN
9093         fnd_msg_pub.add_exc_msg(
9094           'CST_eamCost_PUB',
9095           'get_charge_asset : Statement - '|| to_char(l_stmt_num));
9096       END IF;
9097 
9098       --  Get message count and data
9099       fnd_msg_pub.count_and_get(
9100         p_count => x_msg_count,
9101         p_data  => x_msg_data);
9102   END get_charge_asset;
9103 
9104 ----------------------------------------------------------------------------
9105 -- PROCEDURE                                                              --
9106 --  get_CostEle_for_DirectItem                                        --
9107 --                                                                        --
9108 -- DESCRIPTION                                                            --
9109 --   This API will return which cost element ID is to be charged for the
9110 --   the direct item transactions
9111 -- PURPOSE:                                                               --
9112 --   Oracle Applications 11i.10                                            --
9113 --                                                                        --
9114 -- HISTORY:                                                               --
9115 --    06/26/03  Linda Soo        Created                                   --
9116 ----------------------------------------------------------------------------
9117 PROCEDURE get_CostEle_for_DirectItem (
9118   p_api_version                 IN         NUMBER,
9119   p_init_msg_list               IN         VARCHAR2 := FND_API.G_FALSE,
9120   p_commit                      IN           VARCHAR2 := FND_API.G_FALSE,
9121   p_validation_level            IN           NUMBER := FND_API.G_VALID_LEVEL_FULL,
9122   p_txn_id                      IN           NUMBER,
9123   p_mnt_or_mfg                  IN           NUMBER, -- 1: eam cost element,
9124                                                    -- 2: manufacturing cost ele
9125   p_pac_or_perp                 IN         NUMBER, -- 1 for PAC, 0 (default) for Perpetual
9126   x_cost_element_id             OUT NOCOPY NUMBER,
9127   x_return_status               OUT NOCOPY VARCHAR2,
9128   x_msg_count                   OUT NOCOPY NUMBER,
9129   x_msg_data                    OUT NOCOPY VARCHAR2)
9130 IS
9131   l_api_name            CONSTANT        VARCHAR2(30) := 'get_CostElement_for_DirectItem';
9132   l_api_version         CONSTANT        NUMBER := 1.0;
9133 
9134   l_api_message                         VARCHAR2(240);
9135   l_statement                           NUMBER := 0;
9136   l_debug                   VARCHAR2(80);
9137 
9138   l_count                               NUMBER;
9139   l_po_header_id                        NUMBER;
9140   l_po_line_id                          NUMBER;
9141   l_category_id                         NUMBER;
9142   l_approved_date                       DATE;
9143   l_cost_element_id                     NUMBER;
9144 
9145  l_type_lookup_code                    VARCHAR2(20);
9146   l_po_release_id                       NUMBER;
9147   l_rcv_txn_id                          NUMBER;
9148   l_po_dist_id                          NUMBER;
9149   l_source_code                         VARCHAR2(30);
9150 
9151 
9152 BEGIN
9153   -----------------------------------
9154   -- Standard start of API savepoint
9155   -----------------------------------
9156   SAVEPOINT get_CostEle_for_DirectItem_PVT;
9157 
9158   l_debug := fnd_profile.value('MRP_DEBUG');
9159   if (l_debug = 'Y') THEN
9160     fnd_file.put_line(fnd_file.log, 'In get_CostEle_for_DirectItem');
9161   end if;
9162 
9163   ------------------------------------------------
9164   -- Standard call to check for API compatibility
9165   ------------------------------------------------
9166   l_statement := 10;
9167   IF not fnd_api.compatible_api_call( l_api_version,
9168                                       p_api_version,
9169                                       l_api_name,
9170                                       G_PKG_NAME ) then
9171     RAISE fnd_api.G_exc_unexpected_error;
9172   END IF;
9173 
9174   -------------------------------------------------------------
9175   -- Initialize message list if p_init_msg_list is set to TRUE
9176   -------------------------------------------------------------
9177   l_statement := 20;
9178   IF fnd_api.to_Boolean(p_init_msg_list) then
9179     fnd_msg_pub.initialize;
9180   end if;
9181 
9182   -------------------------------------------
9183   -- Initialize API return status to Success
9184   -------------------------------------------
9185   l_statement := 30;
9186   x_return_status := fnd_api.g_ret_sts_success;
9187 
9188   -----------------------------
9189   -- Validate input parameters
9190   -----------------------------
9191   l_statement := 40;
9192   if (p_txn_id is null or p_mnt_or_mfg is null) then
9193     l_api_message := 'One of the IN parameter is null';
9194     FND_MESSAGE.set_name('BOM','CST_API_MESSAGE');
9195     FND_MESSAGE.set_token('TEXT', l_api_message);
9196     FND_MSG_PUB.add;
9197     RAISE fnd_api.g_exc_error;
9198   end if;
9199 
9200   ----------------------------------------------------------------------
9201   --  Verify if transaction ID exists, Obtain po_header_id and po_line_id
9202   ----------------------------------------------------------------------
9203 
9204 IF p_pac_or_perp = 0 THEN -- Perpetual side code not changed
9205   l_statement := 50;
9206   begin
9207     select nvl(wcti.po_header_id, -1),
9208            nvl(wcti.po_line_id, -1),
9209            nvl(wcti.rcv_transaction_id, -1),
9210 	   decode(source_code,'IPV',nvl(To_Number (SubStr(wcti.REFERENCE,18)),-1),-999999),
9211 	   source_code
9212     into l_po_header_id,
9213          l_po_line_id,
9214          l_rcv_txn_id,
9215 	 l_po_dist_id,
9216 	 l_source_code
9217     from wip_cost_txn_interface wcti
9218     where wcti.transaction_id = p_txn_id;
9219   exception
9220     when no_data_found then
9221       l_api_message := 'Transaction ID does not exist in WIP_COST_TXN_INTERFACE table. ';
9222       FND_MESSAGE.set_name('BOM','CST_API_MESSAGE');
9223       FND_MESSAGE.set_token('TEXT', l_api_message);
9224       FND_MSG_PUB.add;
9225       RAISE fnd_api.g_exc_error;
9226   end;
9227  ELSE -- Done to support eAM in PAC, get data from WT as WCTI contains nothing at this moment
9228   l_statement := 55;
9229   begin
9230     select nvl(wt.po_header_id, -1),
9231            nvl(wt.po_line_id, -1),
9232            nvl(wt.rcv_transaction_id, -1),
9233            decode(source_code,'IPV',nvl(To_Number (SubStr(wt.REFERENCE,18)),-1),-999999),
9234 	   source_code
9235     into l_po_header_id,
9236          l_po_line_id,
9237          l_rcv_txn_id,
9238 	 l_po_dist_id,
9239 	 l_source_code
9240     from wip_transactions wt
9241     where wt.transaction_id = p_txn_id;
9242   exception
9243     when no_data_found then
9244       l_api_message := 'Transaction ID does not exist in WIP_TRANSACTIONS table. ';
9245       FND_MESSAGE.set_name('BOM','CST_API_MESSAGE');
9246       FND_MESSAGE.set_token('TEXT', l_api_message);
9247       FND_MSG_PUB.add;
9248       RAISE fnd_api.g_exc_error;
9249   end;
9250  END IF;
9251   ----------------------------------------
9252   --  Obtain approved_date, po doc type
9253   ---------------------------------------
9254   l_statement := 60;
9255   if (l_po_header_id <> -1) then
9256     select pha.approved_date,
9257            type_lookup_code
9258     into l_approved_date,
9259          l_type_lookup_code
9260     from po_headers_all pha
9261     where pha.po_header_id = l_po_header_id;
9262   else
9263     l_api_message := 'No po_header_id exist for transaction ID: ' || TO_CHAR(p_txn_id);
9264     l_api_message := l_api_message || ' wip_cost_txn_interface ';
9265     FND_MESSAGE.set_name('BOM','CST_API_MESSAGE');
9266     FND_MESSAGE.set_token('TEXT', l_api_message);
9267     FND_MSG_pub.add;
9268     RAISE FND_API.g_exc_error;
9269   end if;
9270 
9271   -----------------------
9272   --  Obtain category_id
9273   -----------------------
9274   l_statement := 70;
9275   if (l_po_line_id <> -1) then
9276     select nvl(pla.category_id, -1)
9277     into l_category_id
9278     from po_lines_all pla
9279     where pla.po_line_id = l_po_line_id;
9280   else
9281     l_api_message := 'No po_line_id exist for transaction ID: ' || TO_CHAR(p_txn_id);
9282     l_api_message := l_api_message || ' wip_cost_txn_interface ';
9283     FND_MESSAGE.set_name('BOM','CST_API_MESSAGE');
9284     FND_MESSAGE.set_token('TEXT', l_api_message);
9285     FND_MSG_pub.add;
9286     RAISE FND_API.g_exc_error;
9287   end if;
9288 
9289   ------------------------
9290   --  Obtain cost element
9291   ------------------------
9292   l_statement := 80;
9293   if (l_category_id <> -1 and l_approved_date is not null) then
9294 
9295      If (l_type_lookup_code = 'BLANKET') then
9296 
9297        IF (l_source_code = 'IPV') then
9298 
9299           If (l_po_dist_id <> -1) then
9300            select po_release_id
9301            into l_po_release_id
9302            from po_distributions_all
9303            where po_distribution_id=l_po_dist_id
9304 	   and po_header_id= l_po_header_id;
9305 
9306 
9307          Else
9308            l_api_message := 'No PO Distribution  exist for transaction ID: ' || TO_CHAR(p_txn_id);
9309            l_api_message := l_api_message || ' wip_cost_txn_interface ';
9310            FND_MESSAGE.set_name('BOM','CST_API_MESSAGE');
9311            FND_MESSAGE.set_token('TEXT', l_api_message);
9312            FND_MSG_pub.add;
9313            RAISE FND_API.g_exc_error;
9314          End if;
9315 
9316        ELSE
9317 
9318          If (l_rcv_txn_id <> -1) then
9319            select po_release_id
9320            into l_po_release_id
9321            from rcv_transactions
9322            where transaction_id = l_rcv_txn_id;
9323          Else
9324            l_api_message := 'No rcv_transaction_id exist for transaction ID: ' || TO_CHAR(p_txn_id);
9325            l_api_message := l_api_message || ' wip_cost_txn_interface ';
9326            FND_MESSAGE.set_name('BOM','CST_API_MESSAGE');
9327            FND_MESSAGE.set_token('TEXT', l_api_message);
9328            FND_MSG_pub.add;
9329            RAISE FND_API.g_exc_error;
9330          End if;
9331 
9332        END IF;
9333 
9334          If (l_po_release_id <> -1) then
9335            select approved_date
9336            into l_approved_date
9337            from po_releases_all
9338            where po_release_id = l_po_release_id;
9339          Else
9340            l_api_message := 'No po_release_id exist for transaction ID: ' || TO_CHAR(p_txn_id);
9341            l_api_message := l_api_message || ' wip_cost_txn_interface ';
9342            FND_MESSAGE.set_name('BOM','CST_API_MESSAGE');
9343            FND_MESSAGE.set_token('TEXT', l_api_message);
9344            FND_MSG_pub.add;
9345            RAISE FND_API.g_exc_error;
9346          End if;
9347 
9348     end if;
9349 
9350     if p_mnt_or_mfg = 1 then
9351       begin
9352         select cceea.mnt_cost_element_id
9353         into l_cost_element_id
9354         from cst_cat_ele_exp_assocs cceea
9355         where cceea.category_id = l_category_id
9356           and l_approved_date >= cceea.start_date
9357           and l_approved_date < (nvl(cceea.end_date,sysdate) + 1);
9358       exception
9359         when no_data_found then
9360           l_cost_element_id := 3;
9361       end;
9362     else
9363       begin
9364         select cceea.mfg_cost_element_id
9365         into l_cost_element_id
9366         from cst_cat_ele_exp_assocs cceea
9367         where cceea.category_id = l_category_id
9368           and l_approved_date >= cceea.start_date
9369           and l_approved_date < (nvl(cceea.end_date, sysdate) + 1);
9370       exception
9371         when no_data_found then
9372           l_cost_element_id := 1;
9373       end;
9374     end if;
9375   elsif (l_category_id = -1) then
9376     l_api_message := 'No category_id exist for PO Line ID: ' || TO_CHAR(l_po_line_id);
9377     FND_MESSAGE.set_name('BOM','CST_API_MESSAGE');
9378     FND_MESSAGE.set_token('TEXT', l_api_message);
9379     FND_MSG_pub.add;
9380     RAISE FND_API.g_exc_error;
9381   else
9382     l_api_message := 'PO Header ID ' || TO_CHAR(l_po_header_id);
9383     l_api_message := l_api_message || ' has not been approved';
9384     FND_MESSAGE.set_name('BOM','CST_API_MESSAGE');
9385     FND_MESSAGE.set_token('TEXT', l_api_message);
9386     FND_MSG_pub.add;
9387     RAISE FND_API.g_exc_error;
9388   end if;
9389 
9390   x_cost_element_id := l_cost_element_id;
9391 
9392   -- Standard Call to get message count and if count = 1, get message info
9393   FND_MSG_PUB.Count_And_Get (
9394     p_count     => x_msg_count,
9395     p_data      => x_msg_data );
9396 
9397 EXCEPTION
9398   WHEN fnd_api.g_exc_error then
9399     x_return_status := fnd_api.g_ret_sts_error;
9400     x_cost_element_id := -1;
9401 
9402     fnd_msg_pub.count_and_get(
9403       p_count => x_msg_count,
9404       p_data  => x_msg_data );
9405 
9406   WHEN fnd_api.g_exc_unexpected_error then
9407     x_return_status := fnd_api.g_ret_sts_unexp_error;
9408     x_cost_element_id := -1;
9409 
9410     fnd_msg_pub.count_and_get(
9411       p_count => x_msg_count,
9412       p_data  => x_msg_data );
9413 
9414   WHEN OTHERS THEN
9415     x_return_status := fnd_api.g_ret_sts_unexp_error ;
9416     x_cost_element_id:= -1;
9417     If fnd_msg_pub.check_msg_level(fnd_msg_pub.g_msg_lvl_unexp_error) then
9418       fnd_msg_pub.add_exc_msg ( 'CST_eamCost_PUB',
9419         ' get_CostElement_for_DirectItem: Statement - ' || to_char(l_statement));
9420     end if;
9421 
9422     fnd_msg_pub.count_and_get(
9423       p_count => x_msg_count,
9424       p_data  => x_msg_data );
9425 END get_CostEle_for_DirectItem;
9426 
9427 /*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
9428 |   PROCEDURE                                                                 |
9429 |     get_ExpType_for_DirectItem                                              |
9430 |                                                                             |
9431 |   DESCRIPTION                                                               |
9432 |     This API retrieves the direct  expenditure type  that will be used  for |
9433 |     direct items , its  logic will default  the  expenditure  type  to  the |
9434 |     expenditure type found  in  the  category  associations  form  for  the |
9435 |     category associated with the purchase order line and if not found there |
9436 |     it will like at the expenditure type in the pjm  project parameters and |
9437 |     if not found there it will look at the expenditure  type in the pjm org |
9438 |     parameters.                                                             |
9439 |                                                                             |
9440 |   PURPOSE:                                                                  |
9441 |     Oracle Applications R12                                                 |
9442 |     To support Cost Collection Transfer to Projects of Direct Items for EAM |
9443 |     work orders                                                             |
9444 |   PARAMETERS:                                                               |
9445 |     p_api_version           IN         NUMBER                               |
9446 |     p_init_msg_list         IN         VARCHAR2 := FND_API.G_FALSE          |
9447 |     p_commit                IN         VARCHAR2 := FND_API.G_FALSE          |
9448 |     p_validation_level      IN         NUMBER := FND_API.G_VALID_LEVEL_FULL |
9449 |     p_txn_id                IN         NUMBER                               |
9450 |     x_expenditure_type      OUT NOCOPY VARCHAR2                             |
9451 |     x_return_status         OUT NOCOPY VARCHAR2                             |
9452 |     x_msg_count             OUT NOCOPY NUMBER                               |
9453 |     x_msg_data              OUT NOCOPY VARCHAR2                             |
9454 |                                                                             |
9455 |                                                                             |
9456 |    HISTORY:                                                                 |
9457 |     06/26/03  Linda Soo        Created                                      |
9458 |     08/20/09  Ivan Pineda      Added logic for  this  API  to  retrieve the |
9459 |                                expenditure type from pjm_project_parameters |
9460 |                                or pjm_org_parameters when its  not found in |
9461 |                                in the category associations                 |
9462 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
9463   PROCEDURE get_ExpType_for_DirectItem (
9464     p_api_version               IN         NUMBER,
9465     p_init_msg_list             IN         VARCHAR2 := FND_API.G_FALSE,
9466     p_commit                    IN           VARCHAR2 := FND_API.G_FALSE,
9467     p_validation_level          IN           NUMBER := FND_API.G_VALID_LEVEL_FULL,
9468     p_txn_id                    IN           NUMBER,
9469     x_expenditure_type          OUT NOCOPY VARCHAR2,
9470     x_return_status             OUT NOCOPY VARCHAR2,
9471     x_msg_count                 OUT NOCOPY NUMBER,
9472     x_msg_data                  OUT NOCOPY VARCHAR2)
9473 IS
9474   l_api_name            CONSTANT        VARCHAR2(30) := 'get_ExpType_for_DirectItem';
9475   l_api_version         CONSTANT        NUMBER := 1.0;
9476 
9477   l_api_message                         VARCHAR2(240);
9478   l_statement                           NUMBER := 0;
9479   l_debug                   VARCHAR2(80);
9480 
9481   l_count                               NUMBER;
9482   l_po_header_id                        NUMBER;
9483   l_po_line_id                          NUMBER;
9484   l_category_id                         NUMBER;
9485   l_approved_date                       DATE;
9486   l_expenditure_type                    VARCHAR2(30);
9487   /*+++++++++++++++++++++++++++++++++++++++++++++++++++++++
9488      Added this two  parameters for bug  7328006 to retrieve
9489      project_id  and o rganization_id in  the same access to
9490      wip_transactions to don't hurt  the  performance and at
9491      the same time be able to access  Pjm_project_parameters
9492      and pjm_org_parameters to check if the expenditure type
9493      is defined in there
9494    ++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
9495   l_organization_id			NUMBER;
9496   l_project_id				NUMBER;
9497 
9498 BEGIN
9499   -----------------------------------
9500   -- Standard start of API savepoint
9501   -----------------------------------
9502   SAVEPOINT get_ExpType_for_DirectItem_PVT;
9503 
9504   l_debug := fnd_profile.value('MRP_DEBUG');
9505   if (l_debug = 'Y') THEN
9506     fnd_file.put_line(fnd_file.log, 'In get_ExpType_for_DirectItem');
9507   end if;
9508 
9509   ------------------------------------------------
9510   -- Standard call to check for API compatibility
9511   ------------------------------------------------
9512   l_statement := 10;
9513   IF not fnd_api.compatible_api_call( l_api_version,
9514                                       p_api_version,
9515                                       l_api_name,
9516                                       G_PKG_NAME ) then
9517     RAISE fnd_api.G_exc_unexpected_error;
9518   END IF;
9519 
9520   -------------------------------------------------------------
9521   -- Initialize message list if p_init_msg_list is set to TRUE
9522   -------------------------------------------------------------
9523   l_statement := 20;
9524   IF fnd_api.to_Boolean(p_init_msg_list) then
9525     fnd_msg_pub.initialize;
9526   end if;
9527 
9528   -------------------------------------------
9529   -- Initialize API return status to Success
9530   -------------------------------------------
9531   l_statement := 30;
9532   x_return_status := fnd_api.g_ret_sts_success;
9533 
9534   -----------------------------
9535   -- Validate input parameters
9536   -----------------------------
9537   l_statement := 40;
9538   if (p_txn_id is null) then
9539     l_api_message := 'IN parameter is null';
9540     FND_MESSAGE.set_name('BOM','CST_API_MESSAGE');
9541     FND_MESSAGE.set_token('TEXT', l_api_message);
9542     FND_MSG_PUB.add;
9543     RAISE fnd_api.g_exc_error;
9544   end if;
9545 
9546   -----------------------------------------------------------------------
9547   --  Verify if transaction ID exists and Obtain po_header_id, po_line_id
9548   --  project_id and organization_id from wip_transactions
9549   -----------------------------------------------------------------------
9550   l_statement := 50;
9551   begin
9552     select nvl(wt.po_header_id, -1),
9553       	   nvl(wt.po_line_id, -1),
9554 	   nvl(wt.project_id, -1),
9555 	   nvl(wt.organization_id, -1)
9556     into   l_po_header_id,
9557            l_po_line_id,
9558            l_project_id,
9559            l_organization_id
9560     from   wip_transactions wt
9561     where  wt.transaction_id = p_txn_id;
9562   exception
9563     when no_data_found then
9564       l_api_message := 'Transaction ID does not exist in WIP_TRANSACTIONS table.';
9565       FND_MESSAGE.set_name('BOM','CST_API_MESSAGE');
9566       FND_MESSAGE.set_token('TEXT', l_api_message);
9567       FND_MSG_PUB.add;
9568       RAISE fnd_api.g_exc_error;
9569   end;
9570 
9571   -------------------------
9572   --  Obtain approved_date
9573   -------------------------
9574   l_statement := 60;
9575   if (l_po_header_id <> -1) then
9576     select pha.approved_date
9577     into l_approved_date
9578     from po_headers_all pha
9579     where pha.po_header_id = l_po_header_id;
9580   else
9581     l_api_message := 'No po_header_id exist for transaction ID: ' || TO_CHAR(p_txn_id);
9582     l_api_message := l_api_message || ' wip_transactions ';
9583     FND_MESSAGE.set_name('BOM','CST_API_MESSAGE');
9584     FND_MESSAGE.set_token('TEXT', l_api_message);
9585     FND_MSG_pub.add;
9586     RAISE FND_API.g_exc_error;
9587   end if;
9588 
9589   -----------------------
9590   --  Obtain category_id
9591   -----------------------
9592   l_statement := 70;
9593   if (l_po_line_id <> -1) then
9594     select nvl(pla.category_id, -1)
9595     into l_category_id
9596     from po_lines_all pla
9597     where pla.po_line_id = l_po_line_id;
9598   else
9599     l_api_message := 'No po_line_id exist for transaction ID: ' || TO_CHAR(p_txn_id);
9600     l_api_message := l_api_message || ' wip_transactions ';
9601     FND_MESSAGE.set_name('BOM','CST_API_MESSAGE');
9602     FND_MESSAGE.set_token('TEXT', l_api_message);
9603     FND_MSG_pub.add;
9604     RAISE FND_API.g_exc_error;
9605   end if;
9606 
9607 /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
9608    The following logic will be used to derive the expenditure
9609    type for direct items:
9610    1. Look  into the category associations to find the exp
9611       type associated with the purchasing category for the
9612       direct item
9613    2. If 1 is not found then look at the expenditure type
9614       at the pjm_project_parameters table defined for
9615       direct items.
9616    3. If 2 is not found (like in the case of the common
9617       project) then use the expenditure type at the
9618       pjm_org_parameters table defined for direct items
9619    4. If 3 is not found then error out
9620    +++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
9621   /*++++++++++++++++++++++++++++++++++++++++++++++++++++++++
9622   |   Check if the expenditure type is  defined in the     |
9623   |   category associations                                |
9624   ++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
9625   l_statement := 80;
9626   if (l_category_id <> -1 and l_approved_date is not null) then
9627     begin
9628       select pet.expenditure_type
9629       into l_expenditure_type
9630       from cst_cat_ele_exp_assocs cceea,
9631         pa_expenditure_types pet
9632       where cceea.category_id = l_category_id
9633         and l_approved_date >= cceea.start_date
9634         and l_approved_date < (nvl(cceea.end_date, sysdate) + 1)
9635     and cceea.expenditure_type_id = pet.expenditure_type_id;
9636     exception
9637       when no_data_found then
9638         l_expenditure_type := to_char(-1);
9639     end;
9640   elsif (l_category_id = -1) then
9641     l_api_message := 'No category_id exist for PO Line ID: ' || TO_CHAR(l_po_line_id);
9642     FND_MESSAGE.set_name('BOM','CST_API_MESSAGE');
9643     FND_MESSAGE.set_token('TEXT', l_api_message);
9644     FND_MSG_pub.add;
9645     RAISE FND_API.g_exc_error;
9646   else
9647     l_api_message := 'PO Header ID ' || TO_CHAR(l_po_header_id);
9648     l_api_message := l_api_message || ' has not been approved';
9649     FND_MESSAGE.set_name('BOM','CST_API_MESSAGE');
9650     FND_MESSAGE.set_token('TEXT', l_api_message);
9651     FND_MSG_pub.add;
9652     RAISE FND_API.g_exc_error;
9653   end if;
9654 
9655   /*++++++++++++++++++++++++++++++++++++++++++++++++++++++++
9656   |   Check if the expenditure type was not defined in the |
9657   |   category associations then try to derive it from     |
9658   |   pjm_project_parameters                               |
9659   ++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
9660   l_statement := 90;
9661   if (l_expenditure_type = to_char(-1)) then
9662   	if (l_debug = 'Y') THEN
9663     		fnd_file.put_line(fnd_file.log, 'No expenditure type found in category associations');
9664     		fnd_file.put_line(fnd_file.log, 'Deriving expenditure type from Project Parameters');
9665  	end if;
9666      	begin
9667       		select 	ppp.dir_item_expenditure_type
9668       		into	l_expenditure_type
9669       		from	pjm_project_parameters ppp
9670       		where	ppp.project_id = l_project_id
9671                 and     ppp.organization_id = l_organization_id;
9672        	exception
9673           	when no_data_found then
9674         		l_expenditure_type := to_char(-1);
9675     	end;
9676    end if;
9677 
9678   /*++++++++++++++++++++++++++++++++++++++++++++++++++++++++
9679   |   Check if the expenditure type was not defined in the |
9680   |   project parameters then try to derive it from the    |
9681   |   pjm_org_parameters                                   |
9682   ++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
9683   l_statement := 100;
9684   if (l_expenditure_type = to_char(-1)) then
9685   	if (l_debug = 'Y') THEN
9686     		fnd_file.put_line(fnd_file.log, 'No expenditure type found in Project Parameters');
9687     		fnd_file.put_line(fnd_file.log, 'Deriving expenditure type from PJM Org Parameters');
9688  	end if;
9689      	begin
9690       		select 	pop.dir_item_expenditure_type
9691       		into	l_expenditure_type
9692       		from	pjm_org_parameters pop
9693       		where	pop.organization_id = l_organization_id;
9694        	exception
9695           	when no_data_found then
9696   			if (l_debug = 'Y') THEN
9697     				fnd_file.put_line(fnd_file.log, 'No expenditure type found, transaction will error out');
9698  			end if;
9699         		l_expenditure_type := to_char(-1);
9700     			l_api_message := 'No expenditure type has been setup in the category, project prameters';
9701                         l_api_message := l_api_message || ' or project organization parameters';
9702    			FND_MESSAGE.set_name('BOM','CST_API_MESSAGE');
9703    			FND_MESSAGE.set_token('TEXT', l_api_message);
9704     			FND_MSG_pub.add;
9705     			RAISE FND_API.g_exc_error;
9706     	end;
9707    end if;
9708 
9709   x_expenditure_type := l_expenditure_type;
9710 
9711   -- Standard Call to get message count and if count = 1, get message info
9712   FND_MSG_PUB.Count_And_Get (
9713     p_count     => x_msg_count,
9714     p_data      => x_msg_data );
9715 
9716 EXCEPTION
9717   WHEN fnd_api.g_exc_error then
9718     x_return_status := fnd_api.g_ret_sts_error;
9719     x_expenditure_type := to_char(-1);
9720 
9721     fnd_msg_pub.count_and_get(
9722       p_count => x_msg_count,
9723       p_data  => x_msg_data );
9724 
9725   WHEN fnd_api.g_exc_unexpected_error then
9726     x_return_status := fnd_api.g_ret_sts_unexp_error;
9727     x_expenditure_type := to_char(-1);
9728 
9729     fnd_msg_pub.count_and_get(
9730       p_count => x_msg_count,
9731       p_data  => x_msg_data );
9732 
9733   WHEN OTHERS THEN
9734     x_return_status := fnd_api.g_ret_sts_unexp_error ;
9735     x_expenditure_type := to_char(-1);
9736     If fnd_msg_pub.check_msg_level(fnd_msg_pub.g_msg_lvl_unexp_error) then
9737       fnd_msg_pub.add_exc_msg ( 'CST_eamCost_PUB',
9738         ' get_ExpType_for_DirectItem: Statement - ' || to_char(l_statement));
9739     end if;
9740 
9741     fnd_msg_pub.count_and_get(
9742       p_count => x_msg_count,
9743       p_data  => x_msg_data );
9744 END get_ExpType_for_DirectItem;
9745 
9746   PROCEDURE Rollup_WorkOrderCost(
9747     p_api_version     IN         NUMBER,
9748     p_init_msg_list   IN         VARCHAR2,
9749     p_commit          IN         VARCHAR2,
9750     p_group_id        IN         NUMBER,
9751     p_organization_id IN         NUMBER,
9752     p_user_id         IN         NUMBER,
9753     p_prog_appl_id    IN         NUMBER,
9754     x_return_status   OUT NOCOPY VARCHAR2
9755    )
9756   IS
9757     l_api_name CONSTANT VARCHAR2(30) := 'Rollup_WorkOrderCost';
9758     l_api_version CONSTANT NUMBER := 1.0;
9759     l_msg_level_threshold NUMBER;
9760     l_max_level NUMBER;
9761     l_stmt_num NUMBER := 0;
9762     l_object_type_count NUMBER;
9763     l_object_type_exc EXCEPTION;
9764   BEGIN
9765     -- Standard Start of API savepoint
9766     SAVEPOINT Rollup_WorkOrderCost_PUB;
9767 
9768     -- Initialize message list if p_init_msg_list is set to TRUE
9769     IF FND_API.to_Boolean(p_init_msg_list) THEN
9770       FND_MSG_PUB.initialize;
9771     END IF;
9772 
9773     -- Check for call compatibility
9774     IF NOT FND_API.Compatible_API_Call
9775            ( p_current_version_number => l_api_version,
9776              p_caller_version_number => p_api_version,
9777              p_api_name => l_api_name,
9778              p_pkg_name => G_PKG_NAME
9779            )
9780     THEN
9781       RAISE FND_API.G_EXC_UNEXPECTED_ERROR;
9782     END IF;
9783 
9784     -- Check for message level threshold
9785     l_msg_level_threshold := FND_PROFILE.Value('FND_AS_MSG_LEVEL_THRESHOLD');
9786 
9787     IF l_msg_level_threshold <= FND_MSG_PUB.G_MSG_LVL_DEBUG_HIGH
9788     THEN
9789       FND_MSG_PUB.Add_Exc_Msg(
9790         p_pkg_name => G_PKG_NAME,
9791         p_procedure_name => l_api_name,
9792         p_error_text => SUBSTR(
9793                           l_stmt_num||':'||
9794                           p_group_id||','||
9795                           p_organization_id||','||
9796                           1,
9797                           240
9798                         )
9799       );
9800     END IF;
9801 
9802     l_stmt_num := 5;
9803     SELECT count(*)
9804     INTO   l_object_type_count
9805     FROM   cst_eam_hierarchy_snapshot
9806     WHERE  group_id = p_group_id
9807     AND    (object_type IS NULL OR parent_object_type IS NULL);
9808 
9809     IF l_object_type_count <> 0 THEN
9810       RAISE l_object_type_exc;
9811     END IF;
9812 
9813     -- Calculate the depth of the hierarchy
9814     l_stmt_num := 10;
9815     SELECT MAX(level_num)
9816     INTO   l_max_level
9817     FROM   cst_eam_hierarchy_snapshot
9818     WHERE  group_id = p_group_id;
9819 
9820     -- Generate a warning if there is no matching record in the supplied group id
9821     l_stmt_num := 15;
9822     IF l_max_level IS NULL and l_msg_level_threshold <= FND_MSG_PUB.G_MSG_LVL_SUCCESS
9823     THEN
9824       FND_MSG_PUB.Add_Exc_Msg(
9825         p_pkg_name => G_PKG_NAME,
9826         p_procedure_name => l_api_name,
9827         p_error_text => 'There is no matching record in CST_EAM_HIERARCHY_SNAPSHOT ' ||
9828                         'for group id ' || p_group_id
9829       );
9830       x_return_status := FND_API.G_RET_STS_SUCCESS;
9831       RETURN;
9832     END IF;
9833 
9834     -- Delete existing calculations for this group id
9835     l_stmt_num := 17;
9836     DELETE cst_eam_rollup_costs
9837     WHERE  group_id = p_group_id;
9838 
9839     -- Generate a warning if there are existing calculations for this group id
9840     l_stmt_num := 19;
9841     IF SQL%ROWCOUNT > 0 and l_msg_level_threshold <= FND_MSG_PUB.G_MSG_LVL_DEBUG_HIGH
9842     THEN
9843       FND_MSG_PUB.Add_Exc_Msg(
9844         p_pkg_name => G_PKG_NAME,
9845         p_procedure_name => l_api_name,
9846         p_error_text => 'Deleted ' || SQL%ROWCOUNT || ' existing calculation for ' ||
9847                         ' group id '|| p_group_id
9848       );
9849     END IF;
9850 
9851     -- Calculate the cumulative costs, starting from the leaf nodes.
9852     l_stmt_num := 20;
9853     FOR l_level IN REVERSE 0 .. l_max_level LOOP
9854       INSERT
9855       INTO   cst_eam_rollup_costs(
9856                group_id,
9857                object_type,
9858                object_id,
9859                period_set_name,
9860                period_name,
9861                maint_cost_category,
9862                actual_mat_cost,
9863                actual_lab_cost,
9864                actual_eqp_cost,
9865                estimated_mat_cost,
9866                estimated_lab_cost,
9867                estimated_eqp_cost,
9868                last_update_date,
9869                last_updated_by,
9870                creation_date,
9871                creation_by,
9872                program_application_id
9873              )
9874       SELECT TEMP.group_id,
9875              TEMP.object_type,
9876              TEMP.object_id,
9877              TEMP.period_set_name,
9878              TEMP.period_name,
9879              TEMP.maint_cost_category,
9880              SUM(TEMP.actual_mat_cost),
9881              SUM(TEMP.actual_lab_cost),
9882              SUM(TEMP.actual_eqp_cost),
9883              SUM(TEMP.estimated_mat_cost),
9884              SUM(TEMP.estimated_lab_cost),
9885              SUM(TEMP.estimated_eqp_cost),
9886              SYSDATE,
9887              p_user_id,
9888              SYSDATE,
9889              p_user_id,
9890              p_prog_appl_id
9891       FROM   (
9892                SELECT CURR.group_id group_id,
9893                       CURR.object_type object_type,
9894                       CURR.object_id object_id,
9895                       WEPB.period_set_name period_set_name,
9896                       WEPB.period_name period_name,
9897                       WEPB.maint_cost_category maint_cost_category,
9898                       SUM(NVL(WEPB.actual_mat_cost,0)) actual_mat_cost,
9899                       SUM(NVL(WEPB.actual_lab_cost,0)) actual_lab_cost,
9900                       SUM(NVL(WEPB.actual_eqp_cost,0)) actual_eqp_cost,
9901                       SUM(NVL(WEPB.system_estimated_mat_cost,0)) estimated_mat_cost,
9902                       SUM(NVL(WEPB.system_estimated_lab_cost,0)) estimated_lab_cost,
9903                       SUM(NVL(WEPB.system_estimated_eqp_cost,0)) estimated_eqp_cost
9904                FROM   cst_eam_hierarchy_snapshot CURR,
9905                       wip_eam_period_balances WEPB
9906                WHERE  CURR.group_id = p_group_id
9907                AND    CURR.level_num = l_level
9908                AND    CURR.object_type = 2 -- WIP job
9909                AND    WEPB.organization_id = p_organization_id
9910                AND    WEPB.wip_entity_id = CURR.object_id
9911                GROUP
9912                BY     CURR.group_id,
9913                       CURR.object_type,
9914                       CURR.object_id,
9915                       WEPB.period_set_name,
9916                       WEPB.period_name,
9917                       WEPB.maint_cost_category
9918                UNION ALL
9919                SELECT CURR.group_id,
9920                       CURR.object_type,
9921                       CURR.object_id,
9922                       CERC.period_set_name,
9923                       CERC.period_name,
9924                       CERC.maint_cost_category,
9925                       SUM(NVL(CERC.actual_mat_cost,0)),
9926                       SUM(NVL(CERC.actual_lab_cost,0)),
9927                       SUM(NVL(CERC.actual_eqp_cost,0)),
9928                       SUM(NVL(CERC.estimated_mat_cost,0)),
9929                       SUM(NVL(CERC.estimated_lab_cost,0)),
9930                       SUM(NVL(CERC.estimated_eqp_cost,0))
9931                FROM   cst_eam_hierarchy_snapshot CURR,
9932                       cst_eam_hierarchy_snapshot CHILDREN,
9933                       cst_eam_rollup_costs CERC
9934                WHERE  CURR.group_id = p_group_id
9935                AND    CURR.level_num = l_level
9936                AND    CHILDREN.group_id = p_group_id
9937                AND    CHILDREN.parent_object_type = CURR.object_type
9938                AND    CHILDREN.parent_object_id = CURR.object_id
9939                AND    CERC.group_id = p_group_id
9940                AND    CERC.object_type = CHILDREN.object_type
9941                AND    CERC.object_id = CHILDREN.object_id
9942                GROUP
9943                BY     CURR.group_id,
9944                       CURR.object_type,
9945                       CURR.object_id,
9946                       CERC.period_set_name,
9947                       CERC.period_name,
9948                       CERC.maint_cost_category
9949              ) TEMP
9950       GROUP
9951       BY     TEMP.group_id,
9952              TEMP.object_type,
9953              TEMP.object_id,
9954              TEMP.period_set_name,
9955              TEMP.period_name,
9956              TEMP.maint_cost_category;
9957     END LOOP;
9958 
9959     IF l_msg_level_threshold <= FND_MSG_PUB.G_MSG_LVL_SUCCESS
9960     THEN
9961       FND_MSG_PUB.Add_Exc_Msg(
9962         p_pkg_name => G_PKG_NAME,
9963         p_procedure_name => l_api_name,
9964         p_error_text => l_stmt_num||
9965                         ': Successfully rolled up the cost for group id '||
9966                         p_group_id
9967       );
9968     END IF;
9969 
9970     x_return_status := FND_API.G_RET_STS_SUCCESS;
9971   EXCEPTION
9972     WHEN FND_API.G_EXC_UNEXPECTED_ERROR THEN
9973       ROLLBACK TO Rollup_WorkOrderCost_PUB;
9974       x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
9975     WHEN l_object_type_exc THEN
9976       ROLLBACK TO Rollup_WorkOrderCost_PUB;
9977       x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
9978       IF l_msg_level_threshold <= FND_MSG_PUB.G_MSG_LVL_ERROR
9979       THEN
9980         FND_MSG_PUB.Add_Exc_Msg(
9981           p_pkg_name => G_PKG_NAME,
9982           p_procedure_name => l_api_name,
9983           p_error_text => 'Object type must be inserted. Use 0 instead of '||
9984                           'NULL for entities that are not a WIP entity'
9985         );
9986       END IF;
9987     WHEN OTHERS THEN
9988       ROLLBACK TO Rollup_WorkOrderCost_PUB;
9989       x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
9990       IF l_msg_level_threshold <= FND_MSG_PUB.G_MSG_LVL_UNEXP_ERROR
9991       THEN
9992         FND_MSG_PUB.Add_Exc_Msg(
9993           p_pkg_name => G_PKG_NAME,
9994           p_procedure_name => l_api_name,
9995           p_error_text => SUBSTR(l_stmt_num||SQLERRM,1,240)
9996         );
9997       END IF;
9998   END Rollup_WorkOrderCost;
9999 
10000   PROCEDURE Purge_RollupCost(
10001     p_api_version      IN         NUMBER,
10002     p_init_msg_list    IN         VARCHAR2,
10003     p_commit           IN         VARCHAR2,
10004     p_group_id         IN         NUMBER,
10005     p_prog_appl_id     IN         NUMBER,
10006     p_last_update_date IN         DATE,
10007     x_return_status    OUT NOCOPY VARCHAR2
10008    )
10009   IS
10010     l_api_name CONSTANT VARCHAR2(30) := 'Purge_RollupCost';
10011     l_api_version CONSTANT NUMBER := 1.0;
10012     l_msg_level_threshold NUMBER;
10013     l_stmt_num NUMBER := 0;
10014   BEGIN
10015     -- Standard Start of API savepoint
10016     SAVEPOINT Purge_RollupCost_PUB;
10017 
10018     -- Initialize message list if p_init_msg_list is set to TRUE
10019     IF FND_API.to_Boolean(p_init_msg_list) THEN
10020       FND_MSG_PUB.initialize;
10021     END IF;
10022 
10023     -- Check for call compatibility
10024     IF NOT FND_API.Compatible_API_Call
10025            ( p_current_version_number => l_api_version,
10026              p_caller_version_number => p_api_version,
10027              p_api_name => l_api_name,
10028              p_pkg_name => G_PKG_NAME
10029            )
10030     THEN
10031       RAISE FND_API.G_EXC_UNEXPECTED_ERROR;
10032     END IF;
10033 
10034     -- Check for message level threshold
10035     l_msg_level_threshold := FND_PROFILE.Value('FND_AS_MSG_LEVEL_THRESHOLD');
10036 
10037     IF l_msg_level_threshold <= FND_MSG_PUB.G_MSG_LVL_DEBUG_HIGH
10038     THEN
10039       FND_MSG_PUB.Add_Exc_Msg(
10040         p_pkg_name => G_PKG_NAME,
10041         p_procedure_name => l_api_name,
10042         p_error_text => SUBSTR(
10043                           l_stmt_num||':'||
10044                           p_group_id||','||
10045                           p_prog_appl_id||','||
10046                           1,
10047                           240
10048                         )
10049       );
10050     END IF;
10051 
10052     l_stmt_num := 10;
10053     DELETE cst_eam_hierarchy_snapshot
10054     WHERE  group_id = NVL(p_group_id,group_id)
10055     AND    program_application_id =
10056            NVL(p_prog_appl_id,program_application_id)
10057     AND    last_update_date < NVL(p_last_update_date,last_update_date+1);
10058 
10059     IF l_msg_level_threshold <= FND_MSG_PUB.G_MSG_LVL_SUCCESS
10060     THEN
10061       FND_MSG_PUB.Add_Exc_Msg(
10062         p_pkg_name => G_PKG_NAME,
10063         p_procedure_name => l_api_name,
10064         p_error_text => l_stmt_num||
10065                         ': Successfully deleted '||
10066                         SQL%ROWCOUNT||
10067                         ' from CST_EAM_HIERARHCY_SNAPSHOT'
10068       );
10069     END IF;
10070 
10071     l_stmt_num := 20;
10072     DELETE cst_eam_rollup_costs
10073     WHERE  group_id = NVL(p_group_id,group_id)
10074     AND    program_application_id =
10075            NVL(p_prog_appl_id,program_application_id)
10076     AND    last_update_date < NVL(p_last_update_date,last_update_date+1);
10077 
10078     IF l_msg_level_threshold <= FND_MSG_PUB.G_MSG_LVL_SUCCESS
10079     THEN
10080       FND_MSG_PUB.Add_Exc_Msg(
10081         p_pkg_name => G_PKG_NAME,
10082         p_procedure_name => l_api_name,
10083         p_error_text => l_stmt_num||
10084                         ': Successfully deleted '||
10085                         SQL%ROWCOUNT||
10086                         ' from CST_EAM_ROLLUP_COSTS'
10087       );
10088     END IF;
10089 
10090     x_return_status := FND_API.G_RET_STS_SUCCESS;
10091   EXCEPTION
10092     WHEN FND_API.G_EXC_UNEXPECTED_ERROR THEN
10093       ROLLBACK TO Purge_RollupCost_PUB;
10094       x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
10095     WHEN OTHERS THEN
10096       ROLLBACK TO Purge_RollupCost_PUB;
10097       x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
10098       IF l_msg_level_threshold <= FND_MSG_PUB.G_MSG_LVL_UNEXP_ERROR
10099       THEN
10100         FND_MSG_PUB.Add_Exc_Msg(
10101           p_pkg_name => G_PKG_NAME,
10102           p_procedure_name => l_api_name,
10103           p_error_text => SUBSTR(l_stmt_num||SQLERRM,1,240)
10104         );
10105       END IF;
10106   END Purge_RollupCost;
10107 
10108 
10109 --------------------------------------------------------------------------
10110 --      API name         : Insert_eamBalAcct
10111 --      Type                : Public
10112 --      Description     : This API inserts data in CST_EAM_BALANCE_BY_ACCOUNTS
10113 --                        table.
10114 --
10115 --      HISTORY
10116 --      04/29/05   Anjali R    Added as part of eAM Requirements Project (R12)
10117 --
10118 --------------------------------------------------------------------------
10119 PROCEDURE Insert_eamBalAcct
10120 (
10121         p_api_version                IN        NUMBER,
10122         p_init_msg_list                IN        VARCHAR2,
10123         p_commit                IN        VARCHAR2,
10124         p_validation_level        IN        NUMBER,
10125         x_return_status         OUT NOCOPY        VARCHAR2,
10126         x_msg_count             OUT NOCOPY        NUMBER,
10127         x_msg_data              OUT NOCOPY        VARCHAR2,
10128         p_period_id             IN      NUMBER,
10129         p_period_set_name       IN      VARCHAR2,
10130         p_period_name           IN      VARCHAR2,
10131         p_org_id                IN      NUMBER,
10132         p_wip_entity_id         IN      NUMBER,
10133         p_owning_dept_id        IN      NUMBER,
10134         p_dept_id               IN      NUMBER,
10135         p_maint_cost_cat        IN      NUMBER,
10136         p_opseq_num             IN      NUMBER,
10137         p_period_start_date     IN          DATE,
10138         p_account_ccid          IN      NUMBER,
10139         p_value                 IN      NUMBER,
10140         p_txn_type              IN      NUMBER,
10141         p_wip_acct_class        IN      VARCHAR2,
10142         p_mfg_cost_element_id   IN      NUMBER,
10143         p_user_id               IN      NUMBER,
10144         p_request_id            IN      NUMBER,
10145         p_prog_id               IN      NUMBER,
10146         p_prog_app_id           IN      NUMBER,
10147         p_login_id              IN      NUMBER
10148 )
10149 IS
10150         l_api_name       CONSTANT VARCHAR2(30) := 'Insert_eamBalAcct';
10151         l_api_version    CONSTANT NUMBER := 1.0;
10152 
10153         l_full_name    CONSTANT VARCHAR2(60) := G_PKG_NAME || '.' || l_api_name;
10154         l_module       CONSTANT VARCHAR2(60) := 'cst.plsql.'||l_full_name;
10155 
10156        /* Log Severities*/
10157        /* 6- UNEXPECTED */
10158        /* 5- ERROR      */
10159        /* 4- EXCEPTION  */
10160        /* 3- EVENT      */
10161        /* 2- PROCEDURE  */
10162        /* 1- STATEMENT  */
10163 
10164 
10165         l_uLog         CONSTANT BOOLEAN := FND_LOG.LEVEL_UNEXPECTED>=G_LOG_LEVEL AND FND_LOG.TEST(FND_LOG.LEVEL_UNEXPECTED, l_module);
10166         l_pLog         CONSTANT BOOLEAN := l_uLog AND (FND_LOG.LEVEL_PROCEDURE >= G_LOG_LEVEL);
10167         l_sLog         CONSTANT BOOLEAN := l_pLog AND (FND_LOG.LEVEL_STATEMENT >= G_LOG_LEVEL);
10168 
10169         l_cnt_cebba    NUMBER;
10170         l_stmt_num     NUMBER;
10171 
10172 BEGIN
10173         -- Standard Start of API savepoint
10174         SAVEPOINT       Insert_eamBalAcct_PUB;
10175 
10176         if( l_pLog ) then
10177                FND_LOG.STRING(FND_LOG.LEVEL_PROCEDURE,
10178                l_module || '.begin',
10179                'Start of ' || l_full_name || '(' ||
10180                'p_user_id=' || p_user_id || ',' ||
10181                'p_login_id=' || p_login_id ||',' ||
10182                'p_prog_app_id=' || p_prog_app_id ||',' ||
10183                'p_prog_id=' || p_prog_id ||',' ||
10184                'p_request_id=' || p_request_id ||',' ||
10185                'p_wip_entity_id=' || p_wip_entity_id ||',' ||
10186                'p_org_id=' || p_org_id ||',' ||
10187                'p_wip_acct_class=' || p_wip_acct_class ||',' ||
10188                'p_account_ccid=' || p_account_ccid ||',' ||
10189                'p_maint_cost_cat =' || p_maint_cost_cat  ||',' ||
10190                'p_opseq_num=' || p_opseq_num ||',' ||
10191                'p_mfg_cost_element_id=' || p_mfg_cost_element_id ||',' ||
10192                'p_dept_id=' || p_dept_id ||',' ||
10193                'p_value=' || p_value ||',' ||
10194                ')');
10195         end if;
10196 
10197         -- Standard call to check for call compatibility.
10198         IF NOT FND_API.Compatible_API_Call (    l_api_version,
10199                                                              p_api_version,
10200                                                             l_api_name ,
10201                                                                 'CST_eamCost_PUB')
10202         THEN
10203                 RAISE FND_API.G_EXC_UNEXPECTED_ERROR;
10204         END IF;
10205         -- Initialize message list if p_init_msg_list is set to TRUE.
10206         IF FND_API.to_Boolean( p_init_msg_list ) THEN
10207                 FND_MSG_PUB.initialize;
10208         END IF;
10209 
10210         l_stmt_num := 10;
10211 
10212         --  Initialize API return status to success
10213         x_return_status := FND_API.G_RET_STS_SUCCESS;
10214 
10215         /* Update the record if already exists else insert a new one */
10216 
10217         MERGE INTO CST_EAM_BALANCE_BY_ACCOUNTS  cebba
10218         USING
10219         (
10220          SELECT NULL FROM DUAL
10221         )
10222         ON
10223         (
10224         cebba.period_set_name     = period_set_name AND
10225         cebba.period_name         = p_period_name    AND
10226         cebba.acct_period_id      = p_period_id     AND
10227         cebba.wip_entity_id       = p_wip_entity_id AND
10228         cebba.organization_id     = p_org_id AND
10229         cebba.maint_cost_category = p_maint_cost_cat AND
10230         cebba.owning_dept_id      = p_owning_dept_id AND
10231         cebba.period_start_date   = p_period_start_date AND
10232         cebba.account_id          = p_account_ccid AND
10233         cebba.txn_type            = p_txn_type AND
10234         cebba.wip_acct_class_code = p_wip_acct_class AND
10235         cebba.mfg_cost_element_id = p_mfg_cost_element_id
10236         )
10237         WHEN MATCHED THEN
10238          UPDATE
10239                 SET cebba.acct_value  = cebba.acct_value + p_value,
10240                 cebba.LAST_UPDATE_DATE = sysdate,
10241                 cebba.LAST_UPDATED_BY = p_user_id,
10242                 cebba.LAST_UPDATE_LOGIN = p_login_id
10243         WHEN NOT MATCHED THEN
10244          Insert
10245                 (
10246                 PERIOD_SET_NAME,
10247                 PERIOD_NAME,
10248                 ACCT_PERIOD_ID,
10249                 WIP_ENTITY_ID,
10250                 ORGANIZATION_ID,
10251                 OPERATIONS_DEPT_ID,
10252                 OPERATIONS_SEQ_NUM,
10253                 MAINT_COST_CATEGORY,
10254                 OWNING_DEPT_ID,
10255                 PERIOD_START_DATE,
10256                 ACCOUNT_ID,
10257                 ACCT_VALUE,
10258                 TXN_TYPE,
10259                 WIP_ACCT_CLASS_CODE,
10260                 MFG_COST_ELEMENT_ID,
10261                 LAST_UPDATE_DATE,
10262                 LAST_UPDATED_BY,
10263                 CREATION_DATE,
10264                 CREATED_BY,
10265                 LAST_UPDATE_LOGIN
10266                 )VALUES
10267                 (
10268                    p_period_set_name,
10269                    p_period_name     ,
10270                    p_period_id      ,
10271                    p_wip_entity_id,
10272                    p_org_id  ,
10273                    p_dept_id,
10274                    p_opseq_num ,
10275                    p_maint_cost_cat,
10276                    p_owning_dept_id,
10277                    p_period_start_date,
10278                    p_account_ccid,
10279                    p_value ,
10280                    p_txn_type,
10281                    p_wip_acct_class,
10282                    p_mfg_cost_element_id,
10283                    sysdate,
10284                    p_user_id ,
10285                    sysdate,
10286                    p_prog_app_id ,
10287                    p_login_id
10288                 );
10289 
10290 
10291         -- Standard check of p_commit.
10292         IF FND_API.To_Boolean( p_commit ) THEN
10293                 COMMIT WORK;
10294         END IF;
10295 
10296 
10297        /* Procedure level log message for Exit point */
10298         IF (l_pLog) THEN
10299            FND_LOG.STRING(
10300                FND_LOG.LEVEL_PROCEDURE,
10301                l_module || '.end',
10302                'End of ' || l_full_name
10303                );
10304         END IF;
10305 
10306         -- Standard call to get message count and if count is 1, get message info.
10307         FND_MSG_PUB.Count_And_Get
10308         (          p_count         =>      x_msg_count     ,
10309                 p_data          =>      x_msg_data
10310         );
10311 
10312 EXCEPTION
10313     WHEN FND_API.G_EXC_UNEXPECTED_ERROR THEN
10314                 ROLLBACK TO Insert_eamBalAcct_PUB;
10315                 x_return_status := FND_API.G_RET_STS_UNEXP_ERROR ;
10316 
10317                 IF (l_uLog) THEN
10318                   FND_LOG.STRING(
10319                    FND_LOG.LEVEL_UNEXPECTED,
10320                           l_module || '.' || l_stmt_num ,
10321                         l_full_name ||'('|| l_stmt_num ||') :' || SUBSTRB(SQLERRM , 1 , 240)
10322                       );
10323                 END IF;
10324 
10325                 FND_MSG_PUB.Count_And_Get
10326                 (          p_count                =>      x_msg_count     ,
10327                         p_data                 =>      x_msg_data
10328                 );
10329     WHEN OTHERS THEN
10330                 ROLLBACK TO Insert_eamBalAcct_PUB;
10331                 x_return_status := FND_API.G_RET_STS_UNEXP_ERROR ;
10332 
10333                 IF (l_uLog) THEN
10334                   FND_LOG.STRING(
10335                      FND_LOG.LEVEL_UNEXPECTED,
10336                      l_module || '.' || l_stmt_num ,
10337                      l_full_name || '( '|| l_stmt_num || ') :' || SUBSTRB(SQLERRM , 1 , 240)
10338                      );
10339                 END IF;
10340 
10341                 IF         FND_MSG_PUB.Check_Msg_Level
10342                         (FND_MSG_PUB.G_MSG_LVL_UNEXP_ERROR)
10343                 THEN
10344                         FND_MSG_PUB.Add_Exc_Msg
10345                             (        'CST_eamCost_PUB'   ,
10346                                     l_api_name
10347                             );
10348                 END IF;
10349                 FND_MSG_PUB.Count_And_Get
10350                 (          p_count                =>      x_msg_count     ,
10351                         p_data                 =>      x_msg_data
10352                 );
10353 END Insert_eamBalAcct;
10354 
10355 
10356 -------------------------------------------------------------------------------
10357 --      API name         : Delete_eamBalAcct
10358 --      Type                : Public
10359 --      Function        : This API deletes data from CST_EAM_BALANCE_BY_ACCOUNTS
10360 --                        table for the given wip_entity_id.
10361 --
10362 --      History                :
10363 --      03/29/05  Anjali R    Added as part of eAM requirements Project (R12)
10364 --
10365 -------------------------------------------------------------------------------
10366 PROCEDURE Delete_eamBalAcct
10367 (
10368         p_api_version                IN        NUMBER,
10369         p_init_msg_list                IN        VARCHAR2,
10370         p_commit                IN        VARCHAR2,
10371         p_validation_level        IN        NUMBER        ,
10372         x_return_status         OUT NOCOPY        VARCHAR2,
10373         x_msg_count             OUT NOCOPY        VARCHAR2,
10374         x_msg_data              OUT NOCOPY        VARCHAR2,
10375         p_org_id                IN          NUMBER,
10376         p_entity_id_tab         IN      CSTPECEP.wip_entity_id_type
10377 )
10378 IS
10379         l_api_name        CONSTANT VARCHAR2(30)        := 'Delete_eamBalAcct';
10380         l_api_version   CONSTANT NUMBER         := 1.0;
10381 
10382         l_full_name    CONSTANT VARCHAR2(60) := G_PKG_NAME || '.' || l_api_name;
10383         l_module       CONSTANT VARCHAR2(60) := 'cst.plsql.'||l_full_name;
10384 
10385         l_uLog         CONSTANT BOOLEAN := FND_LOG.LEVEL_UNEXPECTED>=G_LOG_LEVEL AND FND_LOG.TEST(FND_LOG.LEVEL_UNEXPECTED, l_module);
10386         l_pLog         CONSTANT BOOLEAN := l_uLog AND (FND_LOG.LEVEL_PROCEDURE >= G_LOG_LEVEL);
10387 
10388         l_stmt_num     NUMBER;
10389 BEGIN
10390         -- Standard Start of API savepoint
10391     SAVEPOINT   Delete_eamBalAcct_PUB;
10392     -- Standard call to check for call compatibility.
10393     IF NOT FND_API.Compatible_API_Call (        l_api_version,
10394                                                              p_api_version,
10395                                                             l_api_name ,
10396                                                                 'CST_eamCost_PUB')
10397         THEN
10398                 RAISE FND_API.G_EXC_UNEXPECTED_ERROR;
10399         END IF;
10400         -- Initialize message list if p_init_msg_list is set to TRUE.
10401         IF FND_API.to_Boolean( p_init_msg_list ) THEN
10402                 FND_MSG_PUB.initialize;
10403         END IF;
10404 
10405         if( l_pLog ) then
10406                FND_LOG.STRING(FND_LOG.LEVEL_PROCEDURE,
10407                l_module || '.begin',  'Start of ' || l_full_name );
10408         end if;
10409 
10410 
10411         --  Initialize API return status to success
10412         x_return_status := FND_API.G_RET_STS_SUCCESS;
10413 
10414         l_stmt_num := 10;
10415 
10416        /* Delete data from CST_EAM_BALANCE_BY_ACCOUNTS */
10417        FORALL l_index IN p_entity_id_tab.FIRST..p_entity_id_tab.LAST
10418         Delete from CST_EAM_BALANCE_BY_ACCOUNTS
10419         where wip_entity_id = p_entity_id_tab(l_index)
10420         and organization_id=p_org_id;
10421 
10422         -- Standard check of p_commit.
10423         IF FND_API.To_Boolean( p_commit ) THEN
10424                 COMMIT WORK;
10425         END IF;
10426 
10427        /* Procedure level log message for Exit point */
10428         IF (l_pLog) THEN
10429            FND_LOG.STRING(
10430                FND_LOG.LEVEL_PROCEDURE,
10431                l_module || '.end',
10432                'End of ' || l_full_name
10433                );
10434         END IF;
10435 
10436         -- Standard call to get message count and if count is 1, get message info.
10437         FND_MSG_PUB.Count_And_Get
10438         (          p_count         =>      x_msg_count     ,
10439                 p_data          =>      x_msg_data
10440         );
10441 
10442 EXCEPTION
10443     WHEN FND_API.G_EXC_UNEXPECTED_ERROR THEN
10444                 ROLLBACK TO Delete_eamBalAcct_PUB;
10445                 x_return_status := FND_API.G_RET_STS_UNEXP_ERROR ;
10446 
10447                 IF (l_uLog) THEN
10448                         FND_LOG.STRING(
10449                                 FND_LOG.LEVEL_UNEXPECTED,
10450                                 l_module || '.' || l_stmt_num ,
10451                      l_full_name ||'('|| l_stmt_num ||') :' || SUBSTRB (SQLERRM , 1 , 240));
10452                 END IF;
10453 
10454                 FND_MSG_PUB.Count_And_Get
10455                 (          p_count                =>      x_msg_count     ,
10456                         p_data                 =>      x_msg_data
10457                 );
10458     WHEN OTHERS THEN
10459                 ROLLBACK TO Delete_eamBalAcct_PUB;
10460                 x_return_status := FND_API.G_RET_STS_UNEXP_ERROR ;
10461 
10462                 IF (l_uLog) THEN
10463                   FND_LOG.STRING(
10464                      FND_LOG.LEVEL_UNEXPECTED,
10465                      l_module || '.' || l_stmt_num,
10466                      l_full_name ||'('|| l_stmt_num ||') :' || SUBSTRB (SQLERRM , 1 , 240));
10467                 END IF;
10468 
10469                 IF         FND_MSG_PUB.Check_Msg_Level
10470                         (FND_MSG_PUB.G_MSG_LVL_UNEXP_ERROR)
10471                 THEN
10472                         FND_MSG_PUB.Add_Exc_Msg
10473                             (        'CST_eamCost_PUB'   ,
10474                                     l_api_name
10475                             );
10476                 END IF;
10477                 FND_MSG_PUB.Count_And_Get
10478                 (          p_count                =>      x_msg_count     ,
10479                         p_data                 =>      x_msg_data
10480                 );
10481 END Delete_eamBalAcct;
10482 
10483 
10484 PROCEDURE Insert_tempEstimateDetails
10485 (
10486     p_api_version          IN  NUMBER,
10487     p_init_msg_list        IN  VARCHAR2 := FND_API.G_FALSE,
10488     p_commit               IN  VARCHAR2 := FND_API.G_FALSE,
10489     p_validation_level     IN  VARCHAR2 := FND_API.G_VALID_LEVEL_FULL,
10490     x_return_status        OUT NOCOPY  VARCHAR2,
10491     x_msg_count            OUT NOCOPY  NUMBER,
10492     x_msg_data             OUT NOCOPY  VARCHAR2,
10493     p_entity_id_tab        IN  CSTPECEP.wip_entity_id_type
10494 )
10495 IS
10496     l_api_name     CONSTANT VARCHAR2(30) := 'Delete_eamBalAcct';
10497     l_api_version  CONSTANT NUMBER       := 1.0;
10498 
10499     l_full_name    CONSTANT VARCHAR2(60) := G_PKG_NAME || '.' || l_api_name;
10500     l_module       CONSTANT VARCHAR2(60) := 'cst.plsql.'||l_full_name;
10501 
10502     l_uLog         CONSTANT BOOLEAN := FND_LOG.LEVEL_UNEXPECTED>=G_LOG_LEVEL
10503                                        AND FND_LOG.TEST(FND_LOG.LEVEL_UNEXPECTED, l_module);
10504     l_pLog         CONSTANT BOOLEAN := l_uLog AND (FND_LOG.LEVEL_PROCEDURE >= G_LOG_LEVEL);
10505 
10506     l_stmt_num     NUMBER;
10507 
10508 l_is_shared_proc varchar2(1);
10509 l_currency_code varchar2(20);
10510 l_currency_date date;
10511 l_currency_type varchar2(10);
10512 l_unit_price  number;
10513 l_currency_rate number;
10514 l_return_status varchar2(200);
10515 l_amount number;
10516 l_amount_delivered number;
10517 l_schema VARCHAR2(30);
10518 l_status VARCHAR2(1);
10519 l_industry VARCHAR2(1);
10520 l_gather_stats NUMBER;
10521 
10522 cursor c_cedi is
10523 select project_id,
10524        purchasing_ou_id,
10525        receiving_ou_id,
10526        organization_id,
10527        document_type,
10528        currency_code,
10529        currency_rate,
10530        currency_date,
10531        currency_type,
10532        txn_flow_header_id,
10533        unit_price,
10534        set_of_books_id,
10535        order_type_lookup_code,
10536        amount,
10537        amount_delivered
10538 from cst_eam_direct_items_temp
10539 where purchasing_ou_id <> receiving_ou_id
10540 FOR UPDATE;
10541 
10542 BEGIN
10543 
10544     -- Standard Start of API savepoint
10545     SAVEPOINT Insert_tempEstimateDetails_PUB;
10546 
10547     -- Standard call to check for call compatibility.
10548     IF NOT FND_API.Compatible_API_Call (l_api_version,
10549                                         p_api_version,
10550                                         l_api_name ,
10551                                         'CST_eamCost_PUB') THEN
10552 
10553          RAISE FND_API.G_EXC_UNEXPECTED_ERROR;
10554 
10555     END IF;
10556 
10557     -- Initialize message list if p_init_msg_list is set to TRUE.
10558     IF FND_API.to_Boolean( p_init_msg_list ) THEN
10559             FND_MSG_PUB.initialize;
10560     END IF;
10561 
10562     IF( l_pLog ) THEN
10563            FND_LOG.STRING(FND_LOG.LEVEL_PROCEDURE,
10564            l_module || '.begin',  'Start of ' || l_full_name );
10565     END IF;
10566 
10567     --  Initialize API return status to success
10568     x_return_status := FND_API.G_RET_STS_SUCCESS;
10569 
10570     l_stmt_num := 10;
10571 
10572     /* Insert rows for POs for Direct Items */
10573     FORALL l_index in p_entity_id_tab.FIRST..p_entity_id_tab.LAST
10574     INSERT INTO cst_eam_direct_items_temp
10575     SELECT
10576       pd.wip_entity_id,
10577       pd.wip_operation_seq_num,
10578       pd.destination_organization_id,
10579       wo.department_id,
10580       to_number(null),
10581       poh.segment1 ,
10582       pd.item_description,
10583       uom.uom_code,
10584       pd.unit_price,
10585       to_number(null),
10586       sum(pd.quantity_ordered) ,
10587       sum(pd.quantity_delivered),
10588       to_date(null),
10589       sum(pd.quantity_ordered),
10590       sum(pd.quantity_cancelled),
10591       to_char(null),
10592       to_number(null),
10593       pd.line_location_id,
10594       pd.cancel_flag,
10595       pd.item_id,
10596       null, -- rql.closed_code,
10597       pd.closed_code,
10598       null, --  rqh.authorization_status,
10599       poh.authorization_status,
10600       pd.po_line_id,
10601       poh.po_header_id,
10602       to_number(null), -- rqh.requisition_header_id,
10603       wed.direct_item_sequence_id,
10604       pd.category_id,
10605       pd.po_release_id,
10606       to_number(null), -- rql.requisition_line_id,
10607       pd.order_type_lookup_code,
10608       pd.amount_ordered,
10609       pd.amount_delivered,
10610       pd.req_distribution_id,
10611       poh.approved_date,
10612       pd.project_id, -- PROJECT_ID
10613       pd.org_id, -- PURCHASING_OU_ID
10614       to_number(org_information1), -- SET_OF_BOOKS_ID
10615       to_number(NULL), -- TXN_FLOW_HEADER_ID
10616       to_number(hoi.org_information3), -- RECEIVING_OU_ID
10617       poh.currency_code,   -- CURRENCY_CODE
10618       poh.rate_date,   -- CURRENCY_DATE
10619       poh.rate_type,   -- CURRENCY_TYPE
10620       pd.rate, -- CURRENCY_RATE  ,
10621       poh.type_lookup_code, -- DOCUMENT_TYPE
10622       to_char(null) -- IS_SHARED_PROC
10623     FROM
10624       po_line_types plt,
10625       mtl_units_of_measure uom,
10626       po_headers_all poh,
10627       wip_eam_direct_items wed,
10628       hr_organization_information hoi,
10629       wip_operations wo,
10630       (SELECT
10631           pd1.wip_entity_id,
10632           pd1.wip_operation_seq_num,
10633           pd1.destination_organization_id,
10634           pd1.wip_line_id,
10635           pol.item_description,
10636           pol.unit_price,
10637           pd1.quantity_ordered,
10638           pd1.quantity_cancelled,
10639           pd1.quantity_delivered,
10640           pd1.line_location_id,
10641           pol.cancel_flag,
10642           pol.item_id,
10643           pol.closed_code,
10644           pol.po_line_id,
10645           pol.category_id,
10646           pd1.po_release_id,
10647           pol.order_type_lookup_code,
10648           pd1.amount_ordered,
10649           pd1.amount_delivered,
10650           pd1.req_distribution_id,
10651           pd1.rate,
10652           pol.unit_meas_lookup_code,
10653           pd1.destination_type_code,
10654           pol.line_type_id,
10655           pd1.po_header_id,
10656           pd1.project_id,
10657           pol.org_id
10658        FROM po_lines_all pol,
10659             po_distributions_all pd1
10660        WHERE pol.po_line_id = pd1.po_line_id AND
10661              pd1.wip_entity_id = p_entity_id_tab(l_index)
10662       ) pd
10663     WHERE
10664       pd.po_line_id = pd.po_line_id AND
10665       pd.wip_entity_id = p_entity_id_tab(l_index) AND
10666       poh.po_header_id = pd.po_header_id AND
10667       pd.line_type_id = plt.line_type_id AND
10668       upper(nvl(plt.outside_operation_flag, 'N')) = 'N' AND
10669       pd.destination_type_code = 'SHOP FLOOR' AND
10670       pd.unit_meas_lookup_code = uom.unit_of_measure (+) AND
10671       upper(nvl(pd.cancel_flag, 'N')) <> 'Y' AND
10672       pd.wip_entity_id IS NOT NULL AND
10673       pd.item_description = wed.description(+) AND
10674       pd.wip_entity_id = wed.wip_entity_id (+) AND
10675       pd.wip_operation_seq_num = wed. operation_seq_num (+) AND
10676       pd.destination_organization_id = wed.organization_id (+) AND
10677       hoi.organization_id = pd.destination_organization_id AND
10678       hoi.org_information_context = 'Accounting Information' AND
10679       wo.wip_entity_id(+) = p_entity_id_tab(l_index) AND
10680       wo.organization_id(+) = pd.destination_organization_id AND
10681       wo.operation_seq_num(+) = pd.wip_operation_seq_num
10682     GROUP BY pd.wip_entity_id,
10683              pd.wip_operation_seq_num,
10684              pd.destination_organization_id,
10685              wo.department_id,
10686              poh.segment1,
10687              pd.item_description,
10688              uom.uom_code,
10689              pd.order_type_lookup_code,
10690              pd.unit_price,
10691              pd.amount_ordered,
10692              pd.amount_delivered,
10693              poh.currency_code,
10694              pd.cancel_flag,
10695              pd.item_id,
10696              pd.closed_code,
10697              poh.authorization_status,
10698              pd.po_line_id,
10699              poh.po_header_id,
10700              wed.direct_item_sequence_id,
10701              pd.category_id,
10702              pd.po_release_id,
10703              pd.req_distribution_id,
10704              pd.rate,
10705              poh.approved_date,
10706              pd.wip_line_id,
10707              pd.line_location_id,
10708              pd.project_id,
10709              pd.org_id, -- PURCHASING_OU_ID
10710              to_number(org_information1), -- SET_OF_BOOKS_ID
10711              to_number(hoi.org_information3), -- RECEIVING_OU_ID
10712              poh.currency_code,   -- CURRENCY_CODE
10713              poh.rate_date,   -- CURRENCY_DATE
10714              poh.rate_type,   -- CURRENCY_TYPE
10715              pd.rate, -- CURRENCY_RATE  ,
10716              poh.type_lookup_code; -- DOCUMENT_TYPE
10717 
10718     l_stmt_num := 20;
10719 
10720     UPDATE cst_eam_direct_items_temp cedi
10721     SET TXN_FLOW_HEADER_ID =(SELECT transaction_flow_header_id
10722                              FROM po_line_locations_all poll
10723                              WHERE poll.line_location_id = cedi.line_location_id)
10724     WHERE cedi.line_location_id is not null;
10725 
10726 
10727     /* Will insert for Reqs after updation to avoid extra rows that need not participate in updation */
10728 
10729     UPDATE cst_eam_direct_items_temp cedi
10730     SET (REQUISITION_NUMBER,
10731          REQ_AUTHORIZATION_STATUS,
10732          REQUISITION_HEADER_ID,
10733          REQUISITION_LINE_ID,
10734          CLOSED_CODE
10735          ) = (SELECT rqh.segment1,
10736                      rqh.authorization_status,
10737                      rqh.requisition_header_id,
10738                      rql.requisition_line_id,
10739                      rql.closed_code
10740               FROM   po_requisition_headers_all rqh,
10741                      po_requisition_lines_all rql,
10742                      po_req_distributions_all rqd
10743               WHERE  rql.requisition_header_id = rqh.requisition_header_id AND
10744                      rqd.requisition_line_id = rql.requisition_line_id AND
10745                      rqd.distribution_id(+) = cedi.req_distribution_id
10746               )
10747     WHERE cedi.req_distribution_id IS NOT NULL;
10748 
10749     l_stmt_num := 30;
10750 
10751     /* Insert rows for Reqs for Direct Items */
10752     FORALL l_index in p_entity_id_tab.FIRST..p_entity_id_tab.LAST
10753     INSERT INTO cst_eam_direct_items_temp
10754     SELECT
10755      rql.wip_entity_id,
10756      rql.wip_operation_seq_num,
10757      rql.destination_organization_id,
10758      wo.department_id,
10759      rqh.segment1,
10760      null,
10761      rql.item_description,
10762      uom.uom_code,
10763      rql.unit_price,
10764      rql.quantity,
10765      rql.quantity,
10766      to_number(null),
10767      to_date(null),
10768      to_number(null),
10769      to_number(null),
10770      to_char(null),
10771      to_number(null),
10772      to_number(null),
10773      to_char(null),
10774      rql.item_id,
10775      rql.closed_code,
10776      to_char(null),
10777      rqh.authorization_status,
10778      to_char(null),
10779      to_number(null),
10780      to_number(null),
10781      rqh.requisition_header_id,
10782      wed.direct_item_sequence_id,
10783      rql.category_id,
10784      to_number(null),
10785      rql.requisition_line_id,
10786      rql.order_type_lookup_code,
10787      rql.amount,
10788      to_number(null) ,
10789      to_number(null),
10790      rqh.last_update_date,
10791      to_number(NULL), -- PROJECT_ID
10792      rql.org_id, -- PURCHASING_OU_ID
10793      to_number(hoi.org_information1), -- SET_OF_BOOKS_ID
10794      to_number(NULL), -- TXN_FLOW_HEADER_ID
10795      to_number(hoi.org_information3), -- RECEIVING_OU_ID
10796      rql.currency_code,   -- CURRENCY_CODE
10797      rql.rate_date,   -- CURRENCY_DATE
10798      rql.rate_type,   -- CURRENCY_TYPE
10799      rql.rate, -- CURRENCY_RATE  ,
10800      rqh.type_lookup_code,  -- DOCUMENT_TYPE
10801      to_char(null) -- IS_SHARED_PROC
10802     FROM
10803       po_requisition_lines_all rql,
10804       po_requisition_headers_all rqh,
10805       po_line_types plt,
10806       mtl_units_of_measure uom,
10807       wip_eam_direct_items wed,
10808       hr_organization_information hoi,
10809       wip_operations wo
10810     WHERE
10811       rql.requisition_header_id = rqh.requisition_header_id AND
10812       rql.line_type_id =   plt.line_type_id AND
10813       rql.unit_meas_lookup_code = uom.unit_of_measure (+) AND
10814       upper(rqh.authorization_status) NOT IN ('CANCELLED', 'REJECTED','SYSTEM_SAVED')   AND
10815       rql.line_location_id IS NULL AND
10816       upper(nvl(rql.cancel_flag, 'N')) <> 'Y' AND
10817       upper(nvl(plt.outside_operation_flag, 'N')) = 'N' AND
10818       rql.destination_type_code =   'SHOP FLOOR' AND
10819       rql.wip_entity_id IS NOT NULL AND
10820       rql.item_description =   wed.description (+) AND
10821       rql.wip_entity_id = wed.wip_entity_id (+) AND
10822       RQL.WIP_OPERATION_SEQ_NUM = WED.OPERATION_SEQ_NUM (+) AND
10823       rql.destination_organization_id = wed.organization_id (+) AND
10824       rql.wip_entity_id =   p_entity_id_tab(l_index) AND
10825       hoi.organization_id = rql.destination_organization_id AND
10826       hoi.org_information_context = 'Accounting Information'  AND
10827       wo.wip_entity_id(+) = p_entity_id_tab(l_index) AND
10828       wo.organization_id(+) = rql.destination_organization_id AND
10829       wo.operation_seq_num(+) = RQL.WIP_OPERATION_SEQ_NUM ;
10830 
10831 
10832       for c_cedi_rec in c_cedi loop
10833 
10834         l_amount := 0;
10835         l_amount_delivered := 0;
10836         l_unit_price := 0;
10837 
10838         PO_SHARED_PROC_GRP.check_shared_proc_scenario
10839             (
10840                  p_api_version                => 1.0,
10841                  p_init_msg_list              => FND_API.G_FALSE,
10842                  x_return_status              => l_return_status,
10843                  p_destination_type_code      => 'SHOP FLOOR',
10844                  p_document_type_code         => c_cedi_rec.document_type,
10845                  p_project_id                 => c_cedi_rec.project_id,
10846                  p_purchasing_ou_id           => c_cedi_rec.purchasing_ou_id,
10847                  p_ship_to_inv_org_id         => c_cedi_rec.organization_id,
10848                  p_transaction_flow_header_id => c_cedi_rec.txn_flow_header_id,
10849                  x_is_shared_proc_scenario    => l_is_shared_proc
10850              );
10851 
10852        l_is_shared_proc := nvl(l_is_shared_proc,'N');
10853 
10854        if (l_is_shared_proc = 'Y') then
10855 
10856            IF (c_cedi_rec.currency_code IS NULL) THEN
10857                   SELECT currency_code
10858                   INTO   l_currency_code
10859                   FROM   gl_sets_of_books
10860                   WHERE  set_of_books_id = c_cedi_rec.set_of_books_id;
10861            Else
10862                   l_currency_code := c_cedi_rec.currency_code;
10863            END IF;
10864 
10865            IF (c_cedi_rec.currency_date IS NULL) THEN
10866                   l_currency_date := SYSDATE;
10867            Else
10868                   l_currency_date := c_cedi_rec.currency_date;
10869            END IF;
10870 
10871            fnd_profile.get('IC_CURRENCY_CONVERSION_TYPE', l_currency_type);
10872 
10873            l_currency_rate := PO_CORE_S.get_conversion_rate (
10874                                    c_cedi_rec.set_of_books_id,
10875                                    l_currency_code,
10876                                    l_currency_date,
10877                                    l_currency_type);
10878 
10879            If c_cedi_rec.order_type_lookup_code ='FIXED PRICE' or c_cedi_rec.order_type_lookup_code ='RATE' then
10880                 l_amount := c_cedi_rec.amount * l_currency_rate;
10881                 l_amount_delivered := c_cedi_rec.amount_delivered * l_currency_rate;
10882            else
10883                 l_unit_price := c_cedi_rec.unit_price * l_currency_rate;
10884            end if;
10885 
10886            update cst_eam_direct_items_temp
10887            set unit_price = l_unit_price,
10888                currency_rate = l_currency_rate,
10889                currency_code = l_currency_code,
10890                currency_date = l_currency_date,
10891                currency_type = l_currency_type,
10892                is_shared_proc = l_is_shared_proc,
10893                amount = l_amount,
10894                amount_delivered = l_amount_delivered
10895            where current of c_cedi;
10896 
10897        End If;
10898 
10899       end loop;
10900 
10901       /* Gather stats for the temporary table CST_EAM_DIRECT_ITEMS_TEMP  if number
10902          of work orders are greater than 1000. Full table scan seems better in case of less
10903          work orders*/
10904       If p_entity_id_tab.COUNT> 1000 then
10905 
10906 
10907             l_stmt_num := 26;
10908             l_gather_stats := CST_Utility_PUB.check_Db_Version(
10909                                 p_api_version     => 1.0,
10910                                 x_return_status   => x_return_status,
10911                                 x_msg_count       => x_msg_count,
10912                                 x_msg_data        => x_msg_data
10913                               );
10914             IF l_return_status <> FND_API.G_RET_STS_SUCCESS
10915             THEN
10916               RAISE FND_API.G_EXC_UNEXPECTED_ERROR;
10917             END IF;
10918 
10919             IF l_gather_stats = 1
10920             THEN
10921               l_stmt_num := 37;
10922               IF NOT FND_INSTALLATION.GET_APP_INFO('BOM', l_status, l_industry, l_schema)
10923               THEN
10924                 RAISE FND_API.G_EXC_UNEXPECTED_ERROR;
10925               END IF;
10926 
10927               IF l_schema IS NOT NULL
10928               THEN
10929                 l_stmt_num := 29;
10930                 FND_STATS.GATHER_TABLE_STATS(l_schema, 'CST_EAM_DIRECT_ITEMS_TEMP');
10931               END IF;
10932 
10933             END IF;
10934 
10935        End if;
10936 
10937       l_stmt_num := 40;
10938 
10939     -- Standard check of p_commit.
10940     IF FND_API.To_Boolean( p_commit ) THEN
10941         COMMIT WORK;
10942     END IF;
10943 
10944     /* Procedure level log message for Exit point */
10945     IF (l_pLog) THEN
10946        FND_LOG.STRING(
10947            FND_LOG.LEVEL_PROCEDURE,
10948            l_module || '.end',
10949            'End of ' || l_full_name
10950            );
10951     END IF;
10952 
10953     -- Standard call to get message count and if count is 1, get message info.
10954     FND_MSG_PUB.Count_And_Get
10955     (   p_count => x_msg_count,
10956         p_data  => x_msg_data
10957     );
10958 
10959 EXCEPTION
10960     WHEN FND_API.G_EXC_UNEXPECTED_ERROR THEN
10961          ROLLBACK TO Insert_tempEstimateDetails_PUB;
10962          x_return_status := FND_API.G_RET_STS_UNEXP_ERROR ;
10963 
10964          IF (l_uLog) THEN
10965                  FND_LOG.STRING(
10966                          FND_LOG.LEVEL_UNEXPECTED,
10967                          l_module || '.' || l_stmt_num ,
10968               l_full_name ||'('|| l_stmt_num ||') :' || SUBSTRB (SQLERRM , 1 , 240));
10969          END IF;
10970 
10971          FND_MSG_PUB.Count_And_Get
10972          (   p_count => x_msg_count,
10973              p_data  => x_msg_data
10974          );
10975 
10976     WHEN OTHERS THEN
10977          ROLLBACK TO Insert_tempEstimateDetails_PUB;
10978          x_return_status := FND_API.G_RET_STS_UNEXP_ERROR ;
10979 
10980          IF (l_uLog) THEN
10981            FND_LOG.STRING(
10982               FND_LOG.LEVEL_UNEXPECTED,
10983               l_module || '.' || l_stmt_num,
10984               l_full_name ||'('|| l_stmt_num ||') :' || SUBSTRB (SQLERRM , 1 , 240));
10985          END IF;
10986 
10987          IF FND_MSG_PUB.Check_Msg_Level(FND_MSG_PUB.G_MSG_LVL_UNEXP_ERROR) THEN
10988                  FND_MSG_PUB.Add_Exc_Msg('CST_eamCost_PUB'
10989                                          , l_api_name);
10990          END IF;
10991 
10992          FND_MSG_PUB.Count_And_Get
10993          (   p_count => x_msg_count,
10994              p_data  => x_msg_data
10995          );
10996 
10997 END Insert_tempEstimateDetails;
10998 
10999 
11000 
11001 PROCEDURE Get_Encumbrance_Data(
11002   p_receiving_transaction_id   IN         NUMBER
11003  ,p_api_version                IN         NUMBER DEFAULT 1
11004  ,x_encumbrance_amount         OUT NOCOPY NUMBER
11005  ,x_encumbrance_quantity       OUT NOCOPY NUMBER
11006  ,x_encumbrance_ccid           OUT NOCOPY NUMBER
11007  ,x_encumbrance_type_id        OUT NOCOPY NUMBER
11008  ,x_return_status              OUT NOCOPY VARCHAR2
11009  ,x_msg_count                  OUT NOCOPY NUMBER
11010  ,x_msg_data                   OUT NOCOPY VARCHAR2)
11011 IS
11012   /*Parameters list */
11013   l_rcv_transaction_id       NUMBER := p_receiving_transaction_id;
11014   l_api_version              NUMBER := p_api_version;
11015   l_encumbrance_amount       NUMBER;
11016   l_encumbrance_quantity     NUMBER;
11017   l_encumbrance_ccid         NUMBER;
11018   l_encumbrance_type_id      NUMBER;
11019   l_return_status            VARCHAR2(1);
11020   l_msg_count                NUMBER;
11021   l_msg_text                 VARCHAR2(2000);
11022   l_direct_delivery_flag     VARCHAR2(1) := NULL;
11023 
11024   /*Api details*/
11025   l_api_name        CONSTANT VARCHAR2(30)   := 'Get_Encumbrance_Data';
11026   l_api_message              VARCHAR2(1000);
11027   l_stmt_num                 NUMBER := 0;
11028 
11029   /*Local variable*/
11030   l_po_header_id          NUMBER;
11031   l_po_distribution_id    NUMBER;
11032   l_po_org_id             NUMBER;
11033   l_po_sob_id             NUMBER;
11034   l_destination_type      VARCHAR(25);
11035   l_rcv_trx_date          DATE;
11036   l_drop_ship_flag        NUMBER;
11037   l_rcv_organization_id   NUMBER;
11038   l_category_id           NUMBER;
11039   l_project_id            NUMBER;
11040   l_accrual_flag          VARCHAR2(1)    := 'N';
11041   l_po_document_type_code PO_HEADERS_ALL.type_lookup_code%TYPE;
11042   l_cross_ou_flag         VARCHAR2(1) := 'N'  ;
11043   l_rcv_org_id            NUMBER;
11044   l_rcv_sob_id            NUMBER;
11045   l_procurement_org_flag  VARCHAR2(1)   := 'Y';
11046   l_entered_cr            NUMBER;
11047   l_entered_dr            NUMBER;
11048   l_accounted_cr          NUMBER;
11049   l_accounted_dr          NUMBER;
11050   l_prior_entered_cr      NUMBER;
11051   l_ussgl_option          VARCHAR2(1);
11052   l_msg_data              VARCHAR2(8000) := '';
11053   l_encumbrance_flag      VARCHAR2(1);
11054   lstr                    VARCHAR2(4000);
11055 
11056   /* Currency infomration */
11057   l_curreny_code          VARCHAR2(15);
11058   l_curreny_code_func     VARCHAR2(15);
11059   l_min_acct_unit_doc     NUMBER;
11060   l_min_acct_unit_func    NUMBER;
11061   l_precision_doc         NUMBER;
11062   l_precision_func        NUMBER;
11063   l_chart_of_accounts_id  NUMBER;
11064   l_po_encumbrance_amount NUMBER;
11065   l_rcv_event             rcv_seedevents_pvt.rcv_event_rec_type;
11066 
11067 BEGIN
11068   debug('Get_Encumbrance_Data +');
11069   debug('  p_receiving_transaction_id: '||p_receiving_transaction_id );
11070   debug('  p_api_version             : '||p_api_version );
11071 
11072   --------------------------------------------------------
11073   --In this API logic to return desired value is divided in three steps
11074   --Step 1:
11075   --For a Deliver transaction id  logic  to Seed event record type structure,which will provide
11076   --i) Encumrbance Qty
11077   --ii) Currency Conversion rate
11078   --iii) Encumbrance account
11079   --iv) Unit Price - To compute encumbrance amount
11080   --Step 2 : Get the encumbrance_type_id
11081   --Step 3 : Compute encumbrance amount using values got in Step 1  and assign final
11082   --values to out parameter
11083   ---------------------------------------------------------
11084 
11085   -- Standard start of API savepoint
11086   SAVEPOINT GET_ENCUMBRANCE_DATA_PVT;
11087   l_stmt_num := 10 ;
11088 
11089   -- Initialize API return status to success
11090   x_return_status := FND_API.G_RET_STS_SUCCESS;
11091   x_msg_count     := 0;
11092 
11093 
11094   -- Unlike for Receive transactions, for Deliver transactions, the po_distribution_id
11095   -- is always available.
11096   l_stmt_num := 20;
11097   debug(l_stmt_num);
11098 
11099   SELECT   RT.po_header_id,
11100            RT.po_distribution_id,
11101            POD.destination_type_code,
11102            RT.transaction_date,
11103            NVL(RT.dropship_type_code,3),
11104            POH.org_id,
11105            POLL.ship_to_organization_id,
11106            POL.category_id,
11107            POL.project_id,
11108            NVL(POLL.accrue_on_receipt_flag,'N'),
11109            POH.type_lookup_code,
11110            pod.encumbered_Amount
11111      INTO  l_po_header_id,
11112            l_po_distribution_id,
11113            l_destination_type,
11114            l_rcv_trx_date,
11115            l_drop_ship_flag,
11116            l_po_org_id,
11117            l_rcv_organization_id,
11118            l_category_id,
11119            l_project_id,
11120            l_accrual_flag,
11121            l_po_document_type_code,
11122            l_po_encumbrance_amount
11123      FROM  po_headers_all            POH,
11124            po_line_locations_all     POLL,
11125            po_lines_all              POL,
11126            po_distributions_all      POD,
11127            rcv_transactions          RT
11128     WHERE   RT.transaction_id         = p_receiving_transaction_id
11129     AND     POH.po_header_id          = RT.po_header_id
11130     AND     POLL.line_location_id     = RT.po_line_location_id
11131     AND     POL.po_line_id            = RT.po_line_id
11132     AND     POD.po_distribution_id    = RT.po_distribution_id;
11133 
11134   debug(' RCV Transaction ID :'|| p_receiving_transaction_id ||
11135                           ', PO Header ID : ' || l_po_header_id ||
11136                           ', PO Dist ID : ' || l_po_distribution_id ||
11137                           ', Destination Type : '|| l_destination_type ||
11138                           ', Transaction Date : '|| l_rcv_trx_date ||
11139                           ', Drop Ship Flag : '|| l_drop_ship_flag ||
11140                           ', PO Org ID : ' || l_po_org_id ||
11141                           ', RCV Organization ID : '|| l_rcv_organization_id ||
11142                           ', RCV Org ID : '|| l_rcv_org_id ||
11143                           ', Project ID : '|| l_project_id ||
11144                           ', Category ID : ' || l_category_id ||
11145                          ', Accrual Flag : ' || l_accrual_flag );
11146   l_stmt_num := 25;
11147   debug(l_stmt_num);
11148   debug(' l_po_encumbrance_amount :'||l_po_encumbrance_amount);
11149   IF l_po_encumbrance_amount IS NULL OR l_po_encumbrance_amount = 0 THEN
11150    x_encumbrance_amount    := NULL;
11151    x_encumbrance_quantity  := NULL;
11152    x_encumbrance_ccid      := NULL;
11153    x_encumbrance_type_id   := NULL;
11154    RETURN;
11155   END IF;
11156 
11157 
11158   l_stmt_num := 30;
11159   debug(l_stmt_num);
11160 
11161   -- Get Receiving Operating Unit and SOB
11162   SELECT  operating_unit, ledger_id
11163   INTO    l_rcv_org_id, l_rcv_sob_id
11164   FROM    cst_acct_info_v
11165   WHERE   organization_id = l_rcv_organization_id;
11166 
11167   debug('  l_rcv_org_id:'||l_rcv_org_id);
11168   debug('  l_rcv_sob_id:'||l_rcv_sob_id);
11169 
11170   l_stmt_num := 35;
11171   debug(l_stmt_num);
11172   -- Get PO SOB
11173   SELECT  set_of_books_id
11174   INTO    l_po_sob_id
11175   FROM    financials_system_parameters
11176   WHERE   org_id = l_rcv_org_id;
11177 
11178   debug('  l_po_sob_id:'||l_po_sob_id);
11179 
11180   IF(l_po_org_id <> l_rcv_org_id) THEN  l_cross_ou_flag := 'Y'; END IF;
11181   debug('  l_cross_ou_flag:'||l_cross_ou_flag);
11182 
11183   l_stmt_num := 40;
11184   debug(l_stmt_num);
11185 
11186   RCV_SeedEvents_PVT.Check_EncumbranceFlag(
11187                   p_api_version           => 1.0,
11188                   x_return_status         => x_return_status,
11189                   x_msg_count             => x_msg_count,
11190                   x_msg_data              => x_msg_data,
11191                   p_rcv_sob_id            => l_rcv_sob_id,
11192                   x_encumbrance_flag      => l_encumbrance_flag,
11193                   x_ussgl_option          => l_ussgl_option);
11194 
11195   debug('  l_encumbrance_flag : '||l_encumbrance_flag);
11196   debug('  x_return_status    : '||x_return_status);
11197   debug('  x_msg_count        : '||x_msg_count);
11198   debug('  x_msg_data         : '||x_msg_data);
11199 
11200   IF(l_encumbrance_flag = 'Y') THEN
11201     l_stmt_num := 50 ;
11202     debug(l_stmt_num);
11203 
11204     /*****************************************************
11205     By calling Seed_RAEEvent we are only getting recirds structure with necessary values
11206     such as Qty,Price ,currency_conversion_rate.At any point of time we are not inserting any events
11207     in rcv_accounting_events or any other events table
11208     *****************************************************/
11209     RCV_SeedEvents_PVT.Seed_RAEEvent(
11210               p_api_version           => 1.0,
11211               x_return_status         => x_return_status,
11212               x_msg_count             => x_msg_count,
11213               x_msg_data              => x_msg_data,
11214               p_event_source          => 'RECEIVING',
11215               p_event_type_id         => RCV_SeedEvents_PVT.ENCUMBRANCE_REVERSAL,
11216               p_rcv_transaction_id    => p_receiving_transaction_id,-- parmeter p_rcv_transaction_id
11217               p_inv_distribution_id   => NULL,
11218               p_po_distribution_id    => l_po_distribution_id,
11219               p_direct_delivery_flag  => l_direct_delivery_flag ,-- parameter p_direct_delivery_flag
11220               p_cross_ou_flag         => l_cross_ou_flag,
11221               p_procurement_org_flag  => l_procurement_org_flag,
11222               p_ship_to_org_flag      => 'Y',
11223               p_drop_ship_flag        => l_drop_ship_flag,
11224               p_org_id                => l_rcv_org_id,
11225               p_organization_id       => l_rcv_organization_id,
11226               p_transfer_org_id       => NULL,
11227               p_trx_flow_header_id    => NULL,
11228               p_transfer_organization_id => NULL,
11229               p_transaction_forward_flow_rec  => NULL,
11230               p_transaction_reverse_flow_rec  => NULL,
11231               p_unit_price            => NULL,
11232               p_prior_unit_price      => NULL,
11233               p_lcm_flag              => 'N',
11234               x_rcv_event             => l_rcv_event );
11235 
11236     display_rcv_rev_type(l_rcv_event,lstr);
11237     debug(lstr);
11238     debug('  x_return_status    : '||x_return_status);
11239     debug('  x_msg_count        : '||x_msg_count);
11240     debug('  x_msg_data         : '||x_msg_data);
11241 
11242     -- In the case of encumbrance reversals, the quantity to unencumber
11243     --   may turn out to be zero if the quantity delivered is greater than the quantity
11244     --   ordered. In such a situation, we should not error out the event.
11245     IF x_return_status = FND_API.g_ret_sts_success THEN
11246       NULL;
11247     ELSIF x_return_status <> 'W' THEN
11248       l_api_message := 'EXCEPTION:'||lstr;
11249       debug(l_api_message );
11250       x_msg_data  := l_api_message;
11251       x_msg_count := x_msg_count + 1;
11252       RAISE FND_API.g_exc_unexpected_error;
11253     END IF;
11254   ELSE
11255     l_stmt_num := 55 ;
11256     debug(l_stmt_num);
11257   END IF;  /* l_encumbrance_flag = 'Y' */
11258 
11259  /*******************************************************
11260   Step 2  Getting Encumbrance Type ID
11261   ****************************************************** */
11262   BEGIN
11263     l_stmt_num := 60;
11264     debug(l_stmt_num);
11265 
11266     SELECT g2.ENCUMBRANCE_TYPE_ID
11267     INTO l_encumbrance_type_id  /* Out parameter*/
11268     FROM GL_ENCUMBRANCE_TYPES g2
11269     WHERE g2.encumbrance_type_key = 'Obligation';
11270 
11271     debug('  l_encumbrance_type_id:'||l_encumbrance_type_id);
11272   EXCEPTION
11273     WHEN NO_DATA_FOUND THEN
11274     l_api_message := 'EXCEPTION ENCUMBRANCE_TYPE_ID FROM GL_ENCUMBRANCE_TYPES NOT FOUND';
11275     debug(l_stmt_num||':'||l_api_message);
11276   WHEN OTHERS THEN
11277     l_api_message := 'EXCEPTION '||SQLERRM;
11278     debug(l_stmt_num||':'||l_api_message);
11279     x_msg_data := l_api_message;
11280     RAISE FND_API.g_exc_unexpected_error;
11281   END;
11282 
11283   /*******************************************************
11284   Step 3 Encumbrance Amount Computation Logic
11285   *******************************************************/
11286   -- Document Currency
11287   l_stmt_num := 70;
11288   debug(l_stmt_num);
11289   BEGIN
11290     SELECT
11291       CURRENCY_CODE,
11292       MINIMUM_ACCOUNTABLE_UNIT,
11293       PRECISION
11294     INTO
11295       l_curreny_code,
11296       l_min_acct_unit_doc,
11297       l_precision_doc
11298     FROM
11299       FND_CURRENCIES
11300     WHERE
11301       CURRENCY_CODE =l_rcv_event.currency_code;
11302   EXCEPTION
11303     WHEN NO_DATA_FOUND THEN
11304       l_api_message := l_stmt_num||':EXCEPTION: CURRENCY ISSUE l_rcv_event.currency_code:'||l_rcv_event.currency_code;
11305       debug(l_api_message);
11306       x_msg_data  := l_api_message;
11307       x_msg_count := x_msg_count + 1;
11308       RAISE FND_API.g_exc_unexpected_error;
11309   END;
11310 
11311   -- Functional Currency
11312   BEGIN
11313     l_stmt_num := 80;
11314     debug(l_stmt_num||':COA - BASE_CURRENCY');
11315     SELECT nvl(chart_of_accounts_id, 0),
11316           currency_code
11317     INTO   l_chart_of_accounts_id,
11318          l_curreny_code_func
11319     FROM   GL_SETS_OF_BOOKS
11320     WHERE  set_of_books_id = l_rcv_event.set_of_books_id;
11321 
11322     debug('  l_chart_of_accounts_id:'||l_chart_of_accounts_id||';l_curreny_code_func:'||l_curreny_code_func);
11323 
11324     l_stmt_num := 90 ;
11325     debug(l_stmt_num||':MINUMUM_ACCOUTABLE_UNIT - PRECISION');
11326     SELECT
11327       MINIMUM_ACCOUNTABLE_UNIT,
11328       PRECISION
11329     INTO
11330       l_min_acct_unit_func,
11331       l_precision_func
11332     FROM
11333       FND_CURRENCIES
11334     WHERE
11335       CURRENCY_CODE = l_curreny_code_func;
11336     debug('  l_min_acct_unit_func:'||l_min_acct_unit_func||';l_precision_func:'||l_precision_func);
11337 
11338   EXCEPTION
11339     WHEN NO_DATA_FOUND THEN
11340       l_api_message := l_stmt_num||'EXCEPTION base currency issue';
11341       debug(l_api_message);
11342       x_msg_data  := l_api_message;
11343       x_msg_count := x_msg_count + 1;
11344       RAISE FND_API.g_exc_unexpected_error;
11345   END;
11346 
11347   -- Populate the Accounting Structure
11348   -- Entered_Cr
11349   l_stmt_num := 100;
11350   debug(l_stmt_num);
11351 
11352 /*Adding Non Recoverable Tax to Price/amount to get final accounted/entered amount*/
11353   IF (l_rcv_event.unit_price IS NULL) THEN
11354     l_rcv_event.TRANSACTION_AMOUNT := l_rcv_event.TRANSACTION_AMOUNT + nvl(l_rcv_event.TRANSACTION_AMOUNT*l_rcv_event.unit_nr_tax,0);
11355     l_entered_cr        := l_rcv_event.TRANSACTION_AMOUNT ;
11356   ELSE
11357     l_rcv_event.UNIT_PRICE := l_rcv_event.UNIT_PRICE + nvl(l_rcv_event.unit_nr_tax,0) ;
11358     l_rcv_event.PRIOR_UNIT_PRICE := l_rcv_event.PRIOR_UNIT_PRICE + nvl(l_rcv_event.prior_nr_tax,0);
11359 
11360     l_entered_cr        := l_rcv_event.source_doc_quantity * (l_rcv_event.UNIT_PRICE) ;
11361     l_prior_entered_cr  := l_rcv_event.source_doc_quantity * (l_rcv_event.PRIOR_UNIT_PRICE );
11362   END IF;
11363 
11364   -- Accounted_Dr, Accounted_Nr_Tax, Accounted_Rec_Tax
11365   -- Use Document Currency Precision/MAU to round before doing currency conversion
11366   l_stmt_num := 110;
11367   debug(l_stmt_num);
11368   IF ( l_min_acct_unit_doc IS NOT NULL ) THEN
11369     l_entered_cr        := ROUND (l_entered_cr / l_min_acct_unit_doc)
11370 	                       * l_min_acct_unit_doc;
11371     IF ( l_rcv_event.UNIT_PRICE IS NULL ) THEN
11372       l_accounted_cr := ROUND (l_rcv_event.TRANSACTION_AMOUNT/l_min_acct_unit_doc)
11373 	                    * l_min_acct_unit_doc
11374 						* l_rcv_event.CURRENCY_CONVERSION_RATE;
11375     ELSE
11376       l_accounted_cr := ROUND (l_rcv_event.source_doc_quantity *  l_rcv_event.UNIT_PRICE/l_min_acct_unit_doc)
11377 	                    * l_min_acct_unit_doc
11378 	                    * l_rcv_event.CURRENCY_CONVERSION_RATE;
11379     END IF; -- UNIT_PRICE NULL
11380   ELSE
11381     l_entered_cr        := ROUND (l_entered_cr, l_precision_doc);
11382     -- ACCOUNTED_CR
11383     IF ( l_rcv_event.UNIT_PRICE IS NULL ) THEN
11384       l_accounted_cr := ROUND (l_rcv_event.TRANSACTION_AMOUNT, l_precision_doc)
11385 	                    * l_rcv_event.CURRENCY_CONVERSION_RATE;
11386     ELSE
11387       l_accounted_cr := ROUND (l_rcv_event.source_doc_quantity *  l_rcv_event.UNIT_PRICE, l_precision_doc)
11388 	                    * l_rcv_event.CURRENCY_CONVERSION_RATE;
11389     END IF;
11390   END IF; -- l_min_acct_unit_doc IS NOT NULL
11391 
11392   -- ACCOUNTED_CR, Entered_CR, NR_Tax, Rec_Tax
11393   -- Use Functional Currency to Round the amounts obtained above.
11394   l_stmt_num := 120;
11395   debug(l_stmt_num);
11396   IF ( l_min_acct_unit_func IS NOT NULL ) THEN
11397     l_accounted_cr      := ROUND (l_accounted_cr / l_min_acct_unit_func) * l_min_acct_unit_func;
11398   ELSE
11399     l_accounted_cr      := ROUND (l_accounted_cr, l_precision_func);
11400   END IF;
11401 
11402   l_stmt_num := 130;
11403   debug(l_stmt_num);
11404 
11405   /*Assigning value to LOCAL parameter*/
11406   l_encumbrance_amount	  := l_accounted_cr;
11407   l_encumbrance_quantity  := l_rcv_event.primary_quantity;
11408   l_encumbrance_ccid      := nvl(l_rcv_event.credit_account_id,l_rcv_event.debit_account_id);
11409 
11410   /*Assigning value to OUT parameter*/
11411 
11412   x_encumbrance_amount     := ABS(l_accounted_cr)   ; /*Ensuring that abs value will be returned*/
11413   x_encumbrance_quantity   := l_rcv_event.primary_quantity ;
11414 
11415 
11416   x_encumbrance_quantity   := Get_Transaction_Quantity
11417                                 (p_rcv_trx_id => p_receiving_transaction_id
11418                                 ,p_rcv_qty    => x_encumbrance_quantity);
11419 
11420   x_encumbrance_quantity   := ABS(x_encumbrance_quantity); -- As per design always unsigned
11421 
11422 
11423   x_encumbrance_type_id    := l_encumbrance_type_id;
11424 
11425   /* For return to recieving txn l_rcv_event.credit_account_id will be null and encumbrance account
11426      will be stamped in l_rcv_event.debit_account_id */
11427   x_encumbrance_ccid       :=nvl(l_rcv_event.credit_account_id,l_rcv_event.debit_account_id);
11428 
11429 
11430   debug(' x_encumbrance_amount   :'||x_encumbrance_amount );
11431   debug(' x_encumbrance_quantity :'||x_encumbrance_quantity );
11432   debug(' x_encumbrance_type_id  :'||x_encumbrance_type_id );
11433   debug(' x_encumbrance_ccid     :'||x_encumbrance_ccid );
11434   debug(' x_return_status        :'||x_return_status);
11435   debug(' x_msg_count            :'||x_msg_count);
11436   debug(' x_msg_data             :'||x_msg_data);
11437   debug('Get_Encumbrance_Data -');
11438 
11439 EXCEPTION
11440   WHEN FND_API.g_exc_unexpected_error THEN
11441     ROLLBACK TO GET_ENCUMBRANCE_DATA_PVT;
11442     x_return_status := FND_API.g_ret_sts_unexp_error ;
11443     FND_MSG_PUB.count_and_get
11444           (  p_count  => x_msg_count
11445            , p_data   => x_msg_data
11446           );
11447     debug('UNEXPECTED EXCEPTION GET_ENCUMBRANCE_DATA : '||l_stmt_num||' : '||x_msg_data);
11448 WHEN OTHERS THEN
11449     ROLLBACK TO GET_ENCUMBRANCE_DATA_PVT;
11450     x_return_status := fnd_api.g_ret_sts_unexp_error ;
11451     FND_MSG_PUB.count_and_get
11452           (  p_count  => x_msg_count
11453            , p_data   => x_msg_data
11454           );
11455     debug('OTHERS EXCEPTION GET_ENCUMBRANCE_DATA : '||l_stmt_num||' : '||substr(SQLERRM,1,200));
11456 END Get_Encumbrance_Data;
11457 
11458 PROCEDURE get_account
11459 (p_wip_entity_id      IN   NUMBER,
11460  p_item_id            IN   NUMBER  DEFAULT NULL,
11461  p_account_name       IN   VARCHAR2,
11462  p_api_version        IN   NUMBER  DEFAULT 1,
11463  x_acct               OUT  NOCOPY  NUMBER,
11464  x_return_status      OUT  NOCOPY  VARCHAR2,
11465  x_msg_count          OUT  NOCOPY  NUMBER,
11466  x_msg_data           OUT  NOCOPY  VARCHAR2)
11467 IS
11468   CURSOR c(p_wip_entity_id IN NUMBER) IS
11469   SELECT  we.entity_type                 entity_type
11470   ,       wac.class_code                 class_code
11471   ,       wac.class_type                 class_type
11472   ,       wac.material_account           material_account
11473   ,       wac.material_variance_account  material_variance_account
11474   ,       wac.resource_account           resource_account
11475   ,       wac.outside_processing_account outside_processing_account
11476   ,       wac.overhead_account           overhead_account
11477   ,       wac.encumbrance_account        wac_encumbrance_account
11478   ,       msi.encumbrance_account        msi_encumbrance_account
11479   ,       mp.encumbrance_account         mp_encumbrance_account
11480    FROM wip_entities           we
11481    ,    wip_discrete_jobs      wdj
11482    ,    wip_accounting_classes wac
11483    ,    mtl_system_items       msi
11484    ,    mtl_parameters         mp
11485   WHERE we.wip_entity_id         = p_wip_entity_id
11486     AND we.wip_entity_id         = wdj.wip_entity_id
11487     AND wac.organization_id      = wdj.organization_id
11488     AND wac.class_code           = wdj.class_code
11489     AND msi.inventory_item_id(+) = NVL(p_item_id,-9999)
11490     AND msi.organization_id(+)   = wdj.organization_id
11491     AND wdj.organization_id      = mp.organization_id;
11492   l_rec         c%ROWTYPE;
11493   l_no_row      VARCHAR2(1) := 'N';
11494   no_input      EXCEPTION;
11495   account_name  EXCEPTION;
11496   c_no_row      EXCEPTION;
11497   acct_null     EXCEPTION;
11498 BEGIN
11499   debug('get_account +');
11500   debug('  p_wip_entity_id  : '||p_wip_entity_id );
11501   debug('  p_account_name   : '||p_account_name  );
11502   debug('  p_item_id        : '||p_item_id       );
11503 
11504   fnd_msg_pub.initialize;
11505   x_return_status := FND_API.G_RET_STS_SUCCESS;
11506   x_msg_count     := 0;
11507 
11508   IF p_wip_entity_id IS NULL THEN
11509     RAISE no_input;
11510   END IF;
11511 
11512   debug('10');
11513   IF p_account_name NOT IN ('ENCUMBRANCE',
11514                         'MATERIAL',
11515                         'MATERIAL_VARIANCE',
11516                         'RESOURCE',
11517                         'OSP',
11518                         'OVERHEAD')
11519   THEN
11520     RAISE account_name;
11521   END IF;
11522 
11523   debug('20');
11524   OPEN  c(p_wip_entity_id => p_wip_entity_id);
11525   FETCH c INTO l_rec;
11526   IF c%NOTFOUND THEN
11527     l_no_row := 'Y';
11528   END IF;
11529   CLOSE c;
11530 
11531   IF l_no_row = 'Y' THEN
11532     RAISE c_no_row;
11533   END IF;
11534 
11535   debug('30');
11536   IF    p_account_name = 'ENCUMBRANCE'      THEN
11537 
11538     IF     l_rec.wac_encumbrance_account IS NOT NULL  THEN
11539       debug('  Encumbrance account selected WAC');
11540       x_acct  := l_rec.wac_encumbrance_account;
11541     ELSIF  l_rec.msi_encumbrance_account IS NOT NULL  THEN
11542       debug('  Encumbrance account selected MSI');
11543       x_acct  := l_rec.msi_encumbrance_account;
11544     ELSE
11545       debug('  Encumbrance account selected INV ORG');
11546       x_acct  := l_rec.mp_encumbrance_account;
11547     END IF;
11548 
11549   ELSIF p_account_name = 'MATERIAL'          THEN
11550     debug('  Material Account');
11551     x_acct :=  l_rec.material_account;
11552   ELSIF p_account_name = 'MATERIAL_VARIANCE' THEN
11553     debug('  Material Variance Account');
11554     x_acct :=  l_rec.material_variance_account;
11555   ELSIF p_account_name = 'RESOURCE'          THEN
11556     x_acct :=  l_rec.resource_account;
11557   ELSIF p_account_name = 'OSP'               THEN
11558     debug('  OSP Account');
11559     x_acct :=  l_rec.outside_processing_account;
11560   ELSE
11561     debug('  Overhead Account');
11562     x_acct :=  l_rec.overhead_account;
11563   END IF;
11564 
11565   IF x_acct IS NULL THEN
11566     RAISE acct_null;
11567   END IF;
11568 
11569   debug('  x_acct           : '||x_acct);
11570   debug('  x_return_status  : '||x_return_status);
11571   debug('  x_msg_count      : '||x_msg_count);
11572   debug('  x_msg_data       : '||x_msg_data);
11573   debug('get_account -');
11574 EXCEPTION
11575   WHEN no_input THEN
11576     x_msg_data := 'EXCEPTION NO_INPUTS in GET_ACCOUNT p_wip_entity_id :'||p_wip_entity_id;
11577     x_msg_count:= x_msg_count + 1;
11578     debug(x_msg_data);
11579     x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
11580     x_acct := NULL;
11581   WHEN account_name THEN
11582     FND_MESSAGE.SET_NAME( 'BOM', 'CST_ACCOUNT_UNDEFINED' );
11583     FND_MESSAGE.SET_TOKEN( 'ACCOUNT', p_account_name);
11584     FND_MSG_PUB.ADD;
11585     fnd_msg_pub.count_and_get(
11586       p_encoded => fnd_api.g_false,
11587       p_count   => x_msg_count,
11588       p_data    => x_msg_data);
11589     x_return_status := FND_API.G_RET_STS_ERROR;
11590     x_acct := NULL;
11591     debug('EXCEPTION account_name '||p_account_name||' in GET_ACCOUNT');
11592   WHEN c_no_row THEN
11593     x_msg_data := 'EXCEPTION c_no_row in GET_ACCOUNT p_wip_entity_id :'||p_wip_entity_id;
11594     x_msg_count:= x_msg_count + 1;
11595     x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
11596     x_acct := NULL;
11597     debug(x_msg_data);
11598   WHEN acct_null THEN
11599     FND_MESSAGE.SET_NAME( 'BOM'     , 'CST_NO_ACCOUNT_FOUND' );
11600     FND_MESSAGE.SET_TOKEN( 'ID'     , p_wip_entity_id);
11601     FND_MESSAGE.SET_TOKEN( 'ACCOUNT', p_account_name);
11602     FND_MSG_PUB.ADD;
11603     fnd_msg_pub.count_and_get(
11604       p_encoded => fnd_api.g_false,
11605       p_count   => x_msg_count,
11606       p_data    => x_msg_data);
11607     x_return_status := FND_API.G_RET_STS_ERROR;
11608     x_acct := NULL;
11609     debug('EXCEPTION CST_NO_ACCOUNT_FOUND in GET_ACCOUNT  p_account_name ' || p_account_name ||' - p_wip_entity_id :'||p_wip_entity_id);
11610   WHEN OTHERS THEN
11611     x_msg_data := 'EXCEPTION OTHERS IN get_account '||SQLERRM;
11612     x_msg_count:= x_msg_count + 1;
11613     debug(x_msg_data);
11614     x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
11615     x_acct := NULL;
11616 END;
11617 
11618 
11619 PROCEDURE check_enc_rev_flag
11620 (p_organization_id    IN NUMBER,
11621  x_enc_rev_flag       OUT  NOCOPY  VARCHAR2,
11622  x_return_status      OUT  NOCOPY  VARCHAR2,
11623  x_msg_count          OUT  NOCOPY  NUMBER,
11624  x_msg_data           OUT  NOCOPY  VARCHAR2)
11625 IS
11626   CURSOR c(p_organization_id IN NUMBER) IS
11627   SELECT decode(encumbrance_reversal_flag,1,1,2)
11628     FROM mtl_parameters
11629    WHERE organization_id = p_organization_id;
11630   l_encumbrance_reversal_flag  NUMBER;
11631   l_no_org                     VARCHAR2(1) := 'N';
11632   l_no_org_exc                 EXCEPTION;
11633 BEGIN
11634  debug('check_enc_rev_flag +');
11635  debug('  p_organization_id  : '||p_organization_id );
11636 
11637  x_return_status := FND_API.G_RET_STS_SUCCESS;
11638  x_msg_count     := 0;
11639 
11640  OPEN c(p_organization_id);
11641  FETCH c INTO l_encumbrance_reversal_flag;
11642  IF c%NOTFOUND THEN
11643     debug(' Cursur C does not return any row' );
11644     l_no_org := 'Y';
11645  END IF;
11646  CLOSE c;
11647 
11648  IF l_no_org = 'Y' THEN
11649     RAISE l_no_org_exc;
11650  END IF;
11651 
11652  debug(' l_encumbrance_reversal_flag :'||l_encumbrance_reversal_flag );
11653 
11654  IF     l_encumbrance_reversal_flag = 1 THEN
11655      x_enc_rev_flag := 'Y';
11656  ELSIF  l_encumbrance_reversal_flag = 2 THEN
11657      x_enc_rev_flag := 'N';
11658  ELSE
11659      x_msg_data       := 'Error encumbrance_reversal_flag should be 1 or 2. Current value:'||
11660 	                      l_encumbrance_reversal_flag;
11661      debug(x_msg_data);
11662      x_return_status  := FND_API.G_RET_STS_ERROR;
11663      x_msg_count      := x_msg_count + 1;
11664      x_enc_rev_flag := 'N';
11665  END IF;
11666  debug(x_enc_rev_flag);
11667  debug('check_enc_rev_flag -');
11668 
11669 EXCEPTION
11670   WHEN l_no_org_exc THEN
11671     x_enc_rev_flag  := 'N';
11672     x_return_status := FND_API.G_RET_STS_ERROR;
11673     x_msg_data      := 'EXCEPTION l_no_org_exc: No inventory organization :'||p_organization_id;
11674     debug(x_msg_data);
11675     x_msg_count     := x_msg_count + 1;
11676   WHEN OTHERS THEN
11677     x_enc_rev_flag  := 'N';
11678     x_return_status := FND_API.G_RET_STS_UNEXP_ERROR;
11679     x_msg_data := 'EXCEPTION OTHERS IN check_enc_rev_flag '||SQLERRM;
11680     debug(x_msg_data);
11681     x_msg_count:= x_msg_count + 1;
11682     END;
11683 
11684 END CST_eamCost_PUB;