DBA Data[Home] [Help]

PACKAGE BODY: APPS.CST_REVENUECOGSMATCH_PVT

Source


1 PACKAGE BODY CST_RevenueCogsMatch_PVT AS
2 /* $Header: CSTRCMVB.pls 120.45.12010000.4 2008/12/16 22:32:12 hyu ship $ */
3 
4 G_PKG_NAME     CONSTANT VARCHAR2(30) := 'CST_RevenueCogsMatch_PVT';
5 G_DEBUG        CONSTANT VARCHAR2(1) := NVL(FND_PROFILE.VALUE('AFLOG_ENABLED'),'N');
6 G_LOG_HEAD     CONSTANT VARCHAR2(40) := 'cst.plsql.'||G_PKG_NAME;
7 G_LOG_LEVEL    CONSTANT NUMBER := FND_LOG.G_CURRENT_RUNTIME_LEVEL;
8 g_module_name  VARCHAR2(255) := G_LOG_HEAD;
9 
10 --BUG#7463298
11 g_ledger_id    NUMBER := -1;
12 
13 --------------------------------------------------------------------------------------
14 -- Local routines section : BEGIN
15 --------------------------------------------------------------------------------------
16 -- 1 set g_module_name
17 -- 2 call debug only with line
18 PROCEDURE debug
19 ( line       IN VARCHAR2,
20   msg_prefix IN VARCHAR2  DEFAULT 'CST',
21   msg_module IN VARCHAR2  DEFAULT g_module_name,
22   msg_level  IN NUMBER    DEFAULT FND_LOG.LEVEL_STATEMENT);
23 
24 -- Ensure the MMT transaction_date and the acct_period_id match
25 PROCEDURE ensure_mmt_per_and_date
26 (x_return_status   OUT NOCOPY     VARCHAR2,
27  x_msg_count       OUT NOCOPY     NUMBER,
28  x_msg_data        OUT NOCOPY     VARCHAR2);
29 
30 --{BUG#7387575
31 PROCEDURE crrl_preparation
32 (p_batch_size   IN NUMBER  DEFAULT 1000
33 ,p_ledger_id    IN NUMBER  DEFAULT NULL);
34 
35 PROCEDURE nb_req_active;
36 
37 PROCEDURE updation_potential_crrl
38 (p_batch_size   IN NUMBER  DEFAULT 1000
39 ,p_ledger_id    IN NUMBER);
40 --}
41 
42 -----------------------------------------------------------------------------
43 -- Start of comments                                                       --
44 --                                                                         --
45 -- PROCEDURE                                                               --
46 --  Match_RevenueCOGS This API is the outer wrapper for the concurrent     --
47 --                    request that matches COGS to revenue for OM lines.   --
48 --                    It is run in four phases, each followed by a         --
49 --                    commit:                                              --
50 --                    1) Record any sales order issues and RMA receipts    --
51 --                       that have not yet been inserted into CRCML and    --
52 --                       CCE.                                              --
53 --                    2) Process incoming revenue events and insert        --
54 --                       revenue recognition per period by OM line into    --
55 --                       CRRL.                                             --
56 --                    3) Compare CRRL to CCE (via CRCML) and create new    --
57 --                       COGS recognition events where they don't match.   --
58 --                    4) Cost all of the Cogs Recogntion Events that were  --
59 --                       just created in bulk.                             --
60 --                                                                         --
61 --                                                                         --
62 -- VERSION 1.0                                                             --
63 --                                                                         --
64 -- PARAMETERS                                                              --
65 --                                                                         --
66 --  P_LOW_DATE         Lower bound for the date range.                     --
67 --  P_HIGH_DATE        Upper bound for the date range.                     --
68 --  P_PHASE            Set to a number, this parameter indicates that only --
69 --                     that phase # should be run.  Otherwise all phases   --
70 --                     should be run.                                      --
71 --                                                                         --
72 -- HISTORY:                                                                --
73 --    04/20/05     Bryan Kuntz      Created                                --
74 -- End of comments                                                         --
75 -----------------------------------------------------------------------------
76 PROCEDURE Match_RevenueCOGS(
77                 x_return_status         OUT NOCOPY  VARCHAR2,
78                 x_dummy_out             OUT NOCOPY  NUMBER,
79                 p_api_version           IN          NUMBER,
80                 p_phase                 IN          NUMBER,
81                 p_low_date              IN          VARCHAR2,
82                 p_high_date             IN          VARCHAR2,
83                 p_ledger_id             IN          NUMBER DEFAULT NULL--BUG#5726230
84                ,p_neg_req_id            IN          NUMBER DEFAULT NULL--HYU
85 ) IS
86 
87    l_api_name            CONSTANT VARCHAR2(30)  := 'Match_RevenueCOGS';
88    l_api_version         CONSTANT NUMBER        := 1.0;
89    l_api_message         VARCHAR2(1000);
90 
91    l_return_status       VARCHAR2(1)        := FND_API.G_RET_STS_SUCCESS;
92    l_dummy_status        VARCHAR2(1);  /* not sure why AR needs this, hopefully can remove it ... */
93    l_msg_count           NUMBER             := 0;
94    l_msg_data            VARCHAR2(8000)     := '';
95    l_stmt_num            NUMBER             := 0;
96 
97    l_module   CONSTANT VARCHAR2(100)        := G_LOG_HEAD ||'.'||l_api_name;
98    l_unexpLog CONSTANT BOOLEAN := (FND_LOG.LEVEL_UNEXPECTED >= G_LOG_LEVEL) AND FND_LOG.TEST(FND_LOG.LEVEL_UNEXPECTED, l_module);
99    l_errorLog CONSTANT BOOLEAN := l_unexpLog and (FND_LOG.LEVEL_ERROR >= G_LOG_LEVEL);
100    l_eventLog CONSTANT BOOLEAN := l_errorLog and (FND_LOG.LEVEL_EVENT >= G_LOG_LEVEL);
101    l_procLog  CONSTANT BOOLEAN := l_eventLog and (FND_LOG.LEVEL_PROCEDURE >= G_LOG_LEVEL);
102    l_stmtLog  CONSTANT BOOLEAN := l_procLog  and (FND_LOG.LEVEL_STATEMENT >= G_LOG_LEVEL);
103 
104    program_exception     EXCEPTION;
105    CONC_STATUS           BOOLEAN;            -- variable for concurrent request completion status
106 
107    l_request_id          NUMBER;             -- FND global settings
108    l_user_id             NUMBER;
109    l_login_id            NUMBER;
110    l_pgm_app_id          NUMBER;
111    l_pgm_id              NUMBER;
112 
113    l_schema VARCHAR2(30);                    -- variables for fnd_stats
114    l_status VARCHAR2(1);
115    l_industry VARCHAR2(1);
116 
117    l_low_date            DATE;
118    l_high_date           DATE;
119 
120 BEGIN
121 
122 -- Standard start of API savepoint
123    SAVEPOINT Match_RevenueCOGS_PVT;
124 
125    l_stmt_num := 0;
126 
127    debug('Match_RevenueCOGS+');
128    debug('  p_api_version:'||p_api_version);
129    debug('  p_phase     : '|| p_phase);
130    debug('  p_low_date  : '|| p_low_date);
131    debug('  p_high_date : '|| p_high_date);
132    debug('  p_ledger_id : '|| p_ledger_id);
133    debug('  p_neg_req_id: '|| p_neg_req_id);
134 
135 /*   IF l_procLog THEN
136      FND_LOG.string(FND_LOG.LEVEL_PROCEDURE,l_module||'.begin',
137         'Entering '||G_PKG_NAME||'.'||l_api_name||' with '||
138         'p_api_version = '||p_api_version||','||
139         'p_low_date = '||p_low_date||','||
140         'p_high_date = '||p_high_date||','||
141         'p_phase = '||p_phase);
142    END IF;
143 */
144 -- Standard call to check for call compatibility
145    IF NOT FND_API.Compatible_API_Call (
146                         l_api_version,
147                         p_api_version,
148                         l_api_name,
149                         G_PKG_NAME ) THEN
150      RAISE FND_API.G_EXC_UNEXPECTED_ERROR;
151    END IF;
152 
153 -- Initialize message list if p_init_msg_list is set to TRUE
154    FND_MSG_PUB.initialize;
155 
156 -- Initialize API return status to success
157    x_return_status := FND_API.G_RET_STS_SUCCESS;
158 
159 -- API Body
160 
161    -- Populate WHO column variables
162    l_request_id := FND_GLOBAL.conc_request_id;
163    l_user_id    := FND_GLOBAL.user_id;
164    l_login_id   := FND_GLOBAL.login_id;
165    l_pgm_app_id := FND_GLOBAL.PROG_APPL_ID;
166    l_pgm_id     := FND_GLOBAL.CONC_PROGRAM_ID;
167 
168   /********************************************************************************
169    * Phase 1 - Record any sales order issues and RMA receipts that have not yet   *
170    *           been inserted into the Revenue/COGS matching data model (CRCML and *
171    *           CCE).                                                              *
172    ********************************************************************************/
173 
174    IF ( p_phase = 1 ) THEN
175 
176       --{BUG#7463298
177       IF p_ledger_id IS NOT NULL THEN
178         g_ledger_id := p_ledger_id;
179       END IF;
180       debug(' g_ledger_id : ' ||g_ledger_id);
181       --}
182 
183       l_stmt_num := 10;
184       debug(l_stmt_num);
185 
186       Insert_SoIssues(p_request_id    => l_request_id,
187                       p_user_id       => l_user_id,
188                       p_login_id      => l_login_id,
189                       p_pgm_app_id    => l_pgm_app_id,
190                       p_pgm_id        => l_pgm_id,
191                       x_return_status => l_return_status);
192 
193       IF (l_return_status <> FND_API.G_RET_STS_SUCCESS) THEN
194          IF l_errorLog THEN
195             FND_LOG.string(FND_LOG.LEVEL_ERROR,l_module||'.'||l_stmt_num,substr(SQLERRM,1,250));
196          END IF;
197          raise program_exception;
198       END IF;
199 
200       l_stmt_num := 20;
201       debug(l_stmt_num);
202       insert_RmaReceipts(p_request_id    => l_request_id,
203                          p_user_id       => l_user_id,
204                          p_login_id      => l_login_id,
205                          p_pgm_app_id    => l_pgm_app_id,
206                          p_pgm_id        => l_pgm_id,
207                          x_return_status => l_return_status);
208 
209       IF (l_return_status <> FND_API.G_RET_STS_SUCCESS) THEN
210          IF l_errorLog THEN
211             FND_LOG.string(FND_LOG.LEVEL_ERROR,l_module||'.'||l_stmt_num,substr(SQLERRM,1,250));
212          END IF;
213          raise program_exception;
214       END IF;
215 
216       IF l_eventLog THEN
217           FND_LOG.string(FND_LOG.LEVEL_EVENT,l_module||'.20'
218                  ,'Completed phase 1 successfully.');
219       END IF;
220 
221       IF fnd_msg_pub.check_msg_level(fnd_msg_pub.g_msg_lvl_success) THEN
222          FND_MESSAGE.set_name('BOM', 'CST_SUCCESSFUL_PHASE');
223          FND_MESSAGE.set_token('PHASE', '1');
224          FND_MSG_PUB.ADD;
225       END IF;
226 
227       Print_MessageStack;
228 
229       -- Commit phase 1 insertions
230       COMMIT;
231       SAVEPOINT Match_RevenueCOGS_PVT;
232 
233    END IF;  -- phase 1
234 
235   /********************************************************************************
236    * Phase 2 - Process incoming revenue events and insert revenue recognition per *
237    *           period by OM line into CRRL                                        *
238    ********************************************************************************/
239 
240    IF ( p_phase = 2 ) THEN
241 
242       -- convert input parameters to dates
243       l_low_date := fnd_date.canonical_to_date(p_low_date);
244       l_high_date := trunc(fnd_date.canonical_to_date(p_high_date))+0.99999;
245       IF (l_low_date IS NULL) THEN
246          l_low_date := sysdate - (365*20); -- go back 20 years
247       END IF;
248       -- prevent the collection of future revenue recognition events
249       IF (l_high_date IS NULL OR l_high_date > sysdate) THEN
250          l_high_date := sysdate;
251       END IF;
252 
253       -- Call AR's procedure to populate CRRL with revenue recognition event data
254       -- by OM line and accounting period.
255       l_stmt_num := 30;
256 
257       IF l_stmtLog THEN
258          FND_LOG.string(FND_LOG.LEVEL_STATEMENT, l_module||'.'||l_stmt_num,
259         'Calling AR_MATCH_REV_COGS_GRP.populate_cst_tables with '||
260         'p_from_gl_date = '||l_low_date||','||
261         'p_to_gl_date = '||l_high_date||',');
262       END IF;
263 
264       ar_match_rev_cogs_grp.populate_cst_tables (
265                p_api_version   => 1,
266                p_from_gl_date  => l_low_date,
267                p_to_gl_date    => l_high_date,
268                --{BUG#7533570 add ledger_id
269                p_ledger_id     => p_ledger_id,
270                --}
271                x_status        => l_dummy_status,
272                x_return_status => l_return_status,
273                x_msg_count     => l_msg_count,
274                x_msg_data      => l_msg_data
275                );
276 
277       IF (l_return_status <> FND_API.G_RET_STS_SUCCESS) THEN
278          IF l_errorLog THEN
279             FND_LOG.string(FND_LOG.LEVEL_ERROR,l_module||'.'||l_stmt_num,substr(SQLERRM,1,250));
280          END IF;
281          raise program_exception;
282       END IF;
283 
284       IF l_eventLog THEN
285          FND_LOG.string(FND_LOG.LEVEL_EVENT,l_module||'.20'
286                 ,'Completed phase 2 successfully.');
287       END IF;
288 
289       IF fnd_msg_pub.check_msg_level(fnd_msg_pub.g_msg_lvl_success) THEN
290          FND_MESSAGE.set_name('BOM', 'CST_SUCCESSFUL_PHASE');
291          FND_MESSAGE.set_token('PHASE', '2');
292          FND_MSG_PUB.ADD;
293       END IF;
294 
295       Print_MessageStack;
296 
297       -- Update the "Process Upto Date" in the revenue / COGS control table
298       UPDATE cst_revenue_cogs_control
299       SET last_process_upto_date = l_high_date,
300           last_update_date       = sysdate,
301           last_updated_by        = l_user_id,
302           last_update_login      = l_login_id,
303           request_id             = l_request_id
304       WHERE control_id           = 1;
305 
306       IF (SQL%ROWCOUNT = 0) THEN
307          INSERT INTO cst_revenue_cogs_control (
308                        CONTROL_ID,
309                        LAST_PROCESS_UPTO_DATE,
310                        LAST_UPDATE_DATE,
311                        LAST_UPDATED_BY,
312                        CREATION_DATE,
313                        CREATED_BY,
314                        LAST_UPDATE_LOGIN,
315                        REQUEST_ID,
316                        PROGRAM_APPLICATION_ID,
317                        PROGRAM_ID,
318                        PROGRAM_UPDATE_DATE)
319          VALUES ( 1,
320                   l_high_date,
321                   sysdate,
322                   l_user_id,
323                   sysdate,
324                   l_user_id,
325                   l_login_id,
326                   l_request_id,
327                   l_pgm_app_id,
328                   l_pgm_id,
329                   sysdate);
330       END IF;
331 
332       -- Commit phase 2 inserts and updates
333       COMMIT;
334       SAVEPOINT Match_RevenueCOGS_PVT;
335 
336       -- Now we should gather statistics on CRRL since the above call to
337       -- ar_match_rev_cogs_grp.populate_cst_tables would have added a bunch of rows
338       -- with potentially_unmatched_flag = 'Y'.  This column is a histogram, so we
339       -- need to gather stats before running phase 3, which relies heavily on this
340       -- column.
341       IF NOT FND_INSTALLATION.GET_APP_INFO('BOM', l_status, l_industry, l_schema) THEN
342          RAISE FND_API.G_EXC_UNEXPECTED_ERROR;
343       END IF;
344 
345       IF l_schema IS NOT NULL THEN
346          l_stmt_num := 37;
347          FND_STATS.GATHER_TABLE_STATS(l_schema, 'CST_REVENUE_RECOGNITION_LINES');
348       END IF;
349       SAVEPOINT Match_RevenueCOGS_PVT; -- necessary because of commit within gather_table_stats
350 
351    END IF; -- phase 2
352 
353 
354    IF ( p_phase = 3 ) THEN
355 
356      /********************************************************************************
357       * Phase 3 - Compare CRRL to CCE (via CRCML) and create new COGS recognition    *
358       *           events where they don't match.                                     *
359       ********************************************************************************/
360 
361       -- Update all rows from OM so that any OLTP rows coming in during the
362       -- concurrent request will not get picked up in this run.
363       l_stmt_num := 40;
364       UPDATE cst_revenue_recognition_lines crrl
365          SET potentially_unmatched_flag = 'Y'
366        WHERE potentially_unmatched_flag = 'U';
367 
368       l_stmt_num := 50;
369       Create_CogsRecognitionEvents(p_request_id    => l_request_id,
370                                    p_user_id       => l_user_id,
371                                    p_login_id      => l_login_id,
372                                    p_pgm_app_id    => l_pgm_app_id,
373                                    p_pgm_id        => l_pgm_id,
374                                    x_return_status => l_return_status,
375                                    p_ledger_id     => p_ledger_id    -- BUG#5726230
376                                   ,p_neg_req_id    => p_neg_req_id); -- BUG#7387575
377 
378       IF (l_return_status <> FND_API.G_RET_STS_SUCCESS) THEN
379          IF l_errorLog THEN
380             FND_LOG.string(FND_LOG.LEVEL_ERROR,l_module||'.'||l_stmt_num,substr(SQLERRM,1,250));
381          END IF;
382          raise program_exception;
383       END IF;
384 
385       -- Any rows marked as potentially mismatched would have been picked up for
386       -- comparison this time.  For such rows to be mismatched at this point would
387       -- require a new initiating event.  That event will reset the flag to 'Y' at
388       -- that time, so fow now we set it to NULL indicating it is matched.
389       l_stmt_num := 60;
390 
391       IF p_neg_req_id IS NULL THEN
392 
393         UPDATE cst_revenue_recognition_lines crrl
394         SET potentially_unmatched_flag = NULL,
395             last_update_date           = sysdate,
396             last_updated_by            = l_user_id,
397             last_update_login          = l_login_id,
398             request_id                 = l_request_id,
399             program_application_id     = l_pgm_app_id,
400             program_id                 = l_pgm_id,
401             program_update_date        = sysdate
402         WHERE potentially_unmatched_flag = 'Y'
403         AND ledger_id                  = NVL(p_ledger_id,ledger_id);  --BUG5726230
404 
405       ELSE
406 
407         UPDATE cst_revenue_recognition_lines crrl
408         SET potentially_unmatched_flag = NULL,
409             last_update_date           = sysdate,
410             last_updated_by            = l_user_id,
411             last_update_login          = l_login_id,
412             request_id                 = l_request_id,
413             program_application_id     = l_pgm_app_id,
414             program_id                 = l_pgm_id,
415             program_update_date        = sysdate
416         WHERE potentially_unmatched_flag = 'Y'
417         AND ledger_id                  = NVL(p_ledger_id,ledger_id)  --BUG5726230
418         AND request_id                 = p_neg_req_id;               --BUG7387575
419 
420       END IF;
421 
422       IF l_eventLog THEN
423          FND_LOG.string(FND_LOG.LEVEL_EVENT,l_module||'.20'
424                 ,'Completed phase 3 successfully.');
425       END IF;
426 
427       IF fnd_msg_pub.check_msg_level(fnd_msg_pub.g_msg_lvl_success) THEN
428          FND_MESSAGE.set_name('BOM', 'CST_SUCCESSFUL_PHASE');
429          FND_MESSAGE.set_token('PHASE', '3');
430          FND_MSG_PUB.ADD;
431       END IF;
432 
433       Print_MessageStack;
434 
435       -- Commit phase 3 work
436       COMMIT;
437       SAVEPOINT Match_RevenueCOGS_PVT;
438 
439      /********************************************************************************
440       * Phase 4 - Cost all of the Cogs Recogntion Events that were just created in   *
441       *           bulk.  The cost manager would never be able to handle this.        *
442       ********************************************************************************/
443 
444       l_stmt_num := 70;
445       Cost_BulkCogsRecTxns(p_request_id    => l_request_id,
446                            p_user_id       => l_user_id,
447                            p_login_id      => l_login_id,
448                            p_pgm_app_id    => l_pgm_app_id,
449                            p_pgm_id        => l_pgm_id,
450                            x_return_status => l_return_status,
451                            p_ledger_id     => p_ledger_id   --BUG5726230
452                            ,p_neg_req_id   => p_neg_req_id);--BUG7387575
453 
454       IF (l_return_status <> FND_API.G_RET_STS_SUCCESS) THEN
455          IF l_errorLog THEN
456             FND_LOG.string(FND_LOG.LEVEL_ERROR,l_module||'.'||l_stmt_num,substr(SQLERRM,1,250));
457          END IF;
458          raise program_exception;
459       END IF;
460 
461       IF l_eventLog THEN
462          FND_LOG.string(FND_LOG.LEVEL_EVENT,l_module||'.20'
463                 ,'Completed phase 4 successfully.');
464       END IF;
465 
466       IF fnd_msg_pub.check_msg_level(fnd_msg_pub.g_msg_lvl_success) THEN
467          FND_MESSAGE.set_name('BOM', 'CST_SUCCESSFUL_PHASE');
468          FND_MESSAGE.set_token('PHASE', '4');
469          FND_MSG_PUB.ADD;
470       END IF;
471 
472       -- Print the message stack to the log file
473       Print_MessageStack;
474 
475       -- Commit phase 4 work
476       COMMIT;
477 
478    END IF;  -- phases 3 and 4
479 
480 -- End API Body
481 /*
482    IF l_proclog THEN
483       fnd_log.string(fnd_log.level_procedure,l_module||'.end',
484         'Exiting '||G_PKG_NAME||'.'||l_api_name||' with '||
485         'x_return_status = '||x_return_status||
486         'x_dummy_out = '||x_dummy_out
487       );
488    END IF;
489  */
490    debug('  x_return_status : '||x_return_status);
491    debug('  x_dummy_out     : '||x_dummy_out );
492    debug('Match_RevenueCOGS-');
493 
494 EXCEPTION
495    WHEN program_exception THEN
496       x_return_status := fnd_api.g_ret_sts_error;
497 
498       FND_MESSAGE.set_name('BOM', 'CST_PLSQL_ERROR');
499       FND_MESSAGE.set_token('PACKAGE', G_PKG_NAME);
500       FND_MESSAGE.set_token('PROCEDURE',l_api_name);
501       FND_MESSAGE.set_token('STATEMENT',to_char(l_stmt_num));
502       IF fnd_msg_pub.check_msg_level(fnd_msg_pub.g_msg_lvl_error) THEN
503          FND_MSG_PUB.ADD;
504       END IF;
505 
506       IF l_errorLog THEN
507          FND_LOG.MESSAGE(FND_LOG.LEVEL_ERROR,l_module||'.'||l_stmt_num,TRUE);
508       END IF;
509 
510       CONC_STATUS := FND_CONCURRENT.SET_COMPLETION_STATUS('ERROR',l_module||' failed to complete.');
511 
512       DECLARE
513          l_cnt   NUMBER;
514          l_data  VARCHAR2(2000);
515       BEGIN
516           fnd_msg_pub.Count_And_Get
517            (p_encoded => 'T',
518             p_count	  => l_cnt,
519             p_data	  => l_data);
520           FND_FILE.put_line
521            (fnd_file.log,
522             'PROGRAM_EXCEPTION IN Match_RevenueCOGS at ('||l_stmt_num||'): '||
523              SUBSTRB(l_data,1,400) );
524       END;
525 
526       Print_MessageStack;
527 
528    WHEN OTHERS THEN
529 
530          x_return_status := fnd_api.g_ret_sts_unexp_error ;
531 
532          IF l_unexpLog THEN
533             FND_LOG.string(FND_LOG.LEVEL_UNEXPECTED,G_LOG_HEAD || '.'||l_api_name||'.'||l_stmt_num
534                 ,substrb(SQLERRM,1,250));
535          END IF;
536 
537          IF fnd_msg_pub.check_msg_level(fnd_msg_pub.g_msg_lvl_unexp_error) THEN
538             FND_MESSAGE.set_name('BOM', 'CST_UNEXP_ERROR');
539             FND_MESSAGE.set_token('PACKAGE', G_PKG_NAME);
540             FND_MESSAGE.set_token('PROCEDURE',l_api_name);
541             FND_MESSAGE.set_token('STATEMENT',to_char(l_stmt_num));
542             FND_MSG_PUB.ADD;
543          END IF;
544 
545          FND_FILE.put_line(fnd_file.log, 'OTHERS EXCEPTION IN Match_RevenueCOGS:'||substrb(SQLERRM,1,250) );
546 
547          CONC_STATUS := FND_CONCURRENT.SET_COMPLETION_STATUS('ERROR',l_module||' failed to complete.');
548 
549          Print_MessageStack;
550 
551 END Match_RevenueCOGS;
552 
553 
554 -----------------------------------------------------------------------------
555 -- Start of comments                                                       --
556 --                                                                         --
557 -- PROCEDURE                                                               --
558 --  Insert_SoIssues   This procedure handles the insertion of sales order  --
559 --                    issue transactions in batch into the matching data   --
560 --                    model.  Most sales orders will be inserted into the  --
561 --                    matching data model by the Cost Processor. Any that  --
562 --                    are not processed at that time (e.g. - OPM orgs)     --
563 --                    will be inserted here.                               --
564 --                                                                         --
565 -- VERSION 1.0                                                             --
566 --                                                                         --
567 -- PARAMETERS                                                              --
568 --  X_RETURN_STATUS    Success/Error/Unexplained error - 'S','E', or 'U'   --
569 --  WHO columns                                                            --
570 --                                                                         --
571 -- HISTORY:                                                                --
572 --    04/22/05     Bryan Kuntz      Created using cursor                   --
573 -- End of comments                                                         --
574 -----------------------------------------------------------------------------
575 
576 PROCEDURE Insert_SoIssues(
577                 x_return_status   OUT NOCOPY  VARCHAR2,
578                 p_request_id      IN   NUMBER,
579                 p_user_id         IN   NUMBER,
580                 p_login_id        IN   NUMBER,
581                 p_pgm_app_id      IN   NUMBER,
582                 p_pgm_id          IN   NUMBER
583 ) IS
584 
585    l_api_name            CONSTANT VARCHAR2(30)  := 'Insert_SoIssues';
586    l_api_message         VARCHAR2(100);
587    l_stmt_num            NUMBER         := 0;
588    l_return_status       VARCHAR2(1)        := FND_API.G_RET_STS_SUCCESS;
589 
590    l_module   CONSTANT VARCHAR2(100)        := G_LOG_HEAD ||'.'||l_api_name;
591    l_unexpLog CONSTANT BOOLEAN := (FND_LOG.LEVEL_UNEXPECTED >= G_LOG_LEVEL) AND FND_LOG.TEST(FND_LOG.LEVEL_UNEXPECTED, l_module);
592    l_errorLog CONSTANT BOOLEAN := l_unexpLog and (FND_LOG.LEVEL_ERROR >= G_LOG_LEVEL);
593    l_eventLog CONSTANT BOOLEAN := l_errorLog and (FND_LOG.LEVEL_EVENT >= G_LOG_LEVEL);
594    l_procLog  CONSTANT BOOLEAN := l_eventLog and (FND_LOG.LEVEL_PROCEDURE >= G_LOG_LEVEL);
595    l_stmtLog  CONSTANT BOOLEAN := l_procLog  and (FND_LOG.LEVEL_STATEMENT >= G_LOG_LEVEL);
596 
597    CURSOR c_sales_order_issues IS
598       SELECT mmt.trx_source_line_id cogs_om_line_id,
599              mmt.distribution_account_id cogs_acct_id,
600              mp.deferred_cogs_account def_cogs_acct_id,
601              mmt.transaction_id mmt_txn_id,
602              mmt.organization_id,
603              mmt.inventory_item_id,
604              mmt.transaction_date,
605              mmt.cost_group_id,
606              (-1*mmt.primary_quantity) quantity
607       FROM mtl_material_transactions mmt,
608            mtl_parameters            mp,
609            mtl_secondary_inventories msi,
610            mtl_system_items_b        item
611           ,cst_acct_info_v           caiv  --BUG#7463298
612       WHERE mmt.transaction_action_id in (1,7)
613       /* do not pick up physical SO issue in a drop shipment flow */
614       AND NVL(mmt.parent_transaction_id, -1) = DECODE(mmt.transaction_action_id,1,-1,mmt.parent_transaction_id)
615       AND mmt.transaction_type_id            IN (33, 30)
616       AND mmt.transaction_source_type_id     = 2
617       AND (mmt.costed_flag     = 'N'         OR  mmt.opm_costed_flag = 'N')
618       AND mmt.COGS_RECOGNITION_PERCENT       IS NULL
619       AND mmt.SO_ISSUE_ACCOUNT_TYPE          = 2 /* deferred COGS */
620       AND mp.organization_id                 = mmt.organization_id
621       --{BUG#7463298
622       AND mp.organization_id                 = caiv.organization_id
623       AND DECODE(g_ledger_id,-1
624                 ,caiv.ledger_id,g_ledger_id) = caiv.ledger_id
625       --}
626       AND mmt.subinventory_code              = msi.secondary_inventory_name (+) /* Logical txn  does not have sub code */
627       AND mmt.organization_id                = msi.organization_id (+)
628       AND NVL(msi.asset_inventory,1)         = 1
629       AND item.inventory_item_id             = mmt.inventory_item_id
630       AND item.organization_id               = mmt.organization_id
631       AND item.inventory_asset_flag          = 'Y';
632 
633    l_so_count               pls_integer := 0;
634 
635 BEGIN
636 
637 -- Standard start of API savepoint
638    SAVEPOINT Insert_SoIssues_PVT;
639 
640    l_stmt_num := 0;
641 
642    IF l_procLog THEN
643      FND_LOG.string(FND_LOG.LEVEL_PROCEDURE,l_module||'.begin',
644         'Entering '||G_PKG_NAME||'.'||l_api_name
645      );
646    END IF;
647 
648 -- Initialize return values
649    x_return_status := FND_API.G_RET_STS_SUCCESS;
650 
651 -- API Body
652 
653    debug('  g_ledger_id : '||g_ledger_id);
654 
655    -- Loop through all sales order issues that have not yet been inserted into the Deferred COGS data model.
656    -- Most of them would have been inserted by the cost processor during the course of normal processing.
657    l_stmt_num := 10;
658    <<all_sales_orders_loop>>
659    FOR cv_so_issues IN c_sales_order_issues LOOP
660 
661       Insert_OneSoIssue(
662                 p_api_version      => 1.0,
663                 p_user_id          => p_user_id,
664                 p_login_id         => p_login_id,
665                 p_request_id       => p_request_id,
666                 p_pgm_app_id       => p_pgm_app_id,
667                 p_pgm_id           => p_pgm_id,
668                 x_return_status    => l_return_status,
669                 p_cogs_om_line_id  => cv_so_issues.cogs_om_line_id,
670                 p_cogs_acct_id     => cv_so_issues.cogs_acct_id,
671                 p_def_cogs_acct_id => cv_so_issues.def_cogs_acct_id,
672                 p_mmt_txn_id       => cv_so_issues.mmt_txn_id,
673                 p_organization_id  => cv_so_issues.organization_id,
674                 p_item_id          => cv_so_issues.inventory_item_id,
675                 p_transaction_date => cv_so_issues.transaction_date,
676                 p_cost_group_id    => cv_so_issues.cost_group_id,
677                 p_quantity         => cv_so_issues.quantity
678       );
679 
680       IF (l_return_status <> FND_API.G_RET_STS_SUCCESS) THEN
681          x_return_status := fnd_api.g_ret_sts_error;
682          FND_MESSAGE.set_name('BOM', 'CST_FAILED_DEFCOGS_SO_INSERT');
683          FND_MESSAGE.set_token('COGS_OM_LINE', to_char(cv_so_issues.cogs_om_line_id));
684          FND_MESSAGE.set_token('MMT_TXN_ID',to_char(cv_so_issues.mmt_txn_id));
685          IF fnd_msg_pub.check_msg_level(fnd_msg_pub.g_msg_lvl_unexp_error) THEN
686             FND_MSG_PUB.ADD;
687          END IF;
688          IF l_errorLog THEN
689             FND_LOG.message(FND_LOG.LEVEL_ERROR, l_module||'.10',TRUE);
690          END IF;
691       ELSE
692          l_so_count := l_so_count + 1;
693       END IF;
694 
695    END LOOP all_sales_orders_loop;
696 
697    IF l_eventLog THEN
698       l_api_message :=  'Inserted '||to_char(l_so_count)||' sales order issues into CCE.';
699       FND_LOG.string(FND_LOG.LEVEL_EVENT, G_LOG_HEAD ||'.'|| l_api_name || '.10', l_api_message);
700    END IF;
701 
702 -- End API Body
703 
704    IF l_proclog THEN
705       fnd_log.string(FND_LOG.LEVEL_PROCEDURE,l_module||'.end',
706         'Exiting '||G_PKG_NAME||'.'||l_api_name||' with '||
707         'x_return_status = '||x_return_status
708       );
709    END IF;
710 
711 EXCEPTION
712 
713    WHEN OTHERS THEN
714          ROLLBACK TO Insert_SoIssues_PVT;
715          x_return_status := fnd_api.g_ret_sts_unexp_error ;
716 
717          IF l_unexpLog THEN
718             FND_LOG.string(FND_LOG.LEVEL_UNEXPECTED,G_LOG_HEAD || '.'||l_api_name||l_stmt_num
719                 ,'Insert_SoIssues ('||to_char(l_stmt_num)||') : '||substr(SQLERRM,1,200));
720          END IF;
721 
722          IF fnd_msg_pub.check_msg_level(fnd_msg_pub.g_msg_lvl_unexp_error) THEN
723             FND_MESSAGE.set_name('BOM', 'CST_UNEXP_ERROR');
724             FND_MESSAGE.set_token('PACKAGE', G_PKG_NAME);
725             FND_MESSAGE.set_token('PROCEDURE',l_api_name);
726             FND_MESSAGE.set_token('STATEMENT',to_char(l_stmt_num));
727             FND_MSG_PUB.ADD;
728          END IF;
729 
730          FND_FILE.put_line(fnd_file.log, 'OTHERS EXCEPTION IN Insert_SoIssues:'||substrb(SQLERRM,1,250) );
731 
732 
733 END Insert_SoIssues;
734 
735 -----------------------------------------------------------------------------
736 -- Start of comments                                                       --
737 --                                                                         --
738 -- PROCEDURE                                                               --
739 --  Insert_RmaReceipts  This procedure handles the insertion of RMA        --
740 --                      receipt transactions in batch into the matching    --
741 --                      data model.  Most RMA receipts will be inserted    --
742 --                      by the Cost Processor.  This bulk procedure will   --
743 --                      pick up the rest.                                  --
744 --                                                                         --
745 -- VERSION 1.0                                                             --
746 --                                                                         --
747 -- PARAMETERS                                                              --
748 --  X_RETURN_STATUS    Success/Error/Unexplained error - 'S','E', or 'U'   --
749 --  WHO columns                                                            --
750 --                                                                         --
751 -- HISTORY:                                                                --
752 --    05/06/05     Bryan Kuntz      Created                                --
753 -- End of comments                                                         --
754 -----------------------------------------------------------------------------
755 
756 PROCEDURE Insert_RmaReceipts(
757                 x_return_status   OUT NOCOPY  VARCHAR2,
758                 p_request_id      IN   NUMBER,
759                 p_user_id         IN   NUMBER,
760                 p_login_id        IN   NUMBER,
761                 p_pgm_app_id      IN   NUMBER,
762                 p_pgm_id          IN   NUMBER
763 ) IS
764 
765    l_api_name            CONSTANT VARCHAR2(30)  := 'Insert_RmaReceipts';
766    l_api_message         VARCHAR2(1000);
767    l_module   CONSTANT VARCHAR2(100)        := G_LOG_HEAD ||'.'||l_api_name;
768    l_unexpLog CONSTANT BOOLEAN := (FND_LOG.LEVEL_UNEXPECTED >= G_LOG_LEVEL) AND FND_LOG.TEST(FND_LOG.LEVEL_UNEXPECTED, l_module);
769    l_errorLog CONSTANT BOOLEAN := l_unexpLog and (FND_LOG.LEVEL_ERROR >= G_LOG_LEVEL);
770    l_eventLog CONSTANT BOOLEAN := l_errorLog and (FND_LOG.LEVEL_EVENT >= G_LOG_LEVEL);
771    l_procLog  CONSTANT BOOLEAN := l_eventLog and (FND_LOG.LEVEL_PROCEDURE >= G_LOG_LEVEL);
772    l_stmtLog  CONSTANT BOOLEAN := l_procLog  and (FND_LOG.LEVEL_STATEMENT >= G_LOG_LEVEL);
773 
774    l_stmt_num            NUMBER         := 0;
775 
776    CURSOR c_rma_receipts IS
777       SELECT /* LEADING(mmt) */
778              mmt.trx_source_line_id    rma_om_line_id,
779              ool.reference_line_id     cogs_om_line_id,
780              mmt.transaction_id        mmt_txn_id,
781              mmt.transaction_date      transaction_date,
782              (-1*mmt.primary_quantity) event_quantity,
783              cce.parent_event_id       prior_event_id,
784              cce.cogs_percentage       cogs_percentage,
785              sum(cce.event_quantity)   prior_event_quantity
786       FROM mtl_material_transactions    mmt,
787            oe_order_lines_all           ool,
788            cst_revenue_cogs_match_lines crcml,
789            cst_cogs_events              cce,
790            mtl_secondary_inventories    msi,
791            mtl_system_items_b           item
792           ,cst_acct_info_v              caiv  --BUG#7463298
793       WHERE mmt.transaction_source_type_id = 12
794       AND mmt.transaction_action_id       in (26,27) -- UT: see if this forces index use, otherwise take it out since repeated below
795       AND (mmt.costed_flag    = 'N'       OR  mmt.opm_costed_flag = 'N')
796       AND mmt.cogs_recognition_percent    IS NULL
797       AND mmt.trx_source_line_id          = ool.line_id -- this line and the next will cause this query to
798       AND ool.reference_line_id           = crcml.cogs_om_line_id -- return rows only if crcml has a row for the orig SO
799       AND ((mmt.transaction_action_id = 27
800             AND mmt.subinventory_code = msi.SECONDARY_INVENTORY_NAME
801             AND mmt.organization_id   = msi.organization_id
802             AND msi.asset_inventory   = 1)   OR   mmt.transaction_action_id  = 26)
803       AND item.inventory_item_id          = mmt.inventory_item_id
804       AND item.organization_id            = mmt.organization_id
805       AND item.inventory_asset_flag       = 'Y'
806       --{BUG#7463298
807       AND mmt.organization_id             = caiv.organization_id
808       AND DECODE(g_ledger_id,-1
809                 ,caiv.ledger_id,g_ledger_id) = caiv.ledger_id
810       --}
811       AND crcml.cogs_om_line_id           = cce.cogs_om_line_id
812       AND cce.event_date                 <= mmt.transaction_date
813       AND NOT EXISTS (SELECT 'X'
814                       FROM cst_cogs_events
815                       WHERE event_date   <= mmt.transaction_date
816                       AND cogs_om_line_id = crcml.cogs_om_line_id
817                       AND prior_event_id  = cce.parent_event_id)
818       GROUP BY cce.parent_event_id   , ool.reference_line_id,
819                mmt.transaction_id    , cce.cogs_percentage,
820                mmt.trx_source_line_id, mmt.organization_id,
821                mmt.inventory_item_id , mmt.transaction_date,
822                mmt.primary_quantity
823       ORDER BY cogs_om_line_id, transaction_date;
824 
825    l_rma_om_line_id_tbl      number_table;
826    l_cogs_om_line_id_tbl     number_table;
827    l_mmt_txn_id_tbl          number_table;
828    l_txn_date_tbl            date_table;
829    l_event_quantity_tbl      number_table;
830    l_prior_event_id_tbl      number_table;
831    l_prior_percent_tbl       number_table;
832    l_prior_event_qty_tbl     number_table;
833 
834    l_parent_event_id_tbl     number_table;
835    l_prior_event_id          NUMBER;
836    l_marker                  number_table;
837 
838    l_rma_count               pls_integer := 0;
839    l_last_fetch              BOOLEAN;
840 
841    -- Inventory's API to insert MMT events returns these 3 parameters
842    l_return_num              NUMBER;
843    l_error_code              VARCHAR2(240);
844    l_error_message           VARCHAR2(2000);
845    program_exception         EXCEPTION;
846 
847    -- The following stores the source code from an OE system parameter.
848    l_source_code             VARCHAR2(40);
849 
850 BEGIN
851    debug('Insert_RmaReceipts+');
852    debug('   g_ledger_id :'||g_ledger_id);
853 
854 -- Standard start of API savepoint
855    SAVEPOINT Insert_RmaReceipts_PVT;
856 
857    l_stmt_num := 0;
858 
859 /*   IF l_procLog THEN
860      FND_LOG.string(FND_LOG.LEVEL_PROCEDURE,l_module||'.begin',
861         'Entering '||G_PKG_NAME||'.'||l_api_name
862      );
863    END IF;
864 */
865 -- Initialize return values
866    x_return_status := FND_API.G_RET_STS_SUCCESS;
867 
868 -- API Body
869 
870    l_last_fetch := FALSE; -- initialize boolean variable
871 
872    OPEN c_rma_receipts;
873 
874    <<all_rma_receipts_loop>>
875    LOOP
876       l_stmt_num := 10;
877 
878       debug(l_stmt_num);
879 
880       FETCH c_rma_receipts BULK COLLECT INTO
881          l_rma_om_line_id_tbl ,
882          l_cogs_om_line_id_tbl,
883          l_mmt_txn_id_tbl     ,
884          l_txn_date_tbl       ,
885          l_event_quantity_tbl ,
886          l_prior_event_id_tbl ,
887          l_prior_percent_tbl  ,
888          l_prior_event_qty_tbl
889       LIMIT C_max_bulk_fetch_size;
890 
891       IF c_rma_receipts%NOTFOUND THEN
892          l_last_fetch := TRUE;
893       END IF;
894 
895       IF (l_cogs_om_line_id_tbl.COUNT = 0 AND l_last_fetch) THEN
896          CLOSE c_rma_receipts;
897          EXIT all_rma_receipts_loop;
898       END IF;
899 
900       /* For each RMA Receipt, insert 2 rows in cce - one goes in
901        * the string of events and the other is the quantity adjustment
902        * to that parent event.
903        */
904 
905       l_stmt_num := 20;
906       debug(l_stmt_num);
907 
908       FOR i IN l_cogs_om_line_id_tbl.FIRST..l_cogs_om_line_id_tbl.LAST LOOP
909          l_marker(i) := 1;
910          IF ( (i > l_cogs_om_line_id_tbl.FIRST) AND
911               (l_prior_event_id_tbl(i) = l_prior_event_id_tbl(i-1)) ) THEN
912             l_prior_event_id := l_parent_event_id_tbl(i-1);
913             l_marker(i-1) := 0;
914          ELSE
915             l_prior_event_id := l_prior_event_id_tbl(i);
916          END IF;
917 
918          -- Insert the RMA marker
919          INSERT INTO cst_cogs_events (
920                   event_id,
921                   cogs_om_line_id,
922                   event_date,
923                   mmt_transaction_id,
924                   cogs_percentage,
925                   prior_cogs_percentage,
926                   prior_event_id,
927                   event_type,
928                   event_om_line_id,
929                   event_quantity,
930                   costed,
931                   parent_event_id,
932                   -- WHO COLUMNS
933                   last_update_date,
934                   last_updated_by,
935                   creation_date,
936                   created_by,
937                   last_update_login,
938                   request_id,
939                   program_application_id,
940                   program_id,
941                   program_update_date)
942          VALUES ( cst_cogs_events_s.nextval,
943                   l_cogs_om_line_id_tbl(i),
944                   l_txn_date_tbl(i),
945                   NULL, -- Quantity placeholder - no MMT transaction
946                   l_prior_percent_tbl(i),
947                   l_prior_percent_tbl(i),
948                   l_prior_event_id,
949                   RMA_RECEIPT_PLACEHOLDER,
950                   l_rma_om_line_id_tbl(i),
951                   l_prior_event_qty_tbl(i),
952                   NULL, -- This event is a quantity placeholder, thus is never costed
953                   cst_cogs_events_s.currval,
954                   -- WHO COLUMNS
955                   sysdate,
956                   p_user_id,
957                   sysdate,
958                   p_user_id,
959                   p_login_id,
960                   p_request_id,
961                   p_pgm_app_id,
962                   p_pgm_id,
963                   sysdate)
964          RETURNING event_id INTO l_parent_event_id_tbl(i);
965       END LOOP;
966 
967       l_stmt_num := 30;
968       debug(l_stmt_num);
969       FORALL i IN l_cogs_om_line_id_tbl.FIRST..l_cogs_om_line_id_tbl.LAST
970          -- Insert the RMA receipts as quantity events (as opposed to % events)
971          INSERT INTO cst_cogs_events (
972                   event_id,
973                   cogs_om_line_id,
974                   event_date,
975                   mmt_transaction_id,
976                   cogs_percentage,
977                   prior_cogs_percentage,
978                   prior_event_id,
979                   event_type,
980                   event_om_line_id,
981                   event_quantity,
982                   costed,
983                   parent_event_id,
984                   -- WHO COLUMNS
985                   last_update_date,
986                   last_updated_by,
987                   creation_date,
988                   created_by,
989                   last_update_login,
990                   request_id,
991                   program_application_id,
992                   program_id,
993                   program_update_date)
994          VALUES ( cst_cogs_events_s.nextval,
995                   l_cogs_om_line_id_tbl(i),
996                   l_txn_date_tbl(i),
997                   l_mmt_txn_id_tbl(i),
998                   l_prior_percent_tbl(i), -- COGS percentage
999                   l_prior_percent_tbl(i), -- prior COGS percentage
1000                   NULL,
1001                   RMA_RECEIPT,
1002                   l_rma_om_line_id_tbl(i),
1003                   l_event_quantity_tbl(i),
1004                   'N',
1005                   l_parent_event_id_tbl(i),
1006                   -- WHO COLUMNS
1007                   sysdate,
1008                   p_user_id,
1009                   sysdate,
1010                   p_user_id,
1011                   p_login_id,
1012                   p_request_id,
1013                   p_pgm_app_id,
1014                   p_pgm_id,
1015                   sysdate);
1016 
1017       l_rma_count := l_rma_count + l_cogs_om_line_id_tbl.COUNT;
1018 
1019       -- Mark the cogs percentage column in the MMT transaction, thus indicating that it has been added
1020       -- to the revenue / COGS matching data model.
1021       l_stmt_num := 40;
1022       debug(l_stmt_num);
1023       FORALL i IN l_cogs_om_line_id_tbl.FIRST..l_cogs_om_line_id_tbl.LAST
1024          UPDATE mtl_material_transactions
1025          SET cogs_recognition_percent = l_prior_percent_tbl(i),
1026              last_update_date = sysdate,
1027              last_updated_by = p_user_id,
1028              last_update_login = p_login_id,
1029              request_id = p_request_id,
1030              program_application_id = p_pgm_app_id,
1031              program_id = p_pgm_id,
1032              program_update_date = sysdate
1033          WHERE transaction_id = l_mmt_txn_id_tbl(i);
1034 
1035 
1036       /* If there are events after this RMA (that is, if it's backdated)
1037        * adjust the quantity for each of these events by either updating
1038        * CCE / MMT directly if the parent is uncosted, or inserting new
1039        * events in CCE and MMT in the case that the parent is costed.
1040        */
1041 
1042       -- First insert this new event into the linked list by setting the prior event ID of the
1043       -- next event to this new one.
1044       l_stmt_num := 50;
1045       debug(l_stmt_num);
1046       FORALL i IN l_cogs_om_line_id_tbl.FIRST..l_cogs_om_line_id_tbl.LAST
1047          UPDATE cst_cogs_events
1048          SET PRIOR_EVENT_ID = l_parent_event_id_tbl(i),
1049              last_update_date = sysdate,
1050              last_updated_by = p_user_id,
1051              last_update_login = p_login_id,
1052              request_id = p_request_id
1053          WHERE cogs_om_line_id = l_cogs_om_line_id_tbl(i)
1054          AND   prior_event_id = l_prior_event_id_tbl(i)
1055          AND   event_date > l_txn_date_tbl(i)
1056          AND   l_marker(i) = 1;
1057 
1058       -- Now create quantity adjustment events for all future COGS Rec events
1059       -- First populate the global temp table with all future events that require
1060       -- quantity adjustment children.
1061       l_stmt_num := 60;
1062       debug(l_stmt_num);
1063       FORALL i IN l_cogs_om_line_id_tbl.FIRST..l_cogs_om_line_id_tbl.LAST
1064          INSERT INTO cst_cogs_qty_adj_events_temp (
1065                         adj_event_id,
1066                         adj_mmt_txn_id,
1067                         adj_cogs_om_line_id,
1068                         adj_rma_om_line_id,
1069                         adj_event_date,
1070                         adj_new_cogs_percentage,
1071                         adj_prior_cogs_percentage,
1072                         adj_event_quantity,
1073                         parent_event_id,
1074                         inventory_item_id,
1075                         primary_uom,
1076                         organization_id,
1077                         cost_group_id,
1078                         cogs_acct_id,
1079                         opm_org_flag,
1080                         acct_period_id
1081                         )
1082          SELECT cst_cogs_events_s.nextval,
1083                 decode(event_type, COGS_RECOGNITION_EVENT, mtl_material_transactions_s.nextval,
1084                                    COGS_REC_PERCENT_ADJUSTMENT, mtl_material_transactions_s.nextval,
1085                                    NULL),
1086                 cce.cogs_om_line_id,
1087                 l_rma_om_line_id_tbl(i),
1088                 cce.event_date,
1089                 cogs_percentage, -- could also use cce.prior_cogs_percentage
1090                 prior_cogs_percentage,
1091                 l_event_quantity_tbl(i),
1092                 event_id,
1093                 crcml.inventory_item_id,
1094                 msi.primary_uom_code,
1095                 crcml.organization_id,
1096                 crcml.cost_group_id,
1097                 crcml.cogs_acct_id,
1098                 nvl(mp.process_enabled_flag,'N'),
1099                 oap.acct_period_id -- acct period ID, I should store this in CCE so I don't keep having to go back to OAP
1100          FROM cst_cogs_events cce,
1101               cst_revenue_cogs_match_lines crcml,
1102               mtl_parameters mp,
1103               org_acct_periods oap,
1104               cst_acct_info_v caiv,
1105               mtl_system_items msi
1106          WHERE cce.cogs_om_line_id = l_cogs_om_line_id_tbl(i)
1107          AND   cce.event_date > l_txn_date_tbl(i)
1108          AND   cce.event_id = cce.parent_event_id
1109          AND   cce.cogs_om_line_id = crcml.cogs_om_line_id
1110          AND   crcml.pac_cost_type_id IS NULL
1111          AND   crcml.organization_id = mp.organization_id
1112          AND   crcml.organization_id = oap.organization_id
1113          AND   crcml.inventory_item_id = msi.inventory_item_id
1114          AND   crcml.organization_id = msi.organization_id
1115          AND   crcml.organization_id = caiv.organization_id
1116          AND   inv_le_timezone_pub.get_le_day_time_for_ou(cce.event_date, caiv.operating_unit)
1117                BETWEEN oap.period_start_date AND oap.schedule_close_date+.99999;
1118 
1119       l_stmt_num := 70;
1120       debug(l_stmt_num);
1121       -- Now insert the quantity adjustment child events
1122       INSERT INTO cst_cogs_events (
1123              event_id,
1124              cogs_om_line_id,
1125              event_date,
1126              mmt_transaction_id,
1127              cogs_percentage,
1128              prior_cogs_percentage,
1129              prior_event_id,
1130              event_type,
1131              event_om_line_id,
1132              event_quantity,
1133              costed,
1134              parent_event_id,
1135              -- WHO COLUMNS
1136              last_update_date,
1137              last_updated_by,
1138              creation_date,
1139              created_by,
1140              last_update_login,
1141              request_id,
1142              program_application_id,
1143              program_id,
1144              program_update_date)
1145       SELECT adj_event_id,
1146              adj_cogs_om_line_id,
1147              adj_event_date,
1148              adj_mmt_txn_id,
1149              adj_new_cogs_percentage,
1150              adj_prior_cogs_percentage,
1151              NULL,
1152              COGS_REC_QTY_ADJUSTMENT,
1153              adj_rma_om_line_id,
1154              adj_event_quantity,
1155              decode(adj_mmt_txn_id, NULL, NULL, 'N'),
1156              parent_event_id,
1157              -- WHO COLUMNS
1158              sysdate,
1159              p_user_id,
1160              sysdate,
1161              p_user_id,
1162              p_login_id,
1163              p_request_id,
1164              p_pgm_app_id,
1165              p_pgm_id,
1166              sysdate
1167       FROM cst_cogs_qty_adj_events_temp;
1168 
1169       -- Get the source code from the OE profile system parameter.
1170       -- It can be overridden by the user but most likely uses the default
1171       -- called 'ORDER ENTRY' and will most likely never change.
1172       l_stmt_num := 80;
1173       debug(l_stmt_num);
1174 
1175       l_source_code := FND_PROFILE.VALUE('ONT_SOURCE_CODE'); -- borrowed from OEXVSCHB.pls
1176       debug('  l_source_code : '||l_source_code);
1177 
1178       l_stmt_num := 90;
1179       debug(l_stmt_num);
1180 
1181       -- Insert their quantity adjustments into MMT
1182       INSERT INTO MTL_COGS_RECOGNITION_TEMP (
1183                      TRANSACTION_ID,
1184                      LAST_UPDATE_DATE,
1185                      LAST_UPDATED_BY,
1186                      CREATION_DATE,
1187                      CREATED_BY,
1188                      INVENTORY_ITEM_ID,
1189                      ORGANIZATION_ID,
1190                      COST_GROUP_ID,
1191                      TRANSACTION_TYPE_ID,
1192                      TRANSACTION_ACTION_ID,
1193                      TRANSACTION_SOURCE_TYPE_ID,
1194                      TRANSACTION_SOURCE_ID,
1195                      TRANSACTION_QUANTITY,
1196                      TRANSACTION_UOM,
1197                      PRIMARY_QUANTITY,
1198                      TRANSACTION_DATE,
1199                      ACCT_PERIOD_ID,
1200                      DISTRIBUTION_ACCOUNT_ID,
1201                      COSTED_FLAG,
1202                      OPM_COSTED_FLAG,
1203                      ACTUAL_COST,
1204                      TRANSACTION_COST,
1205                      PRIOR_COST,
1206                      NEW_COST,
1207                      TRX_SOURCE_LINE_ID,
1208                      RMA_LINE_ID,
1209                      LOGICAL_TRANSACTION,
1210                      COGS_RECOGNITION_PERCENT)
1211       SELECT
1212                      ccqa.adj_mmt_txn_id,
1213                      sysdate,
1214                      p_user_id,
1215                      sysdate,
1216                      p_user_id,
1217                      ccqa.inventory_item_id,
1218                      ccqa.organization_id,
1219                      ccqa.cost_group_id,
1220                      10008,
1221                      36,
1222                      2,
1223                      mso.sales_order_id,
1224                      ccqa.adj_event_quantity,
1225                      ccqa.primary_uom, -- Txn UOM
1226                      ccqa.adj_event_quantity,
1227                      ccqa.adj_event_date,
1228                      ccqa.acct_period_id,
1229                      ccqa.cogs_acct_id,
1230                      decode(ccqa.opm_org_flag, 'N', 'N', NULL),
1231                      decode(ccqa.opm_org_flag, 'Y', 'N', NULL),
1232                      NULL, -- Actual Cost
1233                      NULL, -- Txn Cost
1234                      NULL, -- Prior Cost
1235                      NULL, -- New Cost
1236                      ccqa.adj_cogs_om_line_id,
1237                      ccqa.adj_rma_om_line_id, -- RMA Line ID
1238                      1, -- Logical Txn
1239                      ccqa.adj_new_cogs_percentage
1240       FROM  cst_cogs_qty_adj_events_temp ccqa,
1241             mtl_sales_orders mso,
1242             oe_order_lines_all ool,
1243             oe_order_headers_all ooh,
1244             oe_transaction_types_tl ott
1245       WHERE ool.line_id = ccqa.adj_cogs_om_line_id
1246       AND   ool.header_id = ooh.header_id
1247       AND   TO_CHAR(ooh.order_number) = mso.segment1
1248       AND   ooh.order_type_id = ott.transaction_type_id
1249       AND   ott.name = mso.segment2
1250       AND   ott.language = (SELECT language_code
1251                             FROM   fnd_languages
1252                             WHERE  installed_flag = 'B')
1253       AND   mso.segment3 = l_source_code
1254       AND   ccqa.adj_mmt_txn_id IS NOT NULL;
1255 
1256       -- Now Call Inventory API to populate MMT from the above global temp table
1257       l_stmt_num := 100;
1258       debug(l_stmt_num);
1259 
1260       INV_LOGICAL_TRANSACTIONS_PUB.create_cogs_recognition(x_return_status => l_return_num,
1261                                                            x_error_code    => l_error_code,
1262                                                            x_error_message => l_error_message);
1263 
1264       IF (l_return_num <> 0) THEN
1265          x_return_status := fnd_api.g_ret_sts_error;
1266          FND_MESSAGE.set_name('BOM', 'CST_FAILED_COGSREC_MMT_INSERT');
1267          FND_MESSAGE.set_token('ERROR_CODE', l_error_code);
1268          FND_MESSAGE.set_token('ERROR_MESSAGE',substr(l_error_message,1,500));
1269          IF fnd_msg_pub.check_msg_level(fnd_msg_pub.g_msg_lvl_unexp_error) THEN
1270             FND_MSG_PUB.ADD;
1271          END IF;
1272          IF l_errorLog THEN
1273             FND_LOG.message(FND_LOG.LEVEL_ERROR, l_module||'.'||to_char(l_stmt_num),TRUE);
1274          END IF;
1275          raise program_exception;
1276       END IF;
1277 
1278       l_stmt_num := 90;
1279       debug(l_stmt_num);
1280       commit;  --delete from cst_cogs_qty_adj_events_temp;
1281       SAVEPOINT Insert_RmaReceipts_PVT;
1282 
1283    END LOOP all_rma_receipts_loop;
1284 
1285    IF l_eventLog THEN
1286       l_api_message :=  'Inserted '||to_char(l_rma_count)||' RMA Receipts into CCE.';
1287       FND_LOG.string(FND_LOG.LEVEL_EVENT, G_LOG_HEAD ||'.'|| l_api_name || '.'||l_stmt_num, l_api_message);
1288    END IF;
1289 
1290 -- End API Body
1291 
1292    IF l_proclog THEN
1293       fnd_log.string(FND_LOG.LEVEL_PROCEDURE,l_module||'.end',
1294         'Exiting '||G_PKG_NAME||'.'||l_api_name||' with '||
1295         'x_return_status = '||x_return_status
1296       );
1297    END IF;
1298    debug('   x_return_status = '||x_return_status);
1299    debug('Insert_RmaReceipts-');
1300 EXCEPTION
1301    WHEN program_exception THEN
1302       ROLLBACK TO Insert_RmaReceipts_PVT;
1303       x_return_status := fnd_api.g_ret_sts_error;
1304 
1305    WHEN OTHERS THEN
1306          ROLLBACK TO Insert_RmaReceipts_PVT;
1307          x_return_status := fnd_api.g_ret_sts_unexp_error ;
1308 
1309          IF l_unexpLog THEN
1310             FND_LOG.string(FND_LOG.LEVEL_UNEXPECTED,G_LOG_HEAD || '.'||l_api_name||l_stmt_num
1311                 ,'Insert_RmaReceipts ('||to_char(l_stmt_num)||') : '||substr(SQLERRM,1,200));
1312          END IF;
1313 
1314          IF fnd_msg_pub.check_msg_level(fnd_msg_pub.g_msg_lvl_unexp_error) THEN
1315             FND_MESSAGE.set_name('BOM', 'CST_UNEXP_ERROR');
1316             FND_MESSAGE.set_token('PACKAGE', G_PKG_NAME);
1317             FND_MESSAGE.set_token('PROCEDURE',l_api_name);
1318             FND_MESSAGE.set_token('STATEMENT',to_char(l_stmt_num));
1319             FND_MSG_PUB.ADD;
1320          END IF;
1321          FND_FILE.put_line(fnd_file.log, 'OTHERS EXCEPTION IN Insert_RmaReceipts:'||substrb(SQLERRM,1,250) );
1322 
1323 END Insert_RmaReceipts;
1324 
1325 -----------------------------------------------------------------------------
1326 -- Start of comments                                                       --
1327 --                                                                         --
1328 -- PROCEDURE                                                               --
1329 --  Create_CogsRecognitionEvents                                           --
1330 --       This procedure is the main procedure for phase 3 of the program   --
1331 --       to Match COGS to Revenue. It compares the latest Revenue % with   --
1332 --       the latest COGS percentage and, where different, creates new      --
1333 --       COGS recognition events to bring the COGS percentage up to date.  --
1334 --                                                                         --
1335 -- VERSION 1.0                                                             --
1336 --                                                                         --
1337 -- PARAMETERS                                                              --
1338 --  X_RETURN_STATUS    Success/Error/Unexplained error - 'S','E', or 'U'   --
1339 --  WHO columns                                                            --
1340 --                                                                         --
1341 -- HISTORY:                                                                --
1342 --    04/28/05     Bryan Kuntz      Created                                --
1343 -- End of comments                                                         --
1344 -----------------------------------------------------------------------------
1345 
1346 PROCEDURE Create_CogsRecognitionEvents(
1347                 x_return_status   OUT NOCOPY  VARCHAR2,
1348                 p_request_id      IN   NUMBER,
1349                 p_user_id         IN   NUMBER,
1350                 p_login_id        IN   NUMBER,
1351                 p_pgm_app_id      IN   NUMBER,
1352                 p_pgm_id          IN   NUMBER,
1353                 p_ledger_id       IN   NUMBER DEFAULT NULL --BUG#5726230
1354                ,p_neg_req_id      IN   NUMBER DEFAULT NULL --BUG#7387575
1355 ) IS
1356 
1357    l_api_name            CONSTANT VARCHAR2(30)  := 'Create_CogsRecognitionEvents';
1358    l_api_message         VARCHAR2(1000);
1359    l_return_status       VARCHAR2(1)    := FND_API.G_RET_STS_SUCCESS;
1360    l_stmt_num            NUMBER         := 0;
1361 
1362    l_module   CONSTANT VARCHAR2(100)        := G_LOG_HEAD ||'.'||l_api_name;
1363    l_unexpLog CONSTANT BOOLEAN := (FND_LOG.LEVEL_UNEXPECTED >= G_LOG_LEVEL) AND FND_LOG.TEST(FND_LOG.LEVEL_UNEXPECTED, l_module);
1364    l_errorLog CONSTANT BOOLEAN := l_unexpLog and (FND_LOG.LEVEL_ERROR >= G_LOG_LEVEL);
1365    l_eventLog CONSTANT BOOLEAN := l_errorLog and (FND_LOG.LEVEL_EVENT >= G_LOG_LEVEL);
1366    l_procLog  CONSTANT BOOLEAN := l_eventLog and (FND_LOG.LEVEL_PROCEDURE >= G_LOG_LEVEL);
1367    l_stmtLog  CONSTANT BOOLEAN := l_procLog  and (FND_LOG.LEVEL_STATEMENT >= G_LOG_LEVEL);
1368 
1369    --{BUG#5726230
1370    -- Add cursor for ledger access
1371    CURSOR cu_ledger(p_ledger_id IN NUMBER)
1372    IS
1373    SELECT DISTINCT set_of_books_id
1374      FROM gl_sets_of_books
1375     WHERE set_of_books_id = NVL(p_ledger_id,set_of_books_id);
1376 
1377 
1378    -- CRRL.last_event_date corresponds to the Revenue Recognition date that AR pass to CST.
1379    -- Since AR does not store time component, we can assume that the recognition takes place at the end of the day.
1380    CURSOR c_mismatched_lines(p_sob_id                  NUMBER,
1381                              p_process_acct_period_num NUMBER,
1382                              p_cogs_acct_period_num    NUMBER,
1383                              p_neg_req_id              NUMBER   -- HYU
1384 							 ) IS
1385       SELECT crcml.cogs_om_line_id,
1386              crrl.last_event_date + .99999 + clt.number_1,
1387              crrl.revenue_recognition_percent new_percentage,
1388              cce.cogs_percentage prior_percentage,
1389              cce.parent_event_id prior_event_id,
1390              sum(cce.event_quantity) event_quantity,
1391              crcml.cogs_acct_id,
1392              crcml.inventory_item_id,
1393              msi.primary_uom_code,
1394              crcml.organization_id,
1395              crcml.cost_group_id,
1396              nvl(mp.process_enabled_flag,'N') opm_org,
1397              (select oap.acct_period_id
1398               from org_acct_periods oap
1399               where oap.organization_id = crcml.organization_id
1400               and oap.period_name = gps.period_name) acct_period_id,
1401              clt.number_1 date_offset
1402              --{BUG#6809034 use CCE event_date if mmt trx after rev recog
1403              ,MAX(mmt.transaction_id)                     mmt_transaction_id
1404              ,MAX(mmt.transaction_date) + clt.number_1    mmt_transaction_date
1405              ,MAX(mmt.acct_period_id)                     mmt_period_id
1406              --}
1407       FROM   cst_revenue_cogs_match_lines  crcml,
1408              cst_revenue_recognition_lines crrl,
1409              cst_cogs_events               cce,
1410              mtl_parameters                mp,
1411              gl_period_statuses            gps,
1412              cst_lists_temp                clt,
1413              mtl_system_items              msi
1414              --{BUG#6809034
1415              ,mtl_material_transactions     mmt
1416              --}
1417       WHERE  crrl.ledger_id       = p_sob_id
1418         AND  crrl.acct_period_num = p_process_acct_period_num
1419         AND  crrl.potentially_unmatched_flag = 'Y' -- Indexed column should substantially reduce the rows
1420         --{BUG#7387575
1421         AND  DECODE(p_neg_req_id,NULL,
1422                     NVL(crrl.request_id,-99),p_neg_req_id) = NVL(crrl.request_id,-99)
1423         --}
1424         AND  crrl.revenue_om_line_id = crcml.revenue_om_line_id
1425         AND  crcml.organization_id = mp.organization_id
1426         AND  crcml.organization_id = msi.organization_id
1427         AND  crcml.inventory_item_id = msi.inventory_item_id
1428         AND  crcml.pac_cost_type_id IS NULL
1429         AND  gps.application_id = 101
1430         AND  gps.set_of_books_id = p_sob_id
1431         AND  gps.effective_period_num = p_cogs_acct_period_num
1432         AND  cce.event_date <= gps.end_date +.99999 + clt.number_1
1433         AND  clt.list_id = crcml.organization_id
1434         AND  crcml.cogs_om_line_id = cce.cogs_om_line_id
1435         --{BUG#6809034
1436         AND  cce.mmt_transaction_id          = mmt.transaction_id(+)
1437         --}
1438         AND  NOT EXISTS (select 'X'
1439                          from cst_cogs_events
1440                          where event_date <= gps.end_date + .99999 + clt.number_1
1441                          and cogs_om_line_id = crcml.cogs_om_line_id
1442                          and prior_event_id = cce.parent_event_id)
1443         AND  cce.cogs_percentage <> crrl.revenue_recognition_percent
1444       GROUP BY cce.cogs_percentage,
1445                cce.parent_event_id,
1446                crcml.cogs_om_line_id,
1447                crcml.cogs_acct_id,
1448                crcml.inventory_item_id,
1449                crcml.cost_group_id,
1450                msi.primary_uom_code,
1451                crrl.last_event_date,
1452                crrl.revenue_recognition_percent,
1453                clt.number_1,
1454                crcml.organization_id,
1455                mp.process_enabled_flag,
1456                gps.period_name;
1457 
1458 
1459 
1460 
1461    l_revenue_acct_period_num   NUMBER   := NULL;
1462    l_cogs_acct_period_num      NUMBER   := NULL;
1463    l_gl_period_status          VARCHAR2(1);
1464    l_alternate_event_date      DATE;
1465    l_dummy_date                DATE;
1466    l_period_name               gl_period_statuses.period_name%type;
1467 
1468    l_last_fetch                BOOLEAN;
1469    l_cce_count                 PLS_INTEGER := 0;
1470 
1471    l_new_event_id_tbl            number_table;
1472    l_new_mmt_txn_id_tbl          number_table;
1473    l_cogs_om_line_id_tbl         number_table;
1474    l_event_date_tbl              date_table;
1475    l_date_offset_tbl             number_table;
1476    l_new_percentage_tbl          number_table;
1477    l_prior_percentage_tbl        number_table;
1478    l_prior_event_id_tbl          number_table;
1479    l_event_quantity_tbl          number_table;
1480    l_cogs_acct_id_tbl            number_table;
1481    l_item_id_tbl                 number_table;
1482    l_primary_uom_tbl             char3_table;
1483    l_organization_id_tbl         number_table;
1484    l_cost_group_id_tbl           number_table;
1485    l_opm_org_flg_tbl             flag_table;
1486    l_acct_period_id_tbl          number_table;
1487    l_parent_event_id_tbl         number_table;
1488 
1489    l_adj_mmt_txn_id_tbl          number_table;
1490    l_adj_event_id_tbl            number_table;
1491    l_adj_prior_event_id_tbl      number_table;
1492 
1493    --BUG5726230
1494    l_ledger_id_tab               number_table;
1495 
1496    -- Inventory's API to insert MMT events returns these 3 parameters
1497    l_return_num              NUMBER;
1498    l_error_code              VARCHAR2(240);
1499    l_error_message           VARCHAR2(2000);
1500    program_exception         EXCEPTION;
1501 
1502    -- The following stores the source code from an OE system parameter.
1503    l_source_code             VARCHAR2(40);
1504 
1505 --BUG#6809034
1506    l_mmt_transaction_id          number_table;
1507    l_mmt_transaction_date        date_table;
1508    l_mmt_period_id               number_table;
1509    l_msg_count                   NUMBER;
1510 --}
1511 
1512    --{BUG#7438582
1513    l_gl_adj_flag                 VARCHAR2(1);
1514    --}
1515 
1516    l_sob                         NUMBER;
1517    end_of_program                EXCEPTION; --BUG#5726230
1518 BEGIN
1519   debug('Create_CogsRecognitionEvents+');
1520 
1521 -- Standard start of API savepoint
1522    SAVEPOINT Create_CogsRecEvents_PVT;
1523 
1524    l_stmt_num := 0;
1525 
1526    IF l_procLog THEN
1527      FND_LOG.string(FND_LOG.LEVEL_PROCEDURE,l_module||'.begin',
1528         'Entering '||G_PKG_NAME||'.'||l_api_name
1529      );
1530    END IF;
1531 
1532    debug(' p_ledger_id :'||p_ledger_id);
1533 
1534 -- Initialize return values
1535    x_return_status := FND_API.G_RET_STS_SUCCESS;
1536 
1537 -- API Body
1538 
1539    -- Populate offset for each organization that might be affected
1540 
1541    l_dummy_date := sysdate;
1542 
1543    l_stmt_num := 1;
1544 
1545    DELETE cst_lists_temp;
1546 
1547 
1548    --{BUG#5726230
1549    IF p_ledger_id IS NULL THEN
1550 
1551      --BUG#5726230 Current behaviour across multiple Ledgers
1552      --
1553      INSERT
1554      INTO   cst_lists_temp (
1555               list_id,
1556               number_1
1557             )
1558      SELECT organization_id,
1559             inv_le_timezone_pub.get_server_day_time_for_le(
1560               l_dummy_date,
1561               legal_entity
1562             ) - l_dummy_date
1563      FROM   (  SELECT
1564                DISTINCT caiv.organization_id,
1565                         caiv.legal_entity
1566                FROM     cst_revenue_recognition_lines crrl,
1567                         cst_revenue_cogs_match_lines crcml,
1568                         cst_acct_info_v caiv
1569                WHERE    crrl.potentially_unmatched_flag='Y'
1570                AND      DECODE(p_neg_req_id,NULL,NVL(crrl.request_id,-99),p_neg_req_id) = NVL(crrl.request_id,-99)
1571                          -- BUG#7387575
1572                AND      crcml.revenue_om_line_id = crrl.revenue_om_line_id
1573                AND      crcml.pac_cost_type_id IS NULL
1574                AND      caiv.organization_id = crcml.organization_id
1575            );
1576    ELSE
1577 
1578      --BUG#5726230 Restrict to a single ledger
1579      --
1580      INSERT
1581      INTO   cst_lists_temp (
1582               list_id,
1583               number_1
1584             )
1585      SELECT organization_id,
1586             inv_le_timezone_pub.get_server_day_time_for_le(
1587               l_dummy_date,
1588               legal_entity
1589             ) - l_dummy_date
1590      FROM   (  SELECT
1591                DISTINCT caiv.organization_id,
1592                         caiv.legal_entity
1593                FROM     cst_revenue_recognition_lines crrl,
1594                         cst_revenue_cogs_match_lines crcml,
1595                         cst_acct_info_v caiv
1596                WHERE    crrl.potentially_unmatched_flag='Y'
1597                AND      crcml.revenue_om_line_id       =crrl.revenue_om_line_id
1598                AND      DECODE(p_neg_req_id,NULL,NVL(crrl.request_id,-99),p_neg_req_id) = NVL(crrl.request_id,-99)
1599                         -- BUG#7387575
1600                AND      crcml.pac_cost_type_id         IS NULL
1601                AND      caiv.organization_id           =crcml.organization_id
1602                AND      caiv.ledger_id                 =p_ledger_id
1603            );
1604   END IF;
1605 
1606 
1607    -- For a given revenue line, AR only populates a record in CRRL if there
1608    -- is a revenue event in that period. To assist us in recognizing COGS
1609    -- in periods in which there are no revenue events (hence no CRRL from AR),
1610    -- we will create placeholder records with the revenue recognition percent
1611    -- from the latest period prior to that period.
1612 
1613    -- Insert placeholder CRRL records
1614 
1615 --------------------------
1616 --  This is for the case REV line being inserted in the previous accounting period
1617 --  But not being COGS recognized.
1618 --  We try to recover the missing COGS in the current month
1619 --  This is nice to have but it causes dramatically perofmance issue as the volum of CRRL increases
1620 --  and it is for a user mistake where the simple work around would be to recollect revenue
1621 --  information for the missing period
1622 --------------------------
1623 --  Commented out this SQL for now as it is very expensive
1624 --  Confirm with AR in the bug#7438582
1625 --------------------------
1626 --   l_stmt_num := 4;
1627 --   MERGE
1628 --   INTO   cst_revenue_recognition_lines target_crrl
1629 --   USING  (
1630 --            SELECT crcml.revenue_om_line_id,
1631 --                   gps.effective_period_num,
1632 --                   crrl.revenue_recognition_percent,
1633 --                   TRUNC(MAX(cce.event_date-clt.number_1)) last_event_date,
1634 --                   crrl.operating_unit_id,
1635 --                   crrl.ledger_id,
1636 --                   crrl.inventory_item_id
1637 --            FROM   cst_revenue_cogs_match_lines   crcml,
1638 --                   cst_lists_temp                 clt,
1639 --                   gl_period_statuses             gps,
1640 --                   cst_cogs_events                cce,
1641 --                   cst_revenue_recognition_lines  crrl
1642 --            WHERE  crcml.pac_cost_type_id IS NULL
1643 --            AND    clt.list_id            = crcml.organization_id
1644 --            AND    gps.application_id     = 222
1645 --            AND    gps.set_of_books_id    = crrl.ledger_id
1646                    -- pick the last cogs event in this period
1647 --            AND    cce.cogs_om_line_id    = crcml.cogs_om_line_id
1648 --            AND    DECODE(p_neg_req_id,NULL,NVL(crrl.request_id,-99),p_neg_req_id) = NVL(crrl.request_id,-99) -- HYU
1649 --            AND    cce.event_date
1650 --                   BETWEEN gps.start_date + clt.number_1
1651 --                   AND     gps.end_date   + .99999 + clt.number_1
1652                    -- pick the last rev rec percent prior to this period
1653 --            AND    crrl.revenue_om_line_id = crcml.revenue_om_line_id
1654 --            AND    crrl.last_event_date    = (
1655 --                     SELECT /*+ no_unnest */   MAX(last_event_date)   -- Add hint for bug#6697330
1656 --                       FROM  cst_revenue_recognition_lines
1657 --                      WHERE  revenue_om_line_id = crcml.revenue_om_line_id
1658 --                        AND  last_event_date    < gps.start_date
1659 --                   )
1660 --            GROUP
1661 --            BY     crcml.revenue_om_line_id,
1662 --                   gps.effective_period_num,
1663 --                   crrl.revenue_recognition_percent,
1664 --                   crrl.operating_unit_id,
1665 --                   crrl.ledger_id,
1666 --                   crrl.inventory_item_id
1667 --          ) X
1668 --   ON     (
1669 --                target_crrl.revenue_om_line_id = X.revenue_om_line_id
1670 --            AND target_crrl.acct_period_num    = X.effective_period_num
1671 --          )
1672 --   WHEN MATCHED THEN
1673 --     UPDATE
1674 --     SET    revenue_recognition_percent = X.revenue_recognition_percent,
1675 --            potentially_unmatched_flag  = 'Y',
1676 --            last_update_date            = SYSDATE,
1677 --            last_updated_by             = p_user_id,
1678 --            last_update_login           = p_login_id,
1679 --            request_id                  = p_request_id,
1680 --            program_application_id      = p_pgm_app_id,
1681 --            program_id                  = p_pgm_id,
1682 --            program_update_date         = SYSDATE
1683 --     WHERE  revenue_recognition_percent <> X.revenue_recognition_percent
1684 --     AND    created_by                  <> -7 -- don't update records that AR inserted / updated
1685 --   WHEN NOT MATCHED THEN
1686 --     INSERT (
1687 --              revenue_om_line_id,           acct_period_num,
1688 --              potentially_unmatched_flag,   revenue_recognition_percent,
1689 --              last_event_date,              operating_unit_id,
1690 --              ledger_id,                    inventory_item_id,
1691 --              customer_trx_line_id,         last_update_date,
1692 --              last_updated_by,              creation_date,
1693 --              created_by,                   last_update_login,
1694 --              request_id,                   program_application_id,
1695 --              program_id,                   program_update_date
1696 --            )
1697 --     VALUES (
1698 --              X.revenue_om_line_id,         X.effective_period_num,
1699 --              'Y',                          X.revenue_recognition_percent,
1700 --              X.last_event_date,            X.operating_unit_id,
1701 --              X.ledger_id,                  X.inventory_item_id,
1702 --              NULL,                         SYSDATE,
1703 --              p_user_id,                    SYSDATE,
1704 --              -7, /* mark as placeholder */ p_login_id,
1705 --              p_request_id,                 p_pgm_app_id,
1706 --              p_pgm_id,                     SYSDATE
1707 --            );
1708 ------------------------------------------
1709 
1710    -- Loop through all the ledgers defined in the instance
1711    -- We match Revenue to COGS one ledger at a time because each ledger could have a different
1712    -- calendar, and we need to perform the matching sequentially by period.  Thus we guarantee
1713    -- consistency of period endpoints (calendars) by working with one ledger at a time.
1714    --{BUG#5726230: Needs to restrict the access to Ledger based on p_ledger_id parameter
1715    OPEN cu_ledger(p_ledger_id);
1716    FETCH cu_ledger BULK COLLECT INTO l_ledger_id_tab;
1717    CLOSE cu_ledger;
1718 
1719    IF l_ledger_id_tab.COUNT = 0 THEN
1720       RAISE end_of_program;
1721    END IF;
1722 
1723    <<sob_loop>> -- for each ledger defined in the instance
1724    --FOR l_sob IN (SELECT distinct set_of_books_id
1725    --              FROM gl_sets_of_books) LOOP
1726    FOR i IN l_ledger_id_tab.FIRST .. l_ledger_id_tab.LAST LOOP
1727    --}
1728       l_sob   := l_ledger_id_tab(i);
1729       debug(' processing for the ledger_id :'||l_sob);
1730 
1731       <<acct_period_loop>> -- loop in chronological order for each mismatched period in this ledger
1732       LOOP
1733 
1734          l_stmt_num := 10;
1735          debug(l_stmt_num);
1736          -- For each ledger, find the minimum accounting period where there exists mismatched
1737          -- Revenue and COGS.
1738 
1739          -- BUG#6809034
1740          -- In the case of some AR recognition on Sales Order Issue in JAN-XX and some in FEB-XX
1741          -- and all Sales Order Issue in FEB-XX
1742          -- in CRRL has a mix of accting period and last event in JAN-XX and FEB-XX
1743          -- in CCE event date and CRCML for all Sales Order Issue are in FEB-XX
1744          -- min(crrl.acct_period_num) verifying the condition will be in JAN-XX period
1745          -- but the l_revenue_acct_period_num will be in both FEB-XX and JAN-XX
1746          -- and Sales Order Issue COGS Recognition will be using JAN-XX period but
1747          -- transaction date matching to AR last event date in JAN-XX and FEB-XX
1748          -- and the CRRL acct period will be only FEB-XX
1749        debug('  p_neg_req_id : '||p_neg_req_id);
1750        IF p_neg_req_id IS NULL THEN
1751 
1752          SELECT min(crrl.acct_period_num)
1753          INTO l_revenue_acct_period_num
1754          FROM cst_revenue_recognition_lines crrl,
1755               cst_revenue_cogs_match_lines  crcml,
1756               cst_cogs_events               cce,
1757               cst_lists_temp                clt,
1758               gl_period_statuses            gps
1759               --{
1760             -- , cst_cogs_events               cce2
1761               --}
1762          WHERE crrl.ledger_id                =  l_sob  --l_sob.set_of_books_id
1763          AND crrl.potentially_unmatched_flag = 'Y'
1764          AND crrl.revenue_om_line_id         = crcml.revenue_om_line_id
1765          AND crcml.cogs_om_line_id           = cce.cogs_om_line_id
1766          --{
1767          --If Revenue recognition before shiping use shiping date as it is the DCOGS date
1768          AND crrl.last_event_date BETWEEN gps.start_date AND gps.end_date + .99999
1769        --  AND crcml.cogs_om_line_id           = cce2.cogs_om_line_id
1770        --  AND cce2.event_type                 = 1  -- Sales Order Issue
1771        --  AND DECODE(SIGN(crrl.last_event_date - cce2.event_date), 1,
1772        --             crrl.last_event_date,                 -- Rev After Shiping use Revenue date
1773        --             cce2.event_date) BETWEEN gps.start_date AND gps.end_date + .99999
1774          --}
1775          AND gps.application_id              = 222
1776          AND gps.set_of_books_id             = l_sob  --l_sob.set_of_books_id
1777          AND cce.event_date                 <= gps.end_date + .99999 + clt.number_1
1778          AND clt.list_id                     = crcml.organization_id
1779          AND NOT EXISTS (select 'X'
1780                            from cst_cogs_events
1781                           where event_date     <= gps.end_date + .99999 + clt.number_1
1782                             and cogs_om_line_id = crcml.cogs_om_line_id
1783                             and prior_event_id  = cce.parent_event_id)
1784          AND cce.cogs_percentage <> (
1785                SELECT SUM(revenue_recognition_percent)
1786                  FROM cst_revenue_recognition_lines
1787                 WHERE revenue_om_line_id = crrl.revenue_om_line_id
1788                   AND last_event_date   <= crrl.last_event_date
1789              )
1790          AND crcml.pac_cost_type_id IS NULL;
1791 
1792        ELSE
1793 
1794          SELECT min(crrl.acct_period_num)
1795          INTO l_revenue_acct_period_num
1796          FROM cst_revenue_recognition_lines crrl,
1797               cst_revenue_cogs_match_lines  crcml,
1798               cst_cogs_events               cce,
1799               cst_lists_temp                clt,
1800               gl_period_statuses            gps
1801          WHERE crrl.ledger_id                =  l_sob  --l_sob.set_of_books_id
1802          AND crrl.potentially_unmatched_flag = 'Y'
1803          AND crrl.request_id                 = p_neg_req_id  --BUG#7387575
1804          AND crrl.revenue_om_line_id         = crcml.revenue_om_line_id
1805          AND crcml.cogs_om_line_id           = cce.cogs_om_line_id
1806          AND crrl.last_event_date BETWEEN gps.start_date AND gps.end_date + .99999
1807          AND gps.application_id              = 222
1808          AND gps.set_of_books_id             = l_sob  --l_sob.set_of_books_id
1809          AND cce.event_date                 <= gps.end_date + .99999 + clt.number_1
1810          AND clt.list_id                     = crcml.organization_id
1811          AND NOT EXISTS (select 'X'
1812                            from cst_cogs_events
1813                           where event_date     <= gps.end_date + .99999 + clt.number_1
1814                             and cogs_om_line_id = crcml.cogs_om_line_id
1815                             and prior_event_id  = cce.parent_event_id)
1816          AND cce.cogs_percentage <> (
1817                SELECT SUM(revenue_recognition_percent)
1818                  FROM cst_revenue_recognition_lines
1819                 WHERE revenue_om_line_id = crrl.revenue_om_line_id
1820                   AND last_event_date   <= crrl.last_event_date
1821              )
1822          AND crcml.pac_cost_type_id IS NULL;
1823 
1824      END IF;
1825 
1826 
1827          EXIT acct_period_loop WHEN l_revenue_acct_period_num IS NULL;
1828 
1829          IF l_stmtLog THEN
1830             FND_LOG.string(FND_LOG.LEVEL_STATEMENT, l_module||'.10',
1831 --                 'Ledger ID.Min Acct Per Num = '||to_char(l_sob.set_of_books_id)||'.'||to_char(l_revenue_acct_period_num));
1832                  'Ledger ID.Min Acct Per Num = '||l_sob||'.'||l_revenue_acct_period_num);
1833          END IF;
1834 
1835          l_stmt_num := 20;
1836       debug(l_stmt_num);
1837 
1838          -- Check the GL period.  If it is closed, create these events in the next open period
1839          -- BUG#9809034
1840          -- Now suppose JAN-XX is still opened
1841          SELECT closing_status,
1842 	        period_name,
1843                 adjustment_period_flag     --BUG7438582 UTSTAR
1844            INTO l_gl_period_status,
1845                 l_period_name,
1846                 l_gl_adj_flag              --BUG7438582 UTSTAR
1847            FROM gl_period_statuses
1848          WHERE application_id       = 101
1849            AND ledger_id            = l_sob   --l_sob.set_of_books_id
1850            AND effective_period_num = l_revenue_acct_period_num;
1851 
1852          --
1853          -- If the GL period is closed, need to get the next open period
1854          -- BUG7438582  UTSTAR.COM
1855          -- Allow Cogs Reco in Futur not adjustment periods
1856          --
1857          IF (      l_gl_period_status <> 'O'
1858              AND  (l_gl_period_status <> 'F' OR l_gl_adj_flag <> 'N')
1859             )
1860          THEN
1861 
1862             l_stmt_num := 30;
1863             debug(l_stmt_num);
1864             SELECT min(effective_period_num)
1865               INTO l_cogs_acct_period_num
1866               FROM gl_period_statuses
1867              WHERE application_id       = 101
1868                AND ledger_id            = l_sob   --l_sob.set_of_books_id
1869                AND effective_period_num > l_revenue_acct_period_num
1870                AND (closing_status       = 'O'
1871                --{BUG#7438582 UTSTAR - Allow Cogs Reco in Futur not adjustment periods
1872                      OR (closing_status = 'F' AND adjustment_period_flag = 'N')
1873                    );
1874                --}
1875             -- Use the start date of the next open period as the event date
1876             -- for all these new COGS Rec events.
1877             l_stmt_num := 40;
1878             BEGIN
1879                l_stmt_num := 40;
1880                debug(l_stmt_num);
1881                SELECT start_date
1882                  INTO l_alternate_event_date
1883                  FROM  gl_period_statuses
1884                 WHERE application_id       = 101
1885                   AND ledger_id            = l_sob  --l_sob.set_of_books_id
1886                   AND effective_period_num = l_cogs_acct_period_num;
1887             EXCEPTION
1888                WHEN NO_DATA_FOUND THEN
1889                   IF fnd_msg_pub.check_msg_level(fnd_msg_pub.g_msg_lvl_error) THEN
1890                      FND_MESSAGE.set_name('BOM', 'CST_NO_OPEN_GL_PERIOD');
1891                      FND_MESSAGE.set_token('LEDGER', l_sob); -- to_char(l_sob.set_of_books_id)
1892                      FND_MESSAGE.set_token('PERIOD_NAME',l_period_name);
1893                      FND_MSG_PUB.ADD;
1894                      IF l_errorLog THEN
1895                         FND_LOG.MESSAGE(FND_LOG.LEVEL_ERROR,l_module||'.'||l_stmt_num,TRUE);
1896                      END IF;
1897                   END IF;
1898                   raise no_data_found;
1899             END;
1900 
1901          ELSE
1902             -- The period is open, so COGS and Revenue will be matched in this period
1903             -- and we can use the AR date as the event date (instead of alternate event date).
1904             --BUG#6809034
1905             -- If JAN-XX is still opened this is portion all code executed
1906             --
1907             l_cogs_acct_period_num := l_revenue_acct_period_num;
1908             l_alternate_event_date := NULL;
1909 
1910 
1911          END IF;
1912 
1913          l_last_fetch := FALSE; -- initialize boolean variable
1914 
1915 
1916 --         OPEN c_mismatched_lines(l_sob.set_of_books_id, l_revenue_acct_period_num, l_cogs_acct_period_num);
1917          OPEN c_mismatched_lines(l_sob,
1918 	                         l_revenue_acct_period_num,
1919                                  l_cogs_acct_period_num,
1920                                  p_neg_req_id   --BUG#7387575
1921 								 );
1922          <<mismatched_lines_loop>>
1923          LOOP
1924                l_stmt_num := 50;
1925                debug(l_stmt_num);
1926 
1927                -- Fetch 1000 mismatched COGS and Revenue records for processing
1928                FETCH c_mismatched_lines BULK COLLECT INTO
1929                   l_cogs_om_line_id_tbl,
1930                   l_event_date_tbl,
1931                   l_new_percentage_tbl,
1932                   l_prior_percentage_tbl,
1933                   l_prior_event_id_tbl,
1934                   l_event_quantity_tbl,
1935                   l_cogs_acct_id_tbl,
1936                   l_item_id_tbl,
1937                   l_primary_uom_tbl,
1938                   l_organization_id_tbl,
1939                   l_cost_group_id_tbl,
1940                   l_opm_org_flg_tbl,
1941                   l_acct_period_id_tbl,
1942                   l_date_offset_tbl ,
1943              --{BUG#6809034
1944                   l_mmt_transaction_id,
1945                   l_mmt_transaction_date,
1946                   l_mmt_period_id
1947              --}
1948                LIMIT C_max_bulk_fetch_size;
1949 
1950                IF c_mismatched_lines%NOTFOUND THEN
1951                   l_last_fetch := TRUE;
1952                END IF;
1953 
1954                IF (l_cogs_om_line_id_tbl.COUNT = 0 AND l_last_fetch) THEN
1955                   CLOSE c_mismatched_lines;
1956                   EXIT mismatched_lines_loop;
1957                END IF;
1958 
1959                l_stmt_num := 60;
1960                debug(l_stmt_num);
1961                -- create COGS events in cst_cogs_events
1962                FORALL i IN l_cogs_om_line_id_tbl.FIRST..l_cogs_om_line_id_tbl.LAST
1963                   INSERT INTO cst_cogs_events (
1964                      event_id,
1965                      cogs_om_line_id,
1966                      event_date,
1967                      mmt_transaction_id,
1968                      cogs_percentage,
1969                      prior_cogs_percentage,
1970                      prior_event_id,
1971                      event_type,
1972                      event_om_line_id,
1973                      event_quantity,
1974                      costed,
1975                      parent_event_id,
1976                      -- WHO COLUMNS
1977                      last_update_date,
1978                      last_updated_by,
1979                      creation_date,
1980                      created_by,
1981                      last_update_login,
1982                      request_id,
1983                      program_application_id,
1984                      program_id,
1985                      program_update_date)
1986                   VALUES(
1987                      cst_cogs_events_s.nextval,
1988                      l_cogs_om_line_id_tbl(i),
1989                      --BUG#6809034 -- As JAN-XX is opened the transaction_date is AR recognition event date
1990                      --But as the bug is only on the material transaction, this COGS event event_date remains
1991                      --untouch to avoid breaking the current logic based on the CCE,CRCML,CRRL for CCE creation
1992                      --If the problem is hitting the accounting unproper such as to much COGS recognized or not enough
1993                      --this can be the starting point
1994                      nvl(l_alternate_event_date+.99999+l_date_offset_tbl(i),l_event_date_tbl(i)),
1995                      mtl_material_transactions_s.nextval,
1996                      l_new_percentage_tbl(i),
1997                      l_prior_percentage_tbl(i),
1998                      l_prior_event_id_tbl(i),
1999                      COGS_RECOGNITION_EVENT,
2000                      NULL, -- event OM line ID
2001                      l_event_quantity_tbl(i),
2002                      'N',
2003                      cst_cogs_events_s.currval,
2004                      -- WHO COLUMNS
2005                      sysdate,
2006                      p_user_id,
2007                      sysdate,
2008                      p_user_id,
2009                      p_login_id,
2010                      p_request_id,
2011                      p_pgm_app_id,
2012                      p_pgm_id,
2013                      sysdate
2014                   )
2015                   RETURNING event_id, mmt_transaction_id
2016                   BULK COLLECT INTO l_new_event_id_tbl, l_new_mmt_txn_id_tbl;
2017 
2018                l_cce_count := l_cce_count + l_new_event_id_tbl.COUNT;
2019                debug('  l_cce_count  : '||l_cce_count);
2020                l_stmt_num := 70;
2021                debug(l_stmt_num);
2022                -- Insert MMT transactions into the global temp table
2023                FORALL i IN l_new_mmt_txn_id_tbl.FIRST .. l_new_mmt_txn_id_tbl.LAST
2024                   INSERT INTO mtl_cogs_recognition_temp (
2025                      TRANSACTION_ID,
2026                      LAST_UPDATE_DATE,
2027                      LAST_UPDATED_BY,
2028                      CREATION_DATE,
2029                      CREATED_BY,
2030                      INVENTORY_ITEM_ID,
2031                      ORGANIZATION_ID,
2032                      COST_GROUP_ID,
2033                      TRANSACTION_TYPE_ID,
2034                      TRANSACTION_ACTION_ID,
2035                      TRANSACTION_SOURCE_TYPE_ID,
2036                      TRANSACTION_QUANTITY,
2037                      TRANSACTION_UOM,
2038                      PRIMARY_QUANTITY,
2039                      TRANSACTION_DATE,
2040                      ACCT_PERIOD_ID,
2041                      DISTRIBUTION_ACCOUNT_ID,
2042                      COSTED_FLAG,
2043                      OPM_COSTED_FLAG,
2044                      ACTUAL_COST,
2045                      TRANSACTION_COST,
2046                      PRIOR_COST,
2047                      NEW_COST,
2048                      TRX_SOURCE_LINE_ID,
2049                      RMA_LINE_ID,
2050                      LOGICAL_TRANSACTION,
2051                      COGS_RECOGNITION_PERCENT,
2052                      transaction_set_id      -- BUG#7387575
2053 					 )
2054                   VALUES (
2055                      l_new_mmt_txn_id_tbl(i),
2056                      sysdate,
2057                      p_user_id,
2058                      sysdate,
2059                      p_user_id,
2060                      l_item_id_tbl(i),
2061                      l_organization_id_tbl(i),
2062                      l_cost_group_id_tbl(i),
2063                      10008,
2064                      36,
2065                      2,
2066                      l_event_quantity_tbl(i),
2067                      l_primary_uom_tbl(i), -- Txn UOM
2068                      l_event_quantity_tbl(i),
2069                 --BUG#6809034
2070                      --nvl(l_alternate_event_date+.99999+l_date_offset_tbl(i),l_event_date_tbl(i)),
2071                      -- In the scenario JAN-XX is still opened
2072 					 -- the l_alternate_event_date is NULL hence the AR last event date will be used
2073                      -- but the c_mismatched_lines the acct period id will be dictated by CRCML
2074                      -- and it will be for the month of FEB as all Sales Order Issue are created in FEB-XX
2075                      -- creating COGS event date can be out of synch with MMT
2076                      -- Plus in the Case of GSI the Rev Rec can be done without Sales Order Issue
2077                      -- We need to make sure not to recognition COGS before DCOGS is being hit
2078                      DECODE(l_mmt_transaction_date(i), NULL,
2079                            NVL(l_alternate_event_date+.99999+l_date_offset_tbl(i),l_event_date_tbl(i)),
2080                            DECODE(SIGN(l_mmt_transaction_date(i) - l_event_date_tbl(i)), -1, --Sales Order Issue before RR
2081                                   NVL(l_alternate_event_date+.99999+l_date_offset_tbl(i),l_event_date_tbl(i)), --Use AR event
2082                                   l_mmt_transaction_date(i))),-- Use SO DCOGS transaction date
2083                 --}
2084                 --{BUG#6809034
2085                      -- In order to be consitent with the approach, the acct_period_id has to follow the same path
2086                      --l_acct_period_id_tbl(i),
2087                     DECODE(l_mmt_period_id(i), NULL,
2088                            l_acct_period_id_tbl(i),
2089                            DECODE(SIGN(l_mmt_transaction_date(i) - l_event_date_tbl(i)), -1, --Sales Order Issue before RR
2090                                   l_acct_period_id_tbl(i),
2091                                   l_mmt_period_id(i))),
2092                 --}
2093                      l_cogs_acct_id_tbl(i),
2094                      decode(l_opm_org_flg_tbl(i), 'N', 'N', NULL),
2095                      decode(l_opm_org_flg_tbl(i), 'Y', 'N', NULL),
2096                      NULL, -- Actual Cost
2097                      NULL, -- Txn Cost
2098                      NULL, -- Prior Cost
2099                      NULL, -- New Cost
2100                      l_cogs_om_line_id_tbl(i),
2101                      NULL, -- RMA Line ID
2102                      1, -- Logical Txn
2103                      l_new_percentage_tbl(i)
2104                     ,p_neg_req_id              --BUG#7387575
2105 					 );
2106 
2107                -- Don't call Inventory's API to create MMT transactions from these temporary events
2108                -- until after the next insertion into the global temp table (below).
2109 
2110                -- Adjustment Processing
2111                -- First adjust all future events by simply updating those directly that have not been costed yet
2112                l_stmt_num := 80;
2113                debug(l_stmt_num);
2114                FORALL i IN l_cogs_om_line_id_tbl.FIRST..l_cogs_om_line_id_tbl.LAST
2115                   UPDATE cst_cogs_events
2116                   SET PRIOR_COGS_PERCENTAGE = l_new_percentage_tbl(i),
2117                       PRIOR_EVENT_ID        = l_new_event_id_tbl(i),
2118                       last_update_date      = sysdate,
2119                       last_updated_by       = p_user_id,
2120                       last_update_login     = p_login_id,
2121                       request_id            = p_request_id
2122                   WHERE cogs_om_line_id      = l_cogs_om_line_id_tbl(i)
2123                   AND   prior_event_id       = l_prior_event_id_tbl(i)
2124                   AND   event_id            <> l_new_event_id_tbl(i)
2125                   AND   l_opm_org_flg_tbl(i) = 'N'
2126                   AND   costed               = 'N';
2127 
2128                -- Otherwise, for future events that are not directly updatable, insert adjustment events
2129                -- between the newly created events (above) and the future events.
2130                -- It is necessary to first insert these events into a global temp table because a placeholder
2131                -- is required for the update statement below (stmt 170).
2132                -- This portion is for Revenue Recognition adjustment activity for the bug#6809034 remain untouched
2133                l_stmt_num := 90;
2134                debug(l_stmt_num);
2135                FORALL i IN l_cogs_om_line_id_tbl.FIRST..l_cogs_om_line_id_tbl.LAST
2136                   INSERT INTO cst_cogs_pct_adj_events_temp (
2137                                    adj_event_id,
2138                                    adj_mmt_txn_id,
2139                                    adj_cogs_om_line_id,
2140                                    adj_event_date,
2141                                    adj_new_cogs_percentage,
2142                                    adj_prior_cogs_percentage,
2143                                    adj_prior_event_id,
2144                                    adj_event_quantity,
2145                                    ftr_event_id,
2146                                    inventory_item_id,
2147                                    primary_uom,
2148                                    organization_id,
2149                                    cost_group_id,
2150                                    cogs_acct_id,
2151                                    opm_org_flag,
2152                                    acct_period_id
2153                                    )
2154                   SELECT cst_cogs_events_s.nextval,
2155                          mtl_material_transactions_s.nextval,
2156                          cogs_om_line_id,
2157                          event_date,
2158                          l_prior_percentage_tbl(i), -- could also use cce.prior_cogs_percentage
2159                          l_new_percentage_tbl(i),
2160                          l_new_event_id_tbl(i),
2161                          event_quantity,
2162                          event_id,
2163                          l_item_id_tbl(i),
2164                          l_primary_uom_tbl(i),
2165                          l_organization_id_tbl(i),
2166                          l_cost_group_id_tbl(i),
2167                          l_cogs_acct_id_tbl(i),
2168                          l_opm_org_flg_tbl(i),
2169                          oap.acct_period_id
2170                   FROM cst_cogs_events cce,
2171                        org_acct_periods oap
2172                   WHERE cogs_om_line_id =  l_cogs_om_line_id_tbl(i)
2173                   AND   prior_event_id  =  l_prior_event_id_tbl(i)
2174                   AND   event_id        <> l_new_event_id_tbl(i)
2175                   AND   cce.event_date
2176                         BETWEEN oap.period_start_date + l_date_offset_tbl(i)
2177                             AND oap.schedule_close_date + .99999 + l_date_offset_tbl(i)
2178                   AND   oap.organization_id = l_organization_id_tbl(i);
2179 
2180                -- Now load the events into CCE from the temp table
2181                l_stmt_num := 100;
2182                debug(l_stmt_num);
2183                INSERT INTO cst_cogs_events (
2184                      event_id,
2185                      cogs_om_line_id,
2186                      event_date,
2187                      mmt_transaction_id,
2188                      cogs_percentage,
2189                      prior_cogs_percentage,
2190                      prior_event_id,
2191                      event_type,
2192                      event_om_line_id,
2193                      event_quantity,
2194                      costed,
2195                      parent_event_id,
2196                      -- WHO COLUMNS
2197                      last_update_date,
2198                      last_updated_by,
2199                      creation_date,
2200                      created_by,
2201                      last_update_login,
2202                      request_id,
2203                      program_application_id,
2204                      program_id,
2205                      program_update_date)
2206                SELECT adj_event_id,
2207                       adj_cogs_om_line_id,
2208                       adj_event_date,
2209                       adj_mmt_txn_id,
2210                       adj_new_cogs_percentage,
2211                       adj_prior_cogs_percentage,
2212                       adj_prior_event_id,
2213                       COGS_REC_PERCENT_ADJUSTMENT,
2214                       NULL,
2215                       adj_event_quantity,
2216                       'N',
2217                       adj_event_id,
2218                       -- WHO COLUMNS
2219                       sysdate,
2220                       p_user_id,
2221                       sysdate,
2222                       p_user_id,
2223                       p_login_id,
2224                       p_request_id,
2225                       p_pgm_app_id,
2226                       p_pgm_id,
2227                       sysdate
2228                FROM cst_cogs_pct_adj_events_temp;
2229 
2230                l_cce_count := l_cce_count + SQL%ROWCOUNT;
2231                debug('   l_cce_count : '|| l_cce_count);
2232                l_stmt_num := 110;
2233                debug(l_stmt_num);
2234                -- Now create these events in Inventory's table
2235                -- Use the Inventory Temp Table for new MMT txns
2236                INSERT INTO MTL_COGS_RECOGNITION_TEMP (
2237                      TRANSACTION_ID,
2238                      LAST_UPDATE_DATE,
2239                      LAST_UPDATED_BY,
2240                      CREATION_DATE,
2241                      CREATED_BY,
2242                      INVENTORY_ITEM_ID,
2243                      ORGANIZATION_ID,
2244                      COST_GROUP_ID,
2245                      TRANSACTION_TYPE_ID,
2246                      TRANSACTION_ACTION_ID,
2247                      TRANSACTION_SOURCE_TYPE_ID,
2248                      TRANSACTION_QUANTITY,
2249                      TRANSACTION_UOM,
2250                      PRIMARY_QUANTITY,
2251                      TRANSACTION_DATE,
2252                      ACCT_PERIOD_ID,
2253                      DISTRIBUTION_ACCOUNT_ID,
2254                      COSTED_FLAG,
2255                      OPM_COSTED_FLAG,
2256                      ACTUAL_COST,
2257                      TRANSACTION_COST,
2258                      PRIOR_COST,
2259                      NEW_COST,
2260                      TRX_SOURCE_LINE_ID,
2261                      LOGICAL_TRANSACTION,
2262                      COGS_RECOGNITION_PERCENT
2263                     ,transaction_set_id      --BUG#7387575
2264 					 )
2265                SELECT
2266                      adj_mmt_txn_id,
2267                      sysdate,
2268                      p_user_id,
2269                      sysdate,
2270                      p_user_id,
2271                      inventory_item_id,
2272                      organization_id,
2273                      cost_group_id,
2274                      10008,
2275                      36,
2276                      2,
2277                      adj_event_quantity,
2278                      primary_uom, -- Txn UOM
2279                      adj_event_quantity,
2280                      adj_event_date,
2281                      acct_period_id,
2282                      cogs_acct_id,
2283                      decode(opm_org_flag, 'N', 'N', NULL),
2284                      decode(opm_org_flag, 'Y', 'N', NULL),
2285                      NULL, -- Actual Cost
2286                      NULL, -- Txn Cost
2287                      NULL, -- Prior Cost
2288                      NULL, -- New Cost
2289                      adj_cogs_om_line_id,
2290                      1, -- Logical Txn
2291                      adj_new_cogs_percentage
2292                     ,p_neg_req_id                 --BUG#7387575
2293                FROM cst_cogs_pct_adj_events_temp;
2294 
2295                -- Next update MTL_COGS_RECOGNITION_TEMP to populate transaction_source_id with the
2296                -- sales_order_id from mtl_sales_orders.
2297 
2298                -- Get the source code from the OE profile system parameter.
2299                -- It can be overridden by the user but most likely uses the default
2300                -- called 'ORDER ENTRY' and will most likely never change.
2301                l_stmt_num := 145;
2302                debug(l_stmt_num);
2303 
2304                l_source_code := FND_PROFILE.VALUE('ONT_SOURCE_CODE'); -- borrowed from OEXVSCHB.pls
2305                debug('  l_source_code : '||l_source_code);
2306 
2307                l_stmt_num := 150;
2308                debug(l_stmt_num);
2309 
2310                UPDATE mtl_cogs_recognition_temp mcr
2311                SET (transaction_source_id) = (
2312                   SELECT mkts.sales_order_id
2313                   FROM mtl_sales_orders mkts,
2314                        oe_order_lines_all ool,
2315                        oe_order_headers_all ooh,
2316                        oe_transaction_types_tl ott
2317                   WHERE ool.line_id               = mcr.trx_source_line_id
2318                   AND   ool.header_id             = ooh.header_id
2319                   AND   to_char(ooh.order_number) = mkts.segment1
2320                   AND   ooh.order_type_id         = ott.transaction_type_id
2321                   AND   ott.name                  = mkts.segment2
2322                   AND   ott.language = (select language_code
2323                                           from fnd_languages
2324                                          where installed_flag = 'B')
2325                   AND   mkts.segment3             = l_source_code);
2326 
2327 
2328 
2329                --{BUG#6809034
2330                --All the effort has been put in the MMT transaction date, we now ensure the synchronization between
2331                -- transaction_date and acct_period_id before the call to INV transactions
2332                l_stmt_num := 155;
2333                debug(l_stmt_num);
2334 
2335                ensure_mmt_per_and_date(x_return_status   => l_return_status,
2336                                        x_msg_count       => l_msg_count,
2337                                        x_msg_data        => l_error_message);
2338 
2339                IF l_return_status <> fnd_api.g_ret_sts_success THEN
2340                   debug(FND_LOG.LEVEL_ERROR, l_module||'.'||to_char(l_stmt_num));
2341                   raise program_exception;
2342                END IF;
2343                --}
2344 
2345 
2346                -- Now insert into MMT by calling INV API
2347                l_stmt_num := 160;
2348                debug(l_stmt_num);
2349 
2350                INV_LOGICAL_TRANSACTIONS_PUB.create_cogs_recognition(x_return_status => l_return_num,
2351                                                                     x_error_code    => l_error_code,
2352                                                                     x_error_message => l_error_message);
2353 
2354                IF (l_return_num <> 0) THEN
2355                   x_return_status := fnd_api.g_ret_sts_error;
2356                   FND_MESSAGE.set_name('BOM', 'CST_FAILED_COGSREC_MMT_INSERT');
2357                   FND_MESSAGE.set_token('ERROR_CODE', l_error_code);
2358                   FND_MESSAGE.set_token('ERROR_MESSAGE',substr(l_error_message,1,500));
2359                   IF fnd_msg_pub.check_msg_level(fnd_msg_pub.g_msg_lvl_unexp_error) THEN
2360                      FND_MSG_PUB.ADD;
2361                   END IF;
2362                   IF l_errorLog THEN
2363                      FND_LOG.message(FND_LOG.LEVEL_ERROR, l_module||'.'||to_char(l_stmt_num),TRUE);
2364                   END IF;
2365                   raise program_exception;
2366                END IF;
2367 
2368                -- Update the prior event ID in the future event in CCE using the temp table CCPAET
2369                l_stmt_num := 170;
2370                debug(l_stmt_num);
2371 
2372                UPDATE (
2373                   SELECT cce.prior_event_id,
2374                          cba.adj_event_id
2375                     FROM cst_cogs_events              cce,
2376                          cst_cogs_pct_adj_events_temp cba
2377                    WHERE cce.event_id = cba.ftr_event_id)
2378                SET prior_event_id = adj_event_id;
2379 
2380                l_stmt_num := 180;
2381                debug(l_stmt_num);
2382 
2383                COMMIT;  --also deletes from cst_cogs_pct_adj_events_temp;
2384                SAVEPOINT Create_CogsRecEvents_PVT;
2385 
2386          END LOOP mismatched_lines_loop; -- c_mismatched_lines bulk fetches
2387 
2388          IF l_stmtLog THEN
2389             FND_LOG.string(FND_LOG.LEVEL_STATEMENT, l_module||'.100',
2390                  'Ledger.PerNum.InsertedEvents = '||l_sob||'.'||     --to_char(l_sob.set_of_books_id)||'.'||
2391                   l_cogs_acct_period_num||'.'||l_cce_count);
2392          END IF;
2393 
2394          -- Now update the mismatched revenue lines in CRRL in case a future SOB/period iteration fails
2395          l_stmt_num := 190;
2396          debug(l_stmt_num);
2397 
2398          IF p_neg_req_id IS NULL THEN
2399             UPDATE cst_revenue_recognition_lines crrl
2400             SET potentially_unmatched_flag = NULL,
2401                 last_update_date           = sysdate,
2402                 last_updated_by            = p_user_id,
2403                 last_update_login          = p_login_id,
2404                 request_id                 = p_request_id,
2405                 program_application_id     = p_pgm_app_id,
2406                 program_id                 = p_pgm_id,
2407                 program_update_date        = sysdate
2408           WHERE potentially_unmatched_flag = 'Y'
2409             AND ledger_id                  = l_sob   -- l_sob.set_of_books_id
2410             AND acct_period_num            = l_revenue_acct_period_num;
2411 
2412         ELSE
2413 
2414             UPDATE cst_revenue_recognition_lines crrl
2415             SET potentially_unmatched_flag = NULL,
2416                 last_update_date           = sysdate,
2417                 last_updated_by            = p_user_id,
2418                 last_update_login          = p_login_id,
2419                 request_id                 = p_request_id,
2420                 program_application_id     = p_pgm_app_id,
2421                 program_id                 = p_pgm_id,
2422                 program_update_date        = sysdate
2423           WHERE potentially_unmatched_flag = 'Y'
2424             AND request_id                 = p_neg_req_id
2425             AND ledger_id                  = l_sob   -- l_sob.set_of_books_id
2426             AND acct_period_num            = l_revenue_acct_period_num;
2427 
2428         END IF;
2429 
2430         commit;  -- Need to save this update as well
2431         SAVEPOINT Create_CogsRecEvents_PVT;
2432 
2433       END LOOP acct_period_loop;
2434    END LOOP sob_loop;
2435 
2436    IF l_eventLog THEN
2437       l_api_message :=  'Inserted '||to_char(l_cce_count)||' new COGS Recognition Events into CCE.';
2438       FND_LOG.string(FND_LOG.LEVEL_EVENT, G_LOG_HEAD ||'.'|| l_api_name || '.10', l_api_message);
2439    END IF;
2440 
2441 -- End API Body
2442 
2443    IF l_proclog THEN
2444       fnd_log.string(FND_LOG.LEVEL_PROCEDURE,l_module||'.end',
2445         'Exiting '||G_PKG_NAME||'.'||l_api_name||' with '||
2446         'x_return_status = '||x_return_status
2447       );
2448    END IF;
2449 
2450    debug('  x_return_status : '||x_return_status);
2451    debug('Create_CogsRecognitionEvents-');
2452 
2453 EXCEPTION
2454    WHEN end_of_program THEN
2455        ROLLBACK TO Create_CogsRecEvents_PVT;
2456        -- Let the program end normally
2457        x_return_status := FND_API.G_RET_STS_SUCCESS;
2458        debug('EXCEPTION end_of_program Create_CogsRecognitionEvents '||l_stmt_num||' : no ledger found - p_ledger_id :'||p_ledger_id);
2459 
2460    WHEN program_exception THEN
2461       ROLLBACK TO Create_CogsRecEvents_PVT;
2462       x_return_status := fnd_api.g_ret_sts_error;
2463       FND_FILE.put_line(fnd_file.log, 'program_exception EXCEPTION IN Create_CogsRecognitionEvents');
2464 
2465    WHEN OTHERS THEN
2466          ROLLBACK TO Create_CogsRecEvents_PVT;
2467          x_return_status := fnd_api.g_ret_sts_unexp_error ;
2468 
2469          IF fnd_msg_pub.check_msg_level(fnd_msg_pub.g_msg_lvl_unexp_error) THEN
2470             FND_MESSAGE.set_name('BOM', 'CST_UNEXP_ERROR');
2471             FND_MESSAGE.set_token('PACKAGE', G_PKG_NAME);
2472             FND_MESSAGE.set_token('PROCEDURE',l_api_name);
2473             FND_MESSAGE.set_token('STATEMENT',to_char(l_stmt_num));
2474             FND_MSG_PUB.ADD;
2475          END IF;
2476 
2477          IF l_unexpLog THEN
2478             FND_LOG.string(FND_LOG.LEVEL_UNEXPECTED,G_LOG_HEAD || '.'||l_api_name||'.'||l_stmt_num
2479                 ,'Create_CogsRecognitionEvents ('||to_char(l_stmt_num)||') : '||substr(SQLERRM,1,200));
2480          END IF;
2481          FND_FILE.put_line(fnd_file.log, 'OTHERS EXCEPTION IN Create_CogsRecognitionEvents:'||substrb(SQLERRM,1,250) );
2482 
2483 END Create_CogsRecognitionEvents;
2484 
2485 
2486 -----------------------------------------------------------------------------
2487 -- Start of comments                                                       --
2488 --                                                                         --
2489 -- PROCEDURE                                                               --
2490 --  Insert_OneSoIssue    This procedure is very similar to the             --
2491 --             Insert_SoIssues() procedure above.  It differs in that the  --
2492 --             above procedure handles bulk inserts and is called during   --
2493 --             one of the phases of the concurrent request, while this     --
2494 --             version inserts one sales order at a time into the data     --
2495 --             model, and is called from the Cost Processor.               --
2496 --                                                                         --
2497 --             This procedure should only get called for issues out of     --
2498 --             asset subinventories.                                       --
2499 --                                                                         --
2500 -- VERSION 1.0                                                             --
2501 --                                                                         --
2502 -- PARAMETERS                                                              --
2503 --  P_COGS_OM_LINE_ID    Line_ID of the sales order issue from OM table    --
2504 --  P_COGS_ACCT_ID       GL Code Combination for the COGS account          --
2505 --  P_DEF_COGS_ACCT_ID   GCC for the deferred COGS account                 --
2506 --  P_MMT_TXN_ID         Transaction ID from MMT table                     --
2507 --  P_ORGANIZATION_ID    Organization ID                                   --
2508 --  P_ITEM_ID            Inventory Item ID                                 --
2509 --  P_TRANSACTION_DATE   Event Date                                        --
2510 --  P_COGS_GROUP_ID      Cost Group ID                                     --
2511 --  P_QUANTITY           Sales Order Issue Quantity as a POSITIVE value    --
2512 --                                                                         --
2513 -- HISTORY:                                                                --
2514 --    05/13/05     Bryan Kuntz      Created                                --
2515 -- End of comments                                                         --
2516 -----------------------------------------------------------------------------
2517 
2518 PROCEDURE Insert_OneSoIssue(
2519                 p_api_version           IN  NUMBER,
2520                 p_init_msg_list         IN  VARCHAR2 := FND_API.G_FALSE,
2521                 p_commit                IN  VARCHAR2 := FND_API.G_FALSE,
2522                 p_validation_level      IN  NUMBER   := FND_API.G_VALID_LEVEL_FULL,
2523                 p_user_id               IN  NUMBER,
2524                 p_login_id              IN  NUMBER,
2525                 p_request_id            IN  NUMBER,
2526                 p_pgm_app_id            IN  NUMBER,
2527                 p_pgm_id                IN  NUMBER,
2528                 x_return_status         OUT NOCOPY  VARCHAR2,
2529                 p_cogs_om_line_id       IN  NUMBER,
2530                 p_cogs_acct_id          IN  NUMBER,
2531                 p_def_cogs_acct_id      IN  NUMBER,
2532                 p_mmt_txn_id            IN  NUMBER,
2533                 p_organization_id       IN  NUMBER,
2534                 p_item_id               IN  NUMBER,
2535                 p_transaction_date      IN  DATE,
2536                 p_cost_group_id         IN  NUMBER,
2537                 p_quantity              IN  NUMBER
2538 ) IS
2539 
2540    l_api_name               CONSTANT VARCHAR2(30)  := 'Insert_OneSoIssue';
2541    l_api_message            VARCHAR2(1000);
2542    l_api_version            CONSTANT NUMBER        := 1.0;
2543    l_return_status          VARCHAR2(1)            := FND_API.G_RET_STS_SUCCESS;
2544    l_msg_count           NUMBER             := 0;
2545    l_msg_data            VARCHAR2(8000)     := '';
2546    l_stmt_num               NUMBER                 := 0;
2547 
2548    l_module   CONSTANT VARCHAR2(100)        := G_LOG_HEAD ||'.'||l_api_name||'.';
2549    l_unexpLog CONSTANT BOOLEAN := (FND_LOG.LEVEL_UNEXPECTED >= G_LOG_LEVEL) AND FND_LOG.TEST(FND_LOG.LEVEL_UNEXPECTED, l_module);
2550    l_errorLog CONSTANT BOOLEAN := l_unexpLog and (FND_LOG.LEVEL_ERROR >= G_LOG_LEVEL);
2551    l_eventLog CONSTANT BOOLEAN := l_errorLog and (FND_LOG.LEVEL_EVENT >= G_LOG_LEVEL);
2552    l_procLog  CONSTANT BOOLEAN := l_eventLog and (FND_LOG.LEVEL_PROCEDURE >= G_LOG_LEVEL);
2553    l_stmtLog  CONSTANT BOOLEAN := l_procLog  and (FND_LOG.LEVEL_STATEMENT >= G_LOG_LEVEL);
2554 
2555    l_revenue_om_line_id     NUMBER;
2556    l_parent_cce_id          NUMBER;
2557    l_operating_unit_id      NUMBER;
2558    l_ledger_id              NUMBER;
2559 
2560    program_exception        EXCEPTION;
2561 
2562 BEGIN
2563    debug('Insert_OneSoIssue_PVT+');
2564    debug('  p_api_version     : '||p_api_version);
2565    debug('  p_cogs_om_line_id : '||p_cogs_om_line_id);
2566    debug('  p_cogs_acct_id    : '||p_cogs_acct_id);
2567    debug('  p_def_cogs_acct_id: '||p_def_cogs_acct_id);
2568    debug('  p_mmt_txn_id      : '||p_mmt_txn_id);
2569    debug('  p_organization_id : '||p_organization_id);
2570    debug('  p_item_id         : '||p_item_id);
2571    debug('  p_transaction_date: '||to_char(p_transaction_date,'MM-DD-YYYY'));
2572    debug('  p_cost_group_id   : '||p_cost_group_id);
2573    debug('  p_quantity        : '||p_quantity);
2574 
2575 
2576 -- Standard start of API savepoint
2577    SAVEPOINT Insert_OneSoIssue_PVT;
2578 
2579    l_stmt_num := 0;
2580    debug(l_stmt_num);
2581 /*
2582    IF l_proclog THEN
2583       fnd_log.string(FND_LOG.LEVEL_PROCEDURE,l_module||'.begin',
2584         'Entering '||G_PKG_NAME||'.'||l_api_name||' with '||
2585         'p_api_version = '||p_api_version||','||
2586         'p_cogs_om_line_id = '||p_cogs_om_line_id||','||
2587         'p_cogs_acct_id = '||p_cogs_acct_id||','||
2588         'p_def_cogs_acct_id = '||p_def_cogs_acct_id||','||
2589         'p_mmt_txn_id = '||p_mmt_txn_id||','||
2590         'p_organization_id = '||p_organization_id||','||
2591         'p_item_id = '||p_item_id||','||
2592         'p_transaction_date = '||to_char(p_transaction_date,'MM-DD-YYYY')||','||
2593         'p_cost_group_id = '||p_cost_group_id||','||
2594         'p_quantity = '||p_quantity
2595       );
2596    END IF;
2597 */
2598 -- Standard call to check for call compatibility
2599    IF NOT FND_API.Compatible_API_Call (
2600                         l_api_version,
2601                         p_api_version,
2602                         l_api_name,
2603                         G_PKG_NAME ) THEN
2604      RAISE FND_API.G_EXC_UNEXPECTED_ERROR;
2605    END IF;
2606 
2607 -- Initialize message list if p_init_msg_list is set to TRUE
2608    IF FND_API.to_Boolean(p_init_msg_list) THEN
2609      FND_MSG_PUB.initialize;
2610    END IF;
2611 
2612 -- Initialize API return status to success
2613    x_return_status := FND_API.G_RET_STS_SUCCESS;
2614 
2615 -- API Body
2616 
2617    -- initialize
2618    l_revenue_om_line_id := NULL;
2619    l_parent_cce_id := NULL;
2620 
2621    l_stmt_num := 10;
2622    debug(l_stmt_num);
2623    -- get the operating unit
2624    SELECT decode(fpg.multi_org_flag,'Y',TO_NUMBER(hoi.org_information3),TO_NUMBER(NULL)),
2625           TO_NUMBER(hoi.org_information1)
2626    INTO l_operating_unit_id,
2627         l_ledger_id
2628    FROM hr_organization_information hoi,
2629         fnd_product_groups fpg
2630    WHERE hoi.organization_id = p_organization_id
2631    AND hoi.org_information_context = 'Accounting Information';
2632 
2633    l_stmt_num := 20;
2634    debug(l_stmt_num);
2635    -- Using the sales order line ID, find the invoicable line ID by calling OM's view/API
2636    OE_COGS_GRP.get_revenue_event_line(p_shippable_line_id => p_cogs_om_line_id,
2637                                       x_revenue_event_line_id => l_revenue_om_line_id,
2638                                       x_return_status => l_return_status,
2639                                       x_msg_count => l_msg_count,
2640                                       x_msg_data => l_msg_data);
2641 
2642    IF (l_return_status <> FND_API.G_RET_STS_SUCCESS) THEN
2643       FND_MESSAGE.set_name('BOM', 'CST_NO_REVENUE_OM_LINE');
2644       FND_MESSAGE.set_token('COGS_LINE_ID', to_char(p_cogs_om_line_id));
2645       IF fnd_msg_pub.check_msg_level(fnd_msg_pub.g_msg_lvl_error) THEN
2646          FND_MSG_PUB.ADD;
2647       END IF;
2648 
2649       debug('  CST_NO_REVENUE_OM_LINE for p_cogs_om_line_id : '||p_cogs_om_line_id);
2650 
2651       IF l_errorLog THEN
2652          FND_LOG.MESSAGE(FND_LOG.LEVEL_ERROR,G_LOG_HEAD||'.'||l_api_name||'.20',TRUE);
2653       END IF;
2654       raise program_exception;
2655    END IF;
2656 
2657    -- Insert a new row into CRCML - if it already has this row, the unique index will be violated (DUP_VAL_ON_INDEX)
2658    BEGIN
2659       l_stmt_num := 30;
2660       debug(l_stmt_num);
2661       INSERT INTO cst_revenue_cogs_match_lines (
2662                cogs_om_line_id,
2663                revenue_om_line_id,
2664                cogs_acct_id,
2665                deferred_cogs_acct_id,
2666                sales_order_issue_date,
2667                organization_id,
2668                inventory_item_id,
2669                operating_unit_id,
2670                ledger_id,
2671                cost_group_id,
2672                -- WHO COLUMNS
2673                last_update_date,
2674                last_updated_by,
2675                creation_date,
2676                created_by,
2677                last_update_login,
2678                request_id,
2679                program_application_id,
2680                program_id,
2681                program_update_date)
2682       VALUES (
2683                p_cogs_om_line_id,
2684                l_revenue_om_line_id,
2685                p_cogs_acct_id,
2686                p_def_cogs_acct_id,
2687                p_transaction_date,
2688                p_organization_id,
2689                p_item_id,
2690                l_operating_unit_id,
2691                l_ledger_id,
2692                p_cost_group_id,
2693                -- WHO COLUMNS
2694                sysdate,
2695                p_user_id,
2696                sysdate,
2697                p_user_id,
2698                p_login_id,
2699                p_request_id,
2700                p_pgm_app_id,
2701                p_pgm_id,
2702                sysdate
2703              );
2704    EXCEPTION
2705       WHEN DUP_VAL_ON_INDEX THEN
2706          l_stmt_num := 40;
2707          -- The existing event is the parent; this new sales order issue
2708          -- becomes the child of this existing one.
2709          SELECT event_id
2710          INTO l_parent_cce_id
2711          FROM cst_cogs_events
2712          WHERE cogs_om_line_id = p_cogs_om_line_id
2713          AND parent_event_id = event_id;
2714    END;
2715 
2716    l_stmt_num := 50;
2717    debug(l_stmt_num);
2718    -- Now update CRRL to mark any lines that may be unmatched due to this SO insert
2719    UPDATE cst_revenue_recognition_lines
2720    SET potentially_unmatched_flag = 'Y',
2721        last_update_date = sysdate,
2722        last_updated_by = p_user_id,
2723        last_update_login = p_login_id,
2724        request_id = p_request_id
2725    WHERE revenue_om_line_id = l_revenue_om_line_id;
2726 
2727    l_stmt_num := 60;
2728    debug(l_stmt_num);
2729    -- Insert the sales order issue as the first event in the linked list of COGS
2730    -- events with a recognition % of 0.
2731    INSERT INTO cst_cogs_events (
2732                   event_id,
2733                   cogs_om_line_id,
2734                   event_date,
2735                   mmt_transaction_id,
2736                   cogs_percentage,
2737                   prior_cogs_percentage,
2738                   event_type,
2739                   event_om_line_id,
2740                   event_quantity,
2741                   costed,
2742                   parent_event_id,
2743                   -- WHO COLUMNS
2744                   last_update_date,
2745                   last_updated_by,
2746                   creation_date,
2747                   created_by,
2748                   last_update_login,
2749                   request_id,
2750                   program_application_id,
2751                   program_id,
2752                   program_update_date)
2753    VALUES (
2754                   cst_cogs_events_s.nextval,
2755                   p_cogs_om_line_id,
2756                   p_transaction_date,
2757                   p_mmt_txn_id,
2758                   0, -- COGS %
2759                   0, -- prior COGS %
2760                   SO_ISSUE,
2761                   p_cogs_om_line_id,
2762                   p_quantity,
2763                   'N',
2764                   nvl(l_parent_cce_id,cst_cogs_events_s.currval),
2765                   -- WHO COLUMNS
2766                   sysdate,
2767                   p_user_id,
2768                   sysdate,
2769                   p_user_id,
2770                   p_login_id,
2771                   p_request_id,
2772                   p_pgm_app_id,
2773                   p_pgm_id,
2774                   sysdate
2775           );
2776 
2777    l_stmt_num := 70;
2778    debug(l_stmt_num);
2779    -- Mark the cogs percentage column in the MMT transaction, thus indicating that it has been added
2780    -- to the revenue / COGS matching data model.
2781    UPDATE mtl_material_transactions
2782    SET cogs_recognition_percent = 0,
2783        last_update_date = sysdate,
2784        last_updated_by = p_user_id,
2785        last_update_login = p_login_id,
2786        request_id = p_request_id,
2787        program_application_id = p_pgm_app_id,
2788        program_id = p_pgm_id,
2789        program_update_date = sysdate
2790    WHERE transaction_id = p_mmt_txn_id;
2791 
2792 -- End API Body
2793 
2794    IF l_proclog THEN
2795       fnd_log.string(FND_LOG.LEVEL_PROCEDURE,l_module||'.end',
2796         'Exiting '||G_PKG_NAME||'.'||l_api_name||' with '||
2797         'x_return_status = '||x_return_status
2798       );
2799    END IF;
2800    debug('   x_return_status : '||x_return_status);
2801    debug('Insert_OneSoIssue-');
2802 
2803 EXCEPTION
2804    WHEN program_exception THEN
2805       ROLLBACK TO Insert_OneSoIssue_PVT; /*Bug 7384398*/
2806       x_return_status := fnd_api.g_ret_sts_error;
2807    WHEN OTHERS THEN
2808          ROLLBACK TO Insert_OneSoIssue_PVT;
2809          x_return_status := fnd_api.g_ret_sts_unexp_error ;
2810 
2811          IF l_unexpLog THEN
2812             FND_LOG.string(FND_LOG.LEVEL_UNEXPECTED,G_LOG_HEAD || '.'||l_api_name||'.'||l_stmt_num
2813                 ,'Insert_OneSoIssue ('||to_char(l_stmt_num)||') : '||substr(SQLERRM,1,200));
2814          END IF;
2815 
2816          IF fnd_msg_pub.check_msg_level(fnd_msg_pub.g_msg_lvl_unexp_error) THEN
2817             FND_MESSAGE.set_name('BOM', 'CST_UNEXP_ERROR');
2818             FND_MESSAGE.set_token('PACKAGE', G_PKG_NAME);
2819             FND_MESSAGE.set_token('PROCEDURE',l_api_name);
2820             FND_MESSAGE.set_token('STATEMENT',to_char(l_stmt_num));
2821             FND_MSG_PUB.ADD;
2822          END IF;
2823          FND_FILE.put_line(fnd_file.log, 'OTHERS EXCEPTION IN Insert_OneSoIssue:'||substrb(SQLERRM,1,250) );
2824 END Insert_OneSoIssue;
2825 
2826 -----------------------------------------------------------------------------
2827 -- Start of comments                                                       --
2828 --                                                                         --
2829 -- PROCEDURE                                                               --
2830 --  Insert_OneRmaReceipt   This procedure is very similar to the           --
2831 --           Insert_RmaReceipts() procedure above.  It differs in that the --
2832 --           above procedure handles bulk inserts and is called during one --
2833 --           of the phases of the concurrent request, while this version   --
2834 --           inserts one RMA receipt at a time into the data model, and is --
2835 --           called from the Cost Processor.                               --
2836 --                                                                         --
2837 -- VERSION 1.0                                                             --
2838 --                                                                         --
2839 -- PARAMETERS                                                              --
2840 --  P_RMA_OM_LINE_ID     Line_ID of the RMA from OM table                  --
2841 --  P_COGS_OM_LINE_ID    Line_ID of the Original Sales Order Issue         --
2842 --                       referrred to by this RMA Receipt.                 --
2843 --  P_MMT_TXN_ID         Transaction ID from MMT table                     --
2844 --  P_ORGANIZATION_ID    Organization ID                                   --
2845 --  P_ITEM_ID            Inventory Item ID                                 --
2846 --  P_TRANSACTION_DATE   Event Date                                        --
2847 --  P_QUANTITY           Event Quantity                                    --
2848 --  X_COGS_PERCENTAGE    Returns the % at which this RMA will be applied   --
2849 --                       to COGS.                                          --
2850 --                                                                         --
2851 -- HISTORY:                                                                --
2852 --    05/13/05     Bryan Kuntz      Created                                --
2853 -- End of comments                                                         --
2854 -----------------------------------------------------------------------------
2855 
2856 PROCEDURE Insert_OneRmaReceipt(
2857                 p_api_version           IN  NUMBER,
2858                 p_init_msg_list         IN  VARCHAR2 := FND_API.G_FALSE,
2859                 p_commit                IN  VARCHAR2 := FND_API.G_FALSE,
2860                 p_validation_level      IN  NUMBER   := FND_API.G_VALID_LEVEL_FULL,
2861                 p_user_id               IN  NUMBER,
2862                 p_login_id              IN  NUMBER,
2863                 p_request_id            IN  NUMBER,
2864                 p_pgm_app_id            IN  NUMBER,
2865                 p_pgm_id                IN  NUMBER,
2866                 x_return_status         OUT NOCOPY  VARCHAR2,
2867                 x_msg_count             OUT NOCOPY  NUMBER,
2868                 x_msg_data              OUT NOCOPY  VARCHAR2,
2869                 p_rma_om_line_id        IN  NUMBER,
2870                 p_cogs_om_line_id       IN  NUMBER,
2871                 p_mmt_txn_id            IN  NUMBER,
2872                 p_organization_id       IN  NUMBER,
2873                 p_item_id               IN  NUMBER,
2874                 p_transaction_date      IN  DATE,
2875                 p_quantity              IN  NUMBER,
2876                 x_event_id              OUT NOCOPY  NUMBER,
2877                 x_cogs_percentage       OUT NOCOPY  NUMBER
2878 ) IS
2879 
2880    l_api_name            CONSTANT VARCHAR2(30)  := 'Insert_OneRmaReceipt';
2881    l_api_message         VARCHAR2(1000);
2882    l_api_version         CONSTANT NUMBER        := 1.0;
2883    l_stmt_num            NUMBER                 := 0;
2884 
2885    l_module   CONSTANT VARCHAR2(100)        := G_LOG_HEAD ||'.'||l_api_name;
2886    l_unexpLog CONSTANT BOOLEAN := (FND_LOG.LEVEL_UNEXPECTED >= G_LOG_LEVEL) AND FND_LOG.TEST(FND_LOG.LEVEL_UNEXPECTED, l_module);
2887    l_errorLog CONSTANT BOOLEAN := l_unexpLog and (FND_LOG.LEVEL_ERROR >= G_LOG_LEVEL);
2888    l_eventLog CONSTANT BOOLEAN := l_errorLog and (FND_LOG.LEVEL_EVENT >= G_LOG_LEVEL);
2889    l_procLog  CONSTANT BOOLEAN := l_eventLog and (FND_LOG.LEVEL_PROCEDURE >= G_LOG_LEVEL);
2890    l_stmtLog  CONSTANT BOOLEAN := l_procLog  and (FND_LOG.LEVEL_STATEMENT >= G_LOG_LEVEL);
2891 
2892    l_parent_event_id         NUMBER;
2893    l_prior_event_id          NUMBER;
2894    l_cogs_percentage         NUMBER;
2895    l_prior_event_quantity    NUMBER;
2896 
2897    -- Inventory's API to insert MMT events returns these 3 parameters
2898    l_return_num              NUMBER;
2899    l_error_code              VARCHAR2(240);
2900    l_error_message           VARCHAR2(2000);
2901    program_exception         EXCEPTION;
2902 
2903    -- The following stores the source code from an OE system parameter.
2904    l_source_code             VARCHAR2(40);
2905 
2906 BEGIN
2907    debug('Insert_OneRmaReceipt_PVT+');
2908    debug('  p_api_version      : '||p_api_version);
2909    debug('  p_rma_om_line_id   : '||p_rma_om_line_id);
2910    debug('  p_cogs_om_line_id  : '||p_cogs_om_line_id);
2911    debug('  p_mmt_txn_id       : '||p_mmt_txn_id);
2912    debug('  p_organization_id  : '||p_organization_id);
2913    debug('  p_item_id          : '||p_item_id);
2914    debug('  p_transaction_date : '||to_char(p_transaction_date,'MM-DD-YYYY'));
2915    debug('  p_quantity         : '||p_quantity);
2916 -- Standard start of API savepoint
2917    SAVEPOINT Insert_OneRmaReceipt_PVT;
2918 
2919    l_stmt_num := 0;
2920    debug(l_stmt_num);
2921 /*
2922    IF l_proclog THEN
2923       fnd_log.string(FND_LOG.LEVEL_PROCEDURE,l_module||'.begin',
2924         'Entering '||G_PKG_NAME||'.'||l_api_name||' with '||
2925         'p_api_version = '||p_api_version||','||
2926         'p_rma_om_line_id = '||p_rma_om_line_id||','||
2927         'p_cogs_om_line_id = '||p_cogs_om_line_id||','||
2928         'p_mmt_txn_id = '||p_mmt_txn_id||','||
2929         'p_organization_id = '||p_organization_id||','||
2930         'p_item_id = '||p_item_id||','||
2931         'p_transaction_date = '||to_char(p_transaction_date,'MM-DD-YYYY')||','||
2932         'p_quantity = '||p_quantity
2933       );
2934    END IF;
2935 */
2936 -- Standard call to check for call compatibility
2937    IF NOT FND_API.Compatible_API_Call (
2938                         l_api_version,
2939                         p_api_version,
2940                         l_api_name,
2941                         G_PKG_NAME ) THEN
2942      RAISE FND_API.G_EXC_UNEXPECTED_ERROR;
2943    END IF;
2944 
2945 -- Initialize message list if p_init_msg_list is set to TRUE
2946    IF FND_API.to_Boolean(p_init_msg_list) THEN
2947      FND_MSG_PUB.initialize;
2948    END IF;
2949 
2950 -- Initialize API return status to success
2951    x_return_status := FND_API.G_RET_STS_SUCCESS;
2952    x_msg_count := 0;
2953    x_msg_data := '';
2954 
2955 
2956 -- API Body
2957 
2958    x_event_id := NULL;
2959 
2960    l_stmt_num := 10;
2961    debug(l_stmt_num);
2962    -- Retrieve basic information about the original sales order issue
2963    -- and the latest COGS recognition percentage for that sales order
2964    SELECT cce.parent_event_id prior_event_id,
2965           cce.cogs_percentage,
2966           sum(cce.event_quantity) prior_event_quantity
2967    INTO  l_prior_event_id,
2968          l_cogs_percentage,
2969          l_prior_event_quantity
2970    FROM cst_cogs_events cce
2971    WHERE p_cogs_om_line_id = cce.cogs_om_line_id
2972    AND cce.event_date <= p_transaction_date
2973    AND cce.parent_event_id NOT IN (SELECT prior_event_id
2974                                    FROM cst_cogs_events
2975                                    WHERE event_date <= p_transaction_date
2976                                    AND cogs_om_line_id <= p_cogs_om_line_id
2977                                    AND prior_event_id IS NOT NULL)
2978    GROUP BY cce.parent_event_id,
2979             cce.cogs_percentage;
2980 
2981    /* For an RMA Receipt, insert 2 rows in cce - one goes in
2982     * the string of events and the other is the quantity adjustment
2983     * to that parent event.
2984     */
2985 
2986    l_stmt_num := 20;
2987    debug(l_stmt_num);
2988    INSERT INTO cst_cogs_events (
2989             event_id,
2990             cogs_om_line_id,
2991             event_date,
2992             mmt_transaction_id,
2993             cogs_percentage,
2994             prior_cogs_percentage,
2995             prior_event_id,
2996             event_type,
2997             event_om_line_id,
2998             event_quantity,
2999             costed,
3000             parent_event_id,
3001             -- WHO COLUMNS
3002             last_update_date,
3003             last_updated_by,
3004             creation_date,
3005             created_by,
3006             last_update_login,
3007             request_id,
3008             program_application_id,
3009             program_id,
3010             program_update_date)
3011    VALUES ( cst_cogs_events_s.nextval,
3012             p_cogs_om_line_id,
3013             p_transaction_date,
3014             NULL, -- Quantity Placeholder event - no corresponding MMT txn
3015             l_cogs_percentage,
3016             l_cogs_percentage,
3017             l_prior_event_id,
3018             RMA_RECEIPT_PLACEHOLDER,
3019             p_rma_om_line_id,
3020             l_prior_event_quantity,
3021             NULL, -- RMA quantity placeholders are not costed
3022             cst_cogs_events_s.currval,
3023             -- WHO COLUMNS
3024             sysdate,
3025             p_user_id,
3026             sysdate,
3027             p_user_id,
3028             p_login_id,
3029             p_request_id,
3030             p_pgm_app_id,
3031             p_pgm_id,
3032             sysdate)
3033    RETURNING event_id INTO l_parent_event_id;
3034 
3035    l_stmt_num := 30;
3036    debug(l_stmt_num);
3037    -- Now insert the actual RMA event
3038    INSERT INTO cst_cogs_events (
3039             event_id,
3040             cogs_om_line_id,
3041             event_date,
3042             mmt_transaction_id,
3043             cogs_percentage,
3044             prior_cogs_percentage,
3045             prior_event_id,
3046             event_type,
3047             event_om_line_id,
3048             event_quantity,
3049             costed,
3050             parent_event_id,
3051             -- WHO COLUMNS
3052             last_update_date,
3053             last_updated_by,
3054             creation_date,
3055             created_by,
3056             last_update_login,
3057             request_id,
3058             program_application_id,
3059             program_id,
3060             program_update_date)
3061    VALUES ( cst_cogs_events_s.nextval,
3062             p_cogs_om_line_id,
3063             p_transaction_date,
3064             p_mmt_txn_id,
3065             l_cogs_percentage,
3066             l_cogs_percentage,
3067             NULL,
3068             RMA_RECEIPT,
3069             p_rma_om_line_id,
3070             p_quantity,
3071             'N',
3072             l_parent_event_id,
3073             -- WHO COLUMNS
3074             sysdate,
3075             p_user_id,
3076             sysdate,
3077             p_user_id,
3078             p_login_id,
3079             p_request_id,
3080             p_pgm_app_id,
3081             p_pgm_id,
3082             sysdate)
3083    RETURNING event_id INTO x_event_id;
3084 
3085    -- Mark the cogs percentage column in the MMT transaction, thus indicating that it has been added
3086    -- to the revenue / COGS matching data model.
3087    l_stmt_num := 40;
3088    debug(l_stmt_num);
3089    UPDATE mtl_material_transactions
3090    SET cogs_recognition_percent = l_cogs_percentage,
3091        last_update_date = sysdate,
3092        last_updated_by = p_user_id,
3093        last_update_login = p_login_id,
3094        request_id = p_request_id
3095    WHERE transaction_id = p_mmt_txn_id;
3096 
3097    /* If there are events after this RMA (that is, if it's backdated)
3098     * adjust the quantity for each of these events by either updating
3099     * CCE / MMT directly if the parent is uncosted, or inserting new
3100     * events in CCE and MMT in the case that the parent is costed.
3101     */
3102 
3103    -- First insert this new event into the linked list by setting the prior event ID of the
3104    -- next event to this new one.
3105    l_stmt_num := 50;
3106    debug(l_stmt_num);
3107    UPDATE cst_cogs_events
3108    SET PRIOR_EVENT_ID = l_parent_event_id,
3109        last_update_date = sysdate,
3110        last_updated_by = p_user_id,
3111        last_update_login = p_login_id,
3112        request_id = p_request_id
3113    WHERE cogs_om_line_id = p_cogs_om_line_id
3114    AND   prior_event_id = l_prior_event_id
3115    AND   event_date > p_transaction_date;
3116 
3117    -- Now create quantity adjustment events for all future COGS Rec events
3118    -- This is a 2 step process, first insert into the global temp table
3119    l_stmt_num := 60;
3120    debug(l_stmt_num);
3121    INSERT INTO cst_cogs_qty_adj_events_temp (
3122                         adj_event_id,
3123                         adj_mmt_txn_id,
3124                         adj_cogs_om_line_id,
3125                         adj_rma_om_line_id,
3126                         adj_event_date,
3127                         adj_new_cogs_percentage,
3128                         adj_prior_cogs_percentage,
3129                         adj_event_quantity,
3130                         parent_event_id,
3131                         inventory_item_id,
3132                         primary_uom,
3133                         organization_id,
3134                         cost_group_id,
3135                         cogs_acct_id,
3136                         opm_org_flag,
3137                         acct_period_id
3138                         )
3139    SELECT cst_cogs_events_s.nextval,
3140           decode(event_type, COGS_RECOGNITION_EVENT, mtl_material_transactions_s.nextval,
3141                              COGS_REC_PERCENT_ADJUSTMENT, mtl_material_transactions_s.nextval,
3142                              NULL),
3143           cce.cogs_om_line_id,
3144           p_rma_om_line_id,
3145           cce.event_date,
3146           cogs_percentage, -- could also use cce.prior_cogs_percentage
3147           prior_cogs_percentage,
3148           p_quantity,
3149           cce.event_id,
3150           crcml.inventory_item_id,
3151           msi.primary_uom_code,
3152           crcml.organization_id,
3153           crcml.cost_group_id,
3154           crcml.cogs_acct_id,
3155           nvl(mp.process_enabled_flag,'N'),
3156           oap.acct_period_id
3157    FROM cst_cogs_events cce,
3158         cst_revenue_cogs_match_lines crcml,
3159         mtl_parameters mp,
3160         org_acct_periods oap,
3161         cst_acct_info_v caiv,
3162         mtl_system_items msi
3163    WHERE cce.cogs_om_line_id = p_cogs_om_line_id
3164    AND   cce.event_date > p_transaction_date
3165    AND   cce.event_id = cce.parent_event_id
3166    AND   cce.cogs_om_line_id = crcml.cogs_om_line_id
3167    AND   crcml.pac_cost_type_id IS NULL
3168    AND   crcml.organization_id = mp.organization_id
3169    AND   crcml.organization_id = msi.organization_id
3170    AND   crcml.inventory_item_id = msi.inventory_item_id
3171    AND   crcml.organization_id = oap.organization_id
3172    AND   crcml.organization_id = caiv.organization_id
3173    AND   inv_le_timezone_pub.get_le_day_time_for_ou(cce.event_date, caiv.operating_unit)
3174          BETWEEN oap.period_start_date AND oap.schedule_close_date+.99999;
3175 
3176    -- Then insert from the global temp table into CCE
3177    l_stmt_num := 70;
3178    debug(l_stmt_num);
3179    INSERT INTO cst_cogs_events (
3180              event_id,
3181              cogs_om_line_id,
3182              event_date,
3183              mmt_transaction_id,
3184              cogs_percentage,
3185              prior_cogs_percentage,
3186              prior_event_id,
3187              event_type,
3188              event_om_line_id,
3189              event_quantity,
3190              costed,
3191              parent_event_id,
3192              -- WHO COLUMNS
3193              last_update_date,
3194              last_updated_by,
3195              creation_date,
3196              created_by,
3197              last_update_login,
3198              request_id,
3199              program_application_id,
3200              program_id,
3201              program_update_date)
3202    SELECT adj_event_id,
3203           adj_cogs_om_line_id,
3204           adj_event_date,
3205           adj_mmt_txn_id,
3206           adj_new_cogs_percentage,
3207           adj_prior_cogs_percentage,
3208           NULL,
3209           COGS_REC_QTY_ADJUSTMENT,
3210           adj_rma_om_line_id,
3211           adj_event_quantity,
3212           decode(adj_mmt_txn_id, NULL, NULL, 'N'),
3213           parent_event_id,
3214           -- WHO COLUMNS
3215           sysdate,
3216           p_user_id,
3217           sysdate,
3218           p_user_id,
3219           p_login_id,
3220           p_request_id,
3221           p_pgm_app_id,
3222           p_pgm_id,
3223           sysdate
3224    FROM cst_cogs_qty_adj_events_temp;
3225 
3226    -- Get the source code from the OE profile system parameter.
3227    -- It can be overridden by the user but most likely uses the default
3228    -- called 'ORDER ENTRY' and will most likely never change.
3229    l_stmt_num := 80;
3230    debug(l_stmt_num);
3231    l_source_code := FND_PROFILE.VALUE('ONT_SOURCE_CODE'); -- borrowed from OEXVSCHB.pls
3232 
3233    debug('  l_source_code : '||l_source_code);
3234    -- Insert MMT event here (from one global temp table to another)
3235    l_stmt_num := 90;
3236    debug(l_stmt_num);
3237 
3238    INSERT INTO mtl_cogs_recognition_temp (
3239                      TRANSACTION_ID,
3240                      LAST_UPDATE_DATE,
3241                      LAST_UPDATED_BY,
3242                      CREATION_DATE,
3243                      CREATED_BY,
3244                      INVENTORY_ITEM_ID,
3245                      ORGANIZATION_ID,
3246                      COST_GROUP_ID,
3247                      TRANSACTION_TYPE_ID,
3248                      TRANSACTION_ACTION_ID,
3249                      TRANSACTION_SOURCE_TYPE_ID,
3250                      TRANSACTION_SOURCE_ID,
3251                      TRANSACTION_QUANTITY,
3252                      TRANSACTION_UOM,
3253                      PRIMARY_QUANTITY,
3254                      TRANSACTION_DATE,
3255                      ACCT_PERIOD_ID,
3256                      DISTRIBUTION_ACCOUNT_ID,
3257                      COSTED_FLAG,
3258                      OPM_COSTED_FLAG,
3259                      ACTUAL_COST,
3260                      TRANSACTION_COST,
3261                      PRIOR_COST,
3262                      NEW_COST,
3263                      TRX_SOURCE_LINE_ID,
3264                      RMA_LINE_ID,
3265                      LOGICAL_TRANSACTION,
3266                      COGS_RECOGNITION_PERCENT)
3267    SELECT
3268                      ccqa.adj_mmt_txn_id,
3269                      sysdate,
3270                      p_user_id,
3271                      sysdate,
3272                      p_user_id,
3273                      ccqa.inventory_item_id,
3274                      ccqa.organization_id,
3275                      ccqa.cost_group_id,
3276                      10008,
3277                      36,
3278                      2,
3279                      mso.sales_order_id,
3280                      ccqa.adj_event_quantity,
3281                      ccqa.primary_uom, -- Txn UOM
3282                      ccqa.adj_event_quantity,
3283                      ccqa.adj_event_date,
3284                      ccqa.acct_period_id,
3285                      ccqa.cogs_acct_id,
3286                      decode(ccqa.opm_org_flag, 'N', 'N', NULL),
3287                      decode(ccqa.opm_org_flag, 'Y', 'N', NULL),
3288                      NULL, -- Actual Cost
3289                      NULL, -- Txn Cost
3290                      NULL, -- Prior Cost
3291                      NULL, -- New Cost
3292                      ccqa.adj_cogs_om_line_id,
3293                      ccqa.adj_rma_om_line_id, -- RMA Line ID
3294                      1, -- Logical Txn
3295                      ccqa.adj_new_cogs_percentage
3296    FROM  cst_cogs_qty_adj_events_temp ccqa,
3297          mtl_sales_orders mso,
3298          oe_order_lines_all ool,
3299          oe_order_headers_all ooh,
3300          oe_transaction_types_tl ott
3301    WHERE ool.line_id = ccqa.adj_cogs_om_line_id
3302    AND   ool.header_id = ooh.header_id
3303    AND   TO_CHAR(ooh.order_number) = mso.segment1
3304    AND   ooh.order_type_id = ott.transaction_type_id
3305    AND   ott.name = mso.segment2
3306    AND   ott.language = (SELECT language_code
3307                          FROM   fnd_languages
3308                          WHERE  installed_flag = 'B')
3309    AND   mso.segment3 = l_source_code
3310   --{BUG#6909721
3311   -- Ensure the place holder COGS event is not inserted in MMT as not effect on Cost and Accounting
3312    AND   ccqa.adj_mmt_txn_id IS NOT NULL;
3313   --}
3314 
3315    -- Now insert into MMT by calling INV API
3316    l_stmt_num := 100;
3317    debug(l_stmt_num);
3318 
3319    INV_LOGICAL_TRANSACTIONS_PUB.create_cogs_recognition(x_return_status => l_return_num,
3320                                                         x_error_code    => l_error_code,
3321                                                         x_error_message => l_error_message);
3322 
3323    IF (l_return_num <> 0) THEN
3324       x_return_status := fnd_api.g_ret_sts_error;
3325       FND_MESSAGE.set_name('BOM', 'CST_FAILED_COGSREC_MMT_INSERT');
3326       FND_MESSAGE.set_token('ERROR_CODE', l_error_code);
3327       FND_MESSAGE.set_token('ERROR_MESSAGE',substr(l_error_message,1,500));
3328       IF fnd_msg_pub.check_msg_level(fnd_msg_pub.g_msg_lvl_unexp_error) THEN
3329          FND_MSG_PUB.ADD;
3330       END IF;
3331       IF l_errorLog THEN
3332          FND_LOG.message(FND_LOG.LEVEL_ERROR, l_module||'.'||to_char(l_stmt_num),TRUE);
3333       END IF;
3334       raise program_exception;
3335    END IF;
3336 
3337    -- Set the value of the return paramter
3338    x_cogs_percentage := l_cogs_percentage;
3339 
3340 -- End API Body
3341 
3342    FND_MSG_PUB.count_and_get
3343     (  p_count  => x_msg_count
3344      , p_data   => x_msg_data
3345     );
3346 
3347    IF l_proclog THEN
3348       fnd_log.string(FND_LOG.LEVEL_PROCEDURE,l_module||'.end',
3349         'Exiting '||G_PKG_NAME||'.'||l_api_name||' with '||
3350         'x_return_status = '||x_return_status||','||
3351         'x_event_id = '||x_event_id||','||
3352         'x_cogs_percentage = '||x_cogs_percentage
3353       );
3354    END IF;
3355    debug('   x_msg_count : '||x_msg_count);
3356    debug('   x_msg_data  : '||x_msg_data);
3357    debug('Insert_OneRmaReceipt-');
3358 EXCEPTION
3359    WHEN program_exception THEN
3360       ROLLBACK TO Insert_OneRmaReceipt_PVT;
3361       x_return_status := fnd_api.g_ret_sts_error;
3362    WHEN OTHERS THEN
3363          ROLLBACK TO Insert_OneRmaReceipt_PVT;
3364          x_return_status := fnd_api.g_ret_sts_unexp_error ;
3365 
3366          IF l_unexpLog THEN
3367             FND_LOG.string(FND_LOG.LEVEL_UNEXPECTED,G_LOG_HEAD || '.'||l_api_name||'.'||l_stmt_num
3368                 ,'Insert_OneRmaReceipt '||to_char(l_stmt_num)||' : '||substr(SQLERRM,1,200));
3369          END IF;
3370 
3371          IF fnd_msg_pub.check_msg_level(fnd_msg_pub.g_msg_lvl_unexp_error) THEN
3372             FND_MESSAGE.set_name('BOM', 'CST_UNEXP_ERROR');
3373             FND_MESSAGE.set_token('PACKAGE', G_PKG_NAME);
3374             FND_MESSAGE.set_token('PROCEDURE',l_api_name);
3375             FND_MESSAGE.set_token('STATEMENT',to_char(l_stmt_num));
3376             FND_MSG_PUB.ADD;
3377          END IF;
3378 
3379          FND_MSG_PUB.count_and_get
3380           (  p_count  => x_msg_count
3381             , p_data   => x_msg_data
3382            );
3383          FND_FILE.put_line(fnd_file.log, 'OTHERS EXCEPTION IN Insert_OneRmaReceipt:'||substrb(SQLERRM,1,250) );
3384 END Insert_OneRmaReceipt;
3385 
3386 -----------------------------------------------------------------------------
3387 -- Start of comments                                                       --
3388 --                                                                         --
3389 -- PROCEDURE                                                               --
3390 --  Record_SoIssueCost                                                     --
3391 --           This procedure is called by the distribution processors to    --
3392 --           record the outgoing cost of the item at the time of the sales --
3393 --           order issue.  The logic is standard across cost methods so    --
3394 --           it can be called for all perpetual and PAC types.             --
3395 --                                                                         --
3396 -- VERSION 1.0                                                             --
3397 --                                                                         --
3398 -- PARAMETERS                                                              --
3399 --  P_COGS_OM_LINE_ID    OM Line_ID of the Sales Order issue               --
3400 --  P_PAC_COST_TYPE_ID   Periodic Cost Type, Leave NULL for perpetual      --
3401 --  P_UNIT_MATERIAL_COST
3402 --  P_UNIT_MOH_COST
3403 --  P_UNIT_RESOURCE_COST
3404 --  P_UNIT_OP_COST
3405 --  P_UNIT_OVERHEAD_COST
3406 --  P_UNIT_COST
3407 --  P_TXN_QUANTITY
3408 --                                                                         --
3409 -- HISTORY:                                                                --
3410 --    05/16/05     Bryan Kuntz      Created                                --
3411 -- End of comments                                                         --
3412 -----------------------------------------------------------------------------
3413 
3414 PROCEDURE Record_SoIssueCost(
3415                 p_api_version           IN  NUMBER,
3416                 p_init_msg_list         IN  VARCHAR2 := FND_API.G_FALSE,
3417                 p_user_id               IN  NUMBER,
3418                 p_login_id              IN  NUMBER,
3419                 p_request_id            IN  NUMBER,
3420                 p_pgm_app_id            IN  NUMBER,
3421                 p_pgm_id                IN  NUMBER,
3422                 x_return_status         OUT NOCOPY  VARCHAR2,
3423                 x_msg_count             OUT NOCOPY  NUMBER,
3424                 x_msg_data              OUT NOCOPY  VARCHAR2,
3425                 p_cogs_om_line_id       IN  NUMBER,
3426                 p_pac_cost_type_id      IN  NUMBER,
3427                 p_unit_material_cost    IN  NUMBER,
3428                 p_unit_moh_cost         IN  NUMBER,
3429                 p_unit_resource_cost    IN  NUMBER,
3430                 p_unit_op_cost          IN  NUMBER,
3431                 p_unit_overhead_cost    IN  NUMBER,
3432                 p_unit_cost             IN  NUMBER,
3433                 p_txn_quantity          IN  NUMBER
3434 ) IS
3435 
3436    l_api_name            CONSTANT VARCHAR2(30)  := 'Record_SoIssueCost';
3437    l_api_message         VARCHAR2(1000);
3438    l_stmt_num            NUMBER         := 0;
3439    l_api_version         CONSTANT NUMBER        := 1.0;
3440 
3441    l_return_status          VARCHAR2(1)            := FND_API.G_RET_STS_SUCCESS;
3442 
3443    l_module   CONSTANT VARCHAR2(100)        := G_LOG_HEAD ||'.'||l_api_name;
3444    l_unexpLog CONSTANT BOOLEAN := (FND_LOG.LEVEL_UNEXPECTED >= G_LOG_LEVEL) AND FND_LOG.TEST(FND_LOG.LEVEL_UNEXPECTED, l_module);
3445    l_errorLog CONSTANT BOOLEAN := l_unexpLog and (FND_LOG.LEVEL_ERROR >= G_LOG_LEVEL);
3446    l_eventLog CONSTANT BOOLEAN := l_errorLog and (FND_LOG.LEVEL_EVENT >= G_LOG_LEVEL);
3447    l_procLog  CONSTANT BOOLEAN := l_eventLog and (FND_LOG.LEVEL_PROCEDURE >= G_LOG_LEVEL);
3448    l_stmtLog  CONSTANT BOOLEAN := l_procLog  and (FND_LOG.LEVEL_STATEMENT >= G_LOG_LEVEL);
3449 
3450 BEGIN
3451 
3452 -- Standard start of API savepoint
3453    SAVEPOINT Record_SoIssueCost_PVT;
3454 
3455    l_stmt_num := 0;
3456 
3457    IF l_procLog THEN
3458      FND_LOG.string(FND_LOG.LEVEL_PROCEDURE,l_module||'.begin',
3459        'Entering '||G_PKG_NAME||'.'||l_api_name||' with '||
3460        'p_api_version = '||p_api_version||','||
3461        'p_cogs_om_line_id = '||p_cogs_om_line_id||','||
3462        'p_pac_cost_type_id = '||p_pac_cost_type_id||','||
3463        'p_unit_material_cost = '||p_unit_material_cost||','||
3464        'p_unit_moh_cost = '||p_unit_moh_cost||','||
3465        'p_unit_resource_cost = '||p_unit_resource_cost||','||
3466        'p_unit_op_cost = '||p_unit_op_cost||','||
3467        'p_unit_overhead_cost = '||p_unit_overhead_cost||','||
3468        'p_unit_cost = '||p_unit_cost||','||
3469        'p_txn_quantity = '||p_txn_quantity
3470      );
3471    END IF;
3472 
3473 -- Standard call to check for call compatibility
3474    IF NOT FND_API.Compatible_API_Call (
3475                         l_api_version,
3476                         p_api_version,
3477                         l_api_name,
3478                         G_PKG_NAME ) THEN
3479      RAISE FND_API.G_EXC_UNEXPECTED_ERROR;
3480    END IF;
3481 
3482 -- Initialize message list if p_init_msg_list is set to TRUE
3483    IF FND_API.to_Boolean(p_init_msg_list) THEN
3484      FND_MSG_PUB.initialize;
3485    END IF;
3486 
3487 -- Initialize API return status to success
3488    x_return_status := FND_API.G_RET_STS_SUCCESS;
3489    x_msg_count := 0;
3490    x_msg_data := '';
3491 
3492 -- API Body
3493 
3494    l_stmt_num := 10;
3495    -- It's possible that two or more MMT transactions get created for the same sales
3496    -- order line, that's why it is necessary to first check whether the quantity
3497    -- already has a value and, if so, perform an average of the new parameters
3498    -- and whatever is already in the table already for these columns.
3499    UPDATE cst_revenue_cogs_match_lines crcml
3500    SET unit_material_cost = decode(original_shipped_qty, NULL, p_unit_material_cost,
3501                                    ((unit_material_cost*original_shipped_qty) +
3502                                     (p_unit_material_cost*p_txn_quantity)) /
3503                                    (original_shipped_qty + p_txn_quantity)),
3504        unit_moh_cost = decode(original_shipped_qty, NULL, p_unit_moh_cost,
3505                               ((unit_moh_cost*original_shipped_qty) +
3506                                (p_unit_moh_cost*p_txn_quantity)) /
3507                               (original_shipped_qty + p_txn_quantity)),
3508        unit_resource_cost = decode(original_shipped_qty, NULL, p_unit_resource_cost,
3509                                    ((unit_resource_cost*original_shipped_qty) +
3510                                     (p_unit_resource_cost*p_txn_quantity)) /
3511                                    (original_shipped_qty + p_txn_quantity)),
3512        unit_op_cost = decode(original_shipped_qty, NULL, p_unit_op_cost,
3513                              ((unit_op_cost*original_shipped_qty) +
3514                               (p_unit_op_cost*p_txn_quantity)) /
3515                              (original_shipped_qty + p_txn_quantity)),
3516        unit_overhead_cost = decode(original_shipped_qty, NULL, p_unit_overhead_cost,
3517                                    ((unit_overhead_cost*original_shipped_qty) +
3518                                     (p_unit_overhead_cost*p_txn_quantity)) /
3519                                    (original_shipped_qty + p_txn_quantity)),
3520        original_shipped_qty = nvl(original_shipped_qty,0) + p_txn_quantity,
3521        unit_cost = decode(original_shipped_qty, NULL, p_unit_cost,
3522                               ((unit_cost*original_shipped_qty) +
3523                                (p_unit_cost*p_txn_quantity)) /
3524                               (original_shipped_qty + p_txn_quantity)),
3525        last_update_date = sysdate,
3526        last_updated_by = p_user_id,
3527        last_update_login = p_login_id,
3528        request_id = p_request_id,
3529        program_application_id = p_pgm_app_id,
3530        program_id = p_pgm_id,
3531        program_update_date = sysdate
3532    WHERE crcml.cogs_om_line_id = p_cogs_om_line_id
3533    AND   nvl(pac_cost_type_id,0) = nvl(p_pac_cost_type_id,0);
3534 
3535 -- End API Body
3536 
3537    FND_MSG_PUB.count_and_get
3538      (  p_count  => x_msg_count
3539       , p_data   => x_msg_data
3540       , p_encoded => FND_API.g_false
3541      );
3542 
3543    x_return_status := l_return_status;
3544 
3545    IF l_proclog THEN
3546       fnd_log.string(fnd_log.level_procedure,l_module||'.end',
3547         'Exiting '||G_PKG_NAME||'.'||l_api_name||' with '||
3548         'x_return_status = '||x_return_status
3549       );
3550    END IF;
3551 EXCEPTION
3552 
3553    WHEN OTHERS THEN
3554          ROLLBACK TO Record_SoIssueCost_PVT;
3555          x_return_status := fnd_api.g_ret_sts_unexp_error ;
3556 
3557          IF l_unexpLog THEN
3558             FND_LOG.string(FND_LOG.LEVEL_UNEXPECTED,G_LOG_HEAD || '.'||l_api_name||'.'||l_stmt_num
3559                 ,'Record_SoIssueCost '||to_char(l_stmt_num)||' : '||substr(SQLERRM,1,200));
3560          END IF;
3561 
3562          IF fnd_msg_pub.check_msg_level(fnd_msg_pub.g_msg_lvl_unexp_error) THEN
3563             FND_MESSAGE.set_name('BOM', 'CST_UNEXP_ERROR');
3564             FND_MESSAGE.set_token('PACKAGE', G_PKG_NAME);
3565             FND_MESSAGE.set_token('PROCEDURE',l_api_name);
3566             FND_MESSAGE.set_token('STATEMENT',to_char(l_stmt_num));
3567             FND_MSG_PUB.ADD;
3568          END IF;
3569 
3570          FND_MSG_PUB.count_and_get
3571           (  p_count  => x_msg_count
3572             , p_data   => x_msg_data
3573             , p_encoded => FND_API.g_false
3574            );
3575 
3576 END Record_SoIssueCost;
3577 
3578 -----------------------------------------------------------------------------
3579 -- Start of comments                                                       --
3580 --                                                                         --
3581 -- PROCEDURE                                                               --
3582 --  Process_RmaReceipt                                                     --
3583 --           This procedure is called by the distribution processors for   --
3584 --           all perpetual cost methods to create the accounting entries   --
3585 --           for RMAs that are linked to forward flow sales orders with    --
3586 --           COGS deferral.                                                --
3587 --                                                                         --
3588 -- VERSION 1.0                                                             --
3589 --                                                                         --
3590 -- PARAMETERS                                                              --
3591 --  P_RMA_OM_LINE_ID     OM Line ID of the RMA Receipt                     --
3592 --  P_COGS_OM_LINE_ID    OM Line_ID of the Sales Order Issue, not the RMA  --
3593 --  P_COST_TYPE_ID       Cost Type if Periodic, Cost Method if perpetual   --
3594 --  P_TXN_QUANTITY       RMA Receipt quantity                              --
3595 --  P_COGS_PERCENTAGE    Latest COGS Percentage reported for this OM line  --
3596 --                                                                         --
3597 -- HISTORY:                                                                --
3598 --    05/16/05     Bryan Kuntz      Created                                --
3599 -- End of comments                                                         --
3600 -----------------------------------------------------------------------------
3601 
3602 PROCEDURE Process_RmaReceipt(
3603                 x_return_status         OUT NOCOPY  VARCHAR2,
3604                 x_msg_count             OUT NOCOPY  NUMBER,
3605                 x_msg_data              OUT NOCOPY  VARCHAR2,
3606                 p_rma_om_line_id        IN  NUMBER,
3607                 p_cogs_om_line_id       IN  NUMBER,
3608                 p_cost_type_id          IN  NUMBER,
3609                 p_txn_quantity          IN  NUMBER,
3610                 p_cogs_percentage       IN  NUMBER,
3611                 p_organization_id       IN  NUMBER,
3612                 p_transaction_id        IN  NUMBER,
3613                 p_item_id               IN  NUMBER,
3614                 p_sob_id                IN  NUMBER,
3615                 p_txn_date              IN  DATE,
3616                 p_txn_src_id            IN  NUMBER,
3617                 p_src_type_id           IN  NUMBER,
3618                 p_pri_curr              IN  VARCHAR2,
3619                 p_alt_curr              IN  VARCHAR2,
3620                 p_conv_date             IN  DATE,
3621                 p_conv_rate             IN  NUMBER,
3622                 p_conv_type             IN  VARCHAR2,
3623                 p_user_id               IN  NUMBER,
3624                 p_login_id              IN  NUMBER,
3625                 p_req_id                IN  NUMBER,
3626                 p_prg_appl_id           IN  NUMBER,
3627                 p_prg_id                IN  NUMBER
3628 ) IS
3629 
3630    l_api_name            CONSTANT VARCHAR2(30)  := 'Process_RmaReceipt';
3631    l_api_message         VARCHAR2(1000);
3632    l_stmt_num            NUMBER         := 0;
3633    l_return_status       VARCHAR2(1)    := FND_API.G_RET_STS_SUCCESS;
3634    l_msg_count           NUMBER             := 0;
3635    l_msg_data            VARCHAR2(8000)     := '';
3636 
3637    l_elemental_cost      number_table;
3638    l_unit_cost           NUMBER;
3639    l_def_cogs_acct_id    NUMBER;
3640    l_cogs_acct_id        NUMBER;
3641 
3642    l_cogs_percentage     NUMBER;
3643    l_cogs_credit_amount  NUMBER;
3644    l_dcogs_credit_amount NUMBER;
3645 
3646    l_rma_cce_id          NUMBER := NULL;
3647 
3648    l_err_num             NUMBER;
3649    l_err_code            VARCHAR2(240);
3650    l_err_msg             VARCHAR2(240);
3651 
3652    l_module   CONSTANT VARCHAR2(100)        := G_LOG_HEAD ||'.'||l_api_name;
3653    l_unexpLog CONSTANT BOOLEAN := (FND_LOG.LEVEL_UNEXPECTED >= G_LOG_LEVEL) AND FND_LOG.TEST(FND_LOG.LEVEL_UNEXPECTED, l_module);
3654    l_errorLog CONSTANT BOOLEAN := l_unexpLog and (FND_LOG.LEVEL_ERROR >= G_LOG_LEVEL);
3655    l_eventLog CONSTANT BOOLEAN := l_errorLog and (FND_LOG.LEVEL_EVENT >= G_LOG_LEVEL);
3656    l_procLog  CONSTANT BOOLEAN := l_eventLog and (FND_LOG.LEVEL_PROCEDURE >= G_LOG_LEVEL);
3657    l_stmtLog  CONSTANT BOOLEAN := l_procLog  and (FND_LOG.LEVEL_STATEMENT >= G_LOG_LEVEL);
3658    program_exception     EXCEPTION;
3659 
3660 BEGIN
3661 
3662 -- Standard start of API savepoint
3663    SAVEPOINT Process_RmaReceipt_PVT;
3664 
3665    l_stmt_num := 0;
3666 
3667    IF l_proclog THEN
3668       fnd_log.string(FND_LOG.LEVEL_PROCEDURE,l_module||'.begin',
3669         'Entering '||G_PKG_NAME||'.'||l_api_name||' with '||
3670         'p_rma_om_line_id = '||p_rma_om_line_id||','||
3671         'p_cogs_om_line_id = '||p_cogs_om_line_id||','||
3672         'p_cost_type_id = '||p_cost_type_id||','||
3673         'p_txn_quantity = '||p_txn_quantity||','||
3674         'p_cogs_percentage = '||p_cogs_percentage||','||
3675         'p_organization_id = '||p_organization_id||','||
3676         'p_transaction_id = '||p_transaction_id||','||
3677         'p_item_id = '||p_item_id||','||
3678         'p_sob_id = '||p_sob_id||','||
3679         'p_txn_date = '||to_char(p_txn_date,'MM-DD-YYYY')||','||
3680         'p_txn_src_id = '||p_txn_src_id||','||
3681         'p_src_type_id = '||p_src_type_id||','||
3682         'p_pri_curr = '||p_pri_curr||','||
3683         'p_alt_curr = '||p_alt_curr||','||
3684         'p_conv_date = '||to_char(p_conv_date,'MM-DD-YYYY')||','||
3685         'p_conv_rate = '||p_conv_rate||','||
3686         'p_conv_type = '||p_conv_type
3687       );
3688    END IF;
3689 
3690 -- Initialize API return status to success
3691    x_return_status := FND_API.G_RET_STS_SUCCESS;
3692    x_msg_count := 0;
3693    x_msg_data := '';
3694 
3695 -- API Body
3696 
3697    -- Initialize COGS percentage to passed value
3698    l_cogs_percentage := p_cogs_percentage;
3699 
3700    l_stmt_num := 10;
3701    IF (l_cogs_percentage IS NULL) THEN
3702    /* Insert the RMA Receipt into the Revenue / COGS Matching data model *
3703     * retrieving the current cogs percentage in the process.             */
3704 
3705       Insert_OneRmaReceipt(
3706                 p_api_version      => 1,
3707                 p_user_id          => p_user_id,
3708                 p_login_id         => p_login_id,
3709                 p_request_id       => p_req_id,
3710                 p_pgm_app_id       => p_prg_appl_id,
3711                 p_pgm_id           => p_prg_id,
3712                 x_return_status    => l_return_status,
3713                 x_msg_count        => l_msg_count,
3714                 x_msg_data         => l_msg_data,
3715                 p_rma_om_line_id   => p_rma_om_line_id,
3716                 p_cogs_om_line_id  => p_cogs_om_line_id,
3717                 p_mmt_txn_id       => p_transaction_id,
3718                 p_organization_id  => p_organization_id,
3719                 p_item_id          => p_item_id,
3720                 p_transaction_date => p_txn_date,
3721                 p_quantity         => p_txn_quantity,
3722                 x_event_id         => l_rma_cce_id,
3723                 x_cogs_percentage  => l_cogs_percentage
3724                 );
3725 
3726       IF (l_return_status <> FND_API.G_RET_STS_SUCCESS) THEN
3727          x_return_status := fnd_api.g_ret_sts_error;
3728          FND_MESSAGE.set_name('BOM', 'CST_FAILED_DEFCOGS_RMA_INSERT');
3729          FND_MESSAGE.set_token('COGS_OM_LINE', to_char(p_cogs_om_line_id));
3730          FND_MESSAGE.set_token('MMT_TXN_ID',to_char(p_transaction_id));
3731          IF fnd_msg_pub.check_msg_level(fnd_msg_pub.g_msg_lvl_unexp_error) THEN
3732             FND_MSG_PUB.ADD;
3733          END IF;
3734          IF l_errorLog THEN
3735             FND_LOG.message(FND_LOG.LEVEL_ERROR, l_module||'.10',TRUE);
3736          END IF;
3737          raise program_exception;
3738       END IF;
3739 
3740    END IF;
3741 
3742    l_stmt_num := 20;
3743    /* Get the unit elemental costs and accounts for this sales order line ID */
3744    SELECT unit_material_cost,
3745           unit_moh_cost,
3746           unit_resource_cost,
3747           unit_op_cost,
3748           unit_overhead_cost,
3749           unit_cost,
3750           deferred_cogs_acct_id,
3751           cogs_acct_id
3752    INTO l_elemental_cost(1),
3753         l_elemental_cost(2),
3754         l_elemental_cost(3),
3755         l_elemental_cost(4),
3756         l_elemental_cost(5),
3757         l_unit_cost,
3758         l_def_cogs_acct_id,
3759         l_cogs_acct_id
3760    FROM cst_revenue_cogs_match_lines crcml
3761    WHERE cogs_om_line_id = p_cogs_om_line_id
3762    AND   pac_cost_type_id IS NULL;
3763 
3764    IF l_stmtLog THEN
3765       FND_LOG.string(FND_LOG.LEVEL_STATEMENT,l_module||'.20','Unit Material Cost = '||to_char(l_elemental_cost(1)));
3766       FND_LOG.string(FND_LOG.LEVEL_STATEMENT,l_module||'.20','Unit MOH Cost = '||to_char(l_elemental_cost(2)));
3767       FND_LOG.string(FND_LOG.LEVEL_STATEMENT,l_module||'.20','Unit Resource Cost = '||to_char(l_elemental_cost(3)));
3768       FND_LOG.string(FND_LOG.LEVEL_STATEMENT,l_module||'.20','Unit OSP Cost = '||to_char(l_elemental_cost(4)));
3769       FND_LOG.string(FND_LOG.LEVEL_STATEMENT,l_module||'.20','Unit OVHD Cost = '||to_char(l_elemental_cost(5)));
3770       FND_LOG.string(FND_LOG.LEVEL_STATEMENT,l_module||'.20','Unit Cost = '||to_char(l_unit_cost));
3771       FND_LOG.string(FND_LOG.LEVEL_STATEMENT,l_module||'.20','p_txn_quantity = '||to_char(p_txn_quantity));
3772       FND_LOG.string(FND_LOG.LEVEL_STATEMENT,l_module||'.20','l_cogs_percentage = '||to_char(l_cogs_percentage));
3773    END IF;
3774 
3775    FOR i IN 1..5 LOOP
3776       l_stmt_num := 40;
3777       l_cogs_credit_amount := l_elemental_cost(i) * -1 * p_txn_quantity * l_cogs_percentage;
3778       l_dcogs_credit_amount := (l_elemental_cost(i) * -1 * p_txn_quantity) - l_cogs_credit_amount;
3779 
3780       IF l_stmtLog THEN
3781          FND_LOG.string(FND_LOG.LEVEL_STATEMENT,l_module||'.40','Cost Element '||to_char(i)||' COGS Credit Amount = '||to_char(l_cogs_credit_amount));
3782          FND_LOG.string(FND_LOG.LEVEL_STATEMENT,l_module||'.40','Cost Element '||to_char(i)||' Deferred COGS Credit Amount = '||to_char(l_dcogs_credit_amount));
3783       END IF;
3784 
3785       IF (l_cogs_credit_amount <> 0) THEN
3786          l_stmt_num := 50;
3787          -- Create COGS distribution
3788          CSTPACDP.insert_account(p_organization_id, p_transaction_id, p_item_id, -1 * l_cogs_credit_amount,
3789                                  p_txn_quantity, l_cogs_acct_id, p_sob_id, COGS_LINE_TYPE,
3790                                  i, NULL,
3791                                  p_txn_date, p_txn_src_id, p_src_type_id,
3792                                  p_pri_curr, p_alt_curr, p_conv_date, p_conv_rate, p_conv_type,
3793                                  1,p_user_id, p_login_id, p_req_id, p_prg_appl_id,p_prg_id,
3794                                  l_err_num, l_err_code, l_err_msg);
3795       END IF;
3796 
3797       IF (l_dcogs_credit_amount <> 0) THEN
3798          l_stmt_num := 60;
3799          -- Create Deferred COGS distribution
3800          CSTPACDP.insert_account(p_organization_id, p_transaction_id, p_item_id, -1 * l_dcogs_credit_amount,
3801                                  p_txn_quantity, l_def_cogs_acct_id, p_sob_id, DEF_COGS_LINE_TYPE,
3802                                  i, NULL,
3803                                  p_txn_date, p_txn_src_id, p_src_type_id,
3804                                  p_pri_curr, p_alt_curr, p_conv_date, p_conv_rate, p_conv_type,
3805                                  1,p_user_id, p_login_id, p_req_id, p_prg_appl_id,p_prg_id,
3806                                  l_err_num, l_err_code, l_err_msg);
3807       END IF;
3808 
3809    END LOOP;
3810 
3811    l_stmt_num := 70;
3812    -- Mark the RMA event in CCE as costed
3813    UPDATE cst_cogs_events
3814    SET costed = NULL
3815    WHERE mmt_transaction_id = p_transaction_id;
3816 
3817 -- End API Body
3818 
3819    FND_MSG_PUB.count_and_get
3820      (  p_count  => x_msg_count
3821       , p_data   => x_msg_data
3822       , p_encoded => FND_API.g_false
3823      );
3824 
3825    IF l_proclog THEN
3826       fnd_log.string(FND_LOG.LEVEL_PROCEDURE,l_module||'.end',
3827         'Exiting '||G_PKG_NAME||'.'||l_api_name||' with '||
3828         'x_return_status = '||x_return_status
3829       );
3830    END IF;
3831 
3832 EXCEPTION
3833 
3834    WHEN program_exception THEN
3835          ROLLBACK TO Process_RmaReceipt_PVT;
3836          x_return_status := fnd_api.g_ret_sts_error ;
3837 
3838          FND_MESSAGE.set_name('BOM', 'CST_PLSQL_ERROR');
3839          FND_MESSAGE.set_token('PACKAGE', G_PKG_NAME);
3840          FND_MESSAGE.set_token('PROCEDURE',l_api_name);
3841          FND_MESSAGE.set_token('STATEMENT',to_char(l_stmt_num));
3842          IF fnd_msg_pub.check_msg_level(fnd_msg_pub.g_msg_lvl_error) THEN
3843             FND_MSG_PUB.ADD;
3844          END IF;
3845 
3846          IF l_errorLog THEN
3847             FND_LOG.MESSAGE(FND_LOG.LEVEL_ERROR,l_module||'.'||l_stmt_num,TRUE);
3848          END IF;
3849 
3850          FND_MSG_PUB.count_and_get
3851          (  p_count  => x_msg_count,
3852             p_data   => x_msg_data,
3853             p_encoded => FND_API.g_false
3854          );
3855 
3856    WHEN OTHERS THEN
3857          ROLLBACK TO Process_RmaReceipt_PVT;
3858          x_return_status := fnd_api.g_ret_sts_unexp_error ;
3859 
3860          IF l_unexpLog THEN
3861             FND_LOG.string(FND_LOG.LEVEL_UNEXPECTED,l_module||'.'||l_stmt_num
3862                 ,'Process_RmaReceipt '||to_char(l_stmt_num)||' : '||substr(SQLERRM,1,200));
3863          END IF;
3864 
3865          IF fnd_msg_pub.check_msg_level(fnd_msg_pub.g_msg_lvl_unexp_error) THEN
3866             FND_MESSAGE.set_name('BOM', 'CST_UNEXP_ERROR');
3867             FND_MESSAGE.set_token('PACKAGE', G_PKG_NAME);
3868             FND_MESSAGE.set_token('PROCEDURE',l_api_name);
3869             FND_MESSAGE.set_token('STATEMENT',to_char(l_stmt_num));
3870             FND_MSG_PUB.ADD;
3871          END IF;
3872 
3873          FND_MSG_PUB.count_and_get
3874           (  p_count  => x_msg_count
3875             , p_data   => x_msg_data
3876             , p_encoded => FND_API.g_false
3877            );
3878 
3879 END Process_RmaReceipt;
3880 
3881 -----------------------------------------------------------------------------
3882 -- Start of comments                                                       --
3883 --                                                                         --
3884 -- PROCEDURE                                                               --
3885 --  Process_CogsRecognitionTxn                                             --
3886 --           This procedure is called by the distribution processors for   --
3887 --           all perpetual cost methods to create the accounting entries   --
3888 --           for COGS Recognition Events.                                  --
3889 --                                                                         --
3890 -- VERSION 1.0                                                             --
3891 --                                                                         --
3892 -- PARAMETERS                                                              --
3893 --  P_COGS_OM_LINE_ID    OM Line_ID of the Sales Order issue               --
3894 --  All other parameters are pretty standard for Cost Processing           --
3895 --                                                                         --
3896 -- HISTORY:                                                                --
3897 --    05/17/05     Bryan Kuntz      Created                                --
3898 -- End of comments                                                         --
3899 -----------------------------------------------------------------------------
3900 
3901 PROCEDURE Process_CogsRecognitionTxn(
3902                 x_return_status         OUT NOCOPY  VARCHAR2,
3903                 x_msg_count             OUT NOCOPY  NUMBER,
3904                 x_msg_data              OUT NOCOPY  VARCHAR2,
3905                 p_cogs_om_line_id       IN  NUMBER,
3906                 p_transaction_id        IN  NUMBER,
3907                 p_txn_quantity          IN  NUMBER,
3908                 p_organization_id       IN  NUMBER,
3909                 p_item_id               IN  NUMBER,
3910                 p_sob_id                IN  NUMBER,
3911                 p_txn_date              IN  DATE,
3912                 p_txn_src_id            IN  NUMBER,
3913                 p_src_type_id           IN  NUMBER,
3914                 p_pri_curr              IN  VARCHAR2,
3915                 p_alt_curr              IN  VARCHAR2,
3916                 p_conv_date             IN  DATE,
3917                 p_conv_rate             IN  NUMBER,
3918                 p_conv_type             IN  VARCHAR2,
3919                 p_user_id               IN  NUMBER,
3920                 p_login_id              IN  NUMBER,
3921                 p_req_id                IN  NUMBER,
3922                 p_prg_appl_id           IN  NUMBER,
3923                 p_prg_id                IN  NUMBER
3924 ) IS
3925 
3926    l_api_name            CONSTANT VARCHAR2(30)  := 'Process_CogsRecognitionTxn';
3927    l_api_message         VARCHAR2(1000);
3928    l_stmt_num            NUMBER         := 0;
3929    l_module   CONSTANT VARCHAR2(100)        := G_LOG_HEAD ||'.'||l_api_name;
3930    l_unexpLog CONSTANT BOOLEAN := (FND_LOG.LEVEL_UNEXPECTED >= G_LOG_LEVEL) AND FND_LOG.TEST(FND_LOG.LEVEL_UNEXPECTED, l_module);
3931    l_errorLog CONSTANT BOOLEAN := l_unexpLog and (FND_LOG.LEVEL_ERROR >= G_LOG_LEVEL);
3932    l_eventLog CONSTANT BOOLEAN := l_errorLog and (FND_LOG.LEVEL_EVENT >= G_LOG_LEVEL);
3933    l_procLog  CONSTANT BOOLEAN := l_eventLog and (FND_LOG.LEVEL_PROCEDURE >= G_LOG_LEVEL);
3934    l_stmtLog  CONSTANT BOOLEAN := l_procLog  and (FND_LOG.LEVEL_STATEMENT >= G_LOG_LEVEL);
3935 
3936    l_new_percentage      NUMBER;
3937    l_prior_percentage    NUMBER;
3938 
3939    l_elemental_cost      number_table;
3940    l_def_cogs_acct_id    NUMBER;
3941    l_cogs_acct_id        NUMBER;
3942 
3943    l_adjustment_amount   NUMBER;
3944 
3945    l_err_num             NUMBER;
3946    l_err_code            VARCHAR2(240);
3947    l_err_msg             VARCHAR2(240);
3948 
3949 BEGIN
3950 
3951 -- Standard start of API savepoint
3952    SAVEPOINT Process_CogsRecognitionTxn_PVT;
3953 
3954    l_stmt_num := 0;
3955 
3956    IF l_proclog THEN
3957       fnd_log.string(FND_LOG.LEVEL_PROCEDURE,l_module||'.begin',
3958         'Entering '||G_PKG_NAME||'.'||l_api_name||' with '||
3959         'p_cogs_om_line_id = '||p_cogs_om_line_id||','||
3960         'p_transaction_id = '||p_transaction_id||','||
3961         'p_txn_quantity = '||p_txn_quantity||','||
3962         'p_organization_id = '||p_organization_id||','||
3963         'p_item_id = '||p_item_id||','||
3964         'p_sob_id = '||p_sob_id||','||
3965         'p_txn_date = '||to_char(p_txn_date,'MM-DD-YYYY')||','||
3966         'p_txn_src_id = '||p_txn_src_id||','||
3967         'p_src_type_id = '||p_src_type_id||','||
3968         'p_pri_curr = '||p_pri_curr||','||
3969         'p_alt_curr = '||p_alt_curr||','||
3970         'p_conv_date = '||to_char(p_conv_date,'MM-DD-YYYY')||','||
3971         'p_conv_rate = '||p_conv_rate||','||
3972         'p_conv_type = '||p_conv_type
3973       );
3974    END IF;
3975 
3976 -- Initialize API return status to success
3977    x_return_status := FND_API.G_RET_STS_SUCCESS;
3978    x_msg_count := 0;
3979    x_msg_data := '';
3980 
3981 -- API Body
3982 
3983    -- Retrieve the COGS percentage and prior COGS percentage for this
3984    -- event while marking it as costed
3985    l_stmt_num := 10;
3986    UPDATE cst_cogs_events
3987    SET  costed = NULL
3988    WHERE mmt_transaction_id = p_transaction_id
3989    RETURNING cogs_percentage,
3990              prior_cogs_percentage
3991    INTO l_new_percentage,
3992         l_prior_percentage;
3993 
3994 
3995    -- Need the [elemental] unit costs, as well as the accounts from the
3996    -- original sales order to make the COGS adjustment
3997    l_stmt_num := 20;
3998    SELECT unit_material_cost,
3999           unit_moh_cost,
4000           unit_resource_cost,
4001           unit_op_cost,
4002           unit_overhead_cost,
4003           cogs_acct_id,
4004           deferred_cogs_acct_id
4005    INTO l_elemental_cost(1),
4006         l_elemental_cost(2),
4007         l_elemental_cost(3),
4008         l_elemental_cost(4),
4009         l_elemental_cost(5),
4010         l_cogs_acct_id,
4011         l_def_cogs_acct_id
4012    FROM cst_revenue_cogs_match_lines crcml
4013    WHERE cogs_om_line_id = p_cogs_om_line_id
4014    AND   pac_cost_type_id IS NULL;
4015 
4016    FOR i IN 1..5 LOOP
4017       l_stmt_num := 30;
4018       l_adjustment_amount := l_elemental_cost(i) * p_txn_quantity * (l_new_percentage - l_prior_percentage);
4019 
4020       IF (l_adjustment_amount <> 0) THEN
4021          -- Dr. COGS
4022          l_stmt_num := 40;
4023          CSTPACDP.insert_account(p_organization_id, p_transaction_id, p_item_id, l_adjustment_amount,
4024                                  p_txn_quantity, l_cogs_acct_id, p_sob_id, COGS_LINE_TYPE,
4025                                  i, NULL,
4026                                  p_txn_date, p_txn_src_id, p_src_type_id,
4027                                  p_pri_curr, p_alt_curr, p_conv_date, p_conv_rate, p_conv_type,
4028                                  1,p_user_id, p_login_id, p_req_id, p_prg_appl_id,p_prg_id,
4029                                  l_err_num, l_err_code, l_err_msg);
4030 
4031          l_stmt_num := 50;
4032          -- Cr. Deferred COGS
4033          CSTPACDP.insert_account(p_organization_id, p_transaction_id, p_item_id, -1 * l_adjustment_amount,
4034                                  -1 * p_txn_quantity, l_def_cogs_acct_id, p_sob_id, DEF_COGS_LINE_TYPE,
4035                                  i, NULL,
4036                                  p_txn_date, p_txn_src_id, p_src_type_id,
4037                                  p_pri_curr, p_alt_curr, p_conv_date, p_conv_rate, p_conv_type,
4038                                  1,p_user_id, p_login_id, p_req_id, p_prg_appl_id,p_prg_id,
4039                                  l_err_num, l_err_code, l_err_msg);
4040       END IF;
4041 
4042    END LOOP;
4043 
4044 
4045 -- End API Body
4046 
4047    FND_MSG_PUB.count_and_get
4048      (  p_count  => x_msg_count
4049       , p_data   => x_msg_data
4050       , p_encoded => FND_API.g_false
4051      );
4052 
4053    IF l_proclog THEN
4054       fnd_log.string(FND_LOG.LEVEL_PROCEDURE,l_module||'.end',
4055         'Exiting '||G_PKG_NAME||'.'||l_api_name||' with '||
4056         'x_return_status = '||x_return_status
4057       );
4058    END IF;
4059 
4060 EXCEPTION
4061    WHEN OTHERS THEN
4062          ROLLBACK TO Process_CogsRecognitionTxn_PVT;
4063          x_return_status := fnd_api.g_ret_sts_unexp_error ;
4064 
4065          IF l_unexpLog THEN
4066             FND_LOG.string(FND_LOG.LEVEL_UNEXPECTED,G_LOG_HEAD || '.'||l_api_name||l_stmt_num
4067                 ,'Process_CogsRecognitionTxn ('||to_char(l_stmt_num)||') : '||substr(SQLERRM,1,200));
4068          END IF;
4069 
4070          IF fnd_msg_pub.check_msg_level(fnd_msg_pub.g_msg_lvl_unexp_error) THEN
4071             FND_MESSAGE.set_name('BOM', 'CST_UNEXP_ERROR');
4072             FND_MESSAGE.set_token('PACKAGE', G_PKG_NAME);
4073             FND_MESSAGE.set_token('PROCEDURE',l_api_name);
4074             FND_MESSAGE.set_token('STATEMENT',to_char(l_stmt_num));
4075             FND_MSG_PUB.ADD;
4076          END IF;
4077 
4078          FND_MSG_PUB.count_and_get
4079           (  p_count  => x_msg_count
4080             , p_data   => x_msg_data
4081             , p_encoded => FND_API.g_false
4082            );
4083 
4084 END Process_CogsRecognitionTxn;
4085 
4086 
4087 -----------------------------------------------------------------------------
4088 -- Start of comments                                                       --
4089 --                                                                         --
4090 -- PROCEDURE                                                               --
4091 --  Cost_BulkCogsRecTxns                                                   --
4092 --           This procedure is called in phase 4 of the concurrent request --
4093 --           to create the accounting distributions for all of the COGS    --
4094 --           Recognition Events that were created during this run of the   --
4095 --           concurrent request.                                           --
4096 --                                                                         --
4097 -- VERSION 1.0                                                             --
4098 --                                                                         --
4099 -- PARAMETERS                                                              --
4100 --     Standard return status and Who columns                              --
4101 --                                                                         --
4102 -- HISTORY:                                                                --
4103 --    05/17/05     Bryan Kuntz      Created                                --
4104 -- End of comments                                                         --
4105 -----------------------------------------------------------------------------
4106 
4107 PROCEDURE Cost_BulkCogsRecTxns(
4108                 x_return_status   OUT NOCOPY  VARCHAR2,
4109                 p_request_id      IN   NUMBER,
4110                 p_user_id         IN   NUMBER,
4111                 p_login_id        IN   NUMBER,
4112                 p_pgm_app_id      IN   NUMBER,
4113                 p_pgm_id          IN   NUMBER,
4114                 p_ledger_id       IN   NUMBER DEFAULT NULL   --BUG5726230
4115                ,p_neg_req_id      IN   NUMBER DEFAULT NULL   --BUG7387575
4116 ) IS
4117 
4118    l_api_name            CONSTANT VARCHAR2(30)  := 'Cost_BulkCogsRecTxns';
4119    l_api_message         VARCHAR2(1000);
4120    l_module   CONSTANT VARCHAR2(100)        := G_LOG_HEAD ||'.'||l_api_name;
4121    l_unexpLog CONSTANT BOOLEAN := (FND_LOG.LEVEL_UNEXPECTED >= G_LOG_LEVEL) AND FND_LOG.TEST(FND_LOG.LEVEL_UNEXPECTED, l_module);
4122    l_errorLog CONSTANT BOOLEAN := l_unexpLog and (FND_LOG.LEVEL_ERROR >= G_LOG_LEVEL);
4123    l_eventLog CONSTANT BOOLEAN := l_errorLog and (FND_LOG.LEVEL_EVENT >= G_LOG_LEVEL);
4124    l_procLog  CONSTANT BOOLEAN := l_eventLog and (FND_LOG.LEVEL_PROCEDURE >= G_LOG_LEVEL);
4125    l_stmtLog  CONSTANT BOOLEAN := l_procLog  and (FND_LOG.LEVEL_STATEMENT >= G_LOG_LEVEL);
4126 
4127    l_return_status       VARCHAR2(1)    := FND_API.G_RET_STS_SUCCESS;
4128    l_stmt_num            NUMBER         := 0;
4129 
4130    CURSOR c_uncosted_cogs_events(p_sob_id  IN NUMBER) IS
4131       SELECT cce.cogs_om_line_id,
4132              cce.mmt_transaction_id,
4133              cce.cogs_percentage,
4134              cce.prior_cogs_percentage,
4135              cce.event_quantity,
4136             --{BUG#6980119
4137             -- cce.event_date,
4138              mmt.transaction_date,
4139             --}
4140              cce.event_id,
4141              cce.event_type,
4142              crcml.operating_unit_id,
4143              crcml.organization_id,
4144              crcml.cogs_acct_id,
4145              crcml.deferred_cogs_acct_id,
4146              crcml.inventory_item_id,
4147              crcml.unit_material_cost,
4148              crcml.unit_moh_cost,
4149              crcml.unit_resource_cost,
4150              crcml.unit_op_cost,
4151              crcml.unit_overhead_cost,
4152              crcml.unit_cost,
4153              sob.currency_code,
4154 	     NVL(mmt.transaction_source_id, -1)
4155       FROM cst_cogs_events              cce,
4156            cst_revenue_cogs_match_lines crcml,
4157            mtl_parameters               mp,
4158            gl_sets_of_books             sob,
4159            mtl_material_transactions    mmt -- joining here to use the index on costed_flag
4160       WHERE
4161             cce.mmt_transaction_id         = mmt.transaction_id
4162       AND   mmt.costed_flag                = 'N'
4163       AND   mmt.transaction_action_id      = 36
4164       AND   mmt.transaction_source_type_id = 2
4165       ---------------------------------------
4166       -- When the Cogs Recognition program reaches this point the MMT for COGS Regnition are commited to the DB
4167       -- The COGS Recognition program is still running and the Cost Manager should not start as it is incompatible
4168       -- with the Cogs Recognition program. Hence normally the MMT will not be picked up by the Cost Worker
4169       -- But in the case this phase of insertion into MTA stops by user action or by env issue
4170       -- Next time the Cost Manager could have launch the cost worker and during its run the COGS regnition
4171       -- program can start causing the MMT being costed by both program
4172       -- We add the condition transaction_group_id IS NULL as this is the first action the Cost Manager does
4173       -- stamping the transaction_group_id before assigning the job to cost worker and goes back to pending
4174       -- If the MMT is selected by Cost Manager, COGS recognition program should not pick it up
4175       ---------------------------------------
4176       AND   mmt.transaction_group_id         IS NULL --BUG#6730436
4177       AND   cce.costed                        = 'N'
4178       AND   cce.event_type                   IN (COGS_RECOGNITION_EVENT,
4179                                                  COGS_REC_PERCENT_ADJUSTMENT,
4180                                                  COGS_REC_QTY_ADJUSTMENT)
4181       AND   crcml.cogs_om_line_id             = cce.cogs_om_line_id
4182       AND   crcml.pac_cost_type_id           IS NULL
4183       AND   crcml.ledger_id                   = p_sob_id
4184       AND   crcml.original_shipped_qty       IS NOT NULL -- indicator of whether the SO Issue was costed.
4185       AND   crcml.organization_id             = mp.organization_id
4186       AND   nvl(mp.process_enabled_flag, 'N') = 'N'  -- Cost only discrete orgs
4187       AND   crcml.ledger_id                   = sob.set_of_books_id
4188       AND   DECODE(p_neg_req_id,NULL,-99,p_neg_req_id)
4189 	           =    DECODE(p_neg_req_id,NULL,-99,mmt.transaction_set_id); --BUG#7387575
4190 
4191 
4192     --{BUG#5726230
4193     CURSOR cu_ledger(p_ledger_id IN NUMBER) IS
4194     SELECT DISTINCT set_of_books_id
4195       FROM gl_sets_of_books
4196 	 WHERE set_of_books_id = NVL(p_ledger_id, set_of_books_id);
4197 
4198    l_ledger_id_tab               number_table;
4199    l_sob                         NUMBER;
4200    --}
4201    l_cogs_om_line_id_tbl         number_table;
4202    l_mmt_txn_id_tbl              number_table;
4203    l_cogs_percentage_tbl         number_table;
4204    l_prior_percentage_tbl        number_table;
4205    l_event_quantity_tbl          number_table;
4206    l_event_date_tbl              date_table;
4207    l_event_id_tbl                number_table;
4208    l_event_type_tbl              number_table;
4209    l_ou_id_tbl                   number_table;
4210    l_organization_id_tbl         number_table;
4211    l_cogs_acct_id_tbl            number_table;
4212    l_def_cogs_acct_id_tbl        number_table;
4213    l_item_id_tbl                 number_table;
4214    l_e1_tbl                      number_table;
4215    l_e2_tbl                      number_table;
4216    l_e3_tbl                      number_table;
4217    l_e4_tbl                      number_table;
4218    l_e5_tbl                      number_table;
4219    l_unit_cost_tbl               number_table;
4220    l_currency_code_tbl           char15_table;
4221    l_ou_offset_tbl               number_table;
4222    l_le_date_tbl                 date_table;
4223    l_transaction_source_id       number_table;
4224 
4225    l_last_fetch                  BOOLEAN;
4226    end_of_program                EXCEPTION;
4227 BEGIN
4228 
4229 -- Standard start of API savepoint
4230    SAVEPOINT Cost_BulkCogsRecTxns_PVT;
4231 
4232    l_stmt_num := 0;
4233 
4234    IF l_procLog THEN
4235      FND_LOG.string(FND_LOG.LEVEL_PROCEDURE,l_module||'.begin',
4236         'Entering '||G_PKG_NAME||'.'||l_api_name
4237      );
4238    END IF;
4239 
4240 -- Initialize API return status to success
4241    x_return_status := FND_API.G_RET_STS_SUCCESS;
4242 
4243 -- API Body
4244    -- Need to loop by set of books (ledger) because the call to the SLA
4245    -- API requires the ledger as an input parameter.  So we'll have to
4246    -- cost the events ledger by ledger.
4247 
4248    debug('  p_ledger_id :'||p_ledger_id);
4249 
4250    --{BUG5726230
4251    OPEN cu_ledger(p_ledger_id);
4252    FETCH cu_ledger BULK COLLECT INTO l_ledger_id_tab;
4253    CLOSE cu_ledger;
4254 
4255    IF l_ledger_id_tab.COUNT = 0 THEN
4256       RAISE end_of_program;
4257    END IF;
4258 
4259    <<ledger_loop>>
4260 --   FOR l_sob_id IN (SELECT distinct set_of_books_id FROM gl_sets_of_books) LOOP
4261    FOR i IN l_ledger_id_tab.FIRST .. l_ledger_id_tab.LAST LOOP
4262    --}
4263       l_sob  := l_ledger_id_tab(i);
4264       debug(' processing for the ledger:'||l_sob);
4265       l_last_fetch := FALSE; -- initialize boolean variable
4266 
4267       OPEN c_uncosted_cogs_events(l_sob);  --(l_sob_id.set_of_books_id);
4268 
4269       <<uncosted_events_loop>>
4270       LOOP
4271          -- Get 1000 rows or less from the uncosted events cursor
4272          l_stmt_num := 10;
4273          FETCH c_uncosted_cogs_events BULK COLLECT INTO
4274             l_cogs_om_line_id_tbl,
4275             l_mmt_txn_id_tbl,
4276             l_cogs_percentage_tbl,
4277             l_prior_percentage_tbl,
4278             l_event_quantity_tbl,
4279             l_event_date_tbl,
4280             l_event_id_tbl,
4281             l_event_type_tbl,
4282             l_ou_id_tbl,
4283             l_organization_id_tbl,
4284             l_cogs_acct_id_tbl,
4285             l_def_cogs_acct_id_tbl,
4286             l_item_id_tbl,
4287             l_e1_tbl,
4288             l_e2_tbl,
4289             l_e3_tbl,
4290             l_e4_tbl,
4291             l_e5_tbl,
4292             l_unit_cost_tbl,
4293             l_currency_code_tbl,
4294             l_transaction_source_id
4295          LIMIT C_max_bulk_fetch_size;
4296 
4297          IF c_uncosted_cogs_events%NOTFOUND THEN
4298             l_last_fetch := TRUE;
4299          END IF;
4300 
4301          IF (l_cogs_om_line_id_tbl.COUNT = 0 AND l_last_fetch) THEN
4302             CLOSE c_uncosted_cogs_events;
4303             EXIT uncosted_events_loop;
4304          END IF;
4305 
4306          -- Populate the legal entity dates table using each OU from above
4307          FOR i IN l_event_id_tbl.FIRST..l_event_id_tbl.LAST LOOP
4308 
4309            IF NOT l_ou_offset_tbl.EXISTS(l_ou_id_tbl(i)) THEN
4310 
4311              l_ou_offset_tbl(l_ou_id_tbl(i)) := INV_LE_TIMEZONE_PUB.get_le_day_time_for_ou(
4312                                                   SYSDATE, l_ou_id_tbl(i)) - SYSDATE;
4313 
4314            END IF;
4315 
4316            l_le_date_tbl(i) := l_event_date_tbl(i) + l_ou_offset_tbl(l_ou_id_tbl(i));
4317 
4318          END LOOP;
4319 
4320          l_stmt_num := 20;
4321          -- To help create debits and credits in bulk, insert 2 simple rows in
4322          -- cst_lists_temp with opposite signs
4323          -- These insertions are inside the loop because the commit at stmt 80
4324          -- blows these away.
4325          -- Keeping these inserts inside the loop (instead of doing once outside
4326          -- the loop) in case the definition of the cst_lists_temp table ever
4327          -- changes from session to txn based.  If the definition changes, there
4328          -- is no need to change it here since I'm deleting and reinserting each
4329          -- commit cycle.
4330          DELETE cst_lists_temp;
4331 
4332          INSERT INTO cst_lists_temp (list_id)
4333          VALUES (1); -- Dr.
4334 
4335          INSERT INTO cst_lists_temp (list_id)
4336          VALUES (-1); -- Cr.
4337 
4338          -- The following statement will create elemental distributions for all source rows returned
4339          -- by the above cursor.
4340          l_stmt_num := 30;
4341          FORALL i IN l_event_id_tbl.FIRST..l_event_id_tbl.LAST
4342             INSERT INTO mtl_transaction_accounts mta (
4343                          TRANSACTION_ID,
4344                          REFERENCE_ACCOUNT,
4345                          INVENTORY_ITEM_ID,
4346                          ORGANIZATION_ID,
4347                          TRANSACTION_DATE,
4348                          TRANSACTION_SOURCE_ID,
4349                          GL_BATCH_ID,
4350                          ACCOUNTING_LINE_TYPE,
4351                          BASE_TRANSACTION_VALUE,
4352                          CONTRA_SET_ID,
4353                          TRANSACTION_SOURCE_TYPE_ID,
4354                          PRIMARY_QUANTITY,
4355                          RATE_OR_AMOUNT,
4356                          BASIS_TYPE,
4357                          COST_ELEMENT_ID,
4358                          INV_SUB_LEDGER_ID,
4359                          -- WHO COLUMNS
4360                          LAST_UPDATE_DATE,
4361                          LAST_UPDATED_BY,
4362                          CREATION_DATE,
4363                          CREATED_BY,
4364                          LAST_UPDATE_LOGIN,
4365                          REQUEST_ID,
4366                          PROGRAM_APPLICATION_ID,
4367                          PROGRAM_ID,
4368                          PROGRAM_UPDATE_DATE)
4369             SELECT  l_mmt_txn_id_tbl(i),
4370                     decode(clt.list_id, 1, l_cogs_acct_id_tbl(i), -1, l_def_cogs_acct_id_tbl(i), NULL),
4371                     l_item_id_tbl(i),
4372                     l_organization_id_tbl(i),
4373                     l_event_date_tbl(i),
4374                     l_transaction_source_id(i), -- txn_source_id is not necessary, this column is NOT NULL by mistake
4375                     NULL, -- GL batch ID
4376                     decode(clt.list_id, 1, COGS_LINE_TYPE, -1, DEF_COGS_LINE_TYPE, NULL),
4377                     decode(fc.minimum_accountable_unit, NULL,
4378                        ROUND(clt.list_id * l_event_quantity_tbl(i) * (l_cogs_percentage_tbl(i) - l_prior_percentage_tbl(i)) *
4379                              decode(cce.cost_element_id, 1, l_e1_tbl(i),  2, l_e2_tbl(i),  3, l_e3_tbl(i),
4380                                                          4, l_e4_tbl(i),  5, l_e5_tbl(i),  0), fc.precision),
4381                        ROUND(clt.list_id * l_event_quantity_tbl(i) * (l_cogs_percentage_tbl(i) - l_prior_percentage_tbl(i)) *
4382                              decode(cce.cost_element_id, 1, l_e1_tbl(i),  2, l_e2_tbl(i),  3, l_e3_tbl(i),
4383                                                          4, l_e4_tbl(i),  5, l_e5_tbl(i),  0) / fc.minimum_accountable_unit)
4384                           * fc.minimum_accountable_unit),
4385                     1, -- contra set ID
4386                     2, -- transaction source type ID for COGS Recognition Events
4387                     clt.list_id * l_event_quantity_tbl(i),
4388                     clt.list_id * (l_cogs_percentage_tbl(i) - l_prior_percentage_tbl(i)) *
4389                                           decode(cce.cost_element_id,
4390                                                  1, l_e1_tbl(i),
4391                                                  2, l_e2_tbl(i),
4392                                                  3, l_e3_tbl(i),
4393                                                  4, l_e4_tbl(i),
4394                                                  5, l_e5_tbl(i),
4395                                                  0),
4396                     1, -- basis type
4397                     cce.cost_element_id,
4398                     cst_inv_sub_ledger_id_s.nextval,
4399                     -- WHO COLUMNS
4400                     sysdate,
4401                     p_user_id,
4402                     sysdate,
4403                     p_user_id,
4404                     p_login_id,
4405                     p_request_id,
4406                     p_pgm_app_id,
4407                     p_pgm_id,
4408                     sysdate
4409             FROM  cst_cost_elements cce,
4410                   cst_lists_temp    clt,
4411                   fnd_currencies    fc
4412             WHERE fc.currency_code         = l_currency_code_tbl(i)
4413             AND   l_event_quantity_tbl(i)  <> 0
4414             AND   l_cogs_percentage_tbl(i) <> l_prior_percentage_tbl(i)
4415             AND   nvl(decode(cce.cost_element_id,
4416                          1, l_e1_tbl(i),
4417                          2, l_e2_tbl(i),
4418                          3, l_e3_tbl(i),
4419                          4, l_e4_tbl(i),
4420                          5, l_e5_tbl(i),
4421                          0),0) <> 0;
4422 
4423          l_stmt_num := 40;
4424          -- Update the costed flag in cst_cogs_events
4425          FORALL i IN l_event_id_tbl.FIRST..l_event_id_tbl.LAST
4426             UPDATE cst_cogs_events
4427             SET costed            = NULL,
4428                 last_update_date  = sysdate,
4429                 last_updated_by   = p_user_id,
4430                 last_update_login = p_login_id,
4431                 request_id        = p_request_id
4432             WHERE event_id = l_event_id_tbl(i);
4433 
4434          l_stmt_num := 50;
4435          -- Update the costed flag in MMT
4436          FORALL i IN l_event_id_tbl.FIRST..l_event_id_tbl.LAST
4437             UPDATE mtl_material_transactions
4438             SET costed_flag            = NULL,
4439                 last_update_date       = sysdate,
4440                 last_updated_by        = p_user_id,
4441                 last_update_login      = p_login_id,
4442                 request_id             = p_request_id,
4443                 program_application_id = p_pgm_app_id,
4444                 program_id             = p_pgm_id,
4445                 program_update_date    = sysdate
4446             WHERE transaction_id = l_mmt_txn_id_tbl(i);
4447 
4448          -- Pass events to SLA via a bulk insertion into their Global Temp Table
4449 
4450          l_stmt_num := 60;
4451          FORALL i IN l_event_id_tbl.FIRST..l_event_id_tbl.LAST
4452             INSERT INTO xla_events_int_gt
4453                (
4454                   application_id,
4455                   ledger_id,
4456                   entity_code,
4457                   source_id_int_1,
4458                   source_id_int_2,
4459                   source_id_int_3,
4460                   event_class_code,
4461                   event_type_code,
4462                   event_date,
4463                   event_status_code,
4464                   security_id_int_1,
4465                   security_id_int_2,
4466                   transaction_date,
4467                   reference_date_1,
4468                   transaction_number
4469                )
4470             SELECT
4471                   707,
4472                   l_sob,  --l_sob_id.set_of_books_id,
4473                   'MTL_ACCOUNTING_EVENTS',
4474                   l_mmt_txn_id_tbl(i),
4475                   l_organization_id_tbl(i),
4476                   2, -- source type ID for sales order related txns
4477                   'SALES_ORDER',
4478                   decode(l_event_type_tbl(i), COGS_RECOGNITION_EVENT     , 'COGS_RECOGNITION',
4479                                               COGS_REC_PERCENT_ADJUSTMENT, 'COGS_RECOGNITION_ADJ',
4480                                               COGS_REC_QTY_ADJUSTMENT    , 'COGS_RECOGNITION_ADJ',
4481                                               NULL),
4482                   l_event_date_tbl(i),
4483                   XLA_EVENTS_PUB_PKG.C_EVENT_UNPROCESSED,
4484                   l_organization_id_tbl(i),
4485                   l_ou_id_tbl(i),
4486                   l_event_date_tbl(i),
4487                   l_le_date_tbl(i),
4488                   l_mmt_txn_id_tbl(i)
4489             FROM
4490                   mtl_parameters mp,
4491                   pjm_org_parameters pop
4492             WHERE mp.organization_id           = l_organization_id_tbl(i)
4493 	        AND   pop.organization_id (+)      = mp.organization_id
4494             AND   NVL(pop.pa_posting_flag,'N') <> 'Y';
4495 
4496          l_stmt_num := 70;
4497          -- Call this API to instruct SLA to create these events from
4498          -- the data just populated in the global temp table.
4499          xla_events_pub_pkg.create_bulk_events(p_application_id        => 707,
4500                                                p_ledger_id             => l_sob,   --l_sob_id.set_of_books_id,
4501                                                p_entity_type_code      => 'MTL_ACCOUNTING_EVENTS',
4502                                                p_source_application_id => 401);
4503 
4504          l_stmt_num := 80;
4505          commit; -- commit the processing of 1000 input rows at a time
4506          SAVEPOINT Cost_BulkCogsRecTxns_PVT;
4507 
4508       END LOOP uncosted_events_loop;
4509    END LOOP ledger_loop;
4510 
4511 
4512 -- End API Body
4513 
4514    IF l_proclog THEN
4515       fnd_log.string(FND_LOG.LEVEL_PROCEDURE,l_module||'.end',
4516         'Exiting '||G_PKG_NAME||'.'||l_api_name||' with '||
4517         'x_return_status = '||x_return_status
4518       );
4519    END IF;
4520 
4521 EXCEPTION
4522    WHEN end_of_program THEN
4523        ROLLBACK TO Cost_BulkCogsRecTxns_PVT;
4524        -- Let the program end normally
4525        x_return_status := FND_API.G_RET_STS_SUCCESS;
4526        debug('EXCEPTION end_of_program - Cost_BulkCogsRecTxns '||l_stmt_num||' : no ledger found - p_ledger_id :'||p_ledger_id);
4527 
4528    WHEN OTHERS THEN
4529          ROLLBACK TO Cost_BulkCogsRecTxns_PVT;
4530          x_return_status := fnd_api.g_ret_sts_unexp_error ;
4531 
4532          IF l_unexpLog THEN
4533             FND_LOG.string(FND_LOG.LEVEL_UNEXPECTED,G_LOG_HEAD || '.'||l_api_name||l_stmt_num
4534                 ,'Cost_BulkCogsRecTxns '||to_char(l_stmt_num)||' : '||substr(SQLERRM,1,200));
4535          END IF;
4536 
4537          IF fnd_msg_pub.check_msg_level(fnd_msg_pub.g_msg_lvl_unexp_error) THEN
4538             FND_MESSAGE.set_name('BOM', 'CST_UNEXP_ERROR');
4539             FND_MESSAGE.set_token('PACKAGE', G_PKG_NAME);
4540             FND_MESSAGE.set_token('PROCEDURE',l_api_name);
4541             FND_MESSAGE.set_token('STATEMENT',to_char(l_stmt_num));
4542             FND_MSG_PUB.ADD;
4543          END IF;
4544 
4545 END Cost_BulkCogsRecTxns;
4546 
4547 
4548 -----------------------------------------------------------------------------
4549 -- Start of comments                                                       --
4550 --                                                                         --
4551 -- PROCEDURE                                                               --
4552 --  Insert_PacSoIssue    This is the PAC version of Insert_OneSoIssue().   --
4553 --             It creates a new row in CRCML for the given OM Line ID and  --
4554 --             PAC cost type ID.  The purpose is to record the SO issue    --
4555 --             cost so that future related events (e.g. COGS Recognition)  --
4556 --             can query this row and create accting with these amounts.   --
4557 --                                                                         --
4558 -- VERSION 1.0                                                             --
4559 --                                                                         --
4560 -- PARAMETERS                                                              --
4561 --  P_TRANSACTION_ID     MMT Transaction ID                                --
4562 --  P_LAYER_ID           PAC Cost Layer ID (CPIC, CPICD)                   --
4563 --  P_COST_TYPE_ID       PAC Cost Type ID                                  --
4564 --  P_COST_GROUP_ID      PAC Cost Group ID                                 --
4565 --                                                                         --
4566 -- HISTORY:                                                                --
4567 --    06/27/05     Bryan Kuntz      Created                                --
4568 -- End of comments                                                         --
4569 -----------------------------------------------------------------------------
4570 PROCEDURE Insert_PacSoIssue(
4571                 p_api_version      IN  NUMBER,
4572                 p_init_msg_list    IN  VARCHAR2 := FND_API.G_FALSE,
4573                 p_commit           IN  VARCHAR2 := FND_API.G_FALSE,
4574                 p_validation_level IN  NUMBER   := FND_API.G_VALID_LEVEL_FULL,
4575                 x_return_status    OUT NOCOPY VARCHAR2,
4576                 x_msg_count        OUT NOCOPY NUMBER,
4577                 x_msg_data         OUT NOCOPY VARCHAR2,
4578                 p_transaction_id   IN  NUMBER,
4579                 p_layer_id         IN  NUMBER,
4580                 p_cost_type_id     IN  NUMBER,
4581                 p_cost_group_id    IN  NUMBER,
4582                 p_user_id          IN  NUMBER,
4583                 p_login_id         IN  NUMBER,
4584                 p_request_id       IN  NUMBER,
4585                 p_pgm_app_id       IN  NUMBER,
4586                 p_pgm_id           IN  NUMBER
4587 ) IS
4588 
4589    l_api_name               CONSTANT VARCHAR2(30)  := 'Insert_PacSoIssue';
4590    l_api_version            CONSTANT NUMBER        := 1.0;
4591    l_stmt_num               NUMBER                 := 0;
4592 
4593    l_module   CONSTANT VARCHAR2(100)        := G_LOG_HEAD ||'.'||l_api_name||'.';
4594    l_unexpLog CONSTANT BOOLEAN := (FND_LOG.LEVEL_UNEXPECTED >= G_LOG_LEVEL) AND FND_LOG.TEST(FND_LOG.LEVEL_UNEXPECTED, l_module);
4595    l_errorLog CONSTANT BOOLEAN := l_unexpLog and (FND_LOG.LEVEL_ERROR >= G_LOG_LEVEL);
4596    l_eventLog CONSTANT BOOLEAN := l_errorLog and (FND_LOG.LEVEL_EVENT >= G_LOG_LEVEL);
4597    l_procLog  CONSTANT BOOLEAN := l_eventLog and (FND_LOG.LEVEL_PROCEDURE >= G_LOG_LEVEL);
4598    l_stmtLog  CONSTANT BOOLEAN := l_procLog  and (FND_LOG.LEVEL_STATEMENT >= G_LOG_LEVEL);
4599 
4600    l_cogs_om_line_id   NUMBER;
4601 
4602    l_mat_cost NUMBER;
4603    l_moh_cost NUMBER;
4604    l_res_cost NUMBER;
4605    l_osp_cost NUMBER;
4606    l_ovh_cost NUMBER;
4607    l_tot_cost NUMBER;
4608 
4609 BEGIN
4610 
4611 -- Standard start of API savepoint
4612    SAVEPOINT Insert_PacSoIssue_PVT;
4613 
4614    l_stmt_num := 0;
4615 
4616    IF l_proclog THEN
4617       fnd_log.string(FND_LOG.LEVEL_PROCEDURE,l_module||'.begin',
4618         'Entering '||G_PKG_NAME||'.'||l_api_name||' with '||
4619         'p_api_version = '||p_api_version||','||
4620         'p_transaction_id = '||p_transaction_id||','||
4621         'p_layer_id = '||p_layer_id||','||
4622         'p_cost_type_id = '||p_cost_type_id||','||
4623         'p_cost_group_id = '||p_cost_group_id
4624       );
4625    END IF;
4626 
4627 -- Standard call to check for call compatibility
4628    IF NOT FND_API.Compatible_API_Call (
4629                         l_api_version,
4630                         p_api_version,
4631                         l_api_name,
4632                         G_PKG_NAME ) THEN
4633      RAISE FND_API.G_EXC_UNEXPECTED_ERROR;
4634    END IF;
4635 
4636 -- Initialize message list if p_init_msg_list is set to TRUE
4637    IF FND_API.to_Boolean(p_init_msg_list) THEN
4638      FND_MSG_PUB.initialize;
4639    END IF;
4640 
4641 -- Initialize API return status to success
4642    x_return_status := FND_API.G_RET_STS_SUCCESS;
4643    x_msg_count := 0;
4644    x_msg_data := '';
4645 
4646 -- API Body
4647 
4648    l_stmt_num := 10;
4649    -- Get the OM Line ID of this sales order issue transaction
4650    -- but only if the event was inserted into the COGS Events
4651    -- table.  For example, expense item shipments would not have
4652    -- been inserted into CCE, and should not be inserted into CRCML.
4653    BEGIN
4654      SELECT mmt.trx_source_line_id
4655      INTO   l_cogs_om_line_id
4656      FROM   mtl_material_transactions mmt,
4657             cst_cogs_events cce
4658      WHERE  mmt.transaction_id = p_transaction_id
4659      AND    cce.mmt_transaction_id = mmt.transaction_id;
4660    EXCEPTION
4661      WHEN NO_DATA_FOUND THEN
4662      -- Either no records is supposed to be in CCE (undeferred SOs,
4663      -- SOs for expense items), or the transaction has not been
4664      -- costed in perpetual and the Collect Order Management Transaction
4665      -- request has not pick up the transaction. For the latter, it is
4666      -- assummed that PAC process will be run again for this transaction
4667      -- after the transaction is costed (and hence CCE is created) in
4668      -- the future before the PAC period is closed.
4669      IF l_stmtLog THEN
4670         FND_LOG.string(FND_LOG.LEVEL_STATEMENT,l_module||'.10','No COGS Events found for transaction '||to_char(p_transaction_id));
4671      END IF;
4672    END;
4673 
4674    l_stmt_num := 20;
4675 
4676    SELECT  NVL(SUM(DECODE(cost_element_id,1,NVL(actual_cost,0),0)),0),
4677            NVL(SUM(DECODE(cost_element_id,2,NVL(actual_cost,0),0)),0),
4678            NVL(SUM(DECODE(cost_element_id,3,NVL(actual_cost,0),0)),0),
4679            NVL(SUM(DECODE(cost_element_id,4,NVL(actual_cost,0),0)),0),
4680            NVL(SUM(DECODE(cost_element_id,5,NVL(actual_cost,0),0)),0)
4681    INTO    l_mat_cost,
4682            l_moh_cost,
4683            l_res_cost,
4684            l_osp_cost,
4685            l_ovh_cost
4686    FROM    mtl_pac_actual_cost_details
4687    WHERE   transaction_id=p_transaction_id
4688    AND     cost_type_id = p_cost_type_id;
4689 
4690    l_tot_cost := l_mat_cost + l_moh_cost + l_res_cost + l_osp_cost + l_ovh_cost;
4691 
4692    IF l_stmtLog THEN
4693      FND_LOG.string(
4694        FND_LOG.LEVEL_STATEMENT,
4695        l_module||'.20',
4696        'MAT:'||l_mat_cost||' MOH:'||l_moh_cost||' RES:'||l_res_cost||
4697        ' OSP:'||l_osp_cost||' OVH:'||l_ovh_cost
4698      );
4699    END IF;
4700 
4701    MERGE
4702    INTO   cst_revenue_cogs_match_lines crcml
4703    USING  (
4704             SELECT cogs_om_line_id,
4705                    p_cost_type_id pac_cost_type_id,
4706                    revenue_om_line_id,
4707                    deferred_cogs_acct_id,
4708                    cogs_acct_id,
4709                    organization_id,
4710                    inventory_item_id,
4711                    operating_unit_id,
4712                    ledger_id,
4713                    sales_order_issue_date,
4714                    original_shipped_qty
4715             FROM   cst_revenue_cogs_match_lines
4716             WHERE  cogs_om_line_id = l_cogs_om_line_id
4717             AND    pac_cost_type_id IS NULL
4718           ) X
4719    ON     (
4720                 crcml.cogs_om_line_id = X.cogs_om_line_id
4721             AND crcml.pac_cost_type_id = X.pac_cost_type_id
4722           )
4723    WHEN MATCHED THEN
4724      UPDATE
4725      SET    unit_material_cost = l_mat_cost,       unit_moh_cost = l_moh_cost,
4726             unit_resource_cost = l_res_cost,       unit_op_cost = l_osp_cost,
4727             unit_overhead_cost = l_ovh_cost,       unit_cost = l_tot_cost,
4728             last_update_date = sysdate,            last_updated_by = p_user_id,
4729             last_update_login = p_login_id,        request_id = p_request_id,
4730             program_application_id = p_pgm_app_id, program_id = p_pgm_id,
4731             program_update_date = sysdate
4732 
4733    WHEN NOT MATCHED THEN
4734      INSERT (
4735               COGS_OM_LINE_ID,        PAC_COST_TYPE_ID,        REVENUE_OM_LINE_ID,
4736               DEFERRED_COGS_ACCT_ID,  COGS_ACCT_ID,            ORGANIZATION_ID,
4737               INVENTORY_ITEM_ID,      OPERATING_UNIT_ID,       COST_GROUP_ID,
4738               LEDGER_ID,              SALES_ORDER_ISSUE_DATE,  UNIT_MATERIAL_COST,
4739               UNIT_MOH_COST,          UNIT_RESOURCE_COST,      UNIT_OP_COST,
4740               UNIT_OVERHEAD_COST,     UNIT_COST,               ORIGINAL_SHIPPED_QTY,
4741               LAST_UPDATE_DATE,       LAST_UPDATED_BY,         CREATION_DATE,
4742               CREATED_BY,             LAST_UPDATE_LOGIN,       REQUEST_ID,
4743               PROGRAM_APPLICATION_ID, PROGRAM_ID,              PROGRAM_UPDATE_DATE
4744             )
4745      VALUES (
4746               X.cogs_om_line_id,      X.pac_cost_type_id,      X.revenue_om_line_id,
4747               X.deferred_cogs_acct_id,X.cogs_acct_id,          X.organization_id,
4748               X.inventory_item_id,    X.operating_unit_id,     p_cost_group_id,
4749               X.ledger_id,            X.sales_order_issue_date,l_mat_cost,
4750               l_moh_cost,             l_res_cost,              l_osp_cost,
4751               l_ovh_cost,             l_tot_cost,              X.original_shipped_qty,
4752               sysdate,                p_user_id,               sysdate,
4753               p_user_id,              p_login_id,              p_request_id,
4754               p_pgm_app_id,           p_pgm_id,                sysdate
4755             );
4756 
4757 -- End API Body
4758 
4759    IF l_procLog THEN
4760       fnd_log.string(FND_LOG.LEVEL_PROCEDURE,l_module||'.end',
4761         'Exiting '||G_PKG_NAME||'.'||l_api_name||' with '||
4762         'x_return_status = '||x_return_status
4763       );
4764    END IF;
4765 
4766    FND_MSG_PUB.count_and_get
4767    (  p_count  => x_msg_count
4768     , p_data   => x_msg_data
4769     , p_encoded => FND_API.g_false
4770    );
4771 
4772 
4773 
4774 EXCEPTION
4775 
4776    WHEN OTHERS THEN
4777          ROLLBACK TO Insert_PacSoIssue_PVT;
4778          x_return_status := fnd_api.g_ret_sts_unexp_error ;
4779 
4780          IF l_unexpLog THEN
4781             FND_LOG.string(FND_LOG.LEVEL_UNEXPECTED,G_LOG_HEAD || '.'||l_api_name||'.'||l_stmt_num
4782                 ,'Insert_PacSoIssue ('||to_char(l_stmt_num)||') : '||substr(SQLERRM,1,200));
4783          END IF;
4784 
4785          IF fnd_msg_pub.check_msg_level(fnd_msg_pub.g_msg_lvl_unexp_error) THEN
4786             FND_MESSAGE.set_name('BOM', 'CST_UNEXP_ERROR');
4787             FND_MESSAGE.set_token('PACKAGE', G_PKG_NAME);
4788             FND_MESSAGE.set_token('PROCEDURE',l_api_name);
4789             FND_MESSAGE.set_token('STATEMENT',to_char(l_stmt_num));
4790             FND_MSG_PUB.ADD;
4791          END IF;
4792 
4793          FND_MSG_PUB.count_and_get
4794          (  p_count  => x_msg_count
4795           , p_data   => x_msg_data
4796           , p_encoded => FND_API.g_false
4797          );
4798 
4799 END Insert_PacSoIssue;
4800 
4801 -----------------------------------------------------------------------------
4802 -- Start of comments                                                       --
4803 --                                                                         --
4804 -- PROCEDURE                                                               --
4805 --  Process_PacRmaReceipt  The PAC equivalent of Process_OneRmaRecipt()    --
4806 --            This procedure creates the distributions for RMAs that refer --
4807 --            to an original sales order for which COGS was deferred.  It  --
4808 --            creates credits to Deferred COGS and COGS as appropriate.    --
4809 --                                                                         --
4810 -- VERSION 1.0                                                             --
4811 --                                                                         --
4812 -- PARAMETERS                                                              --
4813 --  P_AE_TXN_REC       Transaction Record used throughout PAC processor    --
4814 --  P_AE_CURR_REC      Currency Record used throughout PAC processor       --
4815 --  P_DR_FLAG          Debit = True / Credit = False                       --
4816 --  P_COGS_OM_LINE_ID  OM Line ID of the sales order to which this RMA refers
4817 --  L_AE_LINE_TBL      Table where the distributions are built             --
4818 --                                                                         --
4819 -- HISTORY:                                                                --
4820 --    06/28/05     Bryan Kuntz      Created                                --
4821 -- End of comments                                                         --
4822 -----------------------------------------------------------------------------
4823 PROCEDURE Process_PacRmaReceipt(
4824                 p_ae_txn_rec       IN  CSTPALTY.cst_ae_txn_rec_type,
4825                 p_ae_curr_rec      IN  CSTPALTY.cst_ae_curr_rec_type,
4826                 p_dr_flag          IN  BOOLEAN,
4827                 p_cogs_om_line_id  IN  NUMBER,
4828                 l_ae_line_tbl      IN OUT NOCOPY      CSTPALTY.cst_ae_line_tbl_type,
4829                 x_ae_err_rec       OUT NOCOPY      CSTPALTY.cst_ae_err_rec_type
4830 ) IS
4831 
4832    l_api_name               CONSTANT VARCHAR2(30)  := 'Process_PacRmaReceipt';
4833    l_api_version            CONSTANT NUMBER        := 1.0;
4834    l_stmt_num               NUMBER                 := 0;
4835    process_error            EXCEPTION;
4836 
4837    l_module   CONSTANT VARCHAR2(100)        := G_LOG_HEAD ||'.'||l_api_name||'.';
4838    l_unexpLog CONSTANT BOOLEAN := (FND_LOG.LEVEL_UNEXPECTED >= G_LOG_LEVEL) AND FND_LOG.TEST(FND_LOG.LEVEL_UNEXPECTED, l_module);
4839    l_errorLog CONSTANT BOOLEAN := l_unexpLog and (FND_LOG.LEVEL_ERROR >= G_LOG_LEVEL);
4840    l_eventLog CONSTANT BOOLEAN := l_errorLog and (FND_LOG.LEVEL_EVENT >= G_LOG_LEVEL);
4841    l_procLog  CONSTANT BOOLEAN := l_eventLog and (FND_LOG.LEVEL_PROCEDURE >= G_LOG_LEVEL);
4842    l_stmtLog  CONSTANT BOOLEAN := l_procLog  and (FND_LOG.LEVEL_STATEMENT >= G_LOG_LEVEL);
4843 
4844    l_ae_line_rec             CSTPALTY.cst_ae_line_rec_type;
4845    l_err_rec                 CSTPALTY.cst_ae_err_rec_type;
4846 
4847    l_elemental_cost      number_table;
4848    l_def_cogs_acct_id    NUMBER;
4849    l_cogs_acct_id        NUMBER;
4850 
4851 BEGIN
4852 
4853 -- Standard start of API savepoint
4854    SAVEPOINT Process_PacRmaReceipt_PVT;
4855 
4856    l_stmt_num := 0;
4857 
4858    IF l_proclog THEN
4859       fnd_log.string(FND_LOG.LEVEL_PROCEDURE,l_module||'.begin',
4860         'Entering '||G_PKG_NAME||'.'||l_api_name||' with '||
4861         'p_cogs_om_line_id = '||p_cogs_om_line_id
4862       );
4863    END IF;
4864 
4865 -- API Body
4866 
4867    l_stmt_num := 10;
4868    /* Get the unit elemental costs and accounts for this sales order line ID */
4869    SELECT unit_material_cost,
4870           unit_moh_cost,
4871           unit_resource_cost,
4872           unit_op_cost,
4873           unit_overhead_cost,
4874           deferred_cogs_acct_id,
4875           cogs_acct_id
4876    INTO l_elemental_cost(1),
4877         l_elemental_cost(2),
4878         l_elemental_cost(3),
4879         l_elemental_cost(4),
4880         l_elemental_cost(5),
4881         l_def_cogs_acct_id,
4882         l_cogs_acct_id
4883    FROM cst_revenue_cogs_match_lines crcml
4884    WHERE cogs_om_line_id = p_cogs_om_line_id
4885    AND   pac_cost_type_id = p_ae_txn_rec.cost_type_id;
4886 
4887 
4888    -- Create distributions for each cost element
4889    FOR i IN 1..5 LOOP
4890       -- COGS distribution = elemental cost * quantity * cogs percentage
4891       l_ae_line_rec.transaction_value := abs(l_elemental_cost(i) * p_ae_txn_rec.primary_quantity * p_ae_txn_rec.cogs_percentage);
4892 
4893       IF l_stmtLog THEN
4894          FND_LOG.string(FND_LOG.LEVEL_STATEMENT,l_module||'.40','Cost Element '||to_char(i)||' COGS Credit Amount = '||to_char(l_ae_line_rec.transaction_value));
4895       END IF;
4896 
4897       IF (l_ae_line_rec.transaction_value <> 0) THEN
4898          -- Create COGS distribution
4899 
4900          l_ae_line_rec.account := l_cogs_acct_id;
4901          l_ae_line_rec.resource_id := NULL;
4902          l_ae_line_rec.cost_element_id := i;
4903          l_ae_line_rec.ae_line_type := 35;
4904 
4905          CSTPAPBR.insert_account (p_ae_txn_rec,
4906                          p_ae_curr_rec,
4907                          p_dr_flag,
4908                          l_ae_line_rec,
4909                          l_ae_line_tbl,
4910                          l_err_rec);
4911          -- check error
4912          if(l_err_rec.l_err_num<>0 and l_err_rec.l_err_num is not null) then
4913             raise process_error;
4914          end if;
4915 
4916       END IF;
4917 
4918       -- Deferred COGS distribution = (elemental cost * quantity) - COGS distribution
4919       l_ae_line_rec.transaction_value := abs(l_elemental_cost(i) * p_ae_txn_rec.primary_quantity) - l_ae_line_rec.transaction_value;
4920 
4921       IF l_stmtLog THEN
4922          FND_LOG.string(FND_LOG.LEVEL_STATEMENT,l_module||'.40','Cost Element '||to_char(i)||' Deferred COGS Credit Amount = '||to_char(l_ae_line_rec.transaction_value));
4923       END IF;
4924 
4925       IF (l_ae_line_rec.transaction_value <> 0) THEN
4926          -- Create Deferred COGS distribution
4927 
4928          l_ae_line_rec.account := l_def_cogs_acct_id;
4929          l_ae_line_rec.resource_id := NULL;
4930          l_ae_line_rec.cost_element_id := i;
4931          l_ae_line_rec.ae_line_type := 36;
4932 
4933          CSTPAPBR.insert_account (p_ae_txn_rec,
4934                          p_ae_curr_rec,
4935                          p_dr_flag,
4936                          l_ae_line_rec,
4937                          l_ae_line_tbl,
4938                          l_err_rec);
4939          -- check error
4940          if(l_err_rec.l_err_num<>0 and l_err_rec.l_err_num is not null) then
4941             raise process_error;
4942          end if;
4943 
4944       END IF;
4945 
4946    END LOOP;
4947 
4948 -- End API Body
4949 
4950    IF l_proclog THEN
4951       fnd_log.string(FND_LOG.LEVEL_PROCEDURE,l_module||'.end',
4952         'Exiting '||G_PKG_NAME||'.'||l_api_name
4953       );
4954    END IF;
4955 
4956 EXCEPTION
4957 
4958   when process_error then
4959      ROLLBACK TO Process_PacRmaReceipt_PVT;
4960      x_ae_err_rec.l_err_num := l_err_rec.l_err_num;
4961      x_ae_err_rec.l_err_code := l_err_rec.l_err_code;
4962      x_ae_err_rec.l_err_msg := l_err_rec.l_err_msg;
4963 
4964      IF l_errorLog THEN
4965         FND_LOG.string(FND_LOG.LEVEL_ERROR,G_LOG_HEAD || '.'||l_api_name||'.'||l_stmt_num
4966                 ,'Process_PacRmaReceipt ('||to_char(l_stmt_num)||') : '||substr(l_err_rec.l_err_msg,1,200));
4967      END IF;
4968 
4969   when others then
4970      ROLLBACK TO Process_PacRmaReceipt_PVT;
4971      x_ae_err_rec.l_err_num := SQLCODE;
4972      x_ae_err_rec.l_err_code := '';
4973      x_ae_err_rec.l_err_msg := 'CSTPAPBR.Process_PacRmaReceipt()' ||
4974                                to_char(l_stmt_num) || substr(SQLERRM,1,180);
4975 
4976      IF l_unexpLog THEN
4977         FND_LOG.string(FND_LOG.LEVEL_UNEXPECTED,G_LOG_HEAD || '.'||l_api_name||'.'||l_stmt_num
4978                 ,'Process_PacRmaReceipt ('||to_char(l_stmt_num)||') : '||substr(SQLERRM,1,180));
4979      END IF;
4980 
4981 END Process_PacRmaReceipt;
4982 
4983 -----------------------------------------------------------------------------
4984 -- Start of comments                                                       --
4985 --                                                                         --
4986 -- PROCEDURE                                                               --
4987 --  Process_PacCogsRecTxn  PAC equivalent of Process_CogsRecognitionTxn()  --
4988 --            This procedure is called from the PAC distribution processor --
4989 --            to create the accounting entries for COGS Recognition events --
4990 --                                                                         --
4991 -- VERSION 1.0                                                             --
4992 --                                                                         --
4993 -- PARAMETERS                                                              --
4994 --  P_AE_TXN_REC       Transaction Record used throughout PAC processor    --
4995 --  P_AE_CURR_REC      Currency Record used throughout PAC processor       --
4996 --  L_AE_LINE_TBL      Table where the distributions are built             --
4997 --                                                                         --
4998 -- HISTORY:                                                                --
4999 --    06/28/05     Bryan Kuntz      Created                                --
5000 -- End of comments                                                         --
5001 -----------------------------------------------------------------------------
5002 PROCEDURE Process_PacCogsRecTxn(
5003                 p_ae_txn_rec       IN  CSTPALTY.cst_ae_txn_rec_type,
5004                 p_ae_curr_rec      IN  CSTPALTY.cst_ae_curr_rec_type,
5005                 l_ae_line_tbl      IN OUT NOCOPY      CSTPALTY.cst_ae_line_tbl_type,
5006                 x_ae_err_rec       OUT NOCOPY      CSTPALTY.cst_ae_err_rec_type
5007 ) IS
5008 
5009    l_api_name               CONSTANT VARCHAR2(30)  := 'Process_PacCogsRecTxn';
5010    l_api_version            CONSTANT NUMBER        := 1.0;
5011    l_stmt_num               NUMBER                 := 0;
5012    process_error            EXCEPTION;
5013 
5014    l_module   CONSTANT VARCHAR2(100)        := G_LOG_HEAD ||'.'||l_api_name||'.';
5015    l_unexpLog CONSTANT BOOLEAN := (FND_LOG.LEVEL_UNEXPECTED >= G_LOG_LEVEL) AND FND_LOG.TEST(FND_LOG.LEVEL_UNEXPECTED, l_module);
5016    l_errorLog CONSTANT BOOLEAN := l_unexpLog and (FND_LOG.LEVEL_ERROR >= G_LOG_LEVEL);
5017    l_eventLog CONSTANT BOOLEAN := l_errorLog and (FND_LOG.LEVEL_EVENT >= G_LOG_LEVEL);
5018    l_procLog  CONSTANT BOOLEAN := l_eventLog and (FND_LOG.LEVEL_PROCEDURE >= G_LOG_LEVEL);
5019    l_stmtLog  CONSTANT BOOLEAN := l_procLog  and (FND_LOG.LEVEL_STATEMENT >= G_LOG_LEVEL);
5020 
5021    l_ae_line_rec             CSTPALTY.cst_ae_line_rec_type;
5022    l_err_rec                 CSTPALTY.cst_ae_err_rec_type;
5023    l_dr_flag                 BOOLEAN;
5024 
5025    l_elemental_cost      number_table;
5026    l_def_cogs_acct_id    NUMBER;
5027    l_cogs_acct_id        NUMBER;
5028    l_new_percentage      NUMBER;
5029    l_prior_percentage    NUMBER;
5030 
5031 
5032 
5033 BEGIN
5034 
5035 -- Standard start of API savepoint
5036    SAVEPOINT Process_PacCogsRecTxn_PVT;
5037 
5038    l_stmt_num := 0;
5039 
5040    IF l_proclog THEN
5041       fnd_log.string(FND_LOG.LEVEL_PROCEDURE,l_module||'.begin',
5042         'Entering '||G_PKG_NAME||'.'||l_api_name
5043       );
5044    END IF;
5045 
5046 -- API Body
5047 
5048    l_stmt_num := 10;
5049    -- Get the unit elemental costs and accounts for this sales order line ID
5050    SELECT unit_material_cost,
5051           unit_moh_cost,
5052           unit_resource_cost,
5053           unit_op_cost,
5054           unit_overhead_cost,
5055           deferred_cogs_acct_id,
5056           cogs_acct_id
5057    INTO l_elemental_cost(1),
5058         l_elemental_cost(2),
5059         l_elemental_cost(3),
5060         l_elemental_cost(4),
5061         l_elemental_cost(5),
5062         l_def_cogs_acct_id,
5063         l_cogs_acct_id
5064    FROM cst_revenue_cogs_match_lines crcml
5065    WHERE cogs_om_line_id = p_ae_txn_rec.om_line_id
5066    AND   pac_cost_type_id = p_ae_txn_rec.cost_type_id;
5067 
5068    l_stmt_num := 20;
5069    -- Get the COGS percentage and prior COGS percentage for this event
5070    SELECT cogs_percentage,
5071           prior_cogs_percentage
5072    INTO l_new_percentage,
5073         l_prior_percentage
5074    FROM cst_cogs_events
5075    WHERE mmt_transaction_id = p_ae_txn_rec.transaction_id;
5076 
5077 
5078    -- Loop for each cost element
5079    FOR i IN 1..5 LOOP
5080       l_ae_line_rec.transaction_value := l_elemental_cost(i) * p_ae_txn_rec.primary_quantity * (l_new_percentage - l_prior_percentage);
5081 
5082       IF l_stmtLog THEN
5083          FND_LOG.string(FND_LOG.LEVEL_STATEMENT,l_module||'.20','Cost Element '||to_char(i)||' COGS Adjustment Amount = '||to_char(l_ae_line_rec.transaction_value));
5084       END IF;
5085 
5086       IF (l_ae_line_rec.transaction_value <> 0) THEN
5087          -- Create COGS distribution (debit if percentage increase, credit otherwise)
5088 
5089          l_ae_line_rec.account := l_cogs_acct_id;
5090          l_ae_line_rec.resource_id := NULL;
5091          l_ae_line_rec.cost_element_id := i;
5092          l_ae_line_rec.ae_line_type := 35;
5093 
5094          l_dr_flag := (sign(l_ae_line_rec.transaction_value) > 0);
5095          l_ae_line_rec.transaction_value := abs(l_ae_line_rec.transaction_value);
5096 
5097          CSTPAPBR.insert_account (p_ae_txn_rec,
5098                          p_ae_curr_rec,
5099                          l_dr_flag,
5100                          l_ae_line_rec,
5101                          l_ae_line_tbl,
5102                          l_err_rec);
5103          -- check error
5104          if(l_err_rec.l_err_num<>0 and l_err_rec.l_err_num is not null) then
5105             raise process_error;
5106          end if;
5107 
5108          -- Create Deferred COGS distribution (credit if percentage increase, debit otherwise)
5109 
5110          l_ae_line_rec.account := l_def_cogs_acct_id;
5111          l_ae_line_rec.ae_line_type := 36;
5112          l_dr_flag := not l_dr_flag;
5113 
5114          CSTPAPBR.insert_account (p_ae_txn_rec,
5115                          p_ae_curr_rec,
5116                          l_dr_flag,
5117                          l_ae_line_rec,
5118                          l_ae_line_tbl,
5119                          l_err_rec);
5120          -- check error
5121          if(l_err_rec.l_err_num<>0 and l_err_rec.l_err_num is not null) then
5122             raise process_error;
5123          end if;
5124 
5125       END IF;
5126 
5127    END LOOP;
5128 
5129 
5130 -- End API Body
5131 
5132    IF l_proclog THEN
5133       fnd_log.string(FND_LOG.LEVEL_PROCEDURE,l_module||'.end',
5134         'Exiting '||G_PKG_NAME||'.'||l_api_name
5135       );
5136    END IF;
5137 
5138 
5139 EXCEPTION
5140 
5141   when process_error then
5142      ROLLBACK TO Process_PacCogsRecTxn_PVT;
5143      x_ae_err_rec.l_err_num := l_err_rec.l_err_num;
5144      x_ae_err_rec.l_err_code := l_err_rec.l_err_code;
5145      x_ae_err_rec.l_err_msg := l_err_rec.l_err_msg;
5146 
5147      IF l_errorLog THEN
5148         FND_LOG.string(FND_LOG.LEVEL_ERROR,G_LOG_HEAD || '.'||l_api_name||'.'||l_stmt_num
5149                 ,'Process_PacCogsRecTxn ('||to_char(l_stmt_num)||') : '||substr(l_err_rec.l_err_msg,1,200));
5150      END IF;
5151 
5152   when others then
5153      ROLLBACK TO Process_PacCogsRecTxn_PVT;
5154      x_ae_err_rec.l_err_num := SQLCODE;
5155      x_ae_err_rec.l_err_code := '';
5156      x_ae_err_rec.l_err_msg := 'CSTPAPBR.Process_PacCogsRecTxn(' ||
5157                                to_char(l_stmt_num)||') -' || substr(SQLERRM,1,180);
5158 
5159      IF l_unexpLog THEN
5160         FND_LOG.string(FND_LOG.LEVEL_UNEXPECTED,G_LOG_HEAD || '.'||l_api_name||'.'||l_stmt_num
5161                 ,'Process_PacCogsRecTxn ('||to_char(l_stmt_num)||') : '||substr(SQLERRM,1,180));
5162      END IF;
5163 
5164 END Process_PacCogsRecTxn;
5165 
5166 -----------------------------------------------------------------------------
5167 -- Start of comments                                                       --
5168 --                                                                         --
5169 -- PROCEDURE                                                               --
5170 --  Print_MessageStack                                                     --
5171 --           This procedure is called from Match_RevenueCogs() to spit out --
5172 --           the contents of the message stack to the log file.            --
5173 --                                                                         --
5174 -- VERSION 1.0                                                             --
5175 --                                                                         --
5176 -- PARAMETERS                                                              --
5177 --     none                                                                --
5178 --                                                                         --
5179 -- HISTORY:                                                                --
5180 --    05/17/05     Bryan Kuntz      Created                                --
5181 -- End of comments                                                         --
5182 -----------------------------------------------------------------------------
5183 procedure Print_MessageStack IS
5184    l_msg_count NUMBER;
5185    l_msg_data  VARCHAR2(8000);
5186 BEGIN
5187    FND_MSG_PUB.count_and_get
5188     ( p_count  => l_msg_count,
5189       p_data   => l_msg_data,
5190       p_encoded => FND_API.g_false
5191     );
5192    IF (l_msg_count > 1) THEN
5193       FOR i IN 1..l_msg_count LOOP
5194          l_msg_data := FND_MSG_PUB.get(i, FND_API.g_false);
5195          FND_FILE.PUT_LINE(FND_FILE.LOG, l_msg_data);
5196       END LOOP;
5197    ELSIF (l_msg_count = 1) THEN
5198       FND_FILE.PUT_LINE(FND_FILE.LOG, l_msg_data);
5199    END IF;
5200 
5201    -- Reinitialize the message list
5202    FND_MSG_PUB.initialize;
5203 
5204 END Print_MessageStack;
5205 
5206  /*===========================================================================*/
5207  --      API name        : Generate_DefCOGSXml
5208  --      Type            : Private
5209  --      Function        : Generate XML Data for Deferred COGS Report
5210  --                        Report
5211  --      Pre-reqs        : None.
5212  --      Parameters      :
5213  --      in              : p_cost_method           in number
5214  --          		 : p_ledger_id             in number     (Only used in perpetual)
5215  --          		 : p_pac_legal_entity      in number     (Only used in PAC)
5216  --                      : p_pac_cost_type         in number     (Only used in PAC)
5217  --          		 : p_pac_cost_group        in number     (Only used in PAC)
5218  --                      : p_period_name           in varchar2
5219  --                      : p_sales_order_date_low  in varchar2
5220  --                      : p_sales_order_date_high in varchar2
5221  --          		 : p_all_lines             in varchar2
5222  --                      : p_api_version           in number
5223  --
5224  --      out             :
5225  --                      : errcode                 OUT varchar2
5226  --                      : errno                   OUT number
5227  --
5228  --      Version         : Current version         1.0
5229  --                      : Initial version         1.0
5230  --      History         : 6/24/2005    David Gottlieb  Created
5231  --      Notes           : This Procedure is called by the Deferred COGS Report
5232  --                        This is the wrapper procedure that calls the other
5233  --                        procedures to generate XML data according to report parameters.
5234  -- End of comments
5235  /*===========================================================================*/
5236 
5237  procedure Generate_DefCOGSXml (
5238    errcode			out nocopy	varchar2,
5239    err_code 			out nocopy	number,
5240    p_cost_method		in		number,
5241    p_ledger_id			in		number,
5242    p_pac_legal_entity		in		number,
5243    p_pac_cost_type		in		number,
5244    p_pac_cost_group		in		number,
5245    p_period_name 	  	in		varchar2,
5246    p_sales_order_date_low  	in		varchar2,
5247    p_sales_order_date_high 	in		varchar2,
5248    p_all_lines			in		varchar2,
5249    p_api_version      	     	in 		number) is
5250 
5251    l_operating_unit		number;
5252    l_sales_order_date_low	date;
5253    l_sales_order_date_high	date;
5254    l_qryCtx                     number;
5255    l_ref_cur                    sys_refcursor;
5256    l_xml_doc                    clob;
5257    l_amount                     number;
5258    l_offset                     number;
5259    l_buffer                     varchar2(32767);
5260    l_length                     number;
5261 
5262    l_api_name      		constant varchar2(100)   := 'Generate_DefCOGSXml';
5263    l_api_version   		constant number          := 1.0;
5264 
5265    l_return_status              varchar2(1);
5266    l_msg_count                  number;
5267    l_msg_data                   varchar2(2000);
5268    l_stmt_num                   number;
5269    l_success                    boolean;
5270 
5271    l_full_name     		constant varchar2(2000)  := G_PKG_NAME || '.' || l_api_name;
5272    l_module        		constant varchar2(2000)  := 'cst.plsql.' || l_full_name;
5273    l_uLog          		constant boolean         := (fnd_log.LEVEL_UNEXPECTED >= G_LOG_LEVEL) AND
5274                                                     fnd_log.test(fnd_log.LEVEL_UNEXPECTED, l_module);
5275    l_errorLog      		constant boolean         := l_uLog and (fnd_log.LEVEL_ERROR >= G_LOG_LEVEL);
5276    l_eventLog      		constant boolean         := l_errorLog and (fnd_log.LEVEL_EVENT >= G_LOG_LEVEL);
5277    l_pLog          		constant boolean         := l_eventLog and (fnd_log.LEVEL_PROCEDURE >= G_LOG_LEVEL);
5278    /*Bug 7305146*/
5279    l_encoding                   VARCHAR2(20);
5280    l_xml_header                 VARCHAR2(100);
5281 
5282  begin
5283 
5284    -- Initialize variables
5285 
5286    l_amount         := 16383;
5287    l_offset         := 1;
5288    l_return_status  := fnd_api.g_ret_sts_success;
5289    l_msg_count      := 0;
5290    if(p_cost_method = 1) then
5291      l_operating_unit := mo_global.get_current_org_id;
5292    else
5293      l_operating_unit := -1; /* Operating Unit not used in PAC */
5294    end if; /* p_cost_method = 1 */
5295 
5296    -- Write the module name and user parameters to fnd log file
5297 
5298    IF l_pLog THEN
5299      FND_LOG.string(FND_LOG.LEVEL_PROCEDURE,l_module||'.begin',
5300        'Entering '||G_PKG_NAME||'.'||l_api_name||' with '||
5301        'p_cost_method = '||p_cost_method||','||
5302        'p_ledger_id = '||p_ledger_id||','||
5303        'l_operating_unit ='||l_operating_unit||','||
5304        'p_pac_legal_entity = '||p_pac_legal_entity||','||
5305        'p_pac_cost_type = '||p_pac_cost_type||','||
5306        'p_pac_cost_group = '||p_pac_cost_group||','||
5307        'p_period_name = '||p_period_name||','||
5308        'p_sales_order_date_low = '||p_sales_order_date_low||','||
5309        'p_sales_order_date_high = '||p_sales_order_date_high||','||
5310        'p_all_lines = '||p_all_lines||','||
5311        'p_api_version = '||p_api_version
5312      );
5313    END IF;
5314 
5315    -- Initialze variables for storing XML Data
5316 
5317    dbms_lob.createtemporary(l_xml_doc, TRUE);
5318 
5319    /*Bug 7305146*/
5320    l_encoding       := fnd_profile.value('ICX_CLIENT_IANA_ENCODING');
5321    l_xml_header     := '<?xml version="1.0" encoding="'|| l_encoding ||'"?>';
5322    DBMS_LOB.writeappend (l_xml_doc, length(l_xml_header), l_xml_header);
5323 
5324    dbms_lob.writeappend (l_xml_doc, 8, '<REPORT>');
5325 
5326    -- Initialize message stack
5327 
5328    fnd_msg_pub.initialize;
5329 
5330    -- Standard call to get message count and if count is 1, get message info.
5331 
5332    fnd_msg_pub.Count_And_Get
5333    (       p_count    =>      l_msg_count,
5334            p_data     =>      l_msg_data
5335    );
5336 
5337    -- Standard call to check the API version
5338 
5339    if(not fnd_api.Compatible_API_Call( l_api_version,
5340                                        p_api_version,
5341                                        l_api_name,
5342                                        G_PKG_NAME)) then
5343      raise fnd_api.G_EXC_UNEXPECTED_ERROR;
5344    end if;
5345 
5346    l_stmt_num := 10;
5347 
5348    --set the date parameters if the user has not
5349 
5350    if(p_sales_order_date_low is not null) then
5351      l_sales_order_date_low := trunc(fnd_date.canonical_to_date(p_sales_order_date_low));
5352    else
5353      l_sales_order_date_low := sysdate - 7200;
5354    end if;
5355 
5356    if(p_sales_order_date_high is not null) then
5357      l_sales_order_date_high := trunc(fnd_date.canonical_to_date(p_sales_order_date_high));
5358    else
5359      l_sales_order_date_high := sysdate + 1;
5360    end if;
5361 
5362    /*========================================================================*/
5363    -- Call to Procedure Add Parameters. To Add user entered Parameters to
5364    -- XML data
5365    /*========================================================================*/
5366 
5367    Add_Parameters ( p_api_version           => 1.0,
5368                     p_init_msg_list         => fnd_api.G_FALSE,
5369                     p_validation_level      => fnd_api.G_VALID_LEVEL_FULL,
5370                     x_return_status         => l_return_status,
5371                     x_msg_count             => l_msg_count,
5372                     x_msg_data              => l_msg_data,
5373                     i_cost_method           => p_cost_method,
5374                     i_operating_unit	    => l_operating_unit,
5375 		    i_ledger_id	      	    => p_ledger_id,
5376 		    i_pac_legal_entity      => p_pac_legal_entity,
5377    		    i_pac_cost_type         => p_pac_cost_type,
5378                     i_pac_cost_group	    => p_pac_cost_group,
5379                     i_period_name	    => p_period_name,
5380  		    i_sales_order_date_low  => p_sales_order_date_low,
5381 		    i_sales_order_date_high => p_sales_order_date_high,
5382                     i_all_lines	      	    => p_all_lines,
5383                     x_xml_doc               => l_xml_doc);
5384 
5385    -- Standard call to check the return status from API called
5386 
5387    if(l_return_status <> fnd_api.G_RET_STS_SUCCESS) then
5388      raise fnd_api.G_EXC_UNEXPECTED_ERROR;
5389    end if;
5390 
5391 
5392    l_stmt_num := 20;
5393 
5394    /*========================================================================*/
5395    -- Call to Procedure Add Parameters. To Add AP and PO data to XML data
5396    /*========================================================================*/
5397 
5398    Add_DefCOGSData (p_api_version           => 1.0,
5399                     p_init_msg_list         => FND_API.G_FALSE,
5400                     p_validation_level      => FND_API.G_VALID_LEVEL_FULL,
5401                     x_return_status         => l_return_status,
5402                     x_msg_count             => l_msg_count,
5403                     x_msg_data              => l_msg_data,
5404                     i_cost_method	    => p_cost_method,
5405                     i_operating_unit	    => l_operating_unit,
5406 		    i_ledger_id	            => p_ledger_id,
5407 		    i_pac_legal_entity      => p_pac_legal_entity,
5408                     i_pac_cost_type	    => p_pac_cost_type,
5409                     i_pac_cost_group  	    => p_pac_cost_group,
5410                     i_period_name	    => p_period_name,
5411  		    i_sales_order_date_low  => l_sales_order_date_low,
5412 		    i_sales_order_date_high => l_sales_order_date_high,
5413                     i_all_lines	            => p_all_lines,
5414                     x_xml_doc               => l_xml_doc);
5415 
5416    -- Standard call to check the return status from API called
5417 
5418    if(l_return_status <> fnd_api.G_RET_STS_SUCCESS) then
5419      raise fnd_api.G_EXC_UNEXPECTED_ERROR;
5420    end if;
5421 
5422    -- write the closing tag to the XML data
5423 
5424    dbms_lob.writeappend (l_xml_doc, 9, '</REPORT>');
5425 
5426    -- write xml data to the output file
5427 
5428    l_length := nvl(dbms_lob.getlength(l_xml_doc),0);
5429    loop
5430      exit when l_length <= 0;
5431      dbms_lob.read (l_xml_doc, l_amount, l_offset, l_buffer);
5432      fnd_file.put(fnd_file.output, l_buffer);
5433      l_length := l_length - l_amount;
5434      l_offset := l_offset + l_amount;
5435    end loop;
5436 
5437    dbms_xmlgen.closeContext(l_qryCtx);
5438 
5439    -- Write the event log to fnd log file
5440 
5441    if(l_eventLog) then
5442      fnd_log.string(fnd_log.LEVEL_EVENT,
5443      l_module || '.' || l_stmt_num, 'Completed writing to output file');
5444    end if;
5445 
5446    -- free temporary memory
5447 
5448    dbms_lob.freetemporary(l_xml_doc);
5449 
5450    l_success := fnd_concurrent.set_completion_status('NORMAL', 'Request Completed Successfully');
5451 
5452    -- Write the module name to fnd log file
5453 
5454    IF l_pLog THEN
5455       fnd_log.string(fnd_log.level_procedure,l_module||'.end',
5456         'Exiting '||G_PKG_NAME||'.'||l_api_name||' with '||
5457         'errcode = '||errcode||','||
5458         'err_code = '||err_code
5459       );
5460    END IF;
5461 
5462    exception
5463      when fnd_api.G_EXC_ERROR then
5464        l_return_status := fnd_api.G_RET_STS_ERROR ;
5465        fnd_msg_pub.Count_And_Get
5466        (       p_count     =>      l_msg_count,
5467                p_data      =>      l_msg_data
5468        );
5469 
5470      when fnd_api.G_EXC_UNEXPECTED_ERROR then
5471        fnd_msg_pub.Count_And_Get
5472        (       p_count => l_msg_count,
5473                p_data  => l_msg_data
5474        );
5475 
5476        cst_utility_pub.writelogmessages
5477        (       p_api_version   => 1.0,
5478                p_msg_count     => l_msg_count,
5479                p_msg_data      => l_msg_data,
5480                x_return_status => l_return_status
5481        );
5482 
5483        l_msg_data      := substrb(SQLERRM,1,240);
5484        l_success       := fnd_concurrent.set_completion_status('ERROR', l_msg_data);
5485 
5486      when others then
5487        if(fnd_log.LEVEL_UNEXPECTED >= G_LOG_LEVEL) then
5488          fnd_log.string(fnd_log.LEVEL_UNEXPECTED,
5489                         l_module || '.' || l_stmt_num,
5490                         substrb(SQLERRM , 1 , 240));
5491        end if;
5492 
5493        if(fnd_msg_pub.Check_Msg_Level(fnd_msg_pub.G_MSG_LVL_UNEXP_ERROR)) then
5494          fnd_msg_pub.Add_Exc_Msg(G_PKG_NAME,l_api_name);
5495        end if;
5496 
5497        fnd_msg_pub.Count_And_Get
5498        (       p_count  =>  l_msg_count,
5499                p_data   =>  l_msg_data
5500        );
5501 
5502        cst_utility_pub.writelogmessages
5503        (       p_api_version   => 1.0,
5504                p_msg_count     => l_msg_count,
5505                p_msg_data      => l_msg_data,
5506                x_return_status => l_return_status
5507        );
5508 
5509        l_msg_data      := substrb(SQLERRM,1,240);
5510        l_success       := fnd_concurrent.set_completion_status('ERROR', l_msg_data);
5511 
5512  end Generate_DefCOGSXml;
5513 
5514 
5515  /*===========================================================================*/
5516  --      API name        : add_parameters
5517  --      Type            : Private
5518  --      Function        : Generate XML data for Parameters and append it to
5519  --                        output
5520  --      Pre-reqs        : None.
5521  --      Parameters      :
5522  --      in              : p_api_version           in number
5523  --                      : p_init_msg_list         in varchar2
5524  --                      : p_validation_level      in number
5525  --          		 : p_cost_method           in number
5526  --              	 : p_operating_unit        in number
5527  --          		 : p_ledger_id             in number
5528  --          		 : p_pac_legal_entity      in number
5529  --                      : p_pac_cost_type         in number
5530  --          		 : p_pac_cost_group        in number
5531  --                      : p_period_name           in varchar2
5532  --                      : p_sales_order_date_low  in varchar2
5533  --                      : p_sales_order_date_high in varchar2
5534  --          		 : p_all_lines             in varchar2
5535  --
5536  --      out             :
5537  --                      : x_return_status         out nocopy varchar2
5538  --                      : x_msg_count             out nocopy number
5539  --                      : x_msg_data              out nocopy varchar2
5540  --
5541  --      in out          :
5542  --                      : x_xml_doc               in out nocopy clob
5543  --
5544  --      Version         : Current version         1.0
5545  --                      : Initial version         1.0
5546  --      History         : 6/24/2005    David Gottlieb  Created
5547  --      Notes           : This Procedure is called by Generate_DefCOSXml
5548  --                        procedure. The procedure generates XML data for the
5549  --                        report parameters and appends it to the report
5550  --                        output.
5551  -- End of comments
5552  /*===========================================================================*/
5553  procedure Add_Parameters (
5554    p_api_version           in              number,
5555    p_init_msg_list         in              varchar2,
5556    p_validation_level      in              number,
5557    x_return_status         out nocopy      varchar2,
5558    x_msg_count             out nocopy      number,
5559    x_msg_data              out nocopy      varchar2,
5560    i_cost_method	   in              number,
5561    i_operating_unit	   in		   number,
5562    i_ledger_id		   in		   number,
5563    i_pac_legal_entity	   in		   number,
5564    i_pac_cost_type	   in		   number,
5565    i_pac_cost_group	   in		   number,
5566    i_period_name           in              varchar2,
5567    i_sales_order_date_low  in              varchar2,
5568    i_sales_order_date_high in              varchar2,
5569    i_all_lines             in		   varchar2,
5570    x_xml_doc               in out nocopy   clob) is
5571 
5572    l_api_name      constant varchar2(30)    := 'ADD_PARAMETERS';
5573    l_api_version   constant number          := 1.0;
5574    l_full_name     constant varchar2(2000)  := G_PKG_NAME || '.' || l_api_name;
5575    l_module        constant varchar2(2000)  := 'cst.plsql.' || l_full_name;
5576 
5577    l_ref_cur       sys_refcursor;
5578    l_qryCtx        number;
5579    l_xml_temp      clob;
5580    l_age_option    number;
5581    l_offset        pls_integer;
5582    l_org_code      CST_ORGANIZATION_DEFINITIONS.ORGANIZATION_CODE%TYPE;
5583    l_cost_type     CST_COST_TYPES.COST_TYPE%TYPE;
5584    l_cost_group    CST_COST_GROUPS.COST_GROUP%TYPE;
5585    l_period_name   CST_PAC_PERIODS.PERIOD_NAME%TYPE;
5586    l_meaning       FND_LOOKUPS.MEANING%TYPE;
5587    l_stmt_num      number;
5588 
5589    l_uLog          constant boolean         := (fnd_log.LEVEL_UNEXPECTED >= G_LOG_LEVEL) AND fnd_log.test(fnd_log.LEVEL_UNEXPECTED, l_module);
5590    l_errorLog      constant boolean         := l_uLog and (fnd_log.LEVEL_ERROR >= G_LOG_LEVEL);
5591    l_eventLog      constant boolean         := l_errorLog and (fnd_log.LEVEL_EVENT >= G_LOG_LEVEL);
5592    l_pLog          constant boolean         := l_eventLog and (fnd_log.LEVEL_PROCEDURE >= G_LOG_LEVEL);
5593 
5594  begin
5595 
5596    -- Write the module name to fnd log file
5597 
5598    IF l_pLog THEN
5599      FND_LOG.string(FND_LOG.LEVEL_PROCEDURE,l_module||'.begin',
5600        'Entering '||G_PKG_NAME||'.'||l_api_name||' with '||
5601         'p_api_version = '||p_api_version||','||
5602         'i_cost_method = '||i_cost_method||','||
5603         'i_operating_unit = '||i_operating_unit||','||
5604         'i_ledger_id = '||i_ledger_id||','||
5605         'i_pac_legal_entity = '||i_pac_legal_entity||','||
5606         'i_pac_cost_type = '||i_pac_cost_type||','||
5607         'i_pac_cost_group = '||i_pac_cost_group||','||
5608         'i_period_name = '||i_period_name||','||
5609         'i_sales_order_date_low = '||i_sales_order_date_low||','||
5610         'i_sales_order_date_high = '||i_sales_order_date_high||','||
5611         'i_all_lines = '||i_all_lines
5612      );
5613    END IF;
5614 
5615    -- Standard call to check for call compatibility.
5616 
5617    if(not fnd_api.Compatible_API_Call ( l_api_version,
5618                                         p_api_version,
5619                                         l_api_name,
5620                                         G_PKG_NAME )) then
5621      raise fnd_api.G_EXC_UNEXPECTED_ERROR;
5622    end if;
5623 
5624    -- Initialize message list if p_init_msg_list is set to TRUE.
5625 
5626    if(fnd_api.to_boolean( p_init_msg_list )) then
5627      fnd_msg_pub.initialize;
5628    end if;
5629 
5630    --  Initialize API return status to success
5631 
5632    x_return_status := fnd_api.G_RET_STS_SUCCESS;
5633 
5634    -- Initialize temporary variable to hold xml data
5635 
5636    dbms_lob.createtemporary(l_xml_temp, TRUE);
5637    l_offset := 21;
5638 
5639    -- Get the proile value to determine the aging basis
5640 
5641    fnd_profile.get('CST_ACCRUAL_AGE_IN_DAYS', l_age_option);
5642 
5643    l_stmt_num := 10;
5644 
5645    -- Open Ref Cursor to collect the report parameters
5646 
5647    /* Perpetual */
5648    if(i_cost_method = 1) then
5649      open l_ref_cur for 'select :i_cost_method		 cost_method,
5650 				haou.name		 operating_unit,
5651 	  	                gsb.name		 ledger,
5652 			        :i_period_name 		 period_name,
5653 			        :i_sales_order_date_low	 sales_order_date_from,
5654 			        :i_sales_order_date_high sales_order_date_to,
5655 			        fl.meaning		 all_lines
5656                          from   hr_all_organization_units haou,
5657 			        gl_sets_of_books 	  gsb,
5658 			        fnd_lookups     	  fl
5659                          where  haou.organization_id  = :i_operating_unit
5660 		         and    gsb.set_of_books_id   = :i_ledger_id
5661  		         and    fl.lookup_code	      = :i_all_lines
5662 		         and    fl.lookup_type        = ''YES_NO'''
5663                          using  i_cost_method,
5664 				i_period_name,
5665 			        i_sales_order_date_low,
5666 			        i_sales_order_date_high,
5667 			        i_operating_unit,
5668 			        i_ledger_id,
5669 			        i_all_lines;
5670 
5671    /* Periodic */
5672    elsif(i_cost_method = 3) then
5673      SELECT cost_type
5674      INTO   l_cost_type
5675      FROM   cst_cost_types
5676      WHERE  cost_type_id = i_pac_cost_type;
5677 
5678      SELECT cost_group
5679      INTO   l_cost_group
5680      FROM   cst_cost_groups
5681      WHERE  cost_group_id = i_pac_cost_group;
5682 
5683      SELECT period_name
5684      INTO   l_period_name
5685      FROM   cst_pac_periods
5686      WHERE  pac_period_id = TO_NUMBER(i_period_name);
5687 
5688      SELECT meaning
5689      INTO   l_meaning
5690      FROM   fnd_lookups
5691      WHERE  lookup_type = 'YES_NO'
5692      AND    lookup_code = i_all_lines;
5693 
5694      open l_ref_cur for 'select :i_cost_method		 cost_method,
5695 				xle.name		 legal_entity,
5696 				:l_cost_type		 cost_type,
5697 				:l_cost_group		 cost_group,
5698 			        :l_period_name 	         period_name,
5699 			        :i_sales_order_date_low	 sales_order_date_from,
5700 			        :i_sales_order_date_high sales_order_date_to,
5701 			        :l_meaning		 all_lines
5702                          from   xle_firstparty_information_v	xle
5703 			 where  xle.legal_entity_id = :i_pac_legal_entity'
5704                          using  i_cost_method,
5705                                 l_cost_type,
5706                                 l_cost_group,
5707                                 l_period_name,
5708 			        i_sales_order_date_low,
5709 			        i_sales_order_date_high,
5710                                 l_meaning,
5711 				i_pac_legal_entity;
5712 
5713    end if; /* p_cost_method = 1, p_cost_method = 3*/
5714 
5715        -- create new context
5716 
5717        l_stmt_num := 20;
5718 
5719        l_qryCtx := DBMS_XMLGEN.newContext (l_ref_cur);
5720        dbms_xmlgen.setRowSetTag (l_qryCtx,'PARAMETERS');
5721        dbms_xmlgen.setRowTag (l_qryCtx,NULL);
5722 
5723        l_stmt_num := 30;
5724 
5725        -- get XML into the temporary clob variable
5726 
5727        dbms_xmlgen.getXML (l_qryCtx, l_xml_temp, dbms_xmlgen.none);
5728 
5729        -- remove the header (21 characters) and append the rest to xml output
5730 
5731        if(dbms_xmlgen.getNumRowsProcessed(l_qryCtx) > 0) then
5732          dbms_lob.erase (l_xml_temp, l_offset,1);
5733          dbms_lob.append (x_xml_doc, l_xml_temp);
5734        end if;
5735 
5736        -- close context and free memory
5737 
5738        dbms_xmlgen.closeContext(l_qryCtx);
5739      close l_ref_cur;
5740 
5741    dbms_lob.freetemporary(l_xml_temp);
5742 
5743    -- Standard call to get message count and if count is 1, get message info.
5744 
5745    fnd_msg_pub.Count_And_Get
5746    (    p_count         =>       x_msg_count,
5747         p_data          =>       x_msg_data
5748    );
5749 
5750    -- Write the module name to fnd log file
5751    IF l_plog THEN
5752       fnd_log.string(fnd_log.level_procedure,l_module||'.end',
5753         'Exiting '||G_PKG_NAME||'.'||l_api_name||' with '||
5754         'x_return_status = '||x_return_status
5755       );
5756    END IF;
5757 
5758    exception
5759      when fnd_api.G_EXC_ERROR then
5760        x_return_status := fnd_api.G_RET_STS_ERROR;
5761        fnd_msg_pub.Count_And_Get
5762        (       p_count         =>      x_msg_count,
5763                p_data          =>      x_msg_data
5764        );
5765 
5766      when fnd_api.G_EXC_UNEXPECTED_ERROR then
5767        x_return_status := fnd_api.G_RET_STS_UNEXP_ERROR;
5768        fnd_msg_pub.Count_And_Get
5769        (       p_count         =>      x_msg_count,
5770                p_data          =>      x_msg_data
5771        );
5772 
5773      when others then
5774        x_return_status := fnd_api.G_RET_STS_UNEXP_ERROR;
5775        if(fnd_log.LEVEL_UNEXPECTED >= G_LOG_LEVEL) then
5776          fnd_log.string(fnd_log.LEVEL_UNEXPECTED,
5777                         l_module || '.' || l_stmt_num,
5778                         substrb(SQLERRM , 1 , 240));
5779        end if;
5780 
5781        if(fnd_msg_pub.Check_Msg_Level(fnd_msg_pub.G_MSG_LVL_UNEXP_ERROR)) then
5782          fnd_msg_pub.Add_Exc_Msg
5783          (       G_PKG_NAME,
5784                  l_api_name
5785          );
5786        end if;
5787 
5788        fnd_msg_pub.Count_And_Get
5789        (       p_count         =>      x_msg_count,
5790                p_data          =>      x_msg_data
5791        );
5792 
5793  end Add_Parameters;
5794 
5795 
5796  /*===========================================================================*/
5797  --      API name        : Add_DefCOGSData
5798  --      Type            : Private
5799  --      Function        : Generate XML data from sql query and append it to
5800  --                        output
5801  --      Pre-reqs        : None.
5802  --      Parameters      :
5803  --      in              : p_api_version           in number
5804  --                      : p_init_msg_list         in varchar2
5805  --                      : p_validation_level      in number
5806  --          		 : i_cost_method           in number
5807  --          		 : i_operating_unit    	   in number
5808  --          		 : i_ledger_id         	   in number
5809  --              	 : i_pac_legal_entity      in number
5810  --              	 : i_pac_cost_type     	   in number
5811  --          		 : i_pac_cost_group    	   in number
5812  --                      : i_period_name       	   in varchar2
5813  --                      : i_sales_order_date_low  in date
5814  --                      : i_sales_order_date_high in date
5815  --          		 : i_all_lines         	   in varchar2
5816  --
5817  --      out             : x_return_status         out nocopy varchar2
5818  --                      : x_msg_count             out nocopy number
5819  --                      : x_msg_data              out nocopy varchar2
5820  --
5821  --      in out          : x_xml_doc               in out nocopy clob
5822  --
5823  --      Version         : Current version         1.0
5824  --                      : Initial version         1.0
5825  --      History         : 6/24/2005    David Gottlieb  Created
5826  --      Notes           : This Procedure is called by Generate_DefCOGSXml
5827  --                        procedure. The procedure generates XML data from
5828  --                        sql query and appends it to the report output.
5829  -- End of comments
5830  /*===========================================================================*/
5831  procedure Add_DefCOGSData (
5832    p_api_version           in              number,
5833    p_init_msg_list         in              varchar2,
5834    p_validation_level      in              number,
5835    x_return_status         out nocopy      varchar2,
5836    x_msg_count             out nocopy      number,
5837    x_msg_data              out nocopy      varchar2,
5838    i_cost_method           in              number,
5839    i_operating_unit	   in		   number,
5840    i_ledger_id		   in		   number,
5841    i_pac_legal_entity      in		   number,
5842    i_pac_cost_type	   in 		   number,
5843    i_pac_cost_group	   in		   number,
5844    i_period_name           in              varchar2,
5845    i_sales_order_date_low  in              date,
5846    i_sales_order_date_high in              date,
5847    i_all_lines             in              varchar2,
5848    x_xml_doc               in out nocopy   clob) is
5849 
5850    l_api_name      	constant varchar2(100)   := 'ADD_DEFCOGSDATA';
5851    l_api_version	constant number          := 1.0;
5852 
5853    l_ref_cur            sys_refcursor;
5854    l_qryCtx             number;
5855    l_xml_temp           clob;
5856    l_offset             pls_integer;
5857    l_count              number;
5858    l_stmt_num           number;
5859    l_dummy_date         date;
5860    l_date_offset        number;
5861 
5862    l_full_name     	constant varchar2(2000)  := G_PKG_NAME || '.' || l_api_name;
5863    l_module        	constant varchar2(2000)  := 'cst.plsql.' || l_full_name;
5864    l_uLog          	constant boolean         := (fnd_log.LEVEL_UNEXPECTED >= G_LOG_LEVEL) AND fnd_log.test(fnd_log.LEVEL_UNEXPECTED, l_module);
5865    l_errorLog      	constant boolean         := l_uLog AND (fnd_log.LEVEL_ERROR >= G_LOG_LEVEL);
5866    l_eventLog     	constant boolean         := l_errorLog and (fnd_log.LEVEL_EVENT >= G_LOG_LEVEL);
5867    l_pLog          	constant boolean         := l_eventLog and (fnd_log.LEVEL_PROCEDURE >= G_LOG_LEVEL);
5868 
5869  begin
5870 
5871    -- Write the module name to fnd log file
5872 
5873    IF l_pLog THEN
5874      FND_LOG.string(FND_LOG.LEVEL_PROCEDURE,l_module||'.begin',
5875        'Entering '||G_PKG_NAME||'.'||l_api_name||' with '||
5876         'p_api_version = '||p_api_version||','||
5877         'i_cost_method = '||i_cost_method||','||
5878         'i_operating_unit = '||i_operating_unit||','||
5879         'i_ledger_id = '||i_ledger_id||','||
5880         'i_pac_legal_entity = '||i_pac_legal_entity||','||
5881         'i_pac_cost_type = '||i_pac_cost_type||','||
5882         'i_pac_cost_group = '||i_pac_cost_group||','||
5883         'i_period_name = '||i_period_name||','||
5884         'i_sales_order_date_low = '||to_char(i_sales_order_date_low,'DD-MON-YYYY HH24:MI:SS')||','||
5885         'i_sales_order_date_high = '||to_char(i_sales_order_date_high,'DD-MON-YYYY HH24:MI:SS')||','||
5886         'i_all_lines = '||i_all_lines
5887      );
5888    END IF;
5889 
5890    -- Standard call to check for call compatibility.
5891 
5892    if(not fnd_api.Compatible_API_Call( l_api_version,
5893                                        p_api_version,
5894                                        l_api_name,
5895                                        G_PKG_NAME)) then
5896      raise fnd_api.G_EXC_UNEXPECTED_ERROR;
5897    end if;
5898 
5899    -- Initialize message list if p_init_msg_list is set to TRUE.
5900 
5901    if(fnd_api.to_boolean(p_init_msg_list)) then
5902      fnd_msg_pub.initialize;
5903    end if;
5904 
5905    --  Initialize API return status to success
5906 
5907    x_return_status := fnd_api.G_RET_STS_SUCCESS;
5908 
5909    -- Initialize temporary variable to hold xml data
5910 
5911    dbms_lob.createtemporary(l_xml_temp, TRUE);
5912    l_offset := 21;
5913 
5914    -- open ref cur to fetch Deferred COGS data
5915 
5916    l_stmt_num := 10;
5917 
5918    if(i_cost_method = 1) then
5919 ----------------------------------------------------------------------------------------------
5920 -- Perpetual report
5921 ----------------------------------------------------------------------------------------------
5922 
5923      l_dummy_date := SYSDATE;
5924      l_date_offset := inv_le_timezone_pub.get_le_day_time_for_ou(
5925                         l_dummy_date,
5926                         i_operating_unit
5927                       ) - l_dummy_date;
5928 
5929      open l_ref_cur for '
5930        with Z AS
5931        (
5932         SELECT /* index(srclines RA_CUSTOMER_TRX_LINES_N9) LEADING (Q, srclines) use_nl(Q, srclines) */
5933             Q.ORDER_NUMBER                                      order_number,
5934             Q.booked_date   /* maybe ordered_date? */           order_date,
5935             (select substrb(PARTY.PARTY_NAME,1,50)
5936              from HZ_PARTIES party
5937              where CUST_ACCT.PARTY_ID = PARTY.PARTY_ID) customer_name,
5938             Q.transactional_curr_code                           currency,
5939             Q.line_number                                       sales_order_line,
5940             msi.concatenated_segments                             item,
5941             srclines.line_number                                  invoice_line,
5942             srclines.customer_trx_line_id,
5943             srclines.customer_trx_id,
5944             -------------------------
5945             sum(cce1.EVENT_QUANTITY)                              total_line_quantity,
5946             Q.COGS_BALANCE                                        Earned_COGS,
5947             Q.DEF_COGS_BALANCE                                    Deferred_COGS,
5948             cogs_acct.concatenated_segments                       COGS_account,
5949             dcogs_acct.concatenated_segments                      Deferred_COGS_account
5950         FROM
5951         (
5952          SELECT /*+ leading(crcml), index(crcml CST_REV_COGS_MATCH_LINES_N2) */
5953            OOH.ORDER_NUMBER,
5954            OOH.BOOKED_DATE,
5955            OOH.transactional_curr_code,
5956            OOL.LINE_NUMBER,
5957            OOL.SOLD_TO_ORG_ID,
5958            CRCML.COGS_OM_LINE_ID,
5959            CRCML.REVENUE_OM_LINE_ID,
5960            CRCML.ORGANIZATION_ID,
5961            CRCML.inventory_item_id,
5962            CRCML.UNIT_COST,
5963            CRCML.COGS_ACCT_ID,
5964            CRCML.DEFERRED_COGS_ACCT_ID,
5965            sum(decode(mta.accounting_line_type, 35, MTA.BASE_TRANSACTION_VALUE,0)) COGS_BALANCE,
5966            sum(decode(mta.accounting_line_type, 36, MTA.BASE_TRANSACTION_VALUE,0)) DEF_COGS_BALANCE
5967          FROM
5968            CST_REVENUE_COGS_MATCH_LINES CRCML,
5969            CST_COGS_EVENTS CCE,
5970            GL_PERIOD_STATUSES GPS,
5971            OE_ORDER_LINES_ALL OOL,
5972            OE_ORDER_HEADERS_ALL OOH,
5973            MTL_TRANSACTION_ACCOUNTS MTA
5974          WHERE
5975              CRCML.SALES_ORDER_ISSUE_DATE BETWEEN :i_sales_order_date_low AND :i_sales_order_date_high
5976          AND CRCML.OPERATING_UNIT_ID = :i_operating_unit
5977          AND CRCML.PAC_COST_TYPE_ID IS NULL
5978          AND GPS.APPLICATION_ID = 101
5979          AND GPS.SET_OF_BOOKS_ID = :i_ledger_id
5980          AND GPS.PERIOD_NAME = :i_period_name
5981          AND CCE.EVENT_DATE <= GPS.END_DATE + .99999 - :l_date_offset
5982          AND CCE.COGS_OM_LINE_ID = CRCML.COGS_OM_LINE_ID
5983          AND OOL.HEADER_ID = OOH.HEADER_ID
5984          AND OOL.LINE_ID  = CRCML.COGS_OM_LINE_ID
5985          AND mta.transaction_id (+) = cce.mmt_transaction_id
5986          GROUP BY
5987            OOH.ORDER_NUMBER,
5988            OOH.BOOKED_DATE,
5989            OOH.transactional_curr_code,
5990            OOL.LINE_NUMBER,
5991            OOL.SOLD_TO_ORG_ID,
5992            CRCML.COGS_OM_LINE_ID,
5993            CRCML.REVENUE_OM_LINE_ID,
5994            CRCML.ORGANIZATION_ID,
5995            CRCML.inventory_item_id,
5996            CRCML.UNIT_COST,
5997            CRCML.COGS_ACCT_ID,
5998            CRCML.DEFERRED_COGS_ACCT_ID
5999         ) Q,
6000           MTL_SYSTEM_ITEMS_KFV MSI,
6001           gl_code_combinations_kfv cogs_acct,
6002           gl_code_combinations_kfv dcogs_acct,
6003           ra_customer_trx_lines_all   srclines,
6004           HZ_CUST_ACCOUNTS cust_acct,
6005           cst_cogs_events cce1
6006         WHERE
6007             MSI.INVENTORY_ITEM_ID = Q.INVENTORY_ITEM_ID
6008         AND MSI.ORGANIZATION_ID = Q.ORGANIZATION_ID
6009         AND cogs_acct.code_combination_id = Q.cogs_acct_id
6010         AND dcogs_acct.code_combination_id = Q.deferred_cogs_acct_id
6011         AND Q.sold_to_org_id = cust_acct.CUST_ACCOUNT_ID (+)
6012         AND srclines.line_type                 (+) = ''LINE''
6013         AND srclines.interface_line_context    (+) = ''ORDER ENTRY''
6014         AND srclines.interface_line_attribute6 (+) = to_char(Q.revenue_om_line_id)
6015         AND srclines.sales_order               (+) = to_char(Q.order_number)
6016         AND cce1.cogs_om_line_id = Q.cogs_om_line_id
6017         AND cce1.event_type in (1,2)
6018         GROUP BY
6019             Q.ORDER_NUMBER,
6020             Q.booked_date,
6021             CUST_ACCT.PARTY_ID,
6022             Q.transactional_curr_code,
6023             Q.line_number,
6024             msi.concatenated_segments,
6025             srclines.line_number,
6026             srclines.customer_trx_line_id,
6027             srclines.customer_trx_id,
6028             Q.COGS_BALANCE,
6029             Q.DEF_COGS_BALANCE,
6030             cogs_acct.concatenated_segments,
6031             dcogs_acct.concatenated_segments
6032        )
6033        SELECT :i_all_lines          all_lines,
6034          Z.order_number        order_number,
6035          Z.order_date          order_date,
6036          Z.customer_name       customer,
6037          Z.currency            currency,
6038          Z.sales_order_line    order_line,
6039          trx.trx_number        invoice_number,
6040          Z.invoice_line        invoice_line,
6041          Z.item                item_number,
6042          ROUND(SUM ( DECODE(dist.account_class, ''UNEARN'', 0,
6043             ''UNBILL'', 0, dist.acctd_amount) ), 2)       earned_revenue,
6044          ROUND(SUM ( DECODE(dist.account_class, ''REV'', 0,
6045             ''UNBILL'', 0, dist.acctd_amount) ), 2)       unearned_revenue,
6046          ROUND(SUM ( DECODE(dist.account_class, ''REV'', 0,
6047             ''UNEARN'', 0, dist.acctd_amount) ), 2)       unbilled_revenue,
6048          Z.total_line_quantity order_quantity,
6049          Z.Earned_COGS         earned_cogs,
6050          Z.Deferred_COGS       deferred_cogs,
6051          Z.COGS_account        cogs_account,
6052          Z.Deferred_COGS_account deferred_cogs_account
6053        FROM
6054          Z,
6055          GL_PERIOD_STATUSES GPS1,
6056          ra_cust_trx_line_gl_dist_all   dist,
6057          ra_customer_trx_lines_all      lines,
6058          ra_customer_trx_all            trx
6059        WHERE (Z.customer_trx_line_id = lines.customer_trx_line_id
6060               OR Z.customer_trx_line_id = lines.previous_customer_trx_line_id)
6061        AND Z.customer_trx_id = trx.customer_trx_id
6062        AND GPS1.APPLICATION_ID = 101
6063        AND GPS1.SET_OF_BOOKS_ID = :i_ledger_id
6064        AND GPS1.PERIOD_NAME = :i_period_name
6065        AND    dist.customer_trx_line_id        = lines.customer_trx_line_id
6066        AND    dist.account_set_flag            = ''N''
6067        AND    dist.account_class               IN  (''REV'', ''UNEARN'', ''UNBILL'')
6068        AND    dist.gl_date <= GPS1.END_DATE + .99999-- or AS OF DATE
6069        GROUP BY
6070          Z.ORDER_NUMBER,
6071          Z.order_date,
6072          Z.customer_name,
6073          Z.currency,
6074          Z.sales_order_line,
6075          trx.trx_number,
6076          Z.invoice_line,
6077          Z.item,
6078          Z.total_line_quantity,
6079          Z.Earned_COGS,
6080          Z.Deferred_COGS,
6081          Z.COGS_account,
6082          Z.Deferred_COGS_account
6083        HAVING :i_all_lines = ''Y''
6084          or decode(sum(lines.revenue_amount),0,1,
6085                 round(sum(decode(dist.account_class, ''UNEARN'', 0,
6086                                  ''UNBILL'', 0, dist.acctd_amount))  /
6087                       (sum(lines.revenue_amount) /
6088                        count(dist.cust_trx_line_gl_dist_id)), 3))
6089                  <>
6090             decode(z.earned_cogs, 0, decode(z.deferred_cogs,0,1,0),
6091                 round((z.earned_cogs /
6092                        (z.deferred_cogs + z.earned_cogs)), 3))
6093        UNION
6094        SELECT :i_all_lines           all_lines,
6095          Z.order_number         order_number,
6096          Z.order_date           order_date,
6097          Z.customer_name        customer,
6098          Z.currency             currency,
6099          Z.sales_order_line     order_line,
6100          NULL     invoice_number,
6101          NULL     invoice_line,
6102          Z.item   item_number,
6103          NULL     earned_revenue,
6104          NULL     unearned_revenue,
6105          NULL     unbilled_revenue,
6106          Z.total_line_quantity order_quantity,
6107          Z.Earned_COGS   earned_cogs,
6108          Z.Deferred_COGS deferred_cogs,
6109          Z.COGS_account cogs_account,
6110          Z.Deferred_COGS_account deferred_cogs_account
6111        FROM
6112          Z
6113        WHERE Z.customer_trx_line_id IS NULL
6114           OR Z.customer_trx_id IS NULL'
6115      using i_sales_order_date_low,
6116            i_sales_order_date_high,
6117            i_operating_unit,
6118            i_ledger_id,
6119            i_period_name,
6120            l_date_offset,
6121            i_all_lines,
6122            i_ledger_id,
6123            i_period_name,
6124            i_all_lines,
6125            i_all_lines;
6126 
6127        elsif(i_cost_method = 3) then
6128 ----------------------------------------------------------------------------------------------
6129 -- PAC report
6130 ----------------------------------------------------------------------------------------------
6131          l_dummy_date := SYSDATE;
6132 
6133          SELECT inv_le_timezone_pub.get_server_day_time_for_le(
6134                   l_dummy_date,
6135                   legal_entity
6136                 ) - l_dummy_date
6137          INTO   l_date_offset
6138          FROM   cst_cost_groups
6139          WHERE  cost_group_id = i_pac_cost_group;
6140 
6141          open l_ref_cur for 'with Z AS
6142        (
6143         SELECT /* index(srclines RA_CUSTOMER_TRX_LINES_N9) LEADING (Q, srclines) use_nl(Q, srclines) */
6144             Q.ORDER_NUMBER                                      order_number,
6145             Q.booked_date   /* maybe ordered_date? */           order_date,
6146             (select substrb(PARTY.PARTY_NAME,1,50)
6147              from HZ_PARTIES party
6148              where CUST_ACCT.PARTY_ID = PARTY.PARTY_ID) customer_name,
6149             Q.transactional_curr_code                           currency,
6150             Q.line_number                                       sales_order_line,
6151             msi.concatenated_segments                             item,
6152             srclines.line_number                                  invoice_line,
6153             srclines.customer_trx_line_id,
6154             srclines.customer_trx_id,
6155             -------------------------
6156             sum(cce1.EVENT_QUANTITY)                              total_line_quantity,
6157             Q.COGS_BALANCE                                        Earned_COGS,
6158             Q.DEF_COGS_BALANCE                                    Deferred_COGS,
6159             cogs_acct.concatenated_segments                       COGS_account,
6160             dcogs_acct.concatenated_segments                      Deferred_COGS_account
6161         FROM
6162         (
6163          SELECT /* LEADING(CCGA) */
6164            OOH.ORDER_NUMBER,
6165            OOH.BOOKED_DATE,
6166            OOH.transactional_curr_code,
6167            OOL.LINE_NUMBER,
6168            OOL.SOLD_TO_ORG_ID,
6169            CRCML.COGS_OM_LINE_ID,
6170            CRCML.REVENUE_OM_LINE_ID,
6171            CRCML.ORGANIZATION_ID,
6172            CRCML.inventory_item_id,
6173            CRCML.UNIT_COST,
6174            CRCML.COGS_ACCT_ID,
6175            CRCML.DEFERRED_COGS_ACCT_ID,
6176            sum(decode(CAL.ae_line_type_code, 35, nvl(CAL.accounted_dr,0) - nvl(CAL.accounted_cr,0),0)) COGS_BALANCE,
6177            sum(decode(CAL.ae_line_type_code, 36, nvl(CAL.accounted_dr,0) - nvl(CAL.accounted_cr,0),0)) DEF_COGS_BALANCE
6178          FROM
6179            CST_REVENUE_COGS_MATCH_LINES CRCML,
6180            CST_COGS_EVENTS CCE,
6181            OE_ORDER_LINES_ALL OOL,
6182            OE_ORDER_HEADERS_ALL OOH,
6183            CST_COST_GROUP_ASSIGNMENTS CCGA,
6184            CST_PAC_PERIODS CPP,
6185            CST_AE_HEADERS CAH,
6186            CST_AE_LINES CAL
6187          WHERE
6188              CRCML.SALES_ORDER_ISSUE_DATE BETWEEN :i_sales_order_date_low AND :i_sales_order_date_high
6189          AND CRCML.ORGANIZATION_ID = CCGA.ORGANIZATION_ID
6190          AND CRCML.PAC_COST_TYPE_ID IS NULL -- Want to pick up all events, not just PAC-costed events
6191          AND CCGA.COST_GROUP_ID = :i_pac_cost_group
6192          AND CPP.PAC_PERIOD_ID = TO_NUMBER(:i_period_name)
6193          AND CCE.EVENT_DATE <= CPP.PERIOD_END_DATE + .99999 + :l_date_offset
6194          AND CCE.COGS_OM_LINE_ID = CRCML.COGS_OM_LINE_ID
6195          AND OOL.HEADER_ID = OOH.HEADER_ID
6196          AND OOL.LINE_ID  = CRCML.COGS_OM_LINE_ID
6197          AND CCE.MMT_TRANSACTION_ID = CAH.ACCOUNTING_EVENT_ID (+)
6198          AND CAH.AE_HEADER_ID = CAL.AE_HEADER_ID (+)
6199          GROUP BY
6200            OOH.ORDER_NUMBER,
6201            OOH.BOOKED_DATE,
6202            OOH.transactional_curr_code,
6203            OOL.LINE_NUMBER,
6204            OOL.SOLD_TO_ORG_ID,
6205            CRCML.COGS_OM_LINE_ID,
6206            CRCML.REVENUE_OM_LINE_ID,
6207            CRCML.ORGANIZATION_ID,
6208            CRCML.inventory_item_id,
6209            CRCML.UNIT_COST,
6210            CRCML.COGS_ACCT_ID,
6211            CRCML.DEFERRED_COGS_ACCT_ID
6212         ) Q,
6213           MTL_SYSTEM_ITEMS_KFV MSI,
6214           gl_code_combinations_kfv cogs_acct,
6215           gl_code_combinations_kfv dcogs_acct,
6216           ra_customer_trx_lines_all   srclines,
6217           HZ_CUST_ACCOUNTS cust_acct,
6218           cst_cogs_events cce1
6219         WHERE
6220             MSI.INVENTORY_ITEM_ID = Q.INVENTORY_ITEM_ID
6221         AND MSI.ORGANIZATION_ID = Q.ORGANIZATION_ID
6222         AND cogs_acct.code_combination_id = Q.cogs_acct_id
6223         AND dcogs_acct.code_combination_id = Q.deferred_cogs_acct_id
6224         AND Q.sold_to_org_id = cust_acct.CUST_ACCOUNT_ID (+)
6225         AND srclines.line_type                 (+) = ''LINE''
6226         AND srclines.interface_line_context    (+) = ''ORDER ENTRY''
6227         AND srclines.interface_line_attribute6 (+) = to_char(Q.revenue_om_line_id)
6228         AND srclines.sales_order               (+) = to_char(Q.order_number)
6229         AND cce1.cogs_om_line_id = Q.cogs_om_line_id
6230         AND cce1.event_type in (1,2)
6231         GROUP BY
6232             Q.ORDER_NUMBER,
6233             Q.booked_date,
6234             CUST_ACCT.PARTY_ID,
6235             Q.transactional_curr_code,
6236             Q.line_number,
6237             msi.concatenated_segments,
6238             srclines.line_number,
6239             srclines.customer_trx_line_id,
6240             srclines.customer_trx_id,
6241             Q.COGS_BALANCE,
6242             Q.DEF_COGS_BALANCE,
6243             cogs_acct.concatenated_segments,
6244             dcogs_acct.concatenated_segments
6245        )
6246        SELECT :i_all_lines          all_lines,
6247          Z.order_number        order_number,
6248          Z.order_date          order_date,
6249          Z.customer_name       customer,
6250          Z.currency            currency,
6251          Z.sales_order_line    order_line,
6252          trx.trx_number        invoice_number,
6253          Z.invoice_line        invoice_line,
6254          Z.item                item_number,
6255          ROUND(SUM ( DECODE(dist.account_class, ''UNEARN'', 0,
6256             ''UNBILL'', 0, dist.acctd_amount) ), 2)       earned_revenue,
6257          ROUND(SUM ( DECODE(dist.account_class, ''REV'', 0,
6258             ''UNBILL'', 0, dist.acctd_amount) ), 2)       unearned_revenue,
6259          ROUND(SUM ( DECODE(dist.account_class, ''REV'', 0,
6260             ''UNEARN'', 0, dist.acctd_amount) ), 2)       unbilled_revenue,
6261          Z.total_line_quantity order_quantity,
6262          Z.Earned_COGS         earned_cogs,
6263          Z.Deferred_COGS       deferred_cogs,
6264          Z.COGS_account        cogs_account,
6265          Z.Deferred_COGS_account deferred_cogs_account
6266        FROM
6267          Z,
6268          cst_pac_periods cpp,
6269          ra_cust_trx_line_gl_dist_all   dist,
6270          ra_customer_trx_lines_all      lines,
6271          ra_customer_trx_all            trx
6272        WHERE (Z.customer_trx_line_id = lines.customer_trx_line_id
6273               OR Z.customer_trx_line_id = lines.previous_customer_trx_line_id)
6274        AND Z.customer_trx_id = trx.customer_trx_id
6275        AND cpp.pac_period_id = TO_NUMBER(:i_period_name)
6276        AND    dist.customer_trx_line_id        = lines.customer_trx_line_id
6277        AND    dist.account_set_flag            = ''N''
6278        AND    dist.account_class               IN  (''REV'', ''UNEARN'', ''UNBILL'')
6279        AND    dist.gl_date <= cpp.period_end_date + .99999-- or AS OF DATE
6280        GROUP BY
6281          Z.ORDER_NUMBER,
6282          Z.order_date,
6283          Z.customer_name,
6284          Z.currency,
6285          Z.sales_order_line,
6286          trx.trx_number,
6287          Z.invoice_line,
6288          Z.item,
6289          Z.total_line_quantity,
6290          Z.Earned_COGS,
6291          Z.Deferred_COGS,
6292          Z.COGS_account,
6293          Z.Deferred_COGS_account
6294        HAVING :i_all_lines = ''Y''
6295          or decode(sum(lines.revenue_amount),0,1,
6296                 round(sum(decode(dist.account_class, ''UNEARN'', 0,
6297                                  ''UNBILL'', 0, dist.acctd_amount))  /
6298                       (sum(lines.revenue_amount) /
6299                        count(dist.cust_trx_line_gl_dist_id)), 3))
6300                  <>
6301             decode(z.earned_cogs, 0, decode(z.deferred_cogs,0,1,0),
6302                 round((z.earned_cogs /
6303                        (z.deferred_cogs + z.earned_cogs)), 3))
6304        UNION
6305        SELECT :i_all_lines           all_lines,
6306          Z.order_number         order_number,
6307          Z.order_date           order_date,
6308          Z.customer_name        customer,
6309          Z.currency             currency,
6310          Z.sales_order_line     order_line,
6311          NULL     invoice_number,
6312          NULL     invoice_line,
6313          Z.item   item_number,
6314          NULL     earned_revenue,
6315          NULL     unearned_revenue,
6316          NULL     unbilled_revenue,
6317          Z.total_line_quantity order_quantity,
6318          Z.Earned_COGS   earned_cogs,
6319          Z.Deferred_COGS deferred_cogs,
6320          Z.COGS_account cogs_account,
6321          Z.Deferred_COGS_account deferred_cogs_account
6322        FROM
6323          Z
6324        WHERE Z.customer_trx_line_id IS NULL
6325           OR Z.customer_trx_id IS NULL'
6326 		         using
6327 				  i_sales_order_date_low,
6328 				  i_sales_order_date_high,
6329 				  i_pac_cost_group,
6330 				  i_period_name,
6331                                   l_date_offset,
6332                                   i_all_lines,
6333 				  i_period_name,
6334 				  i_all_lines,
6335 				  i_all_lines;
6336 
6337        end if; /* i_cost_method = 1, i_cost_method = 3 */
6338 
6339        -- create new context
6340 
6341        l_stmt_num := 20;
6342 
6343        l_qryCtx := dbms_xmlgen.newContext(l_ref_cur);
6344        dbms_xmlgen.setRowSetTag(l_qryCtx,'DEF_COGS_DATA');
6345        dbms_xmlgen.setRowTag(l_qryCtx,'DEF_COGS');
6346 
6347        -- get XML into the temporary clob variable
6348 
6349        l_stmt_num := 70;
6350 
6351        dbms_xmlgen.getXML(l_qryCtx, l_xml_temp, dbms_xmlgen.none);
6352 
6353        -- remove the header (21 characters) and append the rest to xml output
6354 
6355        l_count := dbms_xmlgen.getNumRowsProcessed(l_qryCtx);
6356 
6357        if(dbms_xmlgen.getNumRowsProcessed(l_qryCtx) > 0) then
6358          dbms_lob.erase(l_xml_temp, l_offset,1);
6359          dbms_lob.append(x_xml_doc, l_xml_temp);
6360        end if;
6361 
6362        -- close context and free memory
6363 
6364        dbms_xmlgen.closeContext(l_qryCtx);
6365      close l_ref_cur;
6366      dbms_lob.freetemporary(l_xml_temp);
6367 
6368      -- to add number of rows processed
6369 
6370      dbms_lob.createtemporary(l_xml_temp, TRUE);
6371 
6372      -- open ref cursor to get the number of rows processed
6373 
6374      l_stmt_num := 80;
6375 
6376      open l_ref_cur for ' select :l_count l_count
6377                           from dual'
6378                         using l_count;
6379 
6380        -- create new context
6381 
6382        l_stmt_num := 90;
6383 
6384        l_qryCtx := DBMS_XMLGEN.newContext (l_ref_cur);
6385        dbms_xmlgen.setRowSetTag (l_qryCtx,'RECORD_NUM');
6386        dbms_xmlgen.setRowTag (l_qryCtx,NULL);
6387 
6388        -- get XML to add the number of rows processed
6389 
6390        l_stmt_num := 100;
6391 
6392        dbms_xmlgen.getXML (l_qryCtx, l_xml_temp, dbms_xmlgen.none);
6393 
6394        -- remove the header (21 characters) and append the rest to xml output
6395 
6396        if(dbms_xmlgen.getNumRowsProcessed(l_qryCtx) > 0 ) then
6397          dbms_lob.erase (l_xml_temp, l_offset,1);
6398          dbms_lob.append (x_xml_doc, l_xml_temp);
6399        end if;
6400 
6401        -- close context and free memory
6402 
6403        dbms_xmlgen.closeContext(l_qryCtx);
6404      close l_ref_cur;
6405      dbms_lob.freetemporary(l_xml_temp);
6406 
6407      -- Standard call to get message count and if count is 1, get message info.
6408 
6409      fnd_msg_pub.Count_And_Get
6410      (       p_count         =>      x_msg_count,
6411              p_data          =>      x_msg_data
6412      );
6413 
6414      -- Write the module name to fnd log file
6415      IF l_pLog THEN
6416         fnd_log.string(fnd_log.level_procedure,l_module||'.end',
6417           'Exiting '||G_PKG_NAME||'.'||l_api_name||' with '||
6418           'x_return_status = '||x_return_status
6419         );
6420      END IF;
6421 
6422      exception
6423        when fnd_api.G_EXC_ERROR then
6424          x_return_status := fnd_api.G_RET_STS_ERROR;
6425          fnd_msg_pub.Count_And_Get
6426          (       p_count         =>      x_msg_count,
6427                  p_data          =>      x_msg_data
6428          );
6429 
6430        when fnd_api.G_EXC_UNEXPECTED_ERROR then
6431          x_return_status := fnd_api.G_RET_STS_UNEXP_ERROR;
6432          fnd_msg_pub.Count_And_Get
6433          (       p_count         =>      x_msg_count,
6434                  p_data          =>      x_msg_data
6435          );
6436 
6437        when others then
6438          x_return_status := fnd_api.G_RET_STS_UNEXP_ERROR;
6439          if(fnd_log.LEVEL_UNEXPECTED >= G_LOG_LEVEL) then
6440            fnd_log.string(fnd_log.LEVEL_UNEXPECTED,
6441                                         l_module || '.' || l_stmt_num,
6442                                         substrb(SQLERRM , 1 , 240));
6443          end if;
6444 
6445          if(fnd_msg_pub.Check_Msg_Level(fnd_msg_pub.G_MSG_LVL_UNEXP_ERROR)) then
6446            fnd_msg_pub.Add_Exc_Msg (G_PKG_NAME, l_api_name);
6447          end if;
6448 
6449          fnd_msg_pub.Count_And_Get
6450          (     p_count         =>      x_msg_count,
6451                p_data          =>      x_msg_data
6452          );
6453 
6454   end Add_DefCOGSData;
6455 
6456 
6457   PROCEDURE debug
6458   ( line       IN VARCHAR2,
6459     msg_prefix IN VARCHAR2  DEFAULT 'CST',
6460     msg_module IN VARCHAR2  DEFAULT g_module_name,
6461     msg_level  IN NUMBER    DEFAULT FND_LOG.LEVEL_STATEMENT)
6462   IS
6463     l_msg_prefix     VARCHAR2(64);
6464     l_msg_level      NUMBER;
6465     l_msg_module     VARCHAR2(256);
6466     l_beg_end_suffix VARCHAR2(15);
6467     l_org_cnt        NUMBER;
6468     l_line           VARCHAR2(32767);
6469   BEGIN
6470     l_line       := line;
6471     l_msg_prefix := msg_prefix;
6472     l_msg_level  := msg_level;
6473     l_msg_module := msg_module;
6474     IF (INSTRB(upper(l_line), 'EXCEPTION') <> 0) THEN
6475       l_msg_level  := FND_LOG.LEVEL_EXCEPTION;
6476     END IF;
6477     IF l_msg_level <> FND_LOG.LEVEL_EXCEPTION AND G_DEBUG = 'N' THEN
6478       RETURN;
6479     END IF;
6480     IF ( l_msg_level >= FND_LOG.G_CURRENT_RUNTIME_LEVEL ) THEN
6481       FND_LOG.STRING(l_msg_level, l_msg_module, SUBSTRB(l_line,1,4000));
6482     END IF;
6483   EXCEPTION
6484     WHEN OTHERS THEN RAISE;
6485   END debug;
6486 
6487 
6488 
6489 
6490 
6491 
6492 PROCEDURE ensure_mmt_per_and_date
6493 (x_return_status   OUT NOCOPY     VARCHAR2,
6494  x_msg_count       OUT NOCOPY     NUMBER,
6495  x_msg_data        OUT NOCOPY     VARCHAR2)
6496 IS
6497   CURSOR ctrx IS
6498   SELECT  mmtt.rowid
6499          ,mmtt.transaction_id
6500          ,mmtt.transaction_date
6501          ,mmtt.acct_period_id
6502          ,oap.open_flag
6503          ,oap.period_start_date
6504          ,oap.schedule_close_date
6505          ,oap2.acct_period_id
6506          ,oap2.open_flag
6507          ,mmtt.organization_id
6508     FROM mtl_cogs_recognition_temp       mmtt,
6509          org_acct_periods                oap,
6510          (SELECT period_start_date,
6511                  schedule_close_date,
6512                  acct_period_id,
6513                  organization_id,
6514                  open_flag
6515             FROM org_acct_periods)       oap2
6516   WHERE mmtt.acct_period_id   = oap.acct_period_id
6517     AND mmtt.organization_id  = oap.organization_id
6518     AND oap2.organization_id  = mmtt.organization_id
6519 --
6520 --BUG#6873037 : Just check the inventory period mismatch
6521 --
6522     AND oap2.acct_period_id   <> oap.acct_period_id
6523     AND mmtt.transaction_date BETWEEN oap2.period_start_date AND oap2.schedule_close_date
6524     AND ( mmtt.transaction_date < oap.period_start_date   OR
6525           mmtt.transaction_date > oap.schedule_close_date );
6526 --BUG#6873037
6527 -- No need to verify inventory period status
6528 --OR  oap.open_flag         = 'N');
6529 --
6530   l_mmtt_rowid_tab             DBMS_SQL.VARCHAR2_TABLE;
6531   l_transaction_id_tab         DBMS_SQL.NUMBER_TABLE;
6532   l_transaction_date_tab       DBMS_SQL.DATE_TABLE;
6533   l_acct_period_id_tab         DBMS_SQL.NUMBER_TABLE;
6534   l_open_flag                  DBMS_SQL.VARCHAR2_TABLE;
6535   l_period_start_date_tab      DBMS_SQL.DATE_TABLE;
6536   l_schedule_close_date_tab    DBMS_SQL.DATE_TABLE;
6537   l_good_acct_period_id_tab    DBMS_SQL.NUMBER_TABLE;
6538   l_good_open_flag_tab         DBMS_SQL.VARCHAR2_TABLE;
6539   l_organization_id_tab        DBMS_SQL.VARCHAR2_TABLE;
6540 
6541 
6542   CURSOR next_inv_period(p_organization_id    IN NUMBER
6543                         ,p_transaction_date   IN DATE)
6544   IS
6545     SELECT MIN(acct_period_id),
6546            MIN(period_start_date)
6547       FROM org_acct_periods
6548      WHERE organization_id    = p_organization_id
6549        AND open_flag          = 'Y'
6550        AND period_start_date >= p_transaction_date;
6551   l_next_acct_period_id        NUMBER;
6552   l_next_transaction_date      DATE;
6553 
6554   l_upd_transaction_date_tab   DBMS_SQL.DATE_TABLE;
6555   l_upd_acct_period_id_tab     DBMS_SQL.NUMBER_TABLE;
6556   g_bulk_fetch_size            NUMBER             := 9999;
6557   l_last_fetch                 BOOLEAN            := FALSE;
6558   l_msg_count                  NUMBER             := 0;
6559   l_msg_data                   VARCHAR2(8000)     := '';
6560   l_stmt_num                   NUMBER             := 0;
6561 BEGIN
6562   g_module_name := 'CST_RevenueCogsMatch_PVT.Ensure_mmt_PER_and_DATE';
6563   debug('ensure_mmt_per_and_date+');
6564   SAVEPOINT ensure_mmt_per_and_date;
6565   x_return_status := fnd_api.g_ret_sts_success;
6566 
6567   OPEN ctrx;
6568   LOOP
6569     l_stmt_num := 1;
6570     FETCH ctrx BULK COLLECT INTO
6571           l_mmtt_rowid_tab
6572          ,l_transaction_id_tab
6573          ,l_transaction_date_tab
6574          ,l_acct_period_id_tab
6575          ,l_open_flag
6576          ,l_period_start_date_tab
6577          ,l_schedule_close_date_tab
6578          ,l_good_acct_period_id_tab
6579          ,l_good_open_flag_tab
6580          ,l_organization_id_tab
6581     LIMIT g_bulk_fetch_size;
6582 
6583     IF ctrx%NOTFOUND THEN
6584        l_last_fetch := TRUE;
6585     END IF;
6586 
6587     IF l_last_fetch AND l_mmtt_rowid_tab.COUNT = 0 THEN
6588        EXIT;
6589     END IF;
6590 
6591     FOR i IN l_mmtt_rowid_tab.FIRST .. l_mmtt_rowid_tab.LAST LOOP
6592       l_stmt_num := 2;
6593 
6594       debug
6595 (l_stmt_num||'----------------------:
6596 l_transaction_id_tab    :'||l_transaction_id_tab(i)||'
6597 l_transaction_date_tab   :'||l_transaction_date_tab(i)||'
6598 l_acct_period_id_tab     :'||l_acct_period_id_tab(i)||'
6599 l_open_flag              :'||l_open_flag(i)||'
6600 l_period_start_date_tab  :'||l_period_start_date_tab(i)||'
6601 l_schedule_close_date_tab:'||l_schedule_close_date_tab(i)||'
6602 l_good_acct_period_id_tab:'||l_good_acct_period_id_tab(i)||'
6603 l_good_open_flag_tab     :'||l_good_open_flag_tab(i)||'
6604 l_organization_id_tab    :'||l_organization_id_tab(i));
6605 
6606       IF        (l_acct_period_id_tab(i) <> l_good_acct_period_id_tab(i))
6607       THEN
6608          -- Update the acct_period_id with the l_good_acct_period_id_tab
6609          l_stmt_num := 21;
6610          l_upd_transaction_date_tab(i) := l_transaction_date_tab(i);
6611          l_upd_acct_period_id_tab(i)   := l_good_acct_period_id_tab(i);
6612          debug(l_stmt_num||': l_upd_transaction_date_tab:'|| l_upd_transaction_date_tab(i));
6613          debug(l_stmt_num||': l_upd_acct_period_id_tab  :'|| l_upd_acct_period_id_tab(i));
6614       ELSE
6615          -- Update the acct_period and transaction_date to the next opened inventory
6616          -- log a message
6617          l_stmt_num := 22;
6618          -- COGS transaction should not care about the status of inventory period as per design
6619          -- If GL is closed the problem will happen at GL post. Use needs to reopen GL period
6620          -- Not inventory Cst issue
6621          debug('Inventory period and COGS Inventory transaction date are in synchi but
6622 Inventory period has been closed');
6623          l_upd_transaction_date_tab(i) := l_transaction_date_tab(i);
6624          l_upd_acct_period_id_tab(i)   := l_good_acct_period_id_tab(i);
6625 
6626       END IF;
6627     END LOOP;
6628 
6629     l_stmt_num := 3;
6630     debug(l_stmt_num||': UPDATING mtl_cogs_recognition_temp transaction_date and acct_period_id');
6631     FORALL i IN l_mmtt_rowid_tab.FIRST .. l_mmtt_rowid_tab.LAST
6632       UPDATE mtl_cogs_recognition_temp
6633          SET transaction_date = l_upd_transaction_date_tab(i)
6634             ,acct_period_id   = l_upd_acct_period_id_tab(i)
6635        WHERE rowid = l_mmtt_rowid_tab(i);
6636   END LOOP;
6637   CLOSE ctrx;
6638   debug('ensure_mmt_per_and_date-');
6639 EXCEPTION
6640   WHEN OTHERS THEN
6641     --log a message
6642      ROLLBACK TO ensure_mmt_per_and_date;
6643      IF ctrx%ISOPEN THEN CLOSE ctrx; END IF;
6644      IF next_inv_period%ISOPEN THEN CLOSE next_inv_period; END IF;
6645      x_return_status := fnd_api.g_ret_sts_unexp_error ;
6646      debug('OTHERS EXCEPTION ensure_mmt_per_and_date:'||SQLERRM);
6647      fnd_message.set_name('BOM', 'CST_UNEXP_ERROR');
6648      fnd_message.set_token('PACKAGE', 'CST_REVENUECOGSMATCH_PVT');
6649      fnd_message.set_token('PROCEDURE','ensure_mmt_per_and_date');
6650      fnd_message.set_token('STATEMENT',to_char(l_stmt_num));
6651      fnd_msg_pub.ADD;
6652      fnd_msg_pub.count_and_get(
6653         p_encoded                    => fnd_api.g_false,
6654         p_count                      => x_msg_count,
6655         p_data                       => x_msg_data);
6656 END ensure_mmt_per_and_date;
6657 
6658 --BUG#7387575
6659 -- Multi worker Development for performance
6660 -- Coordination of updation in CRRL
6661 --
6662 PROCEDURE crrl_preparation
6663 (p_batch_size   IN NUMBER  DEFAULT 1000
6664 ,p_ledger_id    IN NUMBER  DEFAULT NULL)
6665 IS
6666 
6667  CURSOR c_no_ledger IS
6668  SELECT COUNT(*)
6669       , ledger_id
6670    FROM cst_revenue_recognition_lines crrl
6671   WHERE potentially_unmatched_flag = 'Y'
6672   GROUP BY ledger_id
6673   HAVING COUNT(*) > 0;
6674 
6675   l_cnt_tab   DBMS_SQL.NUMBER_TABLE;
6676   l_lgr_tab   DBMS_SQL.NUMBER_TABLE;
6677   lafin       EXCEPTION;
6678 BEGIN
6679   debug('crrl_preparation +');
6680   debug('   p_batch_size :'||p_batch_size);
6681   debug('   p_ledger_id  :'||p_ledger_id);
6682   IF p_ledger_id IS NULL THEN
6683     OPEN c_no_ledger;
6684     FETCH c_no_ledger BULK COLLECT
6685           INTO l_cnt_tab
6686               ,l_lgr_tab;
6687     CLOSE c_no_ledger;
6688     IF l_lgr_tab.COUNT = 0 THEN
6689       debug('Nothing to run non potential unmatch');
6690       RAISE lafin;
6691     END IF;
6692     FOR i IN l_lgr_tab.FIRST .. l_lgr_tab.LAST LOOP
6693        debug(' Case ledger entered is null - determining ledger_id '||l_lgr_tab(i)||' and calling updation_potential_crrl');
6694        updation_potential_crrl
6695         (p_batch_size   => p_batch_size
6696         ,p_ledger_id    => l_lgr_tab(i));
6697     END LOOP;
6698   ELSE
6699     debug(' Case ledger entered is'||p_ledger_id||' calling updation_potential_crrl');
6700     updation_potential_crrl
6701         (p_batch_size   => p_batch_size
6702         ,p_ledger_id    => p_ledger_id);
6703   END IF;
6704   debug('crrl_preparation -');
6705 EXCEPTION
6706   WHEN lafin THEN NULL;
6707   WHEN OTHERS THEN
6708      debug('EXCEPTION OTHERS crrl_preparation:'||SQLERRM);
6709      RAISE;
6710 END crrl_preparation;
6711 
6712 
6713 ------------------
6714 -- PROCEDURE grouping cst_revenue_recognition_lines to be processed
6715 -- by a request
6716 -- Using the request_id column of the table CRRL
6717 -- This needs to be evaluated but for now we avoid schema changes
6718 -- At the end of the process the request_id in CRRL should back to the
6719 -- concurrent request submitting the process
6720 --------------------
6721 PROCEDURE updation_potential_crrl
6722 (p_batch_size   IN NUMBER  DEFAULT 1000
6723 ,p_ledger_id    IN NUMBER)
6724 IS
6725   CURSOR c IS
6726   SELECT ROWID,
6727          revenue_om_line_id
6728     FROM cst_revenue_recognition_lines crrl
6729    WHERE potentially_unmatched_flag = 'Y'
6730      AND ledger_id = p_ledger_id
6731    ORDER BY revenue_om_line_id ASC;
6732 
6733   l_rowid_tab      DBMS_SQL.VARCHAR2_TABLE;
6734   l_upd_rowid_tab  DBMS_SQL.VARCHAR2_TABLE;
6735   clear_tab        DBMS_SQL.VARCHAR2_TABLE;
6736   l_romlid_tab     DBMS_SQL.NUMBER_TABLE;
6737   l_oml_upd_tab    DBMS_SQL.NUMBER_TABLE;
6738   l_last_fetch     BOOLEAN := FALSE;
6739   l_last_om_id     NUMBER := -9999;
6740   cnt              NUMBER := 0;
6741   l_bulk_size      NUMBER := 9999;
6742 
6743   PROCEDURE update_one_set_crrl
6744    (p_rowid_tab  IN DBMS_SQL.VARCHAR2_TABLE) IS
6745     l_gp_id        NUMBER;
6746   BEGIN
6747     SELECT cst_cogs_events_s.nextval
6748     INTO l_gp_id
6749     FROM dual;
6750 
6751     FORALL j IN p_rowid_tab.FIRST .. p_rowid_tab.LAST
6752     UPDATE cst_revenue_recognition_lines
6753     SET request_id = -1 * l_gp_id
6754     WHERE rowid = p_rowid_tab(j);
6755     COMMIT;
6756     debug(' CST_REV_REC_LINES updated with request_ID ='|| -1 * l_gp_id ||' for the ledger '||p_ledger_id ||
6757           ' Number of records CRRL updated is '|| l_upd_rowid_tab.COUNT);
6758 
6759     INSERT INTO cst_lists_temp
6760     ( list_id
6761      ,number_1
6762      ,VARCHAR_1) VALUES (p_ledger_id
6763                         , -1 * l_gp_id
6764                         , 'INSERTED');
6765     debug(' CST_LISTS_TEMP.list_id  = ledger_id                  : '||p_ledger_id);
6766     debug(' CST_LISTS_TEMP.number_1 = CRRL.request_id for process: '||-1 * l_gp_id);
6767     debug(' CST_LISTS_TEMP.varchar_1= STATUS of Request          : INSERTED');
6768   END update_one_set_crrl;
6769 
6770   PROCEDURE add_rowid
6771   ( p_rowid     IN VARCHAR2
6772    ,x_rowid_tab IN OUT NOCOPY DBMS_SQL.VARCHAR2_TABLE)
6773   IS
6774   BEGIN
6775     x_rowid_tab(x_rowid_tab.COUNT+1) := p_rowid;
6776   END add_rowid;
6777 
6778 BEGIN
6779   debug('updation_potential_crrl +');
6780   debug('   p_batch_size :'||p_batch_size);
6781   debug('   p_ledger_id  :'||p_ledger_id);
6782 
6783   OPEN c;
6784   LOOP
6785     FETCH c BULK COLLECT INTO
6786      l_rowid_tab  ,
6787      l_romlid_tab
6788     LIMIT l_bulk_size;
6789 
6790     cnt := 0;
6791 
6792     IF c%NOTFOUND THEN
6793       l_last_fetch := TRUE;
6794     END IF;
6795 
6796     IF (l_rowid_tab.COUNT = 0) AND (l_last_fetch) THEN
6797       IF l_upd_rowid_tab.COUNT > 0 THEN
6798           update_one_set_crrl(l_upd_rowid_tab);
6799           l_upd_rowid_tab := clear_tab;
6800       END IF;
6801       debug('COUNT = 0 and LAST FETCH ');
6802       EXIT;
6803     END IF;
6804 
6805     FOR i IN l_rowid_tab.FIRST .. l_rowid_tab.LAST LOOP
6806        IF l_last_om_id  <> l_romlid_tab(i) THEN
6807           l_last_om_id  := l_romlid_tab(i);
6808           IF (    l_upd_rowid_tab.COUNT > p_batch_size
6809               AND i <> l_rowid_tab.LAST)
6810           THEN
6811              update_one_set_crrl(l_upd_rowid_tab);
6812              l_upd_rowid_tab := clear_tab;
6813           END IF;
6814        END IF;
6815        add_rowid(l_rowid_tab(i),l_upd_rowid_tab);
6816        cnt := cnt + 1;
6817     END LOOP;
6818 
6819   END LOOP;
6820   CLOSE c;
6821   debug('updation_potential_crrl -');
6822 EXCEPTION
6823 WHEN OTHERS THEN
6824    debug('EXCEPTION OTHERS updation_potential_crrl:'||SQLERRM);
6825    RAISE;
6826 END updation_potential_crrl;
6827 
6828 
6829 
6830 ---------------------
6831 -- Procedure Master ordonnancer of the COGS recognition programs
6832 --
6833 ---------------------
6834 PROCEDURE ordonnancer
6835 (errbuf         OUT  NOCOPY   VARCHAR2
6836 ,retcode        OUT  NOCOPY   VARCHAR2
6837 ,p_batch_size   IN   NUMBER  DEFAULT 1000
6838 ,p_nb_worker    IN   NUMBER  DEFAULT 4
6839 ,p_api_version  IN   NUMBER
6840 ,p_phase        IN   NUMBER
6841 ,p_low_date     IN   VARCHAR2
6842 ,p_high_date    IN   VARCHAR2
6843 ,p_ledger_id    IN   NUMBER  DEFAULT NULL)
6844 IS
6845   CURSOR c_ins IS
6846   SELECT list_id   -- ledger_id
6847         ,number_1  -- process_negative_request_id
6848         ,rowid
6849     FROM cst_lists_temp
6850    WHERE VARCHAR_1 = 'INSERTED';
6851 
6852   CURSOR c_cpt IS
6853   SELECT COUNT(*)
6854     FROM cst_lists_temp
6855    WHERE VARCHAR_1 = 'SUBMITTED';
6856 
6857   l_ledger_id    NUMBER;
6858   l_neg_req_id   NUMBER;
6859   l_rowid        VARCHAR2(200);
6860   l_nb_req_sub   NUMBER := 0;
6861   l_from_date    VARCHAR2(30);
6862   l_to_date      VARCHAR2(30);
6863   l_req_id       NUMBER;
6864 BEGIN
6865   debug('Ordonnancer +');
6866   debug('   p_batch_size :'||p_batch_size);
6867   debug('   p_ledger_id  :'||p_ledger_id);
6868   debug('   p_nb_worker  :'||p_nb_worker);
6869   debug('   p_api_version:'||p_api_version);
6870   debug('   p_phase      :'||p_phase);
6871   debug('   p_low_date   :'||p_low_date);
6872   debug('   p_high_date  :'||p_high_date);
6873   debug('   p_ledger_id  :'||p_ledger_id);
6874   crrl_preparation
6875      (p_batch_size => p_batch_size
6876      ,p_ledger_id  => p_ledger_id);
6877 
6878   OPEN  c_ins;
6879   LOOP
6880      FETCH c_ins INTO l_ledger_id
6881                     ,l_neg_req_id
6882                     ,l_rowid;
6883      EXIT WHEN c_ins%NOTFOUND;
6884      -----------------------
6885      -- submit_req_cogs_reco
6886      -----------------------
6887      l_req_id := FND_REQUEST.SUBMIT_REQUEST
6888 	         (application => 'BOM'
6889                  ,program     => 'CSTRCMCR3S'
6890                  ,description => 'Phase 3 of the concurrent requests for matching COGS to revenue Child'
6891                  ,start_time  => to_char(sysdate,'DD-MON-YY HH:MI:SS')
6892                  ,sub_request => FALSE
6893                  ,argument1   => p_api_version
6894                  ,argument2   => p_phase
6895                  ,argument3   => p_low_date
6896                  ,argument4   => p_high_date
6897                  ,argument5   => l_ledger_id
6898                  ,argument6   => l_neg_req_id);
6899      IF l_req_id > 0 THEN
6900        debug(' Submitted Concurrent request for CSTRCMCR3S  with ledger_id '||l_ledger_id||
6901              ' and process_request_id '||l_neg_req_id);
6902        UPDATE cst_lists_temp
6903           SET number_2  = l_req_id
6904              ,VARCHAR_1 = 'SUBMITTED'
6905         WHERE ROWID    = l_rowid;
6906        COMMIT;
6907      END IF;
6908      l_nb_req_sub := l_nb_req_sub + 1;
6909      debug(' Number of request launched before verification :'||l_nb_req_sub);
6910      IF l_nb_req_sub >= p_nb_worker THEN
6911         LOOP
6912           debug(' Verifying number of active requests');
6913           nb_req_active;
6914           SELECT COUNT(*)
6915             INTO l_nb_req_sub
6916             FROM cst_lists_temp
6917            WHERE VARCHAR_1 = 'SUBMITTED';
6918 
6919           debug(' Number of request active after verification :'||l_nb_req_sub);
6920           IF l_nb_req_sub < p_nb_worker THEN
6921              EXIT;
6922           END IF;
6923         END LOOP;
6924      END IF;
6925   END LOOP;
6926   CLOSE c_ins;
6927 
6928   debug('Ordonnancer -');
6929 EXCEPTION
6930 WHEN OTHERS THEN
6931    debug('EXCEPTION OTHERS Ordonnancer:'||SQLERRM);
6932    RAISE;
6933 END ordonnancer;
6934 
6935 
6936 ---------------------
6937 -- Procedure Checking active request
6938 ---------------------
6939 PROCEDURE nb_req_active
6940 IS
6941   CURSOR c_activity IS
6942   SELECT number_2
6943         ,rowid
6944     FROM cst_lists_temp
6945    WHERE varchar_1 = 'SUBMITTED';
6946 
6947   l_req_id_tab  DBMS_SQL.NUMBER_TABLE;
6948   l_rowid_tab   DBMS_SQL.VARCHAR2_TABLE;
6949   l_res         BOOLEAN;
6950   l_phase       VARCHAR2(30);
6951   l_status      VARCHAR2(30);
6952   l_dev_phase   VARCHAR2(30);
6953   l_dev_status  VARCHAR2(30);
6954   l_message     VARCHAR2(2000);
6955   l_request_id  NUMBER;
6956 
6957 BEGIN
6958   debug('nb_req_active +');
6959 --  DBMS_LOCK.sleep (2);
6960   OPEN c_activity;
6961   FETCH c_activity BULK COLLECT INTO l_req_id_tab
6962                                     ,l_rowid_tab;
6963   CLOSE c_activity;
6964   FOR i IN l_req_id_tab.FIRST .. l_req_id_tab.LAST LOOP
6965       debug(' Status verification for the request '||l_req_id_tab(i));
6966       l_res := FND_CONCURRENT.GET_REQUEST_STATUS
6967            (request_id     => l_req_id_tab(i)
6968            ,phase          => l_phase
6969            ,status         => l_status
6970            ,dev_phase      => l_dev_phase
6971            ,dev_status     => l_dev_status
6972            ,message        => l_message);
6973       debug(' Request Status:'||l_dev_phase);
6974       IF l_dev_phase = 'COMPLETE' THEN
6975          IF     l_dev_status  = 'NORMAL' THEN
6976            debug('The process '||l_req_id_tab(i)||' completed successfully');
6977            debug(l_message);
6978          ELSIF  l_dev_status  = 'ERROR' THEN
6979            debug('The process '||l_req_id_tab(i)||' completed with error');
6980            debug(l_message);
6981          ELSIF  l_dev_status  = 'WARNING' THEN
6982            debug('The process '||l_req_id_tab(i)||' completed with warning');
6983            debug(l_message);
6984          ELSIF  l_dev_status  = 'CANCELLED' THEN
6985            debug('User has aborted the process '||l_req_id_tab(i));
6986            debug(l_message);
6987          ELSIF  l_dev_status  = 'TERMINATED' THEN
6988            debug('User has aborted the process '||l_req_id_tab(i));
6989            debug(l_message);
6990          END IF;
6991          --
6992          debug(' Updating the request as COMPLETED');
6993          UPDATE cst_lists_temp
6994             SET varchar_1 = l_dev_phase
6995           WHERE rowid  = l_rowid_tab(i);
6996      END IF;
6997   END LOOP;
6998   debug('nb_req_active -');
6999 EXCEPTION
7000 WHEN OTHERS THEN
7001    debug('EXCEPTION OTHERS nb_req_active:'||SQLERRM);
7002    RAISE;
7003 END nb_req_active ;
7004 
7005 
7006 END CST_RevenueCogsMatch_PVT;