DBA Data[Home] [Help]

PACKAGE BODY: APPS.CST_EAMCOST_PUB

Source


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