DBA Data[Home] [Help]

PACKAGE BODY: APPS.AP_INVOICE_DISTRIBUTIONS_PKG

Source


1 PACKAGE BODY AP_INVOICE_DISTRIBUTIONS_PKG AS
2 /* $Header: apiindib.pls 120.112.12020000.11 2013/03/12 06:26:25 cmaredup ship $ */
3 
4      G_PKG_NAME          CONSTANT VARCHAR2(30) := 'AP_INVOICE_DISTRIBUTIONS_PKG';
5      G_MSG_UERROR        CONSTANT NUMBER       := FND_MSG_PUB.G_MSG_LVL_UNEXP_ERROR;
6      G_MSG_ERROR         CONSTANT NUMBER       := FND_MSG_PUB.G_MSG_LVL_ERROR;
7      G_MSG_SUCCESS       CONSTANT NUMBER       := FND_MSG_PUB.G_MSG_LVL_SUCCESS;
8      G_MSG_HIGH          CONSTANT NUMBER       := FND_MSG_PUB.G_MSG_LVL_DEBUG_HIGH;
9      G_MSG_MEDIUM        CONSTANT NUMBER       := FND_MSG_PUB.G_MSG_LVL_DEBUG_MEDIUM;
10      G_MSG_LOW           CONSTANT NUMBER       := FND_MSG_PUB.G_MSG_LVL_DEBUG_LOW;
11      G_LINES_PER_FETCH   CONSTANT NUMBER       := 1000;
12 
13      G_CURRENT_RUNTIME_LEVEL CONSTANT NUMBER       := FND_LOG.G_CURRENT_RUNTIME_LEVEL;
14      G_LEVEL_UNEXPECTED      CONSTANT NUMBER       := FND_LOG.LEVEL_UNEXPECTED;
15      G_LEVEL_ERROR           CONSTANT NUMBER       := FND_LOG.LEVEL_ERROR;
16      G_LEVEL_EXCEPTION       CONSTANT NUMBER       := FND_LOG.LEVEL_EXCEPTION;
17      G_LEVEL_EVENT           CONSTANT NUMBER       := FND_LOG.LEVEL_EVENT;
18      G_LEVEL_PROCEDURE       CONSTANT NUMBER       := FND_LOG.LEVEL_PROCEDURE;
19      G_LEVEL_STATEMENT       CONSTANT NUMBER       := FND_LOG.LEVEL_STATEMENT;
20      G_MODULE_NAME           CONSTANT VARCHAR2(100) := 'AP.PLSQL.AP_INVOICE_DISTRIBUTIONS_PKG.';
21 
22 
23      --Invoice Lines: Distributions. Added the parameter X_INVOICE_LINE_NUMBER
24      -----------------------------------------------------------------------
25      -- Procedure check_unique ensures the uniqueness of the primary key.
26      --
27 
28      PROCEDURE CHECK_UNIQUE (X_ROWID                          VARCHAR2,
29                              X_INVOICE_ID                     NUMBER,
30 			     X_INVOICE_LINE_NUMBER	      NUMBER,
31                              X_DISTRIBUTION_LINE_NUMBER       NUMBER,
32                              X_Calling_Sequence               VARCHAR2) IS
33        dummy number := 0;
34        current_calling_sequence VARCHAR2(2000);
35        debug_info               VARCHAR2(100);
36 
37      begin
38 
39        -- Update the calling sequence
40        --
41        current_calling_sequence :=
42              'AP_INVOICE_DISTRIBUTIONS_PKG.CHECK_UNIQUE<-'||X_Calling_Sequence;
43 
44        debug_info := 'Select from ap_invoice_distributions';
45 
46        select count(1)
47        into   dummy
48        from   ap_invoice_distributions
49        where  (invoice_id = X_INVOICE_ID AND
50 	       invoice_line_number = X_INVOICE_LINE_NUMBER AND
51                distribution_line_number = X_DISTRIBUTION_LINE_NUMBER)
52        and    ((X_ROWID is null) or (rowid <> X_ROWID));
53 
54        if (dummy >= 1) then
55           fnd_message.set_name('SQLAP','AP_ALL_DUPLICATE_VALUE');
56           app_exception.raise_exception;
57        end if;
58 
59      EXCEPTION
60        WHEN OTHERS THEN
61          if (SQLCODE <> -20001) then
62            FND_MESSAGE.SET_NAME('SQLAP', 'AP_DEBUG');
63            FND_MESSAGE.SET_TOKEN('ERROR', SQLERRM);
64            FND_MESSAGE.SET_TOKEN('CALLING_SEQUENCE', current_calling_sequence);
65            FND_MESSAGE.SET_TOKEN('PARAMETERS', 'Rowid = '||X_ROWID
66                                          ||', Invoice Id = '||X_INVOICE_ID
67                                          ||', Distribution line number = '||
68                                          X_DISTRIBUTION_LINE_NUMBER);
69            FND_MESSAGE.SET_TOKEN('DEBUG_INFO', debug_info);
70          end if;
71          APP_EXCEPTION.RAISE_EXCEPTION;
72      end CHECK_UNIQUE;
73 
74 
75      -----------------------------------------------------------------------
76 
77 
78      -----------------------------------------------------------------------
79      -- Function Get_UOM returns the unit_of_measure for the given
80      -- ccid
81      --
82      FUNCTION Get_UOM(X_CCID IN NUMBER, X_Ch_Of_Accts_Id IN NUMBER)
83          RETURN VARCHAR2
84      IS
85          column_name     VARCHAR2(20) := '';
86          segment_val     gl_code_combinations.SEGMENT1%TYPE;
87          uom             gl_stat_account_uom.unit_of_measure%TYPE;
88          status          VARCHAR2(10) := '';
89          industry        VARCHAR2(10) := '';
90 
91      BEGIN
92 
93          IF (FND_INSTALLATION.GET(101, 101, status, industry)) then
94            IF (status <> 'I') then
95              return('');
96            END IF;
97          ELSE
98            return('');
99          END IF;
100 
101          IF (FND_FLEX_APIS.get_segment_column(101, 'GL#', X_Ch_Of_Accts_Id,
102                                               'GL_ACCOUNT', column_name)) THEN
103             select decode(column_name, 'SEGMENT1', segment1,
104                                        'SEGMENT2', segment2,
105                                        'SEGMENT3', segment3,
106                                        'SEGMENT4', segment4,
107                                        'SEGMENT5', segment5,
108                                        'SEGMENT6', segment6,
109                                        'SEGMENT7', segment7,
110                                        'SEGMENT8', segment8,
111                                        'SEGMENT9', segment9,
112                                        'SEGMENT10', segment10,
113                                        'SEGMENT11', segment11,
114                                        'SEGMENT12', segment12,
115                                        'SEGMENT13', segment13,
116                                        'SEGMENT14', segment14,
117                                        'SEGMENT15', segment15,
118                                        'SEGMENT16', segment16,
119                                        'SEGMENT17', segment17,
120                                        'SEGMENT18', segment18,
121                                        'SEGMENT19', segment19,
122                                        'SEGMENT20', segment20,
123                                        'SEGMENT21', segment21,
124                                        'SEGMENT22', segment22,
125                                        'SEGMENT23', segment23,
126                                        'SEGMENT24', segment24,
127                                        'SEGMENT25', segment25,
128                                        'SEGMENT26', segment26,
129                                        'SEGMENT27', segment27,
130                                        'SEGMENT28', segment28,
131                                        'SEGMENT29', segment29,
132                                        'SEGMENT30', segment30)
133             into  segment_val
134             from  gl_code_combinations
135             where code_combination_id = X_CCID;
136 
137             select unit_of_measure
138             into   uom
139             from   gl_stat_account_uom
140             where  account_segment_value = segment_val
141             and chart_of_accounts_id =  X_Ch_Of_Accts_Id ;
142 
143             return(uom);
144          ELSE
145             return('');
146          END IF;
147 
148      EXCEPTION
149         WHEN OTHERS THEN
150           RETURN('');
151 
152      END Get_UOM;
153 
154 
155      -----------------------------------------------------------------------
156 
157 
158      -----------------------------------------------------------------------
159      -- Function Get_Posted_Status returns the posted_status for the
160      -- distribution_line.
161      --
162 
163      FUNCTION Get_Posted_Status(X_Accrual_Posted_Flag       VARCHAR2,
164                                 X_Cash_Posted_Flag          VARCHAR2,
165                                 X_Posted_Flag               VARCHAR2,
166                                 X_Org_Id          IN  NUMBER DEFAULT
167                                 mo_global.get_current_org_id )
168         RETURN VARCHAR2
169      IS
170         l_posted_status       ap_lookup_codes.lookup_code%TYPE;
171         l_cash_basis          VARCHAR2(1);
172         l_accrual_posted_flag VARCHAR2(1);
173         l_cash_posted_flag    VARCHAR2(1);
174         l_posted_flag         VARCHAR2(1);
175 
176      BEGIN
177 
178         /*----------------------------------------------------
179          *Manipulate pass in parameters
180          *----------------------------------------------------*/
181          l_accrual_posted_flag := NVL(X_Accrual_Posted_Flag, 'N');
182          l_cash_posted_flag    := NVL(X_Cash_Posted_Flag, 'N');
183          l_Posted_Flag         := NVL(X_Posted_Flag, 'N');
184 
185         /*----------------------------------------------------
186          *Get the accounting method
187          *l_cash_basis: 'Y' -- cash basis
188          *              'N' -- accrual basis
189          *----------------------------------------------------*/
190         SELECT NVL(SLA_LEDGER_CASH_BASIS_FLAG, 'N')
191         INTO   l_cash_basis
192         FROM   ap_system_parameters_all ASP,
193                gl_sets_of_books  SOB
194         WHERE  asp.org_id = x_org_id
195         AND    asp.set_of_books_id = sob.set_of_books_id;
196 
197         /*---------------------------------------------------
198          * Figure out the posted status according to the
199          * combination of flags and accounting options
200          *---------------------------------------------------*/
201         IF (l_cash_basis = 'Y') THEN  -- cash basis
202            IF( l_cash_posted_flag = 'N' AND l_posted_flag = 'S') THEN
203               l_posted_status := 'S';
204            ELSE
205               l_posted_status := l_cash_posted_flag;
206            END IF;
207         ELSE  --accrual basis
208            IF( l_accrual_posted_flag = 'N' AND l_posted_flag = 'S') THEN
209               l_posted_status := 'S';
210            ELSE
211               l_posted_status := l_accrual_posted_flag;
212            END IF;
213         END IF;
214 
215         return(l_posted_status);
216 
217      EXCEPTION
218        WHEN OTHERS THEN
219           RETURN('');
220 
221      END Get_Posted_Status;
222 
223      -----------------------------------------------------------------------
224 
225      -----------------------------------------------------------------------
226      -- Procedure Select_Summary calculates the initial value for the
227      -- distribution line total for an invoice.
228      --
229 
230      PROCEDURE Select_Summary(X_Invoice_Id       IN NUMBER,
231                               X_Total            IN OUT NOCOPY NUMBER,
232                               X_Total_Rtot_DB    IN OUT NOCOPY NUMBER,
233                               X_LINE_NUMBER      IN NUMBER, --Bug4539547
234                               X_Calling_Sequence IN VARCHAR2)
235      IS
236        current_calling_sequence  VARCHAR2(2000);
237        debug_info                VARCHAR2(100);
238      BEGIN
239 
240         -- Update the calling sequence
241         --
242         current_calling_sequence :=
243            'AP_INVOICE_DISTRIBUTIONS_PKG.Select_Summary<-'||X_Calling_Sequence;
244 
245         debug_info := 'Select from ap_invoice_distributions';
246 
247         -- eTax Uptake.
248         -- This select should return the distribution total.  Prepayment and
249         -- Prepayment Tax amount should be included if the flag
250         -- invoice_includes_prepay_flag is set ot Y.
251        --Bug4539547 Added IF statement
252        If (X_LINE_NUMBER is null) then
253         SELECT NVL(SUM(aid.amount), 0)
254           INTO X_Total
255           FROM ap_invoice_distributions_all aid,
256                ap_invoice_lines_all ail
257          WHERE ail.invoice_id = X_Invoice_Id
258            AND ail.invoice_id = aid.invoice_id
259            AND ail.line_number = aid.invoice_line_number
260            AND ((aid.line_type_lookup_code NOT IN ('PREPAY', 'AWT', 'RETAINAGE')
261                  AND aid.prepay_distribution_id IS NULL)
262                  OR  (ail.line_type_lookup_code = 'RETAINAGE RELEASE'
263                       AND aid.line_type_lookup_code = 'RETAINAGE')
264                  OR  NVL(ail.invoice_includes_prepay_flag,'N') = 'Y');
265         else
266         SELECT NVL(SUM(aid.amount), 0)
267           INTO X_Total
268           FROM ap_invoice_distributions_all aid,
269                ap_invoice_lines_all ail
270          WHERE ail.invoice_id = X_Invoice_Id
271            AND ail.invoice_id = aid.invoice_id
272            AND ail.line_number = aid.invoice_line_number
273            AND ail.line_number = X_LINE_NUMBER
274              -- bug 11851968 start
275            AND ((ail.line_type_lookup_code = 'RETAINAGE RELEASE'
276            AND aid.line_type_lookup_code = 'RETAINAGE')
277            OR (ail.line_type_lookup_code = 'PREPAY'
278            AND aid.prepay_distribution_id is not null)
279            OR (aid.line_type_lookup_code NOT IN ('PREPAY',
280                'RETAINAGE')));
281              -- bug 11851968 ends
282 
283             --commented below condition for the bug 7312805/7244811
284            /*AND ((aid.line_type_lookup_code NOT IN ('PREPAY', 'AWT', 'RETAINAGE')
285                  AND aid.prepay_distribution_id IS NULL)
286                  OR  (ail.line_type_lookup_code = 'RETAINAGE RELEASE'
287                       AND aid.line_type_lookup_code = 'RETAINAGE')
288                  OR  NVL(ail.invoice_includes_prepay_flag,'N') = 'Y');*/
289         end if;
290 
291         X_Total_Rtot_DB := X_Total;
292 
293      EXCEPTION
294        WHEN OTHERS THEN
295          if (SQLCODE <> -20001) then
296            FND_MESSAGE.SET_NAME('SQLAP', 'AP_DEBUG');
297            FND_MESSAGE.SET_TOKEN('ERROR', SQLERRM);
298            FND_MESSAGE.SET_TOKEN('CALLING_SEQUENCE', current_calling_sequence);
299            FND_MESSAGE.SET_TOKEN('PARAMETERS','Invoice Id = '||X_Invoice_Id
300                                           ||',Total = '||X_Total
301                                           ||',Total RTOT DB = '||
302                                               X_Total_Rtot_DB);
303            FND_MESSAGE.SET_TOKEN('DEBUG_INFO', debug_info);
304          end if;
305          APP_EXCEPTION.RAISE_EXCEPTION;
306      END Select_Summary;
307 
308  -----------------------------------------------------------------------
309 
310      -----------------------------------------------------------------------
311      -- Procedure Set_Packet_Id reads the packet id for an invoice.
312      --
313 
314      PROCEDURE Set_Inv_Packet_Id(X_Invoice_Id       IN NUMBER,
315                                  X_Packet_id        IN OUT NOCOPY NUMBER,
316                                  X_Calling_Sequence IN VARCHAR2)
317      IS
318        current_calling_sequence  VARCHAR2(2000);
319        debug_info                VARCHAR2(100);
320      BEGIN
321 
322         -- Update the calling sequence
323         --
324         current_calling_sequence :=
325          'AP_INVOICE_DISTRIBUTION_PKG.Set_Inv_Packet_Id<-'||X_Calling_Sequence;
326 
327         debug_info := 'Select from ap_invoice_distributions';
328 
329         select decode(count(distinct(packet_id)),1,max(packet_id),'')
330         into   X_Packet_Id
331         from   ap_invoice_distributions
332         where  invoice_id = X_Invoice_Id
333         and    packet_id is not null;
334 
335      EXCEPTION
336        WHEN OTHERS THEN
337          if (SQLCODE <> -20001) then
338            FND_MESSAGE.SET_NAME('SQLAP', 'AP_DEBUG');
339            FND_MESSAGE.SET_TOKEN('ERROR', SQLERRM);
340            FND_MESSAGE.SET_TOKEN('CALLING_SEQUENCE', current_calling_sequence);
341            FND_MESSAGE.SET_TOKEN('PARAMETERS', 'Invoice Id = '||X_Invoice_Id
342                                          ||', Packet Id = '||X_Packet_Id);
343            FND_MESSAGE.SET_TOKEN('DEBUG_INFO', debug_info);
344          end if;
345          APP_EXCEPTION.RAISE_EXCEPTION;
346 
347      END Set_Inv_Packet_Id;
348 
349      -----------------------------------------------------------------------
350 
351      -----------------------------------------------------------------------
352      -- Function Query_New_Packet_Id returns true if the packet id has changed
353      -- for a particular distribution.
354      --
355 
356      FUNCTION Query_New_Packet_Id(X_Rowid            VARCHAR2,
357                                   X_Packet_Id        NUMBER,
358                                   X_Calling_Sequence VARCHAR2)
359         RETURN BOOLEAN
360      IS
361         dummy  VARCHAR2(10);
362         current_calling_sequence  VARCHAR2(2000);
363         debug_info                VARCHAR2(100);
364      BEGIN
365 
366         -- Update the calling sequence
367         --
368         current_calling_sequence :=
369      'AP_INVOICE_DISTRIBUTIONS_PKG.Query_New_Packet_Id<-'||X_Calling_Sequence;
370 
371         debug_info := 'Select from ap_invoice_distributions';
372 
373         select 'TRUE'
374         into   dummy
375         from   ap_invoice_distributions
376         where  rowid = X_Rowid
377         and    NVL(packet_id, -1) <> NVL(X_Packet_Id, -1);
378 
379         return(TRUE);
380 
381      EXCEPTION
382        WHEN NO_DATA_FOUND THEN
383           RETURN(FALSE);
384        WHEN OTHERS THEN
385           if (SQLCODE <> -20001) then
386             FND_MESSAGE.SET_NAME('SQLAP', 'AP_DEBUG');
387             FND_MESSAGE.SET_TOKEN('ERROR', SQLERRM);
388             FND_MESSAGE.SET_TOKEN('CALLING_SEQUENCE',current_calling_sequence);
389             FND_MESSAGE.SET_TOKEN('PARAMETERS', 'Rowid = '||X_Rowid
390                                            ||', Packet Id = '||X_Packet_Id);
391           end if;
392           APP_EXCEPTION.RAISE_EXCEPTION;
393      END Query_New_Packet_Id;
394 
395      -----------------------------------------------------------------------
396 
397      -----------------------------------------------------------------------
398      -- Function All_Encumbered returns true if given a distribution line
399      -- all other distribution lines for the invoice have been encumbered.
400      --
401 
402      FUNCTION All_Encumbered(X_Invoice_Id       NUMBER,
403                              X_Rowid            VARCHAR2,
404                              X_Calling_Sequence VARCHAR2)
405         RETURN BOOLEAN
406      IS
407         dummy  VARCHAR2(80);
408         current_calling_sequence   VARCHAR2(2000);
409         debug_info                 VARCHAR2(100);
410      BEGIN
411 
412         -- Update the calling sequence
413         --
414         current_calling_sequence :=
415            'AP_INVOICE_DISTRIBUTIONS_PKG.All_Encumbered<-'||X_Calling_Sequence;
416 
417         debug_info := 'Select from sys.dual';
418 
419         select 'There are encumbered dists'
420         into   dummy
421         from   sys.dual
422         where  not exists (select 'There are other unencumbered dists'
423                              from ap_invoice_distributions
424                             where invoice_id = X_Invoice_Id
425                               and NVL(match_status_flag, 'N') <> 'A'
426                               and rowid <> X_Rowid);
427 
428         return(TRUE);
429 
430      EXCEPTION
431        WHEN NO_DATA_FOUND THEN
432           RETURN(FALSE);
433        WHEN OTHERS THEN
434           if (SQLCODE <> -20001) then
435             FND_MESSAGE.SET_NAME('SQLAP', 'AP_DEBUG');
436             FND_MESSAGE.SET_TOKEN('ERROR', SQLERRM);
437             FND_MESSAGE.SET_TOKEN('CALLING_SEQUENCE',current_calling_sequence);
438             FND_MESSAGE.SET_TOKEN('PARAMETERS', 'Invoice Id = '||X_Invoice_Id
439                                            ||', Rowid = '||X_Rowid);
440             FND_MESSAGE.SET_TOKEN('DEBUG_INFO', debug_info);
441           end if;
442           APP_EXCEPTION.RAISE_EXCEPTION;
443      END All_Encumbered;
444 
445          -----------------------------------------------------------------------
446 
447     -----------------------------------------------------------------------
448     -- Function Check_Cash_Basis_Paid returns true if given an invoice
449     -- we are running cash basis and the invoice has 1 of 2 conditions
450     -- set to TRUE; 1) There are posted payments and no voids.
451     --              2) There are unposted payments linked to a void.
452     --
453 
454      FUNCTION Check_Cash_Basis_Paid(X_Invoice_Id       NUMBER,
455                                     X_Calling_Sequence VARCHAR2)
456         RETURN BOOLEAN
457      IS
458         p_acct_meth    ap_system_parameters.accounting_method_option%TYPE;
459         s_acct_meth    ap_system_parameters.secondary_accounting_method%TYPE;
460         dummy          VARCHAR2(80);
461         current_calling_sequence  VARCHAR2(2000);
462         debug_info                VARCHAR2(100);
463         l_cash_basis   VARCHAR2(1);
464         CURSOR  posted_no_voids IS
465            SELECT 'Has posted payment with no corresponding void'
466            FROM   ap_invoice_payments p1
467            WHERE  p1.invoice_id = X_Invoice_Id
468            AND    nvl(p1.cash_posted_flag, 'N') = 'Y'
469            AND    NOT EXISTS (SELECT 'This is the void partner'
470                               FROM ap_invoice_payments p2
471                               WHERE p2.invoice_id = p1.invoice_id
472                               AND   p2.check_id = p1.check_id
473                               AND   p2.payment_num = p1.payment_num
474                               AND   p2.amount = ( -1 * p1.amount));
475        CURSOR  unposted_w_voids IS
476           SELECT 'Has unposted payment that is linked to a voided check'
477           FROM   ap_invoice_payments p, ap_checks c
478           WHERE  p.invoice_id = X_Invoice_Id
479           AND    nvl(p.cash_posted_flag,'N') <> 'Y'
480           AND    p.check_id = c.check_id
481           AND    c.void_date IS NOT NULL;
482      BEGIN
483 
484         -- Update the calling sequence
485         --
486         current_calling_sequence :=
487     'AP_INVOICE_DISTRIBUTIONS_PKG.Check_Cash_Basis_Paid<-'||X_Calling_Sequence;
488 
489         debug_info := 'Select accounting method from SOB';
490 
491         SELECT NVL(sla_ledger_cash_basis_flag, 'N')
492         INTO   l_cash_basis
493         FROM   ap_system_parameters ASP,
494                gl_sets_of_books  SOB,
495                ap_invoices   AI
496         WHERE  AI.invoice_id = x_invoice_id
497         AND    AI.org_id = ASP.org_id
498         AND    asp.set_of_books_id = sob.set_of_books_id;
499 
500         if (l_cash_basis <>'Y') then
501           return(FALSE);
502         end if;
503 
504         debug_info := 'Select from ap_invoice_payments';
505 
506         OPEN posted_no_voids;
507         debug_info := 'Fetch cursor posted_no_voids';
508         FETCH posted_no_voids INTO dummy;
509         if (posted_no_voids%ROWCOUNT <> 0) then
510           debug_info := 'Close cursor posted_no_voids - ROWCOUNT NOT ZERO';
511           CLOSE posted_no_voids;
512           return(TRUE);
513         end if;
514         debug_info := 'Close cursor posted_no_voids';
515         CLOSE posted_no_voids;
516 
517         debug_info := 'Select from ap_invoice_payments and ap_checks';
518 
519         OPEN unposted_w_voids;
520         debug_info := 'Fetch cursor unposted_w_voids';
521         FETCH unposted_w_voids INTO dummy;
522         if (unposted_w_voids%ROWCOUNT <> 0) then
523           debug_info := 'Close cursor unposted_w_voids';
524           CLOSE unposted_w_voids;
525           return(TRUE);
526         end if;
527 
528         return(FALSE);
529 
530      EXCEPTION
531        WHEN OTHERS THEN
532          if (SQLCODE <> -20001) then
533            FND_MESSAGE.SET_NAME('SQLAP', 'AP_DEBUG');
534            FND_MESSAGE.SET_TOKEN('ERROR', SQLERRM);
535            FND_MESSAGE.SET_TOKEN('CALLING_SEQUENCE', current_calling_sequence);
536            FND_MESSAGE.SET_TOKEN('PARAMETERS', 'Invoice Id = '||X_Invoice_Id);
537            FND_MESSAGE.SET_TOKEN('DEBUG_INFO', debug_info);
538          end if;
539          APP_EXCEPTION.RAISE_EXCEPTION;
540 
541      END Check_Cash_Basis_Paid;
542 
543 
544      -----------------------------------------------------------------------
545 
546 
547 
548      -----------------------------------------------------------------------
549      -- Procedure Adjust_PO is given a po_distribution_id, a line_location_id,
550      -- an amount billed and a quantity_billed it adjusts PO accordingly.
551      --
552 
553      PROCEDURE Adjust_PO(X_PO_Distribution_Id NUMBER,
554                          X_Line_Location_id   NUMBER,
555                          X_Quantity_Billed    NUMBER,
556                          X_Amount_Billed      NUMBER,
557                          X_Match_Basis        VARCHAR2,  /* Amount Based Matching */
558                          X_Matched_Uom        VARCHAR2,  /* Bug 4121303 */
559                          X_Calling_Sequence   VARCHAR2)
560      IS
561        l_po_ap_dist_rec          PO_AP_DIST_REC_TYPE;
562        l_po_ap_line_loc_rec      PO_AP_LINE_LOC_REC_TYPE;
563        l_return_status           VARCHAR2(100);
564        l_msg_data                VARCHAR2(4000);
565        current_calling_sequence  VARCHAR2(2000);
566        l_debug_info              VARCHAR2(100);
567        l_api_name		 VARCHAR2(50);
568 
569 
570     BEGIN
571 
572        l_api_name := 'Adjust_Po';
573        current_calling_sequence := 'AP_INVOICE_DISTRIBUTIONS_PKG.Adjust_PO<-'||X_Calling_Sequence;
574 
575        IF (G_LEVEL_PROCEDURE >= G_CURRENT_RUNTIME_LEVEL) THEN
576           FND_LOG.STRING(G_LEVEL_PROCEDURE,G_MODULE_NAME||l_api_name,'AP_INVOICE_DISTRIBUTIONS_PKG.Adjust_Po(-)');
577        END IF;
578 
579        l_debug_info := 'Create l_po_ap_dist_rec object';
580        IF (G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
581           FND_LOG.STRING(G_LEVEL_STATEMENT,G_MODULE_NAME||l_api_name,l_debug_info);
582        END IF;
583 
584        l_po_ap_dist_rec := PO_AP_DIST_REC_TYPE.create_object();
585 
586        l_po_ap_dist_rec.add_change(
587 				 p_po_distribution_id => x_po_distribution_id,
588                                  p_uom_code            => x_matched_uom,
589                                  p_quantity_billed     => x_quantity_billed,
590                                  p_amount_billed       => x_amount_billed,
591                                  p_quantity_financed   => NULL,
592                                  p_amount_financed     => NULL,
593                                  p_quantity_recouped   => NULL,
594                                  p_amount_recouped     => NULL,
595                                  p_retainage_withheld_amt => NULL,
596                                  p_retainage_released_amt => NULL
597                                 );
598 
599        l_debug_info := 'Create l_po_ap_line_loc_rec object and populate the data';
600        IF (G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
601           FND_LOG.STRING(G_LEVEL_STATEMENT,G_MODULE_NAME||l_api_name,l_debug_info);
602        END IF;
603 
604        l_po_ap_line_loc_rec := PO_AP_LINE_LOC_REC_TYPE.create_object(
605                                  p_po_line_location_id => x_line_location_id,
606                                  p_uom_code            => x_matched_uom,
607                                  p_quantity_billed     => x_quantity_billed,
608                                  p_amount_billed       => x_amount_billed,
609                                  p_quantity_financed   => NULL,
610                                  p_amount_financed     => NULL,
611                                  p_quantity_recouped   => NULL,
612                                  p_amount_recouped     => NULL,
613                                  p_retainage_withheld_amt => NULL,
614                                  p_retainage_released_amt => NULL
615                                 );
616 
617        l_debug_info := 'Call the PO_AP_INVOICE_MATCH_GRP to update the Po Distributions and Po Line Locations';
618        IF (G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
619           FND_LOG.STRING(G_LEVEL_STATEMENT,G_MODULE_NAME||l_api_name,l_debug_info);
620        END IF;
621 
622        PO_AP_INVOICE_MATCH_GRP.Update_Document_Ap_Values(
623                                         P_Api_Version 	       => 1.0,
624                                         P_Line_Loc_Changes_Rec => l_po_ap_line_loc_rec,
625                                         P_Dist_Changes_Rec     => l_po_ap_dist_rec,
626                                         X_Return_Status        => l_return_status,
627                                         X_Msg_Data             => l_msg_data);
628 
629 
630        IF (G_LEVEL_PROCEDURE >= G_CURRENT_RUNTIME_LEVEL) THEN
631           FND_LOG.STRING(G_LEVEL_PROCEDURE,G_MODULE_NAME||l_api_name,'AP_INVOICE_DISTRIBUTIONS_PKG.Adjust_Po(-)');
632        END IF;
633 
634      EXCEPTION
635        WHEN OTHERS THEN
636          if (SQLCODE <> -20001) then
637            FND_MESSAGE.SET_NAME('SQLAP', 'AP_DEBUG');
638            FND_MESSAGE.SET_TOKEN('ERROR', SQLERRM);
639            FND_MESSAGE.SET_TOKEN('CALLING_SEQUENCE', current_calling_sequence);
640            FND_MESSAGE.SET_TOKEN('PARAMETERS','PO Distribution Id = '||
641                         X_PO_Distribution_Id||', Line location Id = '||
642                           X_Line_Location_Id||', Quantity Billed = '||
643                            X_Quantity_Billed||', Amount Billed = '||
644                            X_Amount_Billed);
645            FND_MESSAGE.SET_TOKEN('DEBUG_INFO', l_debug_info);
646          end if;
647          APP_EXCEPTION.RAISE_EXCEPTION;
648 
649      END Adjust_PO;
650 
651 
652   -----------------------------------------------------------------------
653 
654      -----------------------------------------------------------------------
655      -- Function Substrbyte is used in substitution for the PL/SQL SUBSTRB.
656      -- Reason: Currently (as of 7/20/95) SUBSTRB in Forms does not work
657      -- properly.
658      --
659 
660      FUNCTION Substrbyte(X_String           VARCHAR2,
661                          X_Start            NUMBER,
662                          X_End              NUMBER,
663                          X_Calling_Sequence VARCHAR2)
664        RETURN VARCHAR2
665      IS
666        result_str  VARCHAR2(2000) := '';
667        current_calling_sequence   VARCHAR2(2000);
668        debug_info                 VARCHAR2(100);
669      BEGIN
670 
671        -- Update the calling sequence
672        --
673        current_calling_sequence :=
674        'AP_INVOICE_DISTRIBUTION_PKG.Substrbyte<-'||X_Calling_Sequence;
675 
676        debug_info := 'Select from sys.dual';
677 
678        select SUBSTRB(X_String, X_Start, X_End)
679        into   result_str
680        from   sys.dual;
681 
682        return(result_str);
683 
684      EXCEPTION
685        WHEN OTHERS THEN
686          if (SQLCODE <> -20001) then
687            FND_MESSAGE.SET_NAME('SQLAP', 'AP_DEBUG');
688            FND_MESSAGE.SET_TOKEN('ERROR', SQLERRM);
689            FND_MESSAGE.SET_TOKEN('CALLING_SEQUENCE', current_calling_sequence);
690            FND_MESSAGE.SET_TOKEN('PARAMETERS', 'String = '||X_String
691                                          ||', Start = '||X_Start
692                                          ||', End = '||X_End);
693            FND_MESSAGE.SET_TOKEN('DEBUG_INFO', debug_info);
694          END IF;
695          APP_EXCEPTION.RAISE_EXCEPTION;
696 
697      END Substrbyte;
698 
699      -----------------------------------------------------------------------
700      -- FUNCTION insert_from_dist_set inserts records into
701      -- ap_invoice_distributions given a line number, distribution set id and
702      -- table of distribution information.  It returns FALSE if an error
703      -- is encountered.
704      -- Called from ap_invoice_lines_pkg.insert_from_dist_set or from Import
705      -----------------------------------------------------------------------
706      FUNCTION Insert_From_Dist_Set(
707               X_batch_id            IN   NUMBER,
708               X_invoice_id          IN   NUMBER,
709               X_line_number         IN   NUMBER,
710               X_dist_tab            IN   AP_INVOICE_LINES_PKG.dist_tab_type,
711               X_Generate_Permanent  IN   VARCHAR2 DEFAULT 'N',
712               X_Debug_Info          OUT  NOCOPY VARCHAR2,
713               X_Debug_Context       OUT  NOCOPY VARCHAR2,
714               X_Calling_Sequence    IN   VARCHAR2) RETURN BOOLEAN
715      IS
716 
717      l_distribution_class     AP_INVOICE_DISTRIBUTIONS.DISTRIBUTION_CLASS%TYPE;
718      l_created_by             AP_INVOICE_DISTRIBUTIONS.CREATED_BY%TYPE;
719      l_inv_dist_id 	      AP_INVOICE_DISTRIBUTIONS.INVOICE_DISTRIBUTION_ID%TYPE;
720      l_last_update_login
721        AP_INVOICE_DISTRIBUTIONS.LAST_UPDATE_LOGIN%TYPE;
722      l_existing_distributions NUMBER := 0;
723      i                        BINARY_INTEGER := 0;
724      current_calling_sequence VARCHAR2(2000);
725      debug_info               VARCHAR2(100);
726      --Bug 4539462 DBI logging
727      l_dbi_key_value_list          ap_dbi_pkg.r_dbi_key_value_arr;
728      l_calling_module        varchar2(30);   --bug7014798
729 
730 
731 	 l_country_code VARCHAR2(20);  --bug 9169915
732 	 l_org_id       NUMBER; --bug 9169915
733 
734      --Bug#10241241
735      l_set_of_books_id  NUMBER;
736      l_chart_of_accounts_id NUMBER;
737      l_dist_updated    NUMBER;
738 	 l_line_type_lookup_code  ap_invoice_lines_all.line_type_lookup_code%TYPE; --Bug16324208
739 
740      BEGIN
741 
742      --------------------------------------------------------------------------
743      -- Step 1 - Update the calling sequence
744      --------------------------------------------------------------------------
745      current_calling_sequence :=
746             'AP_INVOICE_DISTRIBUTIONS_PKG.insert_from_dist_set<-'||
747             X_calling_sequence;
748 
749      --Bug16324208: Start
750      -------------------------------------------------------------------------
751      -- Get line_type_lookup_code
752      -------------------------------------------------------------------------
753      debug_info := 'Get line_type_lookup_code';
754      BEGIN
755        SELECT line_type_lookup_code
756          INTO l_line_type_lookup_code
757          FROM ap_invoice_lines_all
758         WHERE invoice_id = X_invoice_id
759           AND line_number = X_line_number;
760 
761 	  EXCEPTION
762        WHEN OTHERS THEN
763        NULL;
764      END;
765      --Bug16324208: End
766 
767      -------------------------------------------------------------------------
768      -- Step 2 - Validate line does not contain other distributions
769      -------------------------------------------------------------------------
770      debug_info := 'Verify line does not contain distributions';
771      BEGIN
772        SELECT count(*)
773          INTO l_existing_distributions
774          FROM ap_invoice_distributions
775         WHERE invoice_id = X_invoice_id
776           AND invoice_line_number = X_line_number
777 		  AND rownum=1; --13507856 added the rownum condition to improve the performance
778 
779        IF (l_existing_distributions <> 0) then
780          X_debug_info := debug_info || ': line already has distributions';
781          X_debug_context := current_calling_sequence;
782          RETURN(FALSE);
783        END IF;
784 
785      EXCEPTION
786        WHEN OTHERS THEN
787        NULL;
788      END;
789 
790 
791      -------------------------------------------------------------------------
792      -- Step 3 - Set distribution class value (Permanent or Candidate)
793      -------------------------------------------------------------------------
794      if (X_Generate_Permanent = 'N') then
795        l_distribution_class := 'CANDIDATE';
796      else
797        l_distribution_class := 'PERMANENT';
798      end if;
799      -------------------------------------------------------------------------
800      -- Step 4 - Generate distributions
801      -------------------------------------------------------------------------
802      --bug 9169915
803      select org_id,set_of_books_id  --added set_of_books_id for bug#10241241
804        into l_org_id,l_set_of_books_id
805        from ap_invoices
806       where invoice_id = X_invoice_id;
807 
808      SELECT JG_ZZ_SHARED_PKG.GET_COUNTRY(l_org_id, null)
809        INTO l_country_code
810        FROM DUAL;
811      --bug 9169915
812 
813       --Start Bug#10241241
814        select chart_of_accounts_id
815        into l_chart_of_accounts_id
816        from gl_sets_of_books
817        where set_of_books_id = l_set_of_books_id;
818 
819        l_dist_updated := 0;
820       --End Bug#10241241
821 
822      FOR i in nvl(X_dist_tab.FIRST, 0) .. nvl(X_dist_tab.LAST, -1) LOOP
823 
824 	SELECT ap_invoice_distributions_s.nextval INTO l_inv_dist_id FROM DUAL;
825 
826         INSERT INTO ap_invoice_distributions (
827                    batch_id,
828                    invoice_id,
829                    invoice_line_number,
830                    invoice_distribution_id,
831                    distribution_line_number,
832                    line_type_lookup_code,
833                    distribution_class,
834                    description,
835                    dist_match_type,
836                    org_id,
837                    dist_code_combination_id,
838                    accounting_date,
839                    period_name,
840  		   accrual_posted_flag,
841                    cash_posted_flag,
842                    amount_to_post,
843                    base_amount_to_post,
844                    posted_amount,
845                    posted_base_amount,
846                    posted_flag,
847                    accounting_event_id,
848                    upgrade_posted_amt,
849                    upgrade_base_posted_amt,
850                    set_of_books_id,
851                    amount,
852                    base_amount,
853                    rounding_amt,
854                    quantity_variance,
855                    base_quantity_variance,
856                    match_status_flag,
857                    encumbered_flag,
858                    packet_id,
859                    reversal_flag,
860                    parent_reversal_id,
861                    cancellation_flag,
862                    income_tax_region,
863                    type_1099,
864                    stat_amount,
865                    charge_applicable_to_dist_id,
866                    prepay_amount_remaining,
867                    prepay_distribution_id,
868                    parent_invoice_id,
869                    corrected_invoice_dist_id,
870                    corrected_quantity,
871                    other_invoice_id,
872                    po_distribution_id,
873                    rcv_transaction_id,
874                    unit_price,
875                    matched_uom_lookup_code,
876                    quantity_invoiced,
877                    final_match_flag,
878                    related_id,
879                    assets_addition_flag,
880                    assets_tracking_flag,
881                    asset_book_type_code,
882                    asset_category_id,
883                    project_id,
884                    task_id,
885                    expenditure_type,
886                    expenditure_item_date,
887                    expenditure_organization_id,
888 		   project_accounting_context,
889                    pa_quantity,
890                    pa_addition_flag,
891                    award_id,
892                    gms_burdenable_raw_cost,
893                    awt_flag,
894                    awt_group_id,
895                    awt_tax_rate_id,
896                    awt_gross_amount,
897                    awt_invoice_id,
898                    awt_origin_group_id,
899                    awt_invoice_payment_id,
900                    awt_withheld_amt,
901                    inventory_transfer_status,
902                    reference_1,
903                    reference_2,
904                    receipt_verified_flag,
905                    receipt_required_flag,
906                    receipt_missing_flag,
907                    justification,
908                    expense_group,
909                    start_expense_date,
910                    end_expense_date,
911                    receipt_currency_code,
912                    receipt_conversion_rate,
913                    receipt_currency_amount,
914                    daily_amount,
915                    web_parameter_id,
916                    adjustment_reason,
917                    merchant_document_number,
918                    merchant_name,
919                    merchant_reference,
920                    merchant_tax_reg_number,
921                    merchant_taxpayer_id,
922                    country_of_supply,
923                    credit_card_trx_id,
924                    company_prepaid_invoice_id,
925                    cc_reversal_flag,
926                    attribute_category,
927                    attribute1,
928                    attribute2,
929                    attribute3,
930                    attribute4,
931                    attribute5,
932                    attribute6,
933                    attribute7,
934                    attribute8,
935                    attribute9,
936                    attribute10,
937                    attribute11,
938                    attribute12,
939                    attribute13,
940                    attribute14,
941                    attribute15,
942                    global_attribute_category,
943                    global_attribute1,
944                    global_attribute2,
945                    global_attribute3,
946                    global_attribute4,
947                    global_attribute5,
948                    global_attribute6,
949                    global_attribute7,
950                    global_attribute8,
951                    global_attribute9,
952                    global_attribute10,
953                    global_attribute11,
954                    global_attribute12,
955                    global_attribute13,
956                    global_attribute14,
957                    global_attribute15,
958                    global_attribute16,
959                    global_attribute17,
960                    global_attribute18,
961                    global_attribute19,
962                    global_attribute20,
963                    created_by,
964                    creation_date,
965                    last_updated_by,
966                    last_update_date,
967                    last_update_login,
968                    program_application_id,
969                    program_id,
970                    program_update_date,
971                    request_id,
972 		   --ETAX: Invwkb
973 		   intended_use,
974 		   --Freight and Special Charges
975 		   rcv_charge_addition_flag,
976 		---added for 7022001
977 		pay_awt_group_id)
978        VALUES (
979                    X_batch_id,                    -- batch_id
980                    X_invoice_id,                  -- invoice_id
981                    X_line_number,                 -- invoice_line_number
982                    l_inv_dist_id,		  -- invoice_distribution_id
983                    X_dist_tab(i).dist_line_num,   -- distribution_line_number
984                    NVL(l_line_type_lookup_code, 'ITEM'),       -- line_type_lookup_code --Bug16324208
985                    l_distribution_class,          -- distribution_class
986                    X_dist_tab(i).description,     -- description
987                    'NOT_MATCHED',                 -- dist_match_type
988                    X_dist_tab(i).org_id,          -- l_org_id
989                    X_dist_tab(i).dist_ccid,       -- dist_code_combination_id
990                    X_dist_tab(i).accounting_date, -- accounting_date
991                    X_dist_tab(i).period_name,     -- period_name
992                    'N',                           -- accrual_posted_flag
993                    'N',                           -- cash_posted_flag
994                    NULL,                          -- amount_to_post
995                    NULL,                          -- base_amount_to_post
996                    NULL,                          -- posted_amount
997                    NULL,                          -- posted_base_amount
998                    'N',                           -- posted_flag
999                    NULL,                          -- accounting_event_id
1000                    NULL,                          -- upgrade_posted_amt
1001                    NULL,                          -- upgrade_base_posted_amt
1002                    X_dist_tab(i).set_of_books_id, -- set_of_books_id
1003                    X_dist_tab(i).amount,          -- amount
1004                    X_dist_tab(i).base_amount,     -- base_amount
1005                    X_dist_tab(i).rounding_amt,    -- rounding_amt
1006                    NULL,                          -- quantity_variance
1007                    NULL,                          -- base_quantity_variance
1008 		   --Invoice Lines: Distributions, changed match_status_flag
1009                    --to NULL from 'N'.
1010                    NULL,                          -- match_status_flag
1011                    'N',                           -- encumbered_flag
1012                    NULL,                          -- packet_id
1013                    'N',                           -- reversal_flag
1014                    NULL,                          -- parent_reversal_id
1015                    'N',                           -- cancellation_flag
1016                    X_dist_tab(i).income_tax_region,  -- income_tax_region
1017                    X_dist_tab(i).type_1099,       -- type_1099
1018 		   NULL,                          --stat_amount
1019                    NULL,                          -- charge_applicable_to_dist_id
1020                    NULL,                          -- prepay_amount_remaining
1021                    NULL,                          -- prepay_distribution_id
1022                    NULL,                          -- parent_invoice_id
1023                    NULL,                          -- corrected_inv_dist_id
1024                    NULL,                          -- corrected_quantity
1025                    NULL,                          -- other_invoice_id
1026                    NULL,                          -- po_distribution_id
1027                    NULL,                          -- rcv_transaction_id
1028                    NULL,                          -- unit_price
1029                    NULL,                          -- matched_uom_lookup_code
1030                    NULL,                          -- quantity_invoiced
1031                    NULL,                          -- final_match_flag
1032                    NULL,                          -- related_id
1033                    'U',                           -- assets_addition_flag
1034                    X_dist_tab(i).assets_tracking_flag,-- assets_tracking_flag
1035                    X_dist_tab(i).asset_book_type_code,-- asset_book_type_code
1036                    X_dist_tab(i).asset_category_id,   -- asset_category_id
1037                    X_dist_tab(i).project_id,      -- project_id
1038                    X_dist_tab(i).task_id,         -- task_id
1039                    X_dist_tab(i).expenditure_type,-- expenditure_type
1040                    X_dist_tab(i).expenditure_item_date, -- expenditure_item_date
1041                    X_dist_tab(i).expenditure_organization_id, -- expenditure_organization_id
1042 		   X_dist_tab(i).project_accounting_context, --project_accounting_context
1043                    X_dist_tab(i).pa_quantity,     -- pa_quantity
1044                    X_dist_tab(i).pa_addition_flag,-- pa_addition_flag
1045                    X_dist_tab(i).award_id,        -- award_id
1046                    NULL,                          -- gms_burdenable_raw_cost
1047                    NULL,                          -- awt_flag
1048                    X_dist_tab(i).awt_group_id,    -- awt_group_id
1049                    NULL,                          -- awt_tax_rate_id
1050                    NULL,                          -- awt_gross_amount
1051                    NULL,                          -- awt_invoice_id
1052                    NULL,                          -- awt_origin_group_id
1053                    NULL,                          -- awt_invoice_payment_id
1054                    NULL,                          -- awt_withheld_amt
1055                    'N',                           -- inventory_transfer_status
1056 		   --Bug9296445
1057                    X_dist_tab(i).reference_1,     --NULL,   -- reference_1
1058                    X_dist_tab(i).reference_2,     --NULL,   -- reference_2
1059                    NULL,                          -- receipt_verified_flag
1060                    NULL,                          -- receipt_required_flag
1061                    NULL,                          -- receipt_missing_flag
1062                    NULL,                          -- justification
1063                    NULL,                          -- expense_group
1064                    NULL,                          -- start_expense_date
1065                    NULL,                          -- end_expense_date
1066                    NULL,                          -- receipt_currency_code
1067                    NULL,                          -- receipt_conversion_rate
1068                    NULL,                          -- receipt_currency_amount
1069                    NULL,                          -- daily_amount
1070                    NULL,                          -- web_parameter_id
1071                    NULL,                          -- adjustment_reason
1072                    NULL,                          -- merchant_document_number
1073                    NULL,                          -- merchant_name
1074                    NULL,                          -- merchant_reference
1075                    NULL,                          -- merchant_tax_reg_number
1076                    NULL,                          -- merchant_taxpayer_id
1077                    NULL,                          -- country_of_supply
1078                    NULL,                          -- credit_card_trx_id
1079                    NULL,                          -- company_prepaid_invoice_id
1080                    NULL,                          -- cc_reversal_flag
1081                    X_dist_tab(i).attribute_category,  -- attribute_category
1082                    X_dist_tab(i).attribute1,      -- attribute1
1083                    X_dist_tab(i).attribute2,      -- attribute2
1084                    X_dist_tab(i).attribute3,      -- attribute3
1085                    X_dist_tab(i).attribute4,      -- attribute4
1086                    X_dist_tab(i).attribute5,      -- attribute5
1087                    X_dist_tab(i).attribute6,      -- attribute6
1088                    X_dist_tab(i).attribute7,      -- attribute7
1089                    X_dist_tab(i).attribute8,      -- attribute8
1090                    X_dist_tab(i).attribute9,      -- attribute9
1091                    X_dist_tab(i).attribute10,     -- attribute10
1092                    X_dist_tab(i).attribute11,     -- attribute11
1093                    X_dist_tab(i).attribute12,     -- attribute12
1094                    X_dist_tab(i).attribute13,     -- attribute13
1095                    X_dist_tab(i).attribute14,     -- attribute14
1096                    X_dist_tab(i).attribute15,     -- attribute15
1097                    NULL,                          -- global_attribute_category
1098                    NULL,                          -- global_attribute1
1099                    NULL,                          -- global_attribute2
1100 		   --bugfix:4674194
1101 		   Decode(AP_EXTENDED_WITHHOLDING_PKG.AP_EXTENDED_WITHHOLDING_OPTION,
1102 		   	  'Y',X_dist_tab(i).global_attribute3,''), --global_attribute3
1103                    NULL,                          -- global_attribute4
1104                    NULL,                          -- global_attribute5
1105                    NULL,                          -- global_attribute6
1106                    NULL,                          -- global_attribute7
1107                    NULL,                          -- global_attribute8
1108                    NULL,                          -- global_attribute9
1109                    NULL,                          -- global_attribute10
1110                    NULL,                          -- global_attribute11
1111                    NULL,                          -- global_attribute12
1112                    NULL,                          -- global_attribute13
1113                    NULL,                          -- global_attribute14
1114                    NULL,                          -- global_attribute15
1115                    NULL,                          -- global_attribute16
1116                    NULL,                          -- global_attribute17
1117                    NULL,                          -- global_attribute18
1118                    NULL,                          -- global_attribute19
1119                    NULL,                          -- global_attribute20
1120                    FND_GLOBAL.user_id,            -- created_by
1121                    SYSDATE,                       -- creation_date
1122                    FND_GLOBAL.user_id,            -- last_updated_by
1123                    SYSDATE,                       -- last_update_date
1124                    FND_GLOBAL.login_id,           -- last_update_login
1125                    NULL,                          -- program_application_id
1126                    NULL,                          -- program_id
1127                    NULL,                          -- program_update_date
1128                    NULL,                          -- request_id
1129 	  X_Dist_Tab(i).intended_use,    -- intended_use
1130 	 'N',				  -- rcv_charge_addition_flag
1131 	 X_dist_tab(i).pay_awt_group_id    -- added for pay_awt_group_id for 7022001
1132                    );
1133 
1134 		   IF x_dist_tab(i).award_id Is Not Null Then
1135 			GMS_AP_API.CREATE_AWARD_DISTRIBUTIONS
1136 				( p_invoice_id		     => x_invoice_id,
1137 				  p_distribution_line_number => x_dist_tab(i).dist_line_num,
1138 				  p_invoice_distribution_id  => l_inv_dist_id,
1139 				  p_award_id                 => x_dist_tab(i).award_id,
1140 				  p_mode		     => 'AP',
1141 				  p_dist_set_id		     => NULL,
1142 				  p_dist_set_line_number     => NULL);
1143 		   END IF ;
1144 
1145 	 --bug 9169915 bug9737142
1146 	 IF l_country_code IN ('AR','CO') THEN
1147    	   JL_ZZ_AP_AWT_DEFAULT_PKG.SUPP_WH_DEF (X_invoice_id,
1148 	                                         X_line_number,
1149 						 l_inv_dist_id,
1150 						 NULL);
1151          END IF;
1152 	 --bug 9169915
1153 
1154 	 --Bug#10241241
1155 	   IF (l_dist_updated = 0 and
1156 	       x_dist_tab(i).stat_amount is not null and
1157 	       GET_UOM(X_dist_tab(i).dist_ccid,l_chart_of_accounts_id) is not null) THEN
1158 
1159 	   Update ap_invoice_distributions
1160 	   set stat_amount =   X_dist_tab(i).stat_amount
1161 	   where invoice_id  = X_invoice_id
1162              and invoice_line_number= X_line_number
1163 	     and distribution_line_number = X_dist_tab(i).dist_line_num;
1164 
1165              l_dist_updated := 1;
1166 
1167            END IF;
1168 	 --Bug#10241241
1169 
1170 
1171      END LOOP;
1172 
1173 
1174      --Bug 4539462 DBI logging
1175      SELECT invoice_distribution_id
1176      BULK COLLECT INTO  l_dbi_key_value_list
1177      FROM ap_invoice_distributions
1178      WHERE invoice_id = X_invoice_id;
1179 
1180      AP_DBI_PKG.Maintain_DBI_Summary
1181               (p_table_name => 'AP_INVOICE_DISTRIBUTIONS',
1182                p_operation => 'I',
1183                p_key_value1 => X_invoice_id,
1184                p_key_value_list => l_dbi_key_value_list,
1185                 p_calling_sequence => current_calling_sequence);
1186 
1187 
1188   ----------------------------------------------------------------------------
1189   -- Step 5 - Update generate distributions flag in invoice line but only if
1190   -- generating distributions in permanent mode.
1191   ----------------------------------------------------------------------------
1192   debug_info := 'Setting generate distributions flag to Done';
1193   if (l_distribution_class = 'PERMANENT') then
1194     BEGIN
1195       UPDATE AP_INVOICE_LINES
1196          SET GENERATE_DISTS = 'D'
1197          WHERE invoice_id = X_invoice_id
1198          AND line_number = X_line_number;
1199     EXCEPTION
1200       WHEN OTHERS THEN
1201         X_debug_info := debug_info || ': Error encountered';
1202         X_debug_context := current_calling_sequence;
1203         return (FALSE);
1204     END;
1205   end if;
1206 
1207   return(TRUE);
1208 
1209   EXCEPTION
1210     WHEN OTHERS THEN
1211       X_debug_info := 'Error encountered';
1212       X_debug_context := current_calling_sequence;
1213       return (FALSE);
1214 
1215   END insert_from_dist_set;
1216 
1217 
1218   -----------------------------------------------------------------------
1219     -- PROCEDURE update_distributions updates columns in
1220     --   AP_INVOICE_DISTRIBUTIONS such as match_status_flag, base_amount,
1221     --   type_1099, income_tax_region.
1222     -- PRECONDITION: Procedure is called during POST-FORMS-COMMIT
1223     -----------------------------------------------------------------------
1224 
1225     PROCEDURE update_distributions (
1226               X_invoice_id                   IN            number,
1227               X_line_number                  IN            number,
1228               X_type_1099                    IN            varchar2,
1229               X_income_tax_region            IN            varchar2,
1230               X_vendor_changed_flag          IN OUT NOCOPY varchar2,
1231               X_update_base                  IN OUT NOCOPY varchar2,
1232               X_reset_match_status           IN OUT NOCOPY varchar2,
1233               X_update_occurred              IN OUT NOCOPY varchar2,
1234               X_calling_sequence             IN            varchar2)
1235     IS
1236       l_purch_encumbrance_flag varchar2(10);
1237       l_multi_currency_flag    varchar2(10);
1238       l_base_dist_total        number;
1239       l_dist_total             number;
1240       l_base_currency_code
1241           ap_system_parameters.base_currency_code%TYPE;
1242       l_exchange_rate
1243           ap_invoices.exchange_rate%TYPE;
1244       l_exchange_rate_type
1245           ap_invoices.exchange_rate_type%TYPE;
1246       l_exchange_date
1247           ap_invoices.exchange_date%TYPE;
1248       l_base_amount
1249           ap_invoices.base_amount%TYPE;
1250       l_invoice_amount
1251           ap_invoices.invoice_amount%TYPE;
1252       l_invoice_currency_code
1253            ap_invoices.invoice_currency_code%TYPE;
1254       l_last_update_login
1255           ap_invoices.last_update_login%TYPE;
1256       l_last_updated_by
1257           ap_invoices.last_updated_by%TYPE;
1258       l_last_update_date
1259           ap_invoices.last_update_date%TYPE;
1260       l_invoice_distribution_id
1261            ap_invoice_distributions.invoice_distribution_id%TYPE;
1262       l_project_id
1263           ap_invoice_distributions.project_id%TYPE;
1264       l_task_id
1265           ap_invoice_distributions.task_id%TYPE;
1266       l_award_id
1267           ap_invoice_distributions.award_id%TYPE;  -- OGM_0.0 changes
1268       l_expenditure_item_date  DATE;
1269       l_expenditure_type
1270           ap_invoice_distributions.expenditure_type%TYPE;
1271       l_employee_id
1272           po_vendors.employee_id%TYPE;
1273       l_pa_quantity
1274           ap_invoice_distributions.pa_quantity%TYPE;
1275       l_dist_amount
1276           ap_invoice_distributions.amount%TYPE;
1277       l_dist_base_amount
1278           ap_invoice_distributions.base_amount%TYPE;
1279       l_expenditure_organization_id
1280           ap_invoice_distributions.expenditure_organization_id%TYPE;
1281 
1282       l_vendor_id              NUMBER;
1283       l_vendor_site_id         NUMBER;
1284       l_invoice_date           DATE;
1285       l_gl_allow_tax_override
1286           GL_TAX_OPTION_ACCOUNTS.ALLOW_TAX_CODE_OVERRIDE_FLAG%TYPE;
1287       l_tax_recoverable_flag
1288           ap_invoice_distributions.tax_recoverable_flag%TYPE;
1289       l_po_distribution_id
1290           ap_invoice_distributions.po_distribution_id%TYPE;
1291       l_line_location_id
1292           po_distributions.line_location_id%TYPE;
1293       l_accrue_on_receipt
1294            po_distributions.accrue_on_receipt_flag%TYPE;
1295       l_dist_count                   NUMBER;
1296       l_user_id                      NUMBER;
1297       l_dist_attribute_category
1298           ap_invoice_distributions.attribute_category%TYPE;
1299       l_dist_attribute1        ap_invoice_distributions.attribute1%TYPE;
1300       l_dist_attribute2        ap_invoice_distributions.attribute1%TYPE;
1301       l_dist_attribute3        ap_invoice_distributions.attribute1%TYPE;
1302       l_dist_attribute4        ap_invoice_distributions.attribute1%TYPE;
1303       l_dist_attribute5        ap_invoice_distributions.attribute1%TYPE;
1304       l_dist_attribute6        ap_invoice_distributions.attribute1%TYPE;
1305       l_dist_attribute7        ap_invoice_distributions.attribute1%TYPE;
1306       l_dist_attribute8        ap_invoice_distributions.attribute1%TYPE;
1307       l_dist_attribute9        ap_invoice_distributions.attribute1%TYPE;
1308       l_dist_attribute10       ap_invoice_distributions.attribute1%TYPE;
1309       l_dist_attribute11       ap_invoice_distributions.attribute1%TYPE;
1310       l_dist_attribute12       ap_invoice_distributions.attribute1%TYPE;
1311       l_dist_attribute13       ap_invoice_distributions.attribute1%TYPE;
1312       l_dist_attribute14       ap_invoice_distributions.attribute1%TYPE;
1313       l_dist_attribute15       ap_invoice_distributions.attribute1%TYPE;
1314       l_dist_posted_flag       ap_invoice_distributions.posted_flag%TYPE;
1315       l_dist_reversal_flag     ap_invoice_distributions.reversal_flag%TYPE;
1316       l_inv_attribute_category ap_invoices.attribute_category%TYPE;
1317       l_inv_attribute1         ap_invoices.attribute1%TYPE;
1318       l_inv_attribute2         ap_invoices.attribute1%TYPE;
1319       l_inv_attribute3         ap_invoices.attribute1%TYPE;
1320       l_inv_attribute4         ap_invoices.attribute1%TYPE;
1321       l_inv_attribute5         ap_invoices.attribute1%TYPE;
1322       l_inv_attribute6         ap_invoices.attribute1%TYPE;
1323       l_inv_attribute7         ap_invoices.attribute1%TYPE;
1324       l_inv_attribute8         ap_invoices.attribute1%TYPE;
1325       l_inv_attribute9         ap_invoices.attribute1%TYPE;
1326       l_inv_attribute10        ap_invoices.attribute1%TYPE;
1327       l_inv_attribute11        ap_invoices.attribute1%TYPE;
1328       l_inv_attribute12        ap_invoices.attribute1%TYPE;
1329       l_inv_attribute13        ap_invoices.attribute1%TYPE;
1330       l_inv_attribute14        ap_invoices.attribute1%TYPE;
1331       l_inv_attribute15        ap_invoices.attribute1%TYPE;
1332       l_msg_application        VARCHAR2(25);
1333       l_msg_type               VARCHAR2(25);
1334       l_msg_token1             VARCHAR2(30);
1335       l_msg_token2             VARCHAR2(30);
1336       l_msg_token3             VARCHAR2(30);
1337       l_msg_count              NUMBER;
1338       l_msg_data               VARCHAR2(200); /*bug12612482 changed from 30 to 200*/
1339       l_billable_flag          VARCHAR2(25);
1340       l_invoice_type_lookup_code
1341           ap_invoices.invoice_type_lookup_code%TYPE;
1342       l_chart_of_accounts_id           NUMBER;
1343       l_DIST_CODE_COMBINATION_ID       NUMBER;
1344       l_concat_ids                     Varchar2(2000);
1345       l_concat_segs                    Varchar2(2000);
1346       l_concat_descrs                  Varchar2(300);
1347       l_errmsg                         Varchar2(1300);
1348       current_calling_sequence         VARCHAR2(2000);
1349       debug_info                       VARCHAR2(100);
1350       debug_context                    VARCHAR2(2000);
1351       l_key_value_list                 ap_dbi_pkg.r_dbi_key_value_arr; -- bug 9772522
1352       l_line_number
1353           ap_invoice_lines.line_number%TYPE;
1354       l_rounded_dist_id
1355           ap_invoice_distributions.invoice_distribution_id%type;
1356       l_round_amt_exists               BOOLEAN := FALSE;
1357       l_rounded_amt                    NUMBER;
1358        --Bug 4539462 DBI logging
1359        l_dbi_key_value_list        ap_dbi_pkg.r_dbi_key_value_arr;
1360        l_org_id			   ap_invoices_all.org_id%type;
1361 
1362       l_base_amt                   NUMBER; --6892789
1363       l_modified_dist_rounding_amt NUMBER; --6892789
1364       l_round_dist_id_list         AP_INVOICE_LINES_PKG.distribution_id_tab_type; --6892789
1365 
1366       cursor invoice_line_cursor is
1367       SELECT exchange_rate,
1368              exchange_rate_type,
1369              exchange_date,
1370              AI.invoice_currency_code,
1371              invoice_type_lookup_code,
1372              invoice_date,
1373              DECODE(x_line_number, null,
1374                     AI.last_update_login,
1375                     AIL.last_update_login ),
1376              DECODE(x_line_number, null,
1377                     AI.last_updated_by,
1378                     AIL.last_updated_by ),
1379              DECODE(x_line_number, null,
1380                     AI.last_update_date,
1381                     AIL.last_update_date ),
1382              AIL.line_number,
1383 	     AI.org_id
1384       FROM   ap_invoices AI,
1385              ap_invoice_lines AIL
1386       WHERE  AI.invoice_id = X_invoice_id
1387         AND  AIL.invoice_id = AI.invoice_id
1388         AND  AIL.line_number = NVL(X_line_number, AIL.line_number);
1389 
1390       cursor pa_related_dist_cur is
1391       SELECT AID.invoice_distribution_id,
1392              AID.project_id,
1393              AID.task_id,
1394              AID.award_id,  -- OGM_0.0 changes
1395              AID.expenditure_item_date,
1396              AID.expenditure_type,
1397              PV.employee_id,
1398              AID.pa_quantity,
1399              AID.amount,
1400              AID.base_amount,
1401              AID.expenditure_organization_id,
1402              AI.vendor_id,
1403              AI.vendor_site_id,
1404              AID.tax_recoverable_flag,
1405              PD.line_location_id,
1406              PD.accrue_on_receipt_flag,
1407              AID.po_distribution_id,
1408              AID.attribute_category,
1409              AID.attribute1,
1410              AID.attribute2,
1411              AID.attribute3,
1412              AID.attribute4,
1413              AID.attribute5,
1414              AID.attribute6,
1415              AID.attribute7,
1416              AID.attribute8,
1417              AID.attribute9,
1418              AID.attribute10,
1419              AID.attribute11,
1420              AID.attribute12,
1421              AID.attribute13,
1422              AID.attribute14,
1423              AID.attribute15,
1424              NVL(AID.posted_flag,'N'),
1425              NVL(AID.reversal_flag,'N'),
1426              AI.attribute_category,
1427              AI.attribute1,
1428              AI.attribute2,
1429              AI.attribute3,
1430              AI.attribute4,
1431              AI.attribute5,
1432              AI.attribute6,
1433              AI.attribute7,
1434              AI.attribute8,
1435              AI.attribute9,
1436              AI.attribute10,
1437              AI.attribute11,
1438              AI.attribute12,
1439              AI.attribute13,
1440              AI.attribute14,
1441              AI.attribute15,
1442              gsob.chart_of_accounts_id
1443       FROM ap_invoice_distributions AID,
1444            ap_invoices AI,
1445            ap_suppliers PV,
1446            po_distributions PD,
1447            ap_system_parameters ap,
1448            gl_sets_of_books gsob
1449       WHERE  AI.invoice_id = X_invoice_id
1450         AND  AID.invoice_id = AI.invoice_id
1451         AND  AID.invoice_line_number =
1452              NVL(X_line_number, invoice_line_number)
1453         AND  AID.project_id IS NOT NULL
1454         AND  AI.vendor_id = PV.vendor_id
1455         AND  AID.po_distribution_id = PD.po_distribution_id (+)
1456         AND  AID.last_update_login = -3
1457         AND  ap.set_of_books_id = gsob.set_of_books_id
1458         AND  ap.set_of_books_id = AID.set_of_books_id
1459 	AND  ap.org_id = ai.org_id;
1460 
1461         --Bug 1902980 last_update_login is set to -3 if the
1462         --record changes before reaching the PA code.
1463   BEGIN
1464     -- Update the calling sequence
1465     current_calling_sequence :=
1466         'AP_INVOICE_DISTRIBUTIONS_PKG.update_distributions<-'||
1467          X_calling_sequence;
1468 
1469     /*-----------------------------------------------------------------+
1470      |  First, assume that an update to AP_INVOICE_DISTRIBUTIONS       |
1471      |  will not occur.  We will override the this default value       |
1472      |  if an update does occur.                                       |
1473      +-----------------------------------------------------------------*/
1474 
1475     X_update_occurred := 'N';
1476 
1477 
1478     -- Bug 5052593 -- removed redundant code
1479     ----------------------------------------------------------
1480     --debug_info := 'Select from ap_system_parameters and
1481     --		   financials_system_parameters';
1482     ----------------------------------------------------------
1483      --SELECT FSP.purch_encumbrance_flag,
1484      --       SP.multi_currency_flag,
1485      --	    SP.base_currency_code
1486      --INTO l_purch_encumbrance_flag,
1487      --     l_multi_currency_flag,
1488      --	  l_base_currency_code
1489      --FROM financials_system_parameters FSP,
1490      --     ap_system_parameters SP;
1491 
1492     debug_info := 'select AP_INVOICES info';
1493 
1494     /*-----------------------------------------------------------------+
1495      |  Fetch the invoice information that we need in order to update  |
1496      |  the distribution base amounts                                  |
1497      +-----------------------------------------------------------------*/
1498 
1499     OPEN invoice_line_cursor;
1500     debug_info := 'Fetch cursor invoice_cursor';
1501     LOOP
1502     FETCH invoice_line_cursor
1503      INTO l_exchange_rate,
1504           l_exchange_rate_type,
1505           l_exchange_date,
1506           l_invoice_currency_code,
1507           l_invoice_type_lookup_code,
1508           l_invoice_date,
1509           l_last_update_login,
1510           l_last_updated_by,
1511           l_last_update_date,
1512           l_line_number,
1513 	  l_org_id;
1514     EXIT WHEN invoice_line_cursor%NOTFOUND;
1515 
1516     ----------------------------------------------------------
1517     debug_info := 'Select from ap_system_parameters and
1518                   financials_system_parameters';
1519     ----------------------------------------------------------
1520        SELECT FSP.purch_encumbrance_flag,
1521               SP.multi_currency_flag,
1522               SP.base_currency_code
1523          INTO l_purch_encumbrance_flag,
1524               l_multi_currency_flag,
1525               l_base_currency_code
1526          FROM financials_system_parameters FSP,
1527               ap_system_parameters SP
1528 	 WHERE sp.org_id = l_org_id
1529 	  AND  sp.org_id = fsp.org_id;
1530 
1531       ---------------------------------------------------------
1532       debug_info := 'Update AP_INVOICE_DISTRIBUTIONS tax info';
1533       ---------------------------------------------------------
1534 
1535     /*-----------------------------------------------------------------+
1536      |  Update 1099 type and income tax region for each distribution   |
1537      |  line if the vendor changed (test performed in PRE-UPDATE)      |
1538      +-----------------------------------------------------------------*/
1539 
1540       IF (nvl(X_vendor_changed_flag,'N') = 'Y') THEN
1541         UPDATE ap_invoice_distributions
1542            SET type_1099 = X_type_1099,
1543                income_tax_region = X_income_tax_region
1544          WHERE invoice_id = X_invoice_id
1545            AND invoice_line_number = NVL(X_line_number, invoice_line_number);
1546 
1547         IF (SQL%ROWCOUNT > 0) THEN
1548           X_update_occurred := 'Y';
1549         END IF;
1550 
1551         -- Reset the vendor changed flag
1552         X_vendor_changed_flag := 'N';
1553 
1554       END IF; -- end of x_vendor_changed_flag
1555 
1556       --------------------------------------------------------------
1557       debug_info := 'Update AP_INVOICE_DISTRIBUTIONS match status';
1558       --------------------------------------------------------------
1559 
1560        -- Reset the match status flags if X_reset_match_status
1561        -- is Y and encumbrance is not on.
1562        -- Don't change NULLS to N as these have never been through
1563        -- AutoApproval
1564        --
1565       UPDATE ap_invoice_distributions
1566          SET match_status_flag = 'N'
1567        WHERE invoice_id = X_invoice_id
1568          AND invoice_line_number = NVL( x_line_number, invoice_line_number)
1569          --Bug 5003892  AND l_purch_encumbrance_flag <> 'Y'
1570          AND nvl(X_reset_match_status,'N') = 'Y'
1571          AND NVL(match_status_flag,'N') <> 'N'
1572 	 -- Bug 9945411 Begin
1573          AND NVL( posted_flag, 'N' ) = 'N'
1574 	 AND NVL( cash_posted_flag, 'N' ) = 'N'
1575 	 AND NVL( encumbered_flag, 'X' ) <> 'Y'
1576 	 -- Bug 9945411 End
1577 	RETURNING invoice_distribution_id
1578         BULK COLLECT INTO l_dbi_key_value_list;
1579 
1580 	--Bug 4539462 DBI logging
1581         AP_DBI_PKG.Maintain_DBI_Summary
1582               (p_table_name => 'AP_INVOICE_DISTRIBUTIONS',
1583                p_operation => 'U',
1584                p_key_value1 => X_invoice_id,
1585                p_key_value_list => l_dbi_key_value_list,
1586                 p_calling_sequence => current_calling_sequence);
1587 
1588       if (SQL%ROWCOUNT > 0) then
1589         X_update_occurred := 'Y';
1590       end if;
1591 
1592       -- Reset the reset match status flag
1593       X_reset_match_status := 'N';
1594 
1595       IF (nvl(l_multi_currency_flag,'N') = 'Y' AND
1596           nvl(X_update_base,'N') = 'Y') THEN
1597 
1598         -- Update the distributions if this is a foreign currency invoice
1599         -- and there is an invoice exchange rate as something has been changed
1600         -- Check that the base amounts sum to the invoice base amount
1601         -- Fire for functional currency invoices if multi-curr is enabled
1602         -- as it may have just been changed to functional so we want to clear
1603         -- all the base columns
1604         -- Set the exchange rate info, base amount and WHO columns
1605         -- for the distributions
1606 
1607   	   --Bugfix:4644053 changed ap_invoice_distributions
1608 	   --to ap_invoice_distributions_all
1609            debug_info := 'Update AP_INVOICE_DISTRIBUTIONS base amounts';
1610 
1611            UPDATE AP_INVOICE_DISTRIBUTIONS_ALL
1612            SET base_amount        =
1613                    DECODE(l_base_currency_code,
1614                          l_invoice_currency_code, NULL,
1615                          ap_utilities_pkg.ap_round_currency(
1616                          amount * l_exchange_rate,
1617                                   l_base_currency_code)),
1618                last_update_login  =  l_last_update_login,
1619                last_updated_by    = l_last_updated_by,
1620                last_update_date   = SYSDATE
1621            WHERE invoice_id = X_invoice_id
1622            AND invoice_line_number = nvl( x_line_number, invoice_line_number)
1623            AND NVL(posted_flag,'N') = 'N'
1624            AND ( ( base_amount is null AND
1625                        DECODE(l_base_currency_code,
1626                               l_invoice_currency_code, NULL,
1627                               ap_utilities_pkg.ap_round_currency(
1628                                    amount * l_exchange_rate,
1629                                    l_base_currency_code)) is not null)
1630                  OR
1631                  (NVL(base_amount,0) <>
1632                        DECODE(l_base_currency_code,
1633                               l_invoice_currency_code, NULL,
1634                               ap_utilities_pkg.ap_round_currency(
1635                                   amount * l_exchange_rate,
1636                                   l_base_currency_code))
1637                   AND  NVL(reversal_flag,'N') <> 'Y'   --Bug 8347194
1638                                   ))
1639            AND line_type_lookup_code NOT IN ('NONREC_TAX','REC_TAX','TRV','TERV','TIPV','IPV', 'ERV') -- Bug 11654030 --Bug 12691958: Excluded 'IPV' and 'ERV' lines
1640            AND related_id IS NULL -- Bug 13864403
1641                RETURNING invoice_distribution_id
1642                BULK COLLECT INTO l_key_value_list;
1643 
1644            if (SQL%ROWCOUNT > 0) then
1645               X_update_occurred := 'Y';
1646            end if;
1647 
1648            -- Reset the update base flag
1649            X_update_base := 'N';
1650 
1651         --END IF;
1652 
1653 	-- Check to see if the base amounts add up to the invoice base amount
1654 	-- If not update the biggest distribution
1655 	-- Only do this if the distributions add up in the entered currency
1656 
1657         -----------------------------------------------------------------
1658         debug_info := 'Call API to check if rounding amount is existing';
1659         -----------------------------------------------------------------
1660 
1661 
1662  /* modifying following code as per the bug 6892789 as there is a chance that
1663      distribution base amt goes to -ve value (amount being +ve) so in such case,
1664      adjust dist base amount upto zero and adjust the remaing amount in another
1665      distribution having next max amount */
1666     -- get the distributions which can be adjusted
1667     l_round_amt_exists := AP_INVOICE_LINES_PKG.round_base_amts(
1668                               x_invoice_id          => X_invoice_id,
1669                               x_line_number         => l_line_number,
1670                               x_reporting_ledger_id => NULL,
1671                               x_round_dist_id_list  => l_round_dist_id_list,
1672                               x_rounded_amt         => l_rounded_amt,
1673                               x_debug_info          => debug_info,
1674                               x_debug_context       => debug_context,
1675                               x_calling_sequence    => current_calling_sequence);
1676 
1677     -- adjustment required and there are existing distributions that can be adjusted
1678     IF ( l_round_amt_exists  AND l_round_dist_id_list.count > 0 ) THEN
1679       for i in 1 .. l_round_dist_id_list.count -- iterate through dists till there is no need to adjust
1680       loop
1681           IF l_rounded_amt <> 0 THEN
1682 
1683             -- get the existing base amount for the selected distribution
1684             select base_amount
1685             INTO   l_base_amt
1686             FROM   AP_INVOICE_DISTRIBUTIONS
1687             WHERE  invoice_id = X_invoice_id
1688             AND    invoice_line_number = l_line_number
1689             AND    invoice_distribution_id = l_round_dist_id_list(i);
1690 
1691             -- get the calculated adjusted base amount and rounding amount
1692             -- get rounding amount for the next dist, if required
1693             l_base_amt := AP_APPROVAL_PKG.get_adjusted_base_amount(p_base_amount => l_base_amt,
1694                                                                    p_rounding_amt => l_modified_dist_rounding_amt,
1695                                                                    p_next_line_rounding_amt => l_rounded_amt);
1696 
1697             -- update the calculatd base amount, rounding amount
1698             UPDATE AP_INVOICE_DISTRIBUTIONS
1699             SET    base_amount = l_base_amt,
1700             rounding_amt = ABS( l_modified_dist_rounding_amt ),
1701             last_update_date = SYSDATE,
1702             last_updated_by = FND_GLOBAL.user_id,
1703             last_update_login = FND_GLOBAL.login_id
1704             WHERE  invoice_distribution_id = l_round_dist_id_list(i);
1705 
1706             if (SQL%ROWCOUNT > 0) then
1707               X_update_occurred := 'Y';
1708             end if;
1709           ELSE -- adjustment not required or there are no dists that can be adjusted
1710               EXIT;
1711           END IF;
1712      end loop;
1713     END IF;
1714 
1715 /* CHANGES FOR BUG - 3025688 ** STARTS **
1716       /*  Commenting out PA calls as this is no more needed.
1717           If we are doing matching, we expect the details provided in PO
1718           are already validated and no more validation of PA should happen
1719           again. After matching if there is any change in the information
1720           provided in the distribution will be handled in Form validation. */
1721      /*-----------------------------------------------------------------+
1722      | For Projects, the call to flex build the account has changed,   |
1723      | The new design calls for calling the PA routine if the exchange |
1724      | rate information has changed. The exchange rate information     |
1725      | change in the invoice workbench leads to the variable           |
1726      | X_update_base being set to 'Y' so we use this same variable to  |
1727      | determine whether to call the PA flexbuilder routine again or   |
1728      | not                                                             |
1729      +-----------------------------------------------------------------*/
1730 
1731 /*        ------------------------------------------------
1732         debug_info := 'Call PA flex builder procedures';
1733         ------------------------------------------------
1734 
1735         OPEN pa_related_dist_cur;
1736         l_dist_count := 0;
1737 
1738         LOOP
1739           FETCH pa_related_dist_cur INTO
1740                         l_invoice_distribution_id,
1741                         l_project_id,
1742                         l_task_id,
1743                         l_award_id,   -- OGM_0.0 changes...
1744                         l_expenditure_item_date,
1745                         l_expenditure_type,
1746                         l_employee_id,
1747                         l_pa_quantity,
1748                         l_dist_amount,
1749                         l_dist_base_amount,
1750                         l_expenditure_organization_id,
1751                         l_vendor_id,
1752                         l_vendor_site_id,
1753                         l_tax_recoverable_flag,
1754                         l_line_location_id,
1755                         l_accrue_on_receipt,   -- Bug:1609628
1756                         l_po_distribution_id,
1757                         l_dist_attribute_category,
1758                         l_dist_attribute1,
1759                         l_dist_attribute2,
1760                         l_dist_attribute3,
1761                         l_dist_attribute4,
1762                         l_dist_attribute5,
1763                         l_dist_attribute6,
1764                         l_dist_attribute7,
1765                         l_dist_attribute8,
1766                         l_dist_attribute9,
1767                         l_dist_attribute10,
1768                         l_dist_attribute11,
1769                         l_dist_attribute12,
1770                         l_dist_attribute13,
1771                         l_dist_attribute14,
1772                         l_dist_attribute15,
1773                         l_dist_posted_flag, --Bug:1754223
1774                         l_dist_reversal_flag, --Bug:1754223
1775                         l_inv_attribute_category,
1776                         l_inv_attribute1,
1777                         l_inv_attribute2,
1778                         l_inv_attribute3,
1779                         l_inv_attribute4,
1780                         l_inv_attribute5,
1781                         l_inv_attribute6,
1782                         l_inv_attribute7,
1783                         l_inv_attribute8,
1784                         l_inv_attribute9,
1785                         l_inv_attribute10,
1786                         l_inv_attribute11,
1787                         l_inv_attribute12,
1788                         l_inv_attribute13,
1789                         l_inv_attribute14,
1790                         l_inv_attribute15,
1791                         l_chart_of_accounts_id;
1792 
1793           EXIT WHEN pa_related_dist_cur%NOTFOUND;
1794 
1795           -- get the user id
1796           FND_PROFILE.GET('USER_ID',l_user_id);
1797 
1798 	  --Added the below if for bug7014798
1799 
1800           if instr(current_calling_sequence, 'RECURR') <> 0 then
1801              l_calling_module := 'APXRICAD';
1802           else
1803              l_calling_module := 'apiindib.pls';
1804           end if;
1805 
1806 
1807           -- call the new function (replacment of patc.get_status)
1808 
1809           PA_TRANSACTIONS_PUB.VALIDATE_TRANSACTION(
1810                X_PROJECT_ID          => l_project_id,
1811                X_TASK_ID             => l_task_id,
1812                X_EI_DATE             => l_expenditure_item_date,
1813                X_EXPENDITURE_TYPE    => l_expenditure_type,
1814                X_NON_LABOR_RESOURCE  => null,
1815                X_PERSON_ID           => l_employee_id,
1816                X_QUANTITY            => l_pa_quantity,
1817                X_denom_currency_code => l_invoice_currency_code,
1818                X_acct_currency_code  => l_base_currency_code,
1819                X_denom_raw_cost      => l_dist_amount,
1820                X_acct_raw_cost       => l_dist_base_amount,
1821                X_acct_rate_type      => l_exchange_rate_type,
1822                X_acct_rate_date      => l_exchange_date,
1823                X_acct_exchange_rate  => l_exchange_rate,
1824                X_TRANSFER_EI         => null,
1825                X_INCURRED_BY_ORG_ID  => l_expenditure_organization_id,
1826                X_NL_RESOURCE_ORG_ID  => null,
1827                X_TRANSACTION_SOURCE  => null,
1828                X_CALLING_MODULE      => l_calling_module,  --bug7014798
1829                X_VENDOR_ID           => l_vendor_id,
1830                X_ENTERED_BY_USER_ID  => l_user_id,
1831                X_ATTRIBUTE_CATEGORY  => l_dist_attribute_category,
1832                X_ATTRIBUTE1          => l_dist_attribute1,
1833                X_ATTRIBUTE2          => l_dist_attribute2,
1834                X_ATTRIBUTE3          => l_dist_attribute3,
1835                X_ATTRIBUTE4          => l_dist_attribute4,
1836                X_ATTRIBUTE5          => l_dist_attribute5,
1837                X_ATTRIBUTE6          => l_dist_attribute6,
1838                X_ATTRIBUTE7          => l_dist_attribute7,
1839                X_ATTRIBUTE8          => l_dist_attribute8,
1840                X_ATTRIBUTE9          => l_dist_attribute9,
1841                X_ATTRIBUTE10         => l_dist_attribute10,
1842                X_ATTRIBUTE11         => l_dist_attribute11,
1843                X_ATTRIBUTE12         => l_dist_attribute12,
1844                X_ATTRIBUTE13         => l_dist_attribute13,
1845                X_ATTRIBUTE14         => l_dist_attribute14,
1846                X_ATTRIBUTE15         => l_dist_attribute15,
1847                X_msg_application     => l_msg_application,
1848                X_msg_type            => l_msg_type,
1849                X_msg_token1          => l_msg_token1,
1850                X_msg_token2          => l_msg_token2,
1851                X_msg_token3          => l_msg_token3,
1852                X_msg_count           => l_msg_count,
1853                X_msg_data            => l_msg_data,
1854                X_BILLABLE_FLAG       => l_billable_flag);
1855 
1856           IF (l_msg_data is not null) THEN
1857             FND_MESSAGE.SET_NAME(l_msg_application, l_msg_data);
1858             -- For bug3469917. Need to add token values for non-PA applications.
1859 
1860               if (l_msg_application <> 'PA') Then
1861 
1862 
1863                 IF (l_msg_token1 IS NOT NULL) THEN
1864                     fnd_message.set_token('PATC_MSG_TOKEN1',l_msg_token1);
1865                 ELSE
1866                     fnd_message.set_token('PATC_MSG_TOKEN1',app_api.G_NULL_CHAR);
1867                 END IF;
1868                 IF (l_msg_token2 IS NOT NULL) THEN
1869                     fnd_message.set_token('PATC_MSG_TOKEN2',l_msg_token2);
1870                 ELSE
1871                     fnd_message.set_token('PATC_MSG_TOKEN2',app_api.G_NULL_CHAR);
1872                 END IF;
1873                 IF (l_msg_token3 IS NOT NULL) THEN
1874                     fnd_message.set_token('PATC_MSG_TOKEN3',l_msg_token3);
1875                 ELSE
1876                     fnd_message.set_token('PATC_MSG_TOKEN3',app_api.G_NULL_CHAR);
1877                 END IF;
1878 
1879               end if;
1880 
1881              -- End for bug3469917
1882             app_exception.raise_exception;
1883           END IF;
1884 
1885           IF ( ( (l_po_distribution_id is NOT NULL) AND
1886                  (nvl(l_accrue_on_receipt,'N') <> 'Y') )
1887                OR
1888                  (l_po_distribution_id is NULL) ) THEN
1889 
1890             IF (l_invoice_type_lookup_code = 'EXPENSE REPORT') THEN
1891 
1892 	      /*
1893               IF ( NOT pa_acc_gen_wf_pkg.ap_er_generate_account (
1894                            p_project_id        =>l_project_id,
1895                            p_task_id           => l_task_id,
1896                            p_expenditure_type  => l_expenditure_type,
1897                            p_vendor_id         => l_VENDOR_ID,
1898                            p_expenditure_organization_id =>l_EXPENDITURE_ORGANIZATION_ID,
1899                            p_expenditure_item_date =>l_EXPENDITURE_ITEM_DATE,
1900                            p_billable_flag         =>l_billable_flag,
1901                            p_chart_of_accounts_id =>l_CHART_OF_ACCOUNTS_ID,
1902                            p_calling_module       => 'apiindib.pls',
1903                            p_employee_id          => l_employee_id,
1904                            p_employee_ccid        => null,
1905                            p_expense_type         => null,
1906                            p_expense_cc           => null,
1907                            P_ATTRIBUTE_CATEGORY => l_inv_ATTRIBUTE_CATEGORY,
1908                            P_ATTRIBUTE1  => l_inv_ATTRIBUTE1,
1909                            P_ATTRIBUTE2  => l_inv_ATTRIBUTE2,
1910                            P_ATTRIBUTE3  => l_inv_ATTRIBUTE3,
1911                            P_ATTRIBUTE4  => l_inv_ATTRIBUTE4,
1912                            P_ATTRIBUTE5  => l_inv_ATTRIBUTE5,
1913                            P_ATTRIBUTE6  => l_inv_ATTRIBUTE6,
1914                            P_ATTRIBUTE7  => l_inv_ATTRIBUTE7,
1915                            P_ATTRIBUTE8  => l_inv_ATTRIBUTE8,
1916                            P_ATTRIBUTE9  => l_inv_ATTRIBUTE9,
1917                            P_ATTRIBUTE10 => l_inv_ATTRIBUTE10,
1918                            P_ATTRIBUTE11 => l_inv_ATTRIBUTE11,
1919                            P_ATTRIBUTE12 => l_inv_ATTRIBUTE12,
1920                            P_ATTRIBUTE13 => l_inv_ATTRIBUTE13,
1921                            P_ATTRIBUTE14 => l_inv_ATTRIBUTE14,
1922                            P_ATTRIBUTE15 => l_inv_ATTRIBUTE15,
1923                            P_LINE_ATTRIBUTE_CATEGORY => l_dist_ATTRIBUTE_CATEGORY,
1924                            P_LINE_ATTRIBUTE1  => l_dist_ATTRIBUTE1,
1925                            P_LINE_ATTRIBUTE2  => l_dist_ATTRIBUTE2,
1926                            P_LINE_ATTRIBUTE3  => l_dist_ATTRIBUTE3,
1927                            P_LINE_ATTRIBUTE4  => l_dist_ATTRIBUTE4,
1928                            P_LINE_ATTRIBUTE5  => l_dist_ATTRIBUTE5,
1929                            P_LINE_ATTRIBUTE6  => l_dist_ATTRIBUTE6,
1930                            P_LINE_ATTRIBUTE7  => l_dist_ATTRIBUTE7,
1931                            P_LINE_ATTRIBUTE8  => l_dist_ATTRIBUTE8,
1932                            P_LINE_ATTRIBUTE9  => l_dist_ATTRIBUTE9,
1933                            P_LINE_ATTRIBUTE10 => l_dist_ATTRIBUTE10,
1934                            P_LINE_ATTRIBUTE11 => l_dist_ATTRIBUTE11,
1935                            P_LINE_ATTRIBUTE12 => l_dist_ATTRIBUTE12,
1936                            P_LINE_ATTRIBUTE13 => l_dist_ATTRIBUTE13,
1937                            P_LINE_ATTRIBUTE14 => l_dist_ATTRIBUTE14,
1938                            P_LINE_ATTRIBUTE15 => l_dist_ATTRIBUTE15,
1939                            x_return_ccid      => l_DIST_CODE_COMBINATION_ID,
1940                            x_concat_segs      => l_concat_segs,
1941                            x_concat_ids       => l_concat_ids,
1942                            x_concat_descrs    => l_concat_descrs,
1943                            x_error_message    => l_errmsg,
1944                            x_award_set_id     => l_award_id )) THEN
1945 
1946                 fnd_message.set_encoded(l_errmsg);
1947                 app_exception.raise_exception;
1948               END IF;
1949 	      */
1950 /*	      null;
1951             ELSE  -- non expense report
1952 
1953 	      /*
1954               IF ( NOT pa_acc_gen_wf_pkg.ap_inv_generate_account (
1955                            p_project_id  => l_project_id,
1956                            p_task_id     => l_task_id,
1957                            p_expenditure_type  => l_expenditure_type,
1958                            p_vendor_id         => l_VENDOR_ID,
1959                            p_expenditure_organization_id  => l_EXPENDITURE_ORGANIZATION_ID,
1960                            p_expenditure_item_date  => l_EXPENDITURE_ITEM_DATE,
1961                            p_billable_flag        => l_billable_flag,
1962                            p_chart_of_accounts_id =>l_CHART_OF_ACCOUNTS_ID,
1963                            P_ATTRIBUTE_CATEGORY => l_inv_ATTRIBUTE_CATEGORY,
1964                            P_ATTRIBUTE1  => l_inv_ATTRIBUTE1,
1965                            P_ATTRIBUTE2  => l_inv_ATTRIBUTE2,
1966                            P_ATTRIBUTE3  => l_inv_ATTRIBUTE3,
1967                            P_ATTRIBUTE4  => l_inv_ATTRIBUTE4,
1968                            P_ATTRIBUTE5  => l_inv_ATTRIBUTE5,
1969                            P_ATTRIBUTE6  => l_inv_ATTRIBUTE6,
1970                            P_ATTRIBUTE7  => l_inv_ATTRIBUTE7,
1971                            P_ATTRIBUTE8  => l_inv_ATTRIBUTE8,
1972                            P_ATTRIBUTE9  => l_inv_ATTRIBUTE9,
1973                            P_ATTRIBUTE10 => l_inv_ATTRIBUTE10,
1974                            P_ATTRIBUTE11 => l_inv_ATTRIBUTE11,
1975                            P_ATTRIBUTE12 => l_inv_ATTRIBUTE12,
1976                            P_ATTRIBUTE13 => l_inv_ATTRIBUTE13,
1977                            P_ATTRIBUTE14 => l_inv_ATTRIBUTE14,
1978                            P_ATTRIBUTE15 => l_inv_ATTRIBUTE15,
1979                            P_DIST_ATTRIBUTE_CATEGORY => l_dist_ATTRIBUTE_CATEGORY,
1980                            P_DIST_ATTRIBUTE1 => l_dist_ATTRIBUTE1,
1981                            P_DIST_ATTRIBUTE2 => l_dist_ATTRIBUTE2,
1982                            P_DIST_ATTRIBUTE3 => l_dist_ATTRIBUTE3,
1983                            P_DIST_ATTRIBUTE4 => l_dist_ATTRIBUTE4,
1984                            P_DIST_ATTRIBUTE5 => l_dist_ATTRIBUTE5,
1985                            P_DIST_ATTRIBUTE6 => l_dist_ATTRIBUTE6,
1986                            P_DIST_ATTRIBUTE7 => l_dist_ATTRIBUTE7,
1987                            P_DIST_ATTRIBUTE8 => l_dist_ATTRIBUTE8,
1988                            P_DIST_ATTRIBUTE9 => l_dist_ATTRIBUTE9,
1989                            P_DIST_ATTRIBUTE10 => l_dist_ATTRIBUTE10,
1990                            P_DIST_ATTRIBUTE11 => l_dist_ATTRIBUTE11,
1991                            P_DIST_ATTRIBUTE12 => l_dist_ATTRIBUTE12,
1992                            P_DIST_ATTRIBUTE13 => l_dist_ATTRIBUTE13,
1993                            P_DIST_ATTRIBUTE14 => l_dist_ATTRIBUTE14,
1994                            P_DIST_ATTRIBUTE15 => l_dist_ATTRIBUTE15,
1995                            x_return_ccid => l_DIST_CODE_COMBINATION_ID,
1996                            x_concat_segs => l_concat_segs,
1997                            x_concat_ids  => l_concat_ids,
1998                            x_concat_descrs => l_concat_descrs,
1999                            x_error_message    => l_errmsg,
2000                            x_award_set_id  => l_award_id )) THEN
2001 
2002                 FND_MESSAGE.SET_ENCODED(l_errmsg);
2003                 app_exception.raise_exception;
2004 
2005               END IF;
2006 	      */
2007 /*	      null;
2008             END IF; -- end of check l_invoice_type_lookup_code
2009 
2010 
2011 /*-----------------------------------------------------------------+
2012      | update invoice_distributions with l_dist_code_combination_id    |
2013      +-----------------------------------------------------------------*/
2014 
2015  /*           IF (l_dist_posted_flag = 'N') THEN
2016               IF (l_dist_reversal_flag <> 'Y') THEN
2017 
2018                 UPDATE ap_invoice_distributions
2019                     SET dist_code_combination_id   = l_dist_code_combination_id
2020                   WHERE invoice_distribution_id    = l_invoice_distribution_id;
2021 
2022                END IF; -- end of l_dist_reversal_flag
2023              END IF; -- end of l_dist_posted_flag
2024 
2025              l_dist_count := l_dist_count +1;
2026 
2027           END IF; -- end of check l_po_distribution_id/l_accrue_on_receipt_flag
2028         END LOOP; -- end loop of pa_related_dist_cursor
2029         CLOSE pa_related_dist_cur;
2030 
2031         IF (l_dist_count >0) THEN
2032           X_update_occurred := 'Y';
2033         END IF;
2034 
2035         UPDATE AP_INVOICE_DISTRIBUTIONS
2036            SET last_update_login = l_last_update_login
2037          WHERE invoice_id = X_invoice_id
2038            AND last_update_login = -3;
2039 -- CHANGES FOR BUG - 3025688 ** ENDS   **
2040 */
2041       END IF;  -- check l_multi_currency_flag = y and x_update_base=y
2042     END LOOP; -- end of invoice_line_cursor
2043 
2044     debug_info := 'Close cursor invoice_line_cursor';
2045     CLOSE invoice_line_cursor;
2046 
2047     EXCEPTION
2048     WHEN OTHERS THEN
2049       IF (SQLCODE <> -20001) THEN
2050         FND_MESSAGE.SET_NAME('SQLAP','AP_DEBUG');
2051         FND_MESSAGE.SET_TOKEN('ERROR',SQLERRM);
2052         FND_MESSAGE.SET_TOKEN('CALLING_SEQUENCE', current_calling_sequence);
2053         FND_MESSAGE.SET_TOKEN('PARAMETERS',
2054            'X_invoice_id = '             ||X_invoice_id
2055            ||', X_line_number = '        ||X_line_number
2056            ||', X_type_1099 = '          ||X_type_1099
2057            ||', X_income_tax_region = '  ||X_income_tax_region
2058            ||', X_vendor_changed_flag = '||X_vendor_changed_flag
2059            ||', X_update_base = '        ||X_update_base
2060            ||', X_reset_match_status = ' ||X_reset_match_status
2061            ||', X_update_occurred = '    ||X_update_occurred
2062                                        );
2063         FND_MESSAGE.SET_TOKEN('DEBUG_INFO',debug_info);
2064       END IF;
2065       APP_EXCEPTION.RAISE_EXCEPTION;
2066     END Update_Distributions;
2067 
2068 
2069    PROCEDURE Insert_Row(X_Rowid                   IN OUT NOCOPY VARCHAR2,
2070                        X_Invoice_Id                     NUMBER,
2071                        -- Invoice Lines Project Stage 1
2072                        X_Invoice_Line_Number            NUMBER,
2073                        X_Distribution_Class             VARCHAR2,
2074                        X_Invoice_Distribution_Id IN OUT NOCOPY NUMBER,
2075                        X_Dist_Code_Combination_Id       NUMBER,
2076                        X_Last_Update_Date               DATE,
2077                        X_Last_Updated_By                NUMBER,
2078                        X_Accounting_Date                DATE,
2079                        X_Period_Name                    VARCHAR2,
2080                        X_Set_Of_Books_Id                NUMBER,
2081                        X_Amount                         NUMBER,
2082                        X_Description                    VARCHAR2,
2083                        X_Type_1099                      VARCHAR2,
2084                        X_Posted_Flag                    VARCHAR2,
2085                        X_Batch_Id                       NUMBER,
2086                        X_Quantity_Invoiced              NUMBER,
2087                        X_Unit_Price                     NUMBER,
2088                        X_Match_Status_Flag              VARCHAR2,
2089                        X_Attribute_Category             VARCHAR2,
2090                        X_Attribute1                     VARCHAR2,
2091                        X_Attribute2                     VARCHAR2,
2092                        X_Attribute3                     VARCHAR2,
2093                        X_Attribute4                     VARCHAR2,
2094                        X_Attribute5                     VARCHAR2,
2095                        X_Prepay_Amount_Remaining        NUMBER,
2096                        X_Assets_Addition_Flag           VARCHAR2,
2097                        X_Assets_Tracking_Flag           VARCHAR2,
2098                        X_Distribution_Line_Number       NUMBER,
2099                        X_Line_Type_Lookup_Code          VARCHAR2,
2100                        X_Po_Distribution_Id             NUMBER,
2101                        X_Base_Amount                    NUMBER,
2102                        X_Pa_Addition_Flag               VARCHAR2,
2103                        X_Posted_Amount                  NUMBER,
2104                        X_Posted_Base_Amount             NUMBER,
2105                        X_Encumbered_Flag                VARCHAR2,
2106                        X_Accrual_Posted_Flag            VARCHAR2,
2107                        X_Cash_Posted_Flag               VARCHAR2,
2108                        X_Last_Update_Login              NUMBER,
2109                        X_Creation_Date                  DATE,
2110                        X_Created_By                     NUMBER,
2111                        X_Stat_Amount                    NUMBER,
2112                        X_Attribute11                    VARCHAR2,
2113                        X_Attribute12                    VARCHAR2,
2114                        X_Attribute13                    VARCHAR2,
2115                        X_Attribute14                    VARCHAR2,
2116                        X_Attribute6                     VARCHAR2,
2117                        X_Attribute7                     VARCHAR2,
2118                        X_Attribute8                     VARCHAR2,
2119                        X_Attribute9                     VARCHAR2,
2120                        X_Attribute10                    VARCHAR2,
2121                        X_Attribute15                    VARCHAR2,
2122                        X_Accts_Pay_Code_Comb_Id         NUMBER,
2123                        X_Reversal_Flag                  VARCHAR2,
2124                        X_Parent_Invoice_Id              NUMBER,
2125                        X_Income_Tax_Region              VARCHAR2,
2126                        X_Final_Match_Flag               VARCHAR2,
2127                        X_Expenditure_Item_Date          DATE,
2128                        X_Expenditure_Organization_Id    NUMBER,
2129                        X_Expenditure_Type               VARCHAR2,
2130                        X_Pa_Quantity                    NUMBER,
2131                        X_Project_Id                     NUMBER,
2132                        X_Task_Id                        NUMBER,
2133                        X_Quantity_Variance              NUMBER,
2134                        X_Base_Quantity_Variance         NUMBER,
2135                        X_Packet_Id                      NUMBER,
2136                        X_Awt_Flag                       VARCHAR2,
2137                        X_Awt_Group_Id                   NUMBER,
2138 		       X_Pay_Awt_Group_Id               NUMBER,--bug6639866
2139                        X_Awt_Tax_Rate_Id                NUMBER,
2140                        X_Awt_Gross_Amount               NUMBER,
2141                        X_Reference_1                    VARCHAR2,
2142                        X_Reference_2                    VARCHAR2,
2143                        X_Org_Id                         NUMBER,
2144                        X_Other_Invoice_Id               NUMBER,
2145                        X_Awt_Invoice_Id                 NUMBER,
2146                        X_Awt_Origin_Group_Id            NUMBER,
2147                        X_Program_Application_Id         NUMBER,
2148                        X_Program_Id                     NUMBER,
2149                        X_Program_Update_Date            DATE,
2150                        X_Request_Id                     NUMBER,
2151                        X_Tax_Recoverable_Flag           VARCHAR2,
2152                        X_Award_Id                       NUMBER,
2153                        X_Start_Expense_Date             DATE,
2154                        X_Merchant_Document_Number       VARCHAR2,
2155                        X_Merchant_Name                  VARCHAR2,
2156 		       X_Merchant_Reference		VARCHAR2,
2157                        X_Merchant_Tax_Reg_Number        VARCHAR2,
2158                        X_Merchant_Taxpayer_Id           VARCHAR2,
2159                        X_Country_Of_Supply              VARCHAR2,
2160                        X_Parent_Reversal_id    NUMBER,
2161                        X_rcv_transaction_id    NUMBER,
2162                        X_matched_uom_lookup_code  VARCHAR2,
2163                        X_global_attribute_category      VARCHAR2 DEFAULT NULL,
2164                        X_global_attribute1              VARCHAR2 DEFAULT NULL,
2165                        X_global_attribute2              VARCHAR2 DEFAULT NULL,
2166                        X_global_attribute3              VARCHAR2 DEFAULT NULL,
2167                        X_global_attribute4              VARCHAR2 DEFAULT NULL,
2168                        X_global_attribute5              VARCHAR2 DEFAULT NULL,
2169                        X_global_attribute6              VARCHAR2 DEFAULT NULL,
2170                        X_global_attribute7              VARCHAR2 DEFAULT NULL,
2171                        X_global_attribute8              VARCHAR2 DEFAULT NULL,
2172                        X_global_attribute9              VARCHAR2 DEFAULT NULL,
2173                        X_global_attribute10             VARCHAR2 DEFAULT NULL,
2174                        X_global_attribute11             VARCHAR2 DEFAULT NULL,
2175                        X_global_attribute12             VARCHAR2 DEFAULT NULL,
2176                        X_global_attribute13             VARCHAR2 DEFAULT NULL,
2177                        X_global_attribute14             VARCHAR2 DEFAULT NULL,
2178                        X_global_attribute15             VARCHAR2 DEFAULT NULL,
2179                        X_global_attribute16             VARCHAR2 DEFAULT NULL,
2180                        X_global_attribute17             VARCHAR2 DEFAULT NULL,
2181                        X_global_attribute18             VARCHAR2 DEFAULT NULL,
2182                        X_global_attribute19             VARCHAR2 DEFAULT NULL,
2183                        X_global_attribute20             VARCHAR2 DEFAULT NULL,
2184                        -- Invoice Lines Project Stage 1
2185                        X_rounding_amt                   NUMBER DEFAULT NULL,
2186                        X_charge_applicable_to_dist_id   NUMBER DEFAULT NULL,
2187                        X_corrected_invoice_dist_id      NUMBER DEFAULT NULL,
2188                        X_related_id                     NUMBER DEFAULT NULL,
2189                        X_asset_book_type_code           VARCHAR2 DEFAULT NULL,
2190                        X_asset_category_id              NUMBER DEFAULT NULL ,
2191 		       X_Intended_Use			VARCHAR2 DEFAULT NULL,
2192 		       x_calling_sequence               VARCHAR2
2193    ) IS
2194     current_calling_sequence VARCHAR2(2000);
2195     debug_info               VARCHAR2(100);
2196 
2197    BEGIN
2198       -- Update the calling sequence
2199        --
2200        current_calling_sequence :=
2201        'AP_INVOICE_DISTRIBUTIONS_PKG.Insert_Row<-'||X_Calling_Sequence;
2202 
2203        debug_info := 'Calling invoice distribution handler';
2204 
2205        AP_AID_TABLE_HANDLER_PKG.Insert_Row
2206              (X_Rowid,
2207               X_Invoice_Id,
2208               -- Invoice Lines Project Stage 1
2209               X_Invoice_Line_Number,
2210               X_Distribution_Class,
2211               X_Invoice_Distribution_Id,
2212               X_Dist_Code_Combination_Id,
2213               X_Last_Update_Date,
2214               X_Last_Updated_By,
2215               X_Accounting_Date,
2216               X_Period_Name,
2217               X_Set_Of_Books_Id,
2218               X_Amount,
2219               X_Description,
2220               X_Type_1099,
2221               X_Posted_Flag,
2222               X_Batch_Id,
2223               X_Quantity_Invoiced,
2224               X_Unit_Price,
2225               X_Match_Status_Flag,
2226               X_Attribute_Category,
2227               X_Attribute1,
2228               X_Attribute2,
2229               X_Attribute3,
2230               X_Attribute4,
2231               X_Attribute5,
2232               X_Prepay_Amount_Remaining,
2233               X_Assets_Addition_Flag,
2234               X_Assets_Tracking_Flag,
2235               X_Distribution_Line_Number,
2236               X_Line_Type_Lookup_Code,
2237               X_Po_Distribution_Id,
2238               X_Base_Amount,
2239               X_Pa_Addition_Flag,
2240               X_Posted_Amount,
2241               X_Posted_Base_Amount,
2242               X_Encumbered_Flag,
2243               X_Accrual_Posted_Flag,
2244               X_Cash_Posted_Flag,
2245               X_Last_Update_Login,
2246               X_Creation_Date,
2247               X_Created_By,
2248               X_Stat_Amount,
2249               X_Attribute11,
2250               X_Attribute12,
2251               X_Attribute13,
2252               X_Attribute14,
2253               X_Attribute6,
2254               X_Attribute7,
2255               X_Attribute8,
2256               X_Attribute9,
2257               X_Attribute10,
2258               X_Attribute15,
2259               X_Accts_Pay_Code_Comb_Id,
2260               X_Reversal_Flag,
2261               X_Parent_Invoice_Id,
2262               X_Income_Tax_Region,
2263               X_Final_Match_Flag,
2264               X_Expenditure_Item_Date,
2265               X_Expenditure_Organization_Id,
2266               X_Expenditure_Type,
2267               X_Pa_Quantity,
2268               X_Project_Id,
2269               X_Task_Id,
2270               X_Quantity_Variance,
2271               X_Base_Quantity_Variance,
2272               X_Packet_Id,
2273               X_Awt_Flag,
2274               X_Awt_Group_Id,
2275 	      X_Pay_Awt_Group_Id,--bug6639866
2276               X_Awt_Tax_Rate_Id,
2277               X_Awt_Gross_Amount,
2278               X_Reference_1,
2279               X_Reference_2,
2280               X_Org_Id,
2281               X_Other_Invoice_Id,
2282               X_Awt_Invoice_Id,
2283               X_Awt_Origin_Group_Id,
2284               X_Program_Application_Id,
2285               X_Program_Id,
2286               X_Program_Update_Date,
2287               X_Request_Id,
2288               X_Tax_Recoverable_Flag,
2289               X_Award_Id,
2290               X_Start_Expense_Date,
2291               X_Merchant_Document_Number,
2292               X_Merchant_Name,
2293               X_Merchant_Tax_Reg_Number,
2294               X_Merchant_Taxpayer_Id,
2295               X_Country_Of_Supply,
2296               X_Merchant_Reference,
2297               X_Parent_Reversal_Id,
2298               X_rcv_transaction_id,
2299               X_matched_uom_lookup_code,
2300               X_global_attribute_category,
2301               X_global_attribute1,
2302               X_global_attribute2,
2303               X_global_attribute3,
2304               X_global_attribute4,
2305               X_global_attribute5,
2306               X_global_attribute6,
2307               X_global_attribute7,
2308               X_global_attribute8,
2309               X_global_attribute9,
2310               X_global_attribute10,
2311               X_global_attribute11,
2312               X_global_attribute12,
2313               X_global_attribute13,
2314               X_global_attribute14,
2315               X_global_attribute15,
2316               X_global_attribute16,
2317               X_global_attribute17,
2318               X_global_attribute18,
2319               X_global_attribute19,
2320               X_global_attribute20,
2321               current_calling_sequence,
2322            -- Added by iyas cuz params don't exist in ap_aid_table_handlers_pkg
2323               NULL,
2324               NULL,
2325               NULL,
2326               NULL,
2327               NULL,
2328               NULL,
2329               NULL,
2330               NULL,
2331               NULL,
2332               NULL,
2333               NULL,
2334               NULL,
2335               NULL,
2336               NULL,
2337            -- Invoice Lines Project Stage 1
2338               X_rounding_amt,
2339               X_charge_applicable_to_dist_id,
2340               X_corrected_invoice_dist_id,
2341               X_related_id,
2342               X_asset_book_type_code,
2343               X_asset_category_id,
2344 	      X_Intended_Use
2345              );
2346 
2347 
2348   EXCEPTION
2349     WHEN OTHERS THEN
2350       if (SQLCODE <> -20001) then
2351         FND_MESSAGE.SET_NAME('SQLAP', 'AP_DEBUG');
2352         FND_MESSAGE.SET_TOKEN('ERROR', SQLERRM);
2353         FND_MESSAGE.SET_TOKEN('CALLING_SEQUENCE', current_calling_sequence);
2354         FND_MESSAGE.SET_TOKEN('DEBUG_INFO', debug_info);
2355       end if;
2356       APP_EXCEPTION.RAISE_EXCEPTION;
2357 
2358   END Insert_Row;
2359 
2360 
2361   PROCEDURE Lock_Row(X_Rowid                            VARCHAR2,
2362                      X_Invoice_Id                       NUMBER,
2363                      -- Invoice Lines Project Stage 1
2364                      X_Invoice_Line_Number              NUMBER,
2365                      X_Distribution_Class               VARCHAR2,
2366                      X_Invoice_Distribution_Id          NUMBER,
2367                      X_Dist_Code_Combination_Id         NUMBER,
2368                      X_Accounting_Date                  DATE,
2369                      X_Period_Name                      VARCHAR2,
2370                      X_Set_Of_Books_Id                  NUMBER,
2371                      X_Amount                           NUMBER,
2372                      X_Description                      VARCHAR2,
2373                      X_Type_1099                        VARCHAR2,
2374                      X_Posted_Flag                      VARCHAR2,
2375                      X_Batch_Id                         NUMBER,
2376                      X_Quantity_Invoiced                NUMBER,
2377                      X_Unit_Price                       NUMBER,
2378                      X_Match_Status_Flag                VARCHAR2,
2379                      X_Attribute_Category               VARCHAR2,
2380                      X_Attribute1                       VARCHAR2,
2381                      X_Attribute2                       VARCHAR2,
2382                      X_Attribute3                       VARCHAR2,
2383                      X_Attribute4                       VARCHAR2,
2384                      X_Attribute5                       VARCHAR2,
2385                      X_Prepay_Amount_Remaining          NUMBER,
2386                      X_Assets_Addition_Flag             VARCHAR2,
2387                      X_Assets_Tracking_Flag             VARCHAR2,
2388                      X_Distribution_Line_Number         NUMBER,
2389                      X_Line_Type_Lookup_Code            VARCHAR2,
2390                      X_Po_Distribution_Id               NUMBER,
2391                      X_Base_Amount                      NUMBER,
2392                      X_Pa_Addition_Flag                 VARCHAR2,
2393                      X_Posted_Amount                    NUMBER,
2394                      X_Posted_Base_Amount               NUMBER,
2395                      X_Encumbered_Flag                  VARCHAR2,
2396                      X_Accrual_Posted_Flag              VARCHAR2,
2397                      X_Cash_Posted_Flag                 VARCHAR2,
2398                      X_Stat_Amount                      NUMBER,
2399                      X_Attribute11                      VARCHAR2,
2400                      X_Attribute12                      VARCHAR2,
2401                      X_Attribute13                      VARCHAR2,
2402                      X_Attribute14                      VARCHAR2,
2403                      X_Attribute6                       VARCHAR2,
2404                      X_Attribute7                       VARCHAR2,
2405                      X_Attribute8                       VARCHAR2,
2406                      X_Attribute9                       VARCHAR2,
2407                      X_Attribute10                      VARCHAR2,
2408                      X_Attribute15                      VARCHAR2,
2409                      X_Accts_Pay_Code_Comb_Id    NUMBER,
2410                      X_Reversal_Flag                    VARCHAR2,
2411                      X_Parent_Invoice_Id                NUMBER,
2412                      X_Income_Tax_Region                VARCHAR2,
2413                      X_Final_Match_Flag                 VARCHAR2,
2414                      X_Expenditure_Item_Date            DATE,
2415                      X_Expenditure_Organization_Id      NUMBER,
2416                      X_Expenditure_Type                 VARCHAR2,
2417                      X_Pa_Quantity                      NUMBER,
2418                      X_Project_Id                       NUMBER,
2419                      X_Task_Id                          NUMBER,
2420                      X_Quantity_Variance                NUMBER,
2421                      X_Base_Quantity_Variance           NUMBER,
2422                      X_Packet_Id                        NUMBER,
2423                      X_Awt_Flag                         VARCHAR2,
2424                      X_Awt_Group_Id                     NUMBER,
2425 		     X_Pay_Awt_Group_Id                 NUMBER,--bug6639866
2426                      X_Awt_Tax_Rate_Id                  NUMBER,
2427                      X_Awt_Gross_Amount                 NUMBER,
2428                      X_Reference_1                      VARCHAR2,
2429                      X_Reference_2                      VARCHAR2,
2430                      X_Org_Id                           NUMBER,
2431                      X_Other_Invoice_Id                 NUMBER,
2432                      X_Awt_Invoice_Id                   NUMBER,
2433                      X_Awt_Origin_Group_Id              NUMBER,
2434                      X_Program_Application_Id           NUMBER,
2435                      X_Program_Id                       NUMBER,
2436                      X_Program_Update_Date              DATE,
2437                      X_Request_Id                       NUMBER,
2438                      X_Tax_Recoverable_Flag             VARCHAR2,
2439                      X_Award_Id                         NUMBER,
2440                      X_Start_Expense_Date               DATE,
2441                      X_Merchant_Document_Number         VARCHAR2,
2442                      X_Merchant_Name                    VARCHAR2,
2443 		     X_Merchant_Reference               VARCHAR2,
2444                      X_Merchant_Tax_Reg_Number          VARCHAR2,
2445                      X_Merchant_Taxpayer_Id             VARCHAR2,
2446                      X_Country_Of_Supply                VARCHAR2,
2447                      X_global_attribute_category        VARCHAR2 DEFAULT NULL,
2448                      X_global_attribute1                VARCHAR2 DEFAULT NULL,
2449                      X_global_attribute2                VARCHAR2 DEFAULT NULL,
2450                      X_global_attribute3                VARCHAR2 DEFAULT NULL,
2451                      X_global_attribute4                VARCHAR2 DEFAULT NULL,
2452                      X_global_attribute5                VARCHAR2 DEFAULT NULL,
2453                      X_global_attribute6                VARCHAR2 DEFAULT NULL,
2454                      X_global_attribute7                VARCHAR2 DEFAULT NULL,
2455                      X_global_attribute8                VARCHAR2 DEFAULT NULL,
2456                      X_global_attribute9                VARCHAR2 DEFAULT NULL,
2457                      X_global_attribute10               VARCHAR2 DEFAULT NULL,
2458                      X_global_attribute11               VARCHAR2 DEFAULT NULL,
2459                      X_global_attribute12               VARCHAR2 DEFAULT NULL,
2460                      X_global_attribute13               VARCHAR2 DEFAULT NULL,
2461                      X_global_attribute14               VARCHAR2 DEFAULT NULL,
2462                      X_global_attribute15               VARCHAR2 DEFAULT NULL,
2463                      X_global_attribute16               VARCHAR2 DEFAULT NULL,
2464                      X_global_attribute17               VARCHAR2 DEFAULT NULL,
2465                      X_global_attribute18               VARCHAR2 DEFAULT NULL,
2466                      X_global_attribute19               VARCHAR2 DEFAULT NULL,
2467                      X_global_attribute20               VARCHAR2 DEFAULT NULL,
2468                      -- Invoice Lines Project Stage 1
2469                      X_rounding_amt                   NUMBER DEFAULT NULL,
2470                      X_charge_applicable_to_dist_id   NUMBER DEFAULT NULL,
2471                      X_corrected_invoice_dist_id      NUMBER DEFAULT NULL,
2472                      X_related_id                     NUMBER DEFAULT NULL,
2473                      X_asset_book_type_code           VARCHAR2 DEFAULT NULL,
2474                      X_asset_category_id              NUMBER DEFAULT NULL,
2475 		     --ETAX: Invoice Workbench
2476  		     X_Intended_Use		      VARCHAR2 DEFAULT NULL,
2477 		     X_Calling_Sequence		      VARCHAR2
2478   ) IS
2479     current_calling_sequence VARCHAR2(2000);
2480     debug_info               VARCHAR2(100);
2481 
2482       CURSOR C IS
2483         SELECT
2484           PREPAY_DISTRIBUTION_ID,
2485           ACCOUNTING_EVENT_ID, -- Bug 9385883
2486           ACCOUNTING_DATE,
2487           ACCRUAL_POSTED_FLAG,
2488           ASSETS_ADDITION_FLAG,
2489           ASSETS_TRACKING_FLAG,
2490           CASH_POSTED_FLAG,
2491           DISTRIBUTION_LINE_NUMBER,
2492           DIST_CODE_COMBINATION_ID,
2493           INVOICE_ID,
2494           LAST_UPDATED_BY,
2495           LAST_UPDATE_DATE,
2496           LINE_TYPE_LOOKUP_CODE,
2497           PERIOD_NAME,
2498           SET_OF_BOOKS_ID,
2499           ACCTS_PAY_CODE_COMBINATION_ID,
2500           AMOUNT,
2501           BASE_AMOUNT,
2502           BATCH_ID,
2503           CREATED_BY,
2504           CREATION_DATE,
2505           DESCRIPTION,
2506           FINAL_MATCH_FLAG,
2507           INCOME_TAX_REGION,
2508           LAST_UPDATE_LOGIN,
2509           MATCH_STATUS_FLAG,
2510           POSTED_FLAG,
2511           PO_DISTRIBUTION_ID,
2512           PROGRAM_APPLICATION_ID,
2513           PROGRAM_ID,
2514           PROGRAM_UPDATE_DATE,
2515           QUANTITY_INVOICED,
2516           REQUEST_ID,
2517           REVERSAL_FLAG,
2518           TYPE_1099,
2519           UNIT_PRICE,
2520           --AMOUNT_ENCUMBERED,
2521           --BASE_AMOUNT_ENCUMBERED,
2522           ENCUMBERED_FLAG,
2523           --PRICE_ADJUSTMENT_FLAG,
2524           --QUANTITY_UNENCUMBERED,
2525           STAT_AMOUNT,
2526           --AMOUNT_TO_POST,
2527           ATTRIBUTE1,
2528           ATTRIBUTE10,
2529           ATTRIBUTE11,
2530           ATTRIBUTE12,
2531           ATTRIBUTE13,
2532           ATTRIBUTE14,
2533           ATTRIBUTE15,
2534           ATTRIBUTE2,
2535           ATTRIBUTE3,
2536           ATTRIBUTE4,
2537           ATTRIBUTE5,
2538           ATTRIBUTE6,
2539           ATTRIBUTE7,
2540           ATTRIBUTE8,
2541           ATTRIBUTE9,
2542           ATTRIBUTE_CATEGORY,
2543           --BASE_AMOUNT_TO_POST,
2544           EXPENDITURE_ITEM_DATE,
2545           EXPENDITURE_ORGANIZATION_ID,
2546           EXPENDITURE_TYPE,
2547           PARENT_INVOICE_ID,
2548           PA_ADDITION_FLAG,
2549           PA_QUANTITY,
2550           POSTED_AMOUNT,
2551           POSTED_BASE_AMOUNT,
2552           PREPAY_AMOUNT_REMAINING,
2553           PROJECT_ID,
2554           TASK_ID,
2555           --EARLIEST_SETTLEMENT_DATE,
2556           --REQ_DISTRIBUTION_ID,
2557           QUANTITY_VARIANCE,
2558           BASE_QUANTITY_VARIANCE,
2559           PACKET_ID,
2560           AWT_FLAG,
2561           AWT_GROUP_ID,
2562 	  PAY_AWT_GROUP_ID,--bug6639866
2563           AWT_TAX_RATE_ID,
2564           AWT_GROSS_AMOUNT,
2565           AWT_INVOICE_ID,
2566           AWT_ORIGIN_GROUP_ID,
2567           REFERENCE_1,
2568           REFERENCE_2,
2569           ORG_ID,
2570           OTHER_INVOICE_ID,
2571           --AWT_INVOICE_PAYMENT_ID,
2572           GLOBAL_ATTRIBUTE_CATEGORY,
2573           GLOBAL_ATTRIBUTE1,
2574           GLOBAL_ATTRIBUTE2,
2575           GLOBAL_ATTRIBUTE3,
2576           GLOBAL_ATTRIBUTE4,
2577           GLOBAL_ATTRIBUTE5,
2578           GLOBAL_ATTRIBUTE6,
2579           GLOBAL_ATTRIBUTE7,
2580           GLOBAL_ATTRIBUTE8,
2581           GLOBAL_ATTRIBUTE9,
2582           GLOBAL_ATTRIBUTE10,
2583           GLOBAL_ATTRIBUTE11,
2584           GLOBAL_ATTRIBUTE12,
2585           GLOBAL_ATTRIBUTE13,
2586           GLOBAL_ATTRIBUTE14,
2587           GLOBAL_ATTRIBUTE15,
2588           GLOBAL_ATTRIBUTE16,
2589           GLOBAL_ATTRIBUTE17,
2590           GLOBAL_ATTRIBUTE18,
2591           GLOBAL_ATTRIBUTE19,
2592           GLOBAL_ATTRIBUTE20,
2593           --LINE_GROUP_NUMBER,
2594           --RECEIPT_VERIFIED_FLAG,
2595           --RECEIPT_REQUIRED_FLAG,
2596           --RECEIPT_MISSING_FLAG,
2597           --JUSTIFICATION,
2598           --EXPENSE_GROUP,
2599           START_EXPENSE_DATE,
2600           --END_EXPENSE_DATE,
2601           --RECEIPT_CURRENCY_CODE,
2602           --RECEIPT_CONVERSION_RATE,
2603           --RECEIPT_CURRENCY_AMOUNT,
2604           --DAILY_AMOUNT,
2605           --WEB_PARAMETER_ID,
2606           --ADJUSTMENT_REASON,
2607           AWARD_ID,
2608           --MRC_DIST_CODE_COMBINATION_ID,
2609           --MRC_BASE_AMOUNT,
2610           --MRC_BASE_INV_PRICE_VARIANCE,
2611           --MRC_EXCHANGE_RATE_VARIANCE,
2612           --MRC_RATE_VAR_CCID,
2613           --MRC_EXCHANGE_DATE,
2614           --MRC_EXCHANGE_RATE,
2615           --MRC_EXCHANGE_RATE_TYPE,
2616           --MRC_RECEIPT_CONVERSION_RATE,
2617           DIST_MATCH_TYPE,
2618           RCV_TRANSACTION_ID,
2619           -- Invoice Lines Project Stage 1
2620           INVOICE_LINE_NUMBER,
2621           DISTRIBUTION_CLASS,
2622           INVOICE_DISTRIBUTION_ID,
2623           PARENT_REVERSAL_ID,
2624           TAX_RECOVERABLE_FLAG,
2625           --PA_CC_AR_INVOICE_ID,
2626           --PA_CC_AR_INVOICE_LINE_NUM,
2627           --PA_CC_PROCESSED_CODE,
2628           MERCHANT_DOCUMENT_NUMBER,
2629           MERCHANT_NAME,
2630           MERCHANT_REFERENCE,
2631           MERCHANT_TAX_REG_NUMBER,
2632           MERCHANT_TAXPAYER_ID,
2633           COUNTRY_OF_SUPPLY,
2634           MATCHED_UOM_LOOKUP_CODE,
2635           GMS_BURDENABLE_RAW_COST,
2636           --CREDIT_CARD_TRX_ID,
2637           --UPGRADE_POSTED_AMT,
2638           --UPGRADE_BASE_POSTED_AMT,
2639           -- Invoice Lines Project Stage 1
2640           ROUNDING_AMT,
2641           CHARGE_APPLICABLE_TO_DIST_ID,
2642           CORRECTED_INVOICE_DIST_ID,
2643           RELATED_ID,
2644           ASSET_BOOK_TYPE_CODE,
2645           ASSET_CATEGORY_ID,
2646 	  INTENDED_USE
2647         FROM   AP_INVOICE_DISTRIBUTIONS
2648         WHERE  rowid = X_Rowid
2649         FOR UPDATE of Invoice_Id NOWAIT;
2650         Recinfo C%ROWTYPE;
2651 
2652 --Bug 9385883
2653     CURSOR D(l_event_id NUMBER) IS
2654     SELECT 'Locked'
2655       FROM xla_events xe
2656      WHERE xe.event_id      = l_event_id
2657        AND xe.application_id= 200
2658        FOR UPDATE OF event_id NOWAIT;
2659 
2660     Rec_xla_events_Info D%ROWTYPE;
2661 
2662 BEGIN
2663 
2664     -- Update the calling sequence
2665     --
2666     current_calling_sequence :=
2667     'AP_INVOICE_DISTRIBUTIONS_PKG.Lock_Row<-'||X_Calling_Sequence;
2668 
2669     debug_info := 'Select from ap_invoice_distributions';
2670 
2671     OPEN C;
2672 
2673     debug_info := 'Fetch cursor C';
2674     FETCH C INTO Recinfo;
2675     if (C%NOTFOUND) then
2676       debug_info := 'Close cursor C - ROW NOTFOUND';
2677       CLOSE C;
2678       FND_MESSAGE.Set_Name('FND', 'FORM_RECORD_DELETED');
2679       APP_EXCEPTION.Raise_Exception;
2680     end if;
2681     debug_info := 'Close cursor C';
2682     CLOSE C;
2683 
2684 --Bug 9385883
2685      IF (Recinfo.accounting_event_id IS NOT NULL) THEN
2686         debug_info := 'Select from xla_events';
2687         OPEN D(Recinfo.accounting_event_id);
2688         debug_info := 'Fetch curson D';
2689         FETCH D INTO Rec_xla_events_Info;
2690 
2691         IF (D%NOTFOUND) THEN
2692           debug_info := 'Close cursor D - ROW NOTFOUND';
2693           CLOSE D;
2694           FND_MESSAGE.Set_Name('FND', 'FORM_RECORD_DELETED');
2695           APP_EXCEPTION.Raise_Exception;
2696         END IF;
2697 
2698         debug_info := 'Close cursor D';
2699         CLOSE D;
2700     END IF;
2701 
2702     if (
2703                (Recinfo.invoice_id =  X_Invoice_Id)
2704            AND (Recinfo.dist_code_combination_id =  X_Dist_Code_Combination_Id)
2705            -- Invoice Lines Project Stage 1
2706            AND (Recinfo.invoice_line_number = X_Invoice_Line_Number)
2707            AND (   (Recinfo.distribution_class  = X_Distribution_Class)
2708 	   --Bug9336977
2709 		OR (	(Recinfo.distribution_class IS NULL)
2710 		    AND (X_Distribution_Class IS NULL)))
2711            AND (Recinfo.invoice_distribution_id = X_Invoice_Distribution_Id)
2712            AND (Recinfo.accounting_date =  X_Accounting_Date)
2713            AND (Recinfo.period_name =  X_Period_Name)
2714            AND (Recinfo.set_of_books_id =  X_Set_Of_Books_Id)
2715            AND (   (Recinfo.amount =  X_Amount)
2716                 OR (    (Recinfo.amount IS NULL)
2717                     AND (X_Amount IS NULL)))
2718            AND (   (Recinfo.description =  X_Description)
2719                 OR (    (Recinfo.description IS NULL)
2720                     AND (X_Description IS NULL)))
2721            AND (   (Recinfo.type_1099 =  X_Type_1099)
2722                 OR (    (Recinfo.type_1099 IS NULL)
2723                     AND (X_Type_1099 IS NULL)))
2724            AND (   (Recinfo.posted_flag =  X_Posted_Flag)
2725                 OR (    (Recinfo.posted_flag IS NULL)
2726                     AND (X_Posted_Flag IS NULL)))
2727            AND (   (Recinfo.batch_id =  X_Batch_Id)
2728                 OR (    (Recinfo.batch_id IS NULL)
2729                     AND (X_Batch_Id IS NULL)))
2730            AND (   (Recinfo.quantity_invoiced =  X_Quantity_Invoiced)
2731                 OR (    (Recinfo.quantity_invoiced IS NULL)
2732                     AND (X_Quantity_Invoiced IS NULL)))
2733            AND (   (Recinfo.unit_price =  X_Unit_Price)
2734                 OR (    (Recinfo.unit_price IS NULL)
2735                     AND (X_Unit_Price IS NULL)))
2736            AND (   (Recinfo.match_status_flag =  X_Match_Status_Flag)
2737                 OR (    (Recinfo.match_status_flag IS NULL)
2738                     AND (X_Match_Status_Flag IS NULL)))
2739            AND (   (Recinfo.attribute_category =  X_Attribute_Category)
2740                 OR (    (Recinfo.attribute_category IS NULL)
2741                     AND (X_Attribute_Category IS NULL)))
2742            AND (   (Recinfo.attribute1 =  X_Attribute1)
2743                 OR (    (Recinfo.attribute1 IS NULL)
2744                     AND (X_Attribute1 IS NULL)))
2745            AND (   (Recinfo.attribute2 =  X_Attribute2)
2746                 OR (    (Recinfo.attribute2 IS NULL)
2747                     AND (X_Attribute2 IS NULL)))
2748            AND (   (Recinfo.attribute3 =  X_Attribute3)
2749                 OR (    (Recinfo.attribute3 IS NULL)
2750                     AND (X_Attribute3 IS NULL)))
2751            AND (   (Recinfo.attribute4 =  X_Attribute4)
2752                 OR (    (Recinfo.attribute4 IS NULL)
2753                     AND (X_Attribute4 IS NULL)))
2754            AND (   (Recinfo.attribute5 =  X_Attribute5)
2755                 OR (    (Recinfo.attribute5 IS NULL)
2756                     AND (X_Attribute5 IS NULL)))
2757            AND (Recinfo.assets_addition_flag =  X_Assets_Addition_Flag)
2758            AND (Recinfo.assets_tracking_flag =  X_Assets_Tracking_Flag)
2759            AND (Recinfo.distribution_line_number =  X_Distribution_Line_Number)
2760            AND (Recinfo.line_type_lookup_code =  X_Line_Type_Lookup_Code)
2761            AND (   (Recinfo.po_distribution_id =  X_Po_Distribution_Id)
2762                 OR (    (Recinfo.po_distribution_id IS NULL)
2763                     AND (X_Po_Distribution_Id IS NULL)))
2764            AND (   (Recinfo.base_amount =  X_Base_Amount)
2765                 OR (    (Recinfo.base_amount IS NULL)
2766                     AND (X_Base_Amount IS NULL)))
2767            AND (   (Recinfo.pa_addition_flag =  X_Pa_Addition_Flag)
2768                 OR (    (Recinfo.pa_addition_flag IS NULL)
2769                     AND (X_Pa_Addition_Flag IS NULL)))
2770            AND (   (Recinfo.posted_amount =  X_Posted_Amount)
2771                 OR (    (Recinfo.posted_amount IS NULL)
2772                     AND (X_Posted_Amount IS NULL)))
2773            AND (   (Recinfo.posted_base_amount =  X_Posted_Base_Amount)
2774                 OR (    (Recinfo.posted_base_amount IS NULL)
2775                     AND (X_Posted_Base_Amount IS NULL)))
2776            AND (   (Recinfo.encumbered_flag =  X_Encumbered_Flag)
2777                 OR (    (Recinfo.encumbered_flag IS NULL)
2778                     AND (X_Encumbered_Flag IS NULL)))
2779             AND (   (Recinfo.accrual_posted_flag =  X_Accrual_Posted_Flag)
2780                 OR ( (Recinfo.accrual_posted_flag IS NULL) AND (X_Accrual_Posted_Flag IS NULL))) --bug 16227625
2781            AND (   (Recinfo.cash_posted_flag =  X_Cash_Posted_Flag)
2782                 OR ( (Recinfo.cash_posted_flag IS NULL) AND (X_Cash_Posted_Flag IS NULL))) --bug 16227625
2783            AND (   (Recinfo.stat_amount =  X_Stat_Amount)
2784                 OR (    (Recinfo.stat_amount IS NULL)
2785                     AND (X_Stat_Amount IS NULL)))
2786            AND (   (Recinfo.attribute11 =  X_Attribute11)
2787                 OR (    (Recinfo.attribute11 IS NULL)
2788                     AND (X_Attribute11 IS NULL)))
2789            AND (   (Recinfo.attribute12 =  X_Attribute12)
2790                 OR (    (Recinfo.attribute12 IS NULL)
2791                     AND (X_Attribute12 IS NULL)))
2792            AND (   (Recinfo.attribute13 =  X_Attribute13)
2793                 OR (    (Recinfo.attribute13 IS NULL)
2794                     AND (X_Attribute13 IS NULL)))) then
2795       null;
2796     else
2797       FND_MESSAGE.Set_Name('FND', 'FORM_RECORD_CHANGED');
2798       APP_EXCEPTION.Raise_Exception;
2799     end if;
2800 
2801     if (
2802                (   (Recinfo.attribute14 =  X_Attribute14)
2803                 OR (    (Recinfo.attribute14 IS NULL)
2804                     AND (X_Attribute14 IS NULL)))
2805            AND (   (Recinfo.attribute6 =  X_Attribute6)
2806                 OR (    (Recinfo.attribute6 IS NULL)
2807                     AND (X_Attribute6 IS NULL)))
2808            AND (   (Recinfo.attribute7 =  X_Attribute7)
2809                 OR (    (Recinfo.attribute7 IS NULL)
2810                     AND (X_Attribute7 IS NULL)))
2811            AND (   (Recinfo.attribute8 =  X_Attribute8)
2812                 OR (    (Recinfo.attribute8 IS NULL)
2813                     AND (X_Attribute8 IS NULL)))
2814            AND (   (Recinfo.attribute9 =  X_Attribute9)
2815                 OR (    (Recinfo.attribute9 IS NULL)
2816                     AND (X_Attribute9 IS NULL)))
2817            AND (   (Recinfo.attribute10 =  X_Attribute10)
2818                 OR (    (Recinfo.attribute10 IS NULL)
2819                     AND (X_Attribute10 IS NULL)))
2820            AND (   (Recinfo.attribute15 =  X_Attribute15)
2821                 OR (    (Recinfo.attribute15 IS NULL)
2822                     AND (X_Attribute15 IS NULL)))
2823            AND (   (Recinfo.accts_pay_code_combination_id =  X_Accts_Pay_Code_Comb_Id)
2824                 OR (    (Recinfo.accts_pay_code_combination_id IS NULL)
2825                     AND (X_Accts_Pay_Code_Comb_Id IS NULL)))
2826            AND (   (Recinfo.reversal_flag =  X_Reversal_Flag)
2827                 OR (    (Recinfo.reversal_flag IS NULL)
2828                     AND (X_Reversal_Flag IS NULL)))
2829            AND (   (Recinfo.parent_invoice_id =  X_Parent_Invoice_Id)
2830                 OR (    (Recinfo.parent_invoice_id IS NULL)
2831                     AND (X_Parent_Invoice_Id IS NULL)))
2832            AND (   (Recinfo.income_tax_region =  X_Income_Tax_Region)
2833                 OR (    (Recinfo.income_tax_region IS NULL)
2834                     AND (X_Income_Tax_Region IS NULL)))
2835            AND (   (Recinfo.final_match_flag =  X_Final_Match_Flag)
2836                 OR (    (Recinfo.final_match_flag IS NULL)
2837                     AND (X_Final_Match_Flag IS NULL)))
2838            AND (   (Recinfo.expenditure_item_date =  X_Expenditure_Item_Date)
2839                 OR (    (Recinfo.expenditure_item_date IS NULL)
2840                     AND (X_Expenditure_Item_Date IS NULL)))
2841            AND (   (Recinfo.expenditure_organization_id =  X_Expenditure_Organization_Id)
2842                 OR (    (Recinfo.expenditure_organization_id IS NULL)
2843                     AND (X_Expenditure_Organization_Id IS NULL)))
2844            AND (   (Recinfo.expenditure_type =  X_Expenditure_Type)
2845                 OR (    (Recinfo.expenditure_type IS NULL)
2846                     AND (X_Expenditure_Type IS NULL)))
2847            AND (   (Recinfo.pa_quantity =  X_Pa_Quantity)
2848                 OR (    (Recinfo.pa_quantity IS NULL)
2849                     AND (X_Pa_Quantity IS NULL)))
2850            AND (   (Recinfo.project_id =  X_Project_Id)
2851                 OR (    (Recinfo.project_id IS NULL)
2852                     AND (X_Project_Id IS NULL)))
2853            AND (   (Recinfo.task_id =  X_Task_Id)
2854                 OR (    (Recinfo.task_id IS NULL)
2855                     AND (X_Task_Id IS NULL)))
2856            AND (   (Recinfo.quantity_variance =  X_Quantity_Variance)
2857                 OR (    (Recinfo.quantity_variance IS NULL)
2858                     AND (X_Quantity_Variance IS NULL)))
2859            AND (   (Recinfo.base_quantity_variance =  X_Base_Quantity_Variance)
2860                 OR (    (Recinfo.base_quantity_variance IS NULL)
2861                     AND (X_Base_Quantity_Variance IS NULL)))
2862            AND (   (Recinfo.packet_id =  X_Packet_Id)
2863                 OR (    (Recinfo.packet_id IS NULL)
2864                     AND (X_Packet_Id IS NULL)))
2865            AND (   (Recinfo.awt_flag =  X_Awt_Flag)
2866                 OR (    (Recinfo.awt_flag IS NULL)
2867                     AND (X_Awt_Flag IS NULL)))
2868            AND (   (Recinfo.awt_group_id =  X_Awt_Group_Id)
2869                 OR (    (Recinfo.awt_group_id IS NULL)
2870                     AND (X_Awt_Group_Id IS NULL)))
2871            AND (   (Recinfo.pay_awt_group_id =  X_Pay_Awt_Group_Id)
2872                 OR (    (Recinfo.pay_awt_group_id IS NULL)
2873                     AND (X_Pay_Awt_Group_Id IS NULL)))       --bug6639866
2874            AND (   (Recinfo.awt_tax_rate_id =  X_Awt_Tax_Rate_Id)
2875                 OR (    (Recinfo.awt_tax_rate_id IS NULL)
2876                     AND (X_Awt_Tax_Rate_Id IS NULL)))
2877            AND (   (Recinfo.awt_gross_amount =  X_Awt_Gross_Amount)
2878                 OR (    (Recinfo.awt_gross_amount IS NULL)
2879                     AND (X_Awt_Gross_Amount IS NULL)))
2880            AND (   (Recinfo.reference_1 =  X_Reference_1)
2881                 OR (    (Recinfo.reference_1 IS NULL)
2882                     AND (X_Reference_1 IS NULL)))
2883            AND (   (Recinfo.reference_2 =  X_Reference_2)
2884                 OR (    (Recinfo.reference_2 IS NULL)
2885                     AND (X_Reference_2 IS NULL)))
2886            AND (   (Recinfo.other_invoice_id =  X_Other_Invoice_Id)
2887                 OR (    (Recinfo.other_invoice_id IS NULL)
2888                     AND (X_Other_Invoice_Id IS NULL)))
2889            AND (   (Recinfo.awt_invoice_id =  X_Awt_Invoice_Id)
2890                 OR (    (Recinfo.awt_invoice_id IS NULL)
2891                     AND (X_Awt_Invoice_Id IS NULL)))
2892            AND (   (Recinfo.awt_origin_group_id =  X_Awt_Origin_Group_Id)
2893                 OR (    (Recinfo.awt_origin_group_id IS NULL)
2894                     AND (X_Awt_Origin_Group_Id IS NULL)))
2895            AND (   (Recinfo.program_application_id = X_Program_Application_Id)
2896                 OR (    (Recinfo.program_application_id IS NULL)
2897                     AND (X_Program_Application_id IS NULL)))
2898            AND (   (Recinfo.program_id = X_Program_Id)
2899                 OR (    (Recinfo.program_id IS NULL)
2900                     AND (X_Program_Id IS NULL)))
2901            AND (   (Recinfo.program_update_date = X_Program_Update_Date)
2902                 OR (    (Recinfo.program_update_date IS NULL)
2903                     AND (X_Program_Update_Date IS NULL)))
2904            AND (   (Recinfo.request_id = X_Request_Id)
2905                 OR (    (Recinfo.request_id IS NULL)
2906                     AND (X_Request_Id IS NULL)))
2907            AND (    (Recinfo.tax_recoverable_flag = X_Tax_Recoverable_Flag)
2908                 OR (    (Recinfo.tax_recoverable_flag IS NULL)
2909                      AND (X_Tax_Recoverable_Flag IS NULL)))
2910            AND (    (Recinfo.award_id = X_Award_Id)
2911                 OR (    (Recinfo.award_id IS NULL)
2912                      AND (X_Award_Id IS NULL)))
2913            AND (    (Recinfo.start_expense_date = X_Start_Expense_Date)
2914                 OR (    (Recinfo.start_expense_date IS NULL)
2915                      AND (X_Start_Expense_Date IS NULL)))
2916            AND (    (Recinfo.merchant_document_number = X_Merchant_Document_Number)
2917                 OR (    (Recinfo.merchant_document_number IS NULL)
2918                      AND (X_Merchant_Document_Number IS NULL)))
2919            AND (    (Recinfo.merchant_name = X_Merchant_Name)
2920                 OR (    (Recinfo.merchant_name IS NULL)
2921                      AND (X_Merchant_Name IS NULL)))
2922            AND (    (Recinfo.merchant_tax_reg_number = X_Merchant_Tax_Reg_Number)
2923                 OR (    (Recinfo.merchant_tax_reg_number IS NULL)
2924                      AND (X_Merchant_Tax_Reg_Number IS NULL)))
2925            AND (    (Recinfo.merchant_taxpayer_id = X_Merchant_Taxpayer_Id)
2926                 OR (    (Recinfo.merchant_taxpayer_id IS NULL)
2927                      AND (X_Merchant_Taxpayer_Id IS NULL)))
2928            AND (    (Recinfo.merchant_reference = X_Merchant_Reference)
2929                 OR (    (Recinfo.merchant_reference IS NULL)
2930                      AND (X_Merchant_Reference IS NULL)))
2931            AND (    (Recinfo.country_of_supply = X_Country_Of_Supply)
2932                 OR (    (Recinfo.country_of_supply IS NULL)
2933                      AND (X_Country_Of_Supply IS NULL)))
2934 
2935       ) then
2936       null;
2937     else
2938       FND_MESSAGE.Set_Name('FND', 'FORM_RECORD_CHANGED');
2939       APP_EXCEPTION.Raise_Exception;
2940     end if;
2941 
2942    if (
2943                (   (Recinfo.global_attribute_category =  X_global_attribute_category)
2944                 OR (    (Recinfo.global_attribute_category IS NULL)
2945                     AND (X_global_attribute_category IS NULL)))
2946            AND (   (Recinfo.global_attribute1 =  X_global_attribute1)
2947                 OR (    (Recinfo.global_attribute1 IS NULL)
2948                     AND (X_global_attribute1 IS NULL)))
2949            AND (   (Recinfo.global_attribute2 =  X_global_attribute2)
2950                 OR (    (Recinfo.global_attribute2 IS NULL)
2951                     AND (X_global_attribute2 IS NULL)))
2952            AND (   (Recinfo.global_attribute3 =  X_global_attribute3)
2953                 OR (    (Recinfo.global_attribute3 IS NULL)
2954                     AND (X_global_attribute3 IS NULL)))
2955            AND (   (Recinfo.global_attribute4 =  X_global_attribute4)
2956                 OR (    (Recinfo.global_attribute4 IS NULL)
2957                     AND (X_global_attribute4 IS NULL)))
2958            AND (   (Recinfo.global_attribute5 =  X_global_attribute5)
2959                 OR (    (Recinfo.global_attribute5 IS NULL)
2960                     AND (X_global_attribute5 IS NULL)))
2961            AND (   (Recinfo.global_attribute6 =  X_global_attribute6)
2962                 OR (    (Recinfo.global_attribute6 IS NULL)
2963                     AND (X_global_attribute6 IS NULL)))
2964            AND (   (Recinfo.global_attribute7 =  X_global_attribute7)
2965                 OR (    (Recinfo.global_attribute7 IS NULL)
2966                     AND (X_global_attribute7 IS NULL)))
2967            AND (   (Recinfo.global_attribute8 =  X_global_attribute8)
2968                 OR (    (Recinfo.global_attribute8 IS NULL)
2969                     AND (X_global_attribute8 IS NULL)))
2970            AND (   (Recinfo.global_attribute9 =  X_global_attribute9)
2971                 OR (    (Recinfo.global_attribute9 IS NULL)
2972                     AND (X_global_attribute9 IS NULL)))
2973            AND (   (Recinfo.global_attribute10 =  X_global_attribute10)
2974                 OR (    (Recinfo.global_attribute10 IS NULL)
2975                     AND (X_global_attribute10 IS NULL)))
2976            AND (   (Recinfo.global_attribute11 =  X_global_attribute11)
2977                 OR (    (Recinfo.global_attribute11 IS NULL)
2978                     AND (X_global_attribute11 IS NULL)))
2979            AND (   (Recinfo.global_attribute12 =  X_global_attribute12)
2980                 OR (    (Recinfo.global_attribute12 IS NULL)
2981                     AND (X_global_attribute12 IS NULL)))
2982            AND (   (Recinfo.global_attribute13 =  X_global_attribute13)
2983                 OR (    (Recinfo.global_attribute13 IS NULL)
2984                     AND (X_global_attribute13 IS NULL)))
2985            AND (   (Recinfo.global_attribute14 =  X_global_attribute14)
2986                 OR (    (Recinfo.global_attribute14 IS NULL)
2987                     AND (X_global_attribute14 IS NULL)))
2988            AND (   (Recinfo.global_attribute15 =  X_global_attribute15)
2989                 OR (    (Recinfo.global_attribute15 IS NULL)
2990                     AND (X_global_attribute15 IS NULL)))
2991            AND (   (Recinfo.global_attribute16 =  X_global_attribute16)
2992                 OR (    (Recinfo.global_attribute16 IS NULL)
2993                     AND (X_global_attribute16 IS NULL)))
2994            AND (   (Recinfo.global_attribute17 =  X_global_attribute17)
2995                 OR (    (Recinfo.global_attribute17 IS NULL)
2996                     AND (X_global_attribute17 IS NULL)))
2997            AND (   (Recinfo.global_attribute18 =  X_global_attribute18)
2998                 OR (    (Recinfo.global_attribute18 IS NULL)
2999                     AND (X_global_attribute18 IS NULL)))
3000            AND (   (Recinfo.global_attribute19 =  X_global_attribute19)
3001                 OR (    (Recinfo.global_attribute19 IS NULL)
3002                     AND (X_global_attribute19 IS NULL)))
3003            AND (   (Recinfo.global_attribute20 =  X_global_attribute20)
3004                 OR (    (Recinfo.global_attribute20 IS NULL)
3005                     AND (X_global_attribute20 IS NULL)))
3006           ) then
3007       return;
3008     else
3009       FND_MESSAGE.Set_Name('FND', 'FORM_RECORD_CHANGED');
3010       APP_EXCEPTION.Raise_Exception;
3011     end if;
3012 
3013        -- Invoice Lines Project Stage 1
3014        IF (
3015            (   (Recinfo.rOUNDING_AMT =  X_ROUNDING_AMT)
3016                 OR (    (Recinfo.ROUNDING_AMT IS NULL)
3017                     AND (X_ROUNDING_AMT IS NULL)))
3018            AND (   (Recinfo.CHARGE_APPLICABLE_TO_DIST_ID =  X_CHARGE_APPLICABLE_TO_DIST_ID)
3019                 OR (    (Recinfo.CHARGE_APPLICABLE_TO_DIST_ID IS NULL)
3020                     AND (X_CHARGE_APPLICABLE_TO_DIST_ID IS NULL)))
3021            AND (   (Recinfo.CORRECTED_INVOICE_DIST_ID =  X_CORRECTED_INVOICE_DIST_ID)
3022                 OR (    (Recinfo.CORRECTED_INVOICE_DIST_ID IS NULL)
3023                     AND (X_CORRECTED_INVOICE_DIST_ID IS NULL)))
3024            AND (   (Recinfo.RELATED_ID =  X_RELATED_ID)
3025                 OR (    (Recinfo.RELATED_ID IS NULL)
3026                     AND (X_RELATED_ID IS NULL)))
3027            AND (   (Recinfo.ASSET_BOOK_TYPE_CODE =  X_ASSET_BOOK_TYPE_CODE)
3028                 OR (    (Recinfo.ASSET_BOOK_TYPE_CODE IS NULL)
3029                     AND (X_ASSET_BOOK_TYPE_CODE IS NULL)))
3030            AND (   (Recinfo.ASSET_CATEGORY_ID =  X_ASSET_CATEGORY_ID)
3031                 OR (    (Recinfo.ASSET_CATEGORY_ID IS NULL)
3032                     AND (X_ASSET_CATEGORY_ID IS NULL)))
3033            AND (   (Recinfo.INTENDED_USE =  X_INTENDED_USE)
3034 	        OR (    (Recinfo.INTENDED_USE IS NULL)
3035 	            AND (X_INTENDED_USE IS NULL)))
3036       ) then
3037       return;
3038     else
3039       FND_MESSAGE.Set_Name('FND', 'FORM_RECORD_CHANGED');
3040       APP_EXCEPTION.Raise_Exception;
3041     end if;
3042 
3043   EXCEPTION
3044     WHEN OTHERS THEN
3045       if (SQLCODE <> -20001) then
3046         IF (SQLCODE = -54) THEN
3047           FND_MESSAGE.SET_NAME('SQLAP','AP_RESOURCE_BUSY');
3048         ELSE
3049           FND_MESSAGE.SET_NAME('SQLAP', 'AP_DEBUG');
3050           FND_MESSAGE.SET_TOKEN('ERROR', SQLERRM);
3051           FND_MESSAGE.SET_TOKEN('CALLING_SEQUENCE', current_calling_sequence);
3052           FND_MESSAGE.SET_TOKEN('DEBUG_INFO', debug_info);
3053         END IF;
3054       end if;
3055       APP_EXCEPTION.RAISE_EXCEPTION;
3056 
3057   END Lock_Row;
3058 
3059   PROCEDURE Update_Row(X_Rowid                          VARCHAR2,
3060                        X_Invoice_Id                     NUMBER,
3061                        -- Invoice Lines Project Stage 1
3062                        X_Invoice_Line_Number            NUMBER,
3063                        X_Distribution_Class             VARCHAR2,
3064                        X_Dist_Code_Combination_Id       NUMBER,
3065                        X_Last_Update_Date               DATE,
3066                        X_Last_Updated_By                NUMBER,
3067                        X_Accounting_Date                DATE,
3068                        X_Period_Name                    VARCHAR2,
3069                        X_Set_Of_Books_Id                NUMBER,
3070                        X_Amount                         NUMBER,
3071                        X_Description                    VARCHAR2,
3072                        X_Type_1099                      VARCHAR2,
3073                        X_Posted_Flag                    VARCHAR2,
3074                        X_Batch_Id                       NUMBER,
3075                        X_Quantity_Invoiced              NUMBER,
3076                        X_Unit_Price                     NUMBER,
3077                        X_Match_Status_Flag              VARCHAR2,
3078                        X_Attribute_Category             VARCHAR2,
3079                        X_Attribute1                     VARCHAR2,
3080                        X_Attribute2                     VARCHAR2,
3081                        X_Attribute3                     VARCHAR2,
3082                        X_Attribute4                     VARCHAR2,
3083                        X_Attribute5                     VARCHAR2,
3084                        X_Prepay_Amount_Remaining        NUMBER,
3085                        X_Assets_Addition_Flag           VARCHAR2,
3086                        X_Assets_Tracking_Flag           VARCHAR2,
3087                        X_Distribution_Line_Number       NUMBER,
3088                        X_Line_Type_Lookup_Code          VARCHAR2,
3089                        X_Po_Distribution_Id             NUMBER,
3090                        X_Base_Amount                    NUMBER,
3091                        X_Pa_Addition_Flag               VARCHAR2,
3092                        X_Posted_Amount                  NUMBER,
3093                        X_Posted_Base_Amount             NUMBER,
3094                        X_Encumbered_Flag                VARCHAR2,
3095                        X_Accrual_Posted_Flag            VARCHAR2,
3096                        X_Cash_Posted_Flag               VARCHAR2,
3097                        X_Last_Update_Login              NUMBER,
3098                        X_Stat_Amount                    NUMBER,
3099                        X_Attribute11                    VARCHAR2,
3100                        X_Attribute12                    VARCHAR2,
3101                        X_Attribute13                    VARCHAR2,
3102                        X_Attribute14                    VARCHAR2,
3103                        X_Attribute6                     VARCHAR2,
3104                        X_Attribute7                     VARCHAR2,
3105                        X_Attribute8                     VARCHAR2,
3106                        X_Attribute9                     VARCHAR2,
3107                        X_Attribute10                    VARCHAR2,
3108                        X_Attribute15                    VARCHAR2,
3109                        X_Accts_Pay_Code_Comb_Id         NUMBER,
3110                        X_Reversal_Flag                  VARCHAR2,
3111                        X_Parent_Invoice_Id              NUMBER,
3112                        X_Income_Tax_Region              VARCHAR2,
3113                        X_Final_Match_Flag               VARCHAR2,
3114                        X_Expenditure_Item_Date          DATE,
3115                        X_Expenditure_Organization_Id    NUMBER,
3116                        X_Expenditure_Type               VARCHAR2,
3117                        X_Pa_Quantity                    NUMBER,
3118                        X_Project_Id                     NUMBER,
3119                        X_Task_Id                        NUMBER,
3120                        X_Quantity_Variance              NUMBER,
3121                        X_Base_Quantity_Variance         NUMBER,
3122                        X_Packet_Id                      NUMBER,
3123                        X_Awt_Flag                       VARCHAR2,
3124                        X_Awt_Group_Id                   NUMBER,
3125 		       X_Pay_Awt_Group_Id               NUMBER,--bug6639866
3126                        X_Awt_Tax_Rate_Id                NUMBER,
3127                        X_Awt_Gross_Amount               NUMBER,
3128                        X_Reference_1                    VARCHAR2,
3129                        X_Reference_2                    VARCHAR2,
3130                        X_Org_Id                         NUMBER,
3131                        X_Other_Invoice_Id               NUMBER,
3132                        X_Awt_Invoice_Id                 NUMBER,
3133                        X_Awt_Origin_Group_Id            NUMBER,
3134                        X_Program_Application_Id         NUMBER,
3135                        X_Program_Id                     NUMBER,
3136                        X_Program_Update_Date            DATE,
3137                        X_Request_Id                     NUMBER,
3138                        X_Tax_Recoverable_Flag           VARCHAR2,
3139                        X_Award_Id                       NUMBER,
3140                        X_Start_Expense_Date             DATE,
3141                        X_Merchant_Document_Number       VARCHAR2,
3142                        X_Merchant_Name                  VARCHAR2,
3143                        X_Merchant_Tax_Reg_Number        VARCHAR2,
3144                        X_Merchant_Taxpayer_Id           VARCHAR2,
3145                        X_Country_Of_Supply              VARCHAR2,
3146                        X_Merchant_Reference             VARCHAR2,
3147                        X_global_attribute_category      VARCHAR2 DEFAULT NULL,
3148                        X_global_attribute1              VARCHAR2 DEFAULT NULL,
3149                        X_global_attribute2              VARCHAR2 DEFAULT NULL,
3150                        X_global_attribute3              VARCHAR2 DEFAULT NULL,
3151                        X_global_attribute4              VARCHAR2 DEFAULT NULL,
3152                        X_global_attribute5              VARCHAR2 DEFAULT NULL,
3153                        X_global_attribute6              VARCHAR2 DEFAULT NULL,
3154                        X_global_attribute7              VARCHAR2 DEFAULT NULL,
3155                        X_global_attribute8              VARCHAR2 DEFAULT NULL,
3156                        X_global_attribute9              VARCHAR2 DEFAULT NULL,
3157                        X_global_attribute10             VARCHAR2 DEFAULT NULL,
3158                        X_global_attribute11             VARCHAR2 DEFAULT NULL,
3159                        X_global_attribute12             VARCHAR2 DEFAULT NULL,
3160                        X_global_attribute13             VARCHAR2 DEFAULT NULL,
3161                        X_global_attribute14             VARCHAR2 DEFAULT NULL,
3162                        X_global_attribute15             VARCHAR2 DEFAULT NULL,
3163                        X_global_attribute16             VARCHAR2 DEFAULT NULL,
3164                        X_global_attribute17             VARCHAR2 DEFAULT NULL,
3165                        X_global_attribute18             VARCHAR2 DEFAULT NULL,
3166                        X_global_attribute19             VARCHAR2 DEFAULT NULL,
3167                        X_global_attribute20             VARCHAR2 DEFAULT NULL,
3168                        X_Calling_Sequence               VARCHAR2,
3169                        -- Invoice Lines Project Stage 1
3170                        X_rounding_amt                   NUMBER DEFAULT NULL,
3171                        X_charge_applicable_to_dist_id    NUMBER DEFAULT NULL,
3172                        X_corrected_invoice_dist_id      NUMBER DEFAULT NULL,
3173                        X_related_id                     NUMBER DEFAULT NULL,
3174                        X_asset_book_type_code           VARCHAR2 DEFAULT NULL,
3175                        X_asset_category_id              NUMBER DEFAULT NULL,
3176 		       X_intended_use			VARCHAR2 DEFAULT NULL
3177   ) IS
3178     current_calling_sequence VARCHAR2(2000);
3179     debug_info               VARCHAR2(100);
3180 
3181     --Bug9819170
3182     l_return_status              VARCHAR2(2000) ;
3183     l_api_name                   CONSTANT VARCHAR2(100) := 'Update_Row';
3184     --Bug9819170
3185 
3186 
3187   BEGIN
3188 
3189     -- Update the calling sequence
3190     --
3191     current_calling_sequence :=
3192     'AP_INVOICE_DISTRIBUTIONS_PKG.Update_Row<-'||X_Calling_Sequence;
3193 
3194      AP_AID_TABLE_HANDLER_PKG.Update_Row
3195              (X_Rowid,
3196               X_Invoice_Id,
3197               -- Invoice Lines Project Stage 1
3198               X_Invoice_Line_number,
3199               X_Distribution_Class,
3200               X_Dist_Code_Combination_Id,
3201               X_Last_Update_Date,
3202               X_Last_Updated_By,
3203               X_Accounting_Date,
3204               X_Period_Name,
3205               X_Set_Of_Books_Id,
3206               X_Amount,
3207               X_Description,
3208               X_Type_1099,
3209               X_Posted_Flag,
3210               X_Batch_Id,
3211               X_Quantity_Invoiced,
3212               X_Unit_Price,
3213               X_Match_Status_Flag,
3214               X_Attribute_Category,
3215               X_Attribute1,
3216               X_Attribute2,
3217               X_Attribute3,
3218               X_Attribute4,
3219               X_Attribute5,
3220               X_Prepay_Amount_Remaining,
3221               X_Assets_Addition_Flag,
3222               X_Assets_Tracking_Flag,
3223               X_Distribution_Line_Number,
3224               X_Line_Type_Lookup_Code,
3225               X_Po_Distribution_Id,
3226               X_Base_Amount,
3227               X_Pa_Addition_Flag,
3228               X_Posted_Amount,
3229               X_Posted_Base_Amount,
3230               X_Encumbered_Flag,
3231               X_Accrual_Posted_Flag,
3232               X_Cash_Posted_Flag,
3233               X_Last_Update_Login,
3234               X_Stat_Amount,
3235               X_Attribute11,
3236               X_Attribute12,
3237               X_Attribute13,
3238               X_Attribute14,
3239               X_Attribute6,
3240               X_Attribute7,
3241               X_Attribute8,
3242               X_Attribute9,
3243               X_Attribute10,
3244               X_Attribute15,
3245               X_Accts_Pay_Code_Comb_Id,
3246               X_Reversal_Flag,
3247               X_Parent_Invoice_Id,
3248               X_Income_Tax_Region,
3249               X_Final_Match_Flag,
3250               X_Expenditure_Item_Date,
3251               X_Expenditure_Organization_Id,
3252               X_Expenditure_Type,
3253               X_Pa_Quantity,
3254               X_Project_Id,
3255               X_Task_Id,
3256               X_Quantity_Variance,
3257               X_Base_Quantity_Variance,
3258               X_Packet_Id,
3259               X_Awt_Flag,
3260               X_Awt_Group_Id,
3261 	      X_Pay_Awt_Group_Id,--bug6639866
3262               X_Awt_Tax_Rate_Id,
3263               X_Awt_Gross_Amount,
3264               X_Reference_1,
3265               X_Reference_2,
3266               X_Org_Id,
3267               X_Other_Invoice_Id,
3268               X_Awt_Invoice_Id,
3269               X_Awt_Origin_Group_Id,
3270               X_Program_Application_Id,
3271               X_Program_Id,
3272               X_Program_Update_Date,
3273               X_Request_Id,
3274               X_Tax_Recoverable_Flag,
3275               X_Award_Id,
3276               X_Start_Expense_Date,
3277               X_Merchant_Document_Number,
3278               X_Merchant_Name,
3279               X_Merchant_Tax_Reg_Number,
3280               X_Merchant_Taxpayer_Id,
3281               X_Country_Of_Supply,
3282               X_Merchant_Reference,
3283               X_global_attribute_category,
3284               X_global_attribute1,
3285               X_global_attribute2,
3286               X_global_attribute3,
3287               X_global_attribute4,
3288               X_global_attribute5,
3289               X_global_attribute6,
3290               X_global_attribute7,
3291               X_global_attribute8,
3292               X_global_attribute9,
3293               X_global_attribute10,
3294               X_global_attribute11,
3295               X_global_attribute12,
3296               X_global_attribute13,
3297               X_global_attribute14,
3298               X_global_attribute15,
3299               X_global_attribute16,
3300               X_global_attribute17,
3301               X_global_attribute18,
3302               X_global_attribute19,
3303               X_global_attribute20,
3304               current_calling_sequence,
3305               -- Invoice Lines Project Stage 1
3306               X_rounding_amt,
3307               X_charge_applicable_to_dist_id,
3308               X_corrected_invoice_dist_id,
3309               X_related_id,
3310               X_asset_book_type_code,
3311               X_asset_category_id,
3312 	      X_intended_use
3313              );
3314 
3315 
3316             --Bug9819170
3317             debug_info :='CALL synchronize_tax_dff';
3318             IF (G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
3319                FND_LOG.STRING(G_LEVEL_STATEMENT,G_MODULE_NAME||l_api_name,debug_info);
3320             END IF;
3321 
3322                ap_etax_services_pkg.synchronize_tax_dff
3323                   (p_invoice_id            =>  X_Invoice_Id,
3324                    p_invoice_dist_id       =>  NULL,
3325                    p_related_id            =>  X_related_id,
3326                    p_detail_tax_dist_id    =>  NULL,
3327                    p_line_type_lookup_code =>  NULL,
3328                    p_invoice_line_number   =>  X_Invoice_Line_Number,
3329                    p_distribution_line_number => X_Distribution_Line_Number,
3330                    P_ATTRIBUTE1            =>  X_Attribute1,
3331                    P_ATTRIBUTE2            =>  X_Attribute2,
3332                    P_ATTRIBUTE3            =>  X_Attribute3,
3333                    P_ATTRIBUTE4            =>  X_Attribute4,
3334                    P_ATTRIBUTE5            =>  X_Attribute5,
3335                    P_ATTRIBUTE6            =>  X_Attribute6,
3336                    P_ATTRIBUTE7            =>  X_Attribute7,
3337                    P_ATTRIBUTE8            =>  X_Attribute8,
3338                    P_ATTRIBUTE9            =>  X_Attribute9,
3339                    P_ATTRIBUTE10           =>  X_Attribute10,
3340                    P_ATTRIBUTE11           =>  X_Attribute11,
3341                    P_ATTRIBUTE12           =>  X_Attribute12,
3342                    P_ATTRIBUTE13           =>  X_Attribute13,
3343                    P_ATTRIBUTE14           =>  X_Attribute14,
3344                    P_ATTRIBUTE15           =>  X_Attribute15,
3345                    P_ATTRIBUTE_CATEGORY    =>  X_Attribute_Category,
3346                    p_calling_sequence      =>  current_calling_sequence,
3347                    x_return_status         =>  l_return_status);
3348 
3349             --Bug9819170
3350 
3351 
3352   EXCEPTION
3353     WHEN OTHERS THEN
3354       if (SQLCODE <> -20001) then
3355         FND_MESSAGE.SET_NAME('SQLAP', 'AP_DEBUG');
3356         FND_MESSAGE.SET_TOKEN('ERROR', SQLERRM);
3357         FND_MESSAGE.SET_TOKEN('CALLING_SEQUENCE', current_calling_sequence);
3358         FND_MESSAGE.SET_TOKEN('DEBUG_INFO', debug_info);
3359       end if;
3360       APP_EXCEPTION.RAISE_EXCEPTION;
3361 
3362   END Update_Row;
3363 
3364 
3365  PROCEDURE Delete_Row(X_Rowid            VARCHAR2,
3366                        X_Calling_Sequence VARCHAR2) IS
3367     current_calling_sequence VARCHAR2(2000);
3368     debug_info               VARCHAR2(100);
3369     l_invoice_distribution_id       AP_INVOICE_DISTRIBUTIONS.INVOICE_DISTRIBUTION_ID%TYPE;
3370 
3371    BEGIN
3372 
3373     -- Update the calling sequence
3374     --
3375     current_calling_sequence :=
3376     'AP_INVOICE_DISTRIBUTIONS_PKG.Delete_Row<-'||X_Calling_Sequence;
3377 
3378      AP_AID_TABLE_HANDLER_PKG.Delete_Row(
3379        X_Rowid,
3380        current_calling_sequence);
3381 
3382   EXCEPTION
3383     WHEN OTHERS THEN
3384       if (SQLCODE <> -20001) then
3385         FND_MESSAGE.SET_NAME('SQLAP', 'AP_DEBUG');
3386         FND_MESSAGE.SET_TOKEN('ERROR', SQLERRM);
3387         FND_MESSAGE.SET_TOKEN('CALLING_SEQUENCE', current_calling_sequence);
3388         FND_MESSAGE.SET_TOKEN('DEBUG_INFO', debug_info);
3389       end if;
3390       APP_EXCEPTION.RAISE_EXCEPTION;
3391 
3392   END Delete_Row;
3393 
3394 
3395   FUNCTION Get_UOM_From_Segments(
3396           X_Concatenated_Segments         IN      VARCHAR2,
3397           X_Ch_Of_Accts_Id                IN      NUMBER)
3398   RETURN VARCHAR2 IS
3399 
3400        l_segments                      FND_FLEX_EXT.SEGMENTARRAY;
3401        l_num_segments                  NUMBER;
3402        l_account_segment_num           NUMBER;
3403        l_result                        BOOLEAN;
3404        l_segment_delimiter             VARCHAR2(1);
3405        l_uom                           gl_stat_account_uom.unit_of_measure%TYPE;
3406        l_status                        VARCHAR2(10) := '';
3407        l_industry                      VARCHAR2(10) := '';
3408 
3409   BEGIN
3410        -- Verify GL is installed
3411        --
3412        IF (FND_INSTALLATION.GET(101, 101, l_status, l_industry)) then
3413          IF (l_status <> 'I') then
3414            return('');
3415          END IF;
3416        ELSE
3417          return('');
3418        END IF;
3419 
3420        -- Get the delimiter used in the Accounting FF
3421        --
3422        l_segment_delimiter := FND_FLEX_EXT.GET_DELIMITER(
3423                                                 'SQLGL',
3424                                                 'GL#',
3425                                                 X_Ch_Of_Accts_Id);
3426 
3427        IF (l_segment_delimiter IS NULL) THEN
3428              RETURN('');
3429        END IF;
3430 
3431        -- Break the passed concatenated segment into an array of segments
3432        --
3433        IF (X_Concatenated_Segments IS NOT NULL) THEN
3434            l_num_segments := FND_FLEX_EXT.breakup_segments(X_concatenated_segments,
3435                                           l_segment_delimiter,
3436                                           l_segments); --OUT
3437        END IF;
3438 
3439        -- Get the index of the Account segment in the FF
3440        --
3441        l_result := FND_FLEX_APIS.GET_QUALIFIER_SEGNUM(
3442                                     101,
3443                                     'GL#',
3444                                     X_Ch_Of_Accts_Id,
3445                                     'GL_ACCOUNT',
3446                                     l_account_segment_num);
3447 
3448        IF (NOT l_result) THEN
3449            RETURN('');
3450        END IF;
3451 
3452        -- Using the segment array and the index: Get the UOM value
3453        --
3454        SELECT unit_of_measure
3455        INTO   l_uom
3456        FROM   gl_stat_account_uom
3457        WHERE  account_segment_value = l_segments(l_account_segment_num)
3458        AND chart_of_accounts_id = X_Ch_Of_Accts_Id;
3459 
3460        RETURN(l_uom);
3461 
3462   EXCEPTION
3463      WHEN OTHERS THEN
3464         RETURN('');
3465 
3466   END Get_UOM_From_Segments;
3467 
3468 
3469   -- Bug 1567235.
3470   /* Function to get the sum of distribution amount for a given invoice
3471      and the balancing segment  */
3472   FUNCTION Get_Segment_Dist_Amount(
3473            X_Invoice_Id                   IN      NUMBER,
3474            X_Prepay_Dist_CCID             IN      NUMBER,
3475            X_Sob_Id                       IN      NUMBER) RETURN NUMBER IS
3476 
3477   l_dist_amount    NUMBER;
3478 
3479   BEGIN
3480 
3481      -- Bug 1892826. Added the line_type_lookup_code predicate
3482      -- Bug 2404982.  Added package qualifier to procedure call.
3483      SELECT sum(amount)
3484        INTO l_dist_amount
3485        FROM ap_invoice_distributions
3486       WHERE invoice_id = X_Invoice_Id
3487         AND line_type_lookup_code IN ('ITEM','PREPAY')
3488         AND nvl(reversal_flag,'N') <> 'Y'
3489         AND AP_INVOICE_DISTRIBUTIONS_PKG.get_balancing_segment_value(
3490     dist_code_combination_id, X_Sob_Id) =
3491                 AP_INVOICE_DISTRIBUTIONS_PKG.get_balancing_segment_value(
3492     X_Prepay_Dist_CCID, X_Sob_Id);
3493 
3494      RETURN (l_dist_amount);
3495 
3496   END Get_Segment_Dist_Amount;
3497 
3498 
3499   -- Bug 1567235.
3500   /* Procedure to get the sum of distribution amount for a given invoice
3501      and the sum of the distribution amount for a given prepayment */
3502   PROCEDURE Get_Prepay_Amount_Available(
3503             X_Invoice_ID                   IN      NUMBER,
3504             X_Prepay_ID                    IN      NUMBER,
3505             X_Sob_Id                       IN      NUMBER,
3506             X_Balancing_Segment            OUT NOCOPY     VARCHAR2,
3507             X_Prepay_Amount                OUT NOCOPY     NUMBER,
3508             X_Invoice_Amount               OUT NOCOPY     NUMBER) IS
3509 
3510   l_prepay_amount         NUMBER;
3511   l_invoice_amount        NUMBER;
3512   l_bal_segment           VARCHAR2(30);
3513 
3514   -- Bug 2404982.  Added package qualifier to procedure call.
3515   CURSOR c_prepay_dist IS
3516   SELECT sum(nvl(prepay_amount_remaining,amount)),
3517          AP_INVOICE_DISTRIBUTIONS_PKG.get_balancing_segment_value(
3518     aip.dist_code_combination_id, X_Sob_Id)
3519     FROM ap_invoice_distributions aip
3520    WHERE aip.invoice_id = X_Prepay_Id
3521      --bugfix:3881673
3522      AND aip.line_type_lookup_code in ('ITEM','ACCRUAL')
3523      AND nvl(aip.reversal_flag,'N') <> 'Y'
3524      AND nvl(aip.prepay_amount_remaining,amount) > 0
3525      AND AP_INVOICE_DISTRIBUTIONS_PKG.get_balancing_segment_value(
3526     aip.dist_code_combination_id, X_Sob_Id) IN
3527              (SELECT AP_INVOICE_DISTRIBUTIONS_PKG.get_balancing_segment_value(
3528     aid.dist_code_combination_id, X_Sob_Id)
3529                 FROM ap_invoice_distributions aid
3530                WHERE aid.invoice_id = X_Invoice_ID)
3531    GROUP BY AP_INVOICE_DISTRIBUTIONS_PKG.get_balancing_segment_value(
3532     aip.dist_code_combination_id, X_Sob_Id)
3533    ORDER BY AP_INVOICE_DISTRIBUTIONS_PKG.get_balancing_segment_value(
3534     aip.dist_code_combination_id, X_Sob_Id);
3535 
3536   BEGIN
3537 
3538      OPEN c_prepay_dist;
3539      LOOP
3540        FETCH c_prepay_dist into l_prepay_amount, l_bal_segment;
3541        EXIT WHEN c_prepay_dist%NOTFOUND;
3542 
3543   -- Bug 2404982.  Added package qualifier to procedure call
3544        SELECT sum(amount)
3545          INTO l_invoice_amount
3546          FROM ap_invoice_distributions
3547         WHERE invoice_id = X_Invoice_ID
3548           AND line_type_lookup_code IN ('ITEM','PREPAY')
3549           AND nvl(reversal_flag,'N') <> 'Y'
3550           AND AP_INVOICE_DISTRIBUTIONS_PKG.get_balancing_segment_value(
3551     dist_code_combination_id, X_Sob_Id)
3552                    = l_bal_segment;
3553 
3554        IF l_invoice_amount <> 0 THEN
3555           EXIT;
3556        END IF;
3557 
3558      END LOOP;
3559      CLOSE c_prepay_dist;
3560 
3561      X_Balancing_Segment := l_bal_segment;
3562      X_Prepay_Amount := l_prepay_amount;
3563      X_Invoice_Amount := l_invoice_amount;
3564 
3565   END Get_Prepay_Amount_Available;
3566 
3567 
3568   -- Bug 1648309.
3569   /* Function to check if an invoice has item lines with different balancing
3570      segments. */
3571   FUNCTION Check_Diff_Dist_Segments(
3572            X_Invoice_Id                   IN      NUMBER,
3573            X_Sob_Id                       IN      NUMBER) RETURN BOOLEAN IS
3574 
3575   l_dist_count         NUMBER;
3576 
3577   BEGIN
3578 
3579   --Bug 2404982. Added package qualifier to procedure call.
3580      SELECT count(distinct(
3581                  AP_INVOICE_DISTRIBUTIONS_PKG.get_balancing_segment_value(
3582                  dist_code_combination_id, X_Sob_Id)) )
3583        INTO l_dist_count
3584        FROM ap_invoice_distributions
3585       WHERE invoice_id = X_Invoice_Id;
3586 
3587      IF l_dist_count > 1 THEN
3588         RETURN (TRUE);
3589      ELSE
3590         RETURN (FALSE);
3591      END IF;
3592 
3593   END Check_Diff_Dist_Segments;
3594 
3595 
3596   -- Bug 1567235
3597   /* Function to get the value of the balancing segment for a given
3598      CCID */
3599 FUNCTION get_balancing_segment_value(
3600          X_Dist_Code_Combination_Id      IN      NUMBER,
3601          X_Sob_Id                        IN      NUMBER) RETURN VARCHAR2 IS
3602 
3603   l_dist_segments            FND_FLEX_EXT.SEGMENTARRAY ;
3604   l_segments                 FND_FLEX_EXT.SEGMENTARRAY ;
3605   l_num_of_segments          NUMBER ;
3606   l_result                   BOOLEAN ;
3607   l_coa_id                   NUMBER ;
3608   l_flex_segment_num         NUMBER ;
3609 
3610 BEGIN
3611 
3612   SELECT chart_of_accounts_id
3613   INTO   l_coa_id
3614   FROM   gl_sets_of_books
3615   WHERE  set_of_books_id = X_Sob_Id;
3616 
3617   -- Get the segments of the two given accounts
3618   IF (NOT FND_FLEX_EXT.GET_SEGMENTS('SQLGL', 'GL#',
3619                                     l_coa_id,
3620                                     X_Dist_Code_Combination_Id,
3621                                     l_num_of_segments,
3622                                     l_dist_segments)
3623      ) THEN
3624 
3625     -- Return -1 if flex failed
3626     RETURN (-1);
3627 
3628   END IF;
3629 
3630   IF (NOT FND_FLEX_APIS.GET_QUALIFIER_SEGNUM(
3631                               101, 'GL#',
3632                               l_coa_id,
3633                               'GL_BALANCING',
3634                               l_flex_segment_num)
3635      ) THEN
3636 
3637     RETURN (-1);
3638 
3639   END IF;
3640 
3641   FOR i IN 1.. l_num_of_segments LOOP
3642 
3643     IF (i = l_flex_segment_num) THEN
3644         RETURN(l_dist_segments(i));
3645     END IF;
3646 
3647   END LOOP;
3648 
3649 END Get_Balancing_Segment_Value;
3650 
3651   -- Bug 2118673
3652   /* Function to get the value of the balancing segment for a given
3653      account */
3654 FUNCTION get_balancing_seg_from_acc(
3655          X_account      IN      VARCHAR2,
3656          X_Sob_Id       IN      NUMBER) RETURN VARCHAR2 IS
3657 
3658   l_delimiter                VARCHAR2(1);
3659   l_dist_segments            FND_FLEX_EXT.SEGMENTARRAY ;
3660   l_num_of_segments          NUMBER ;
3661   l_coa_id                   NUMBER ;
3662   l_flex_segment_num         NUMBER ;
3663 
3664 BEGIN
3665 
3666   SELECT chart_of_accounts_id
3667   INTO   l_coa_id
3668   FROM   gl_sets_of_books
3669   WHERE  set_of_books_id = X_Sob_Id;
3670 
3671   -- Get the delimiter
3672   l_delimiter := FND_FLEX_EXT.GET_DELIMITER('SQLGL', 'GL#', l_coa_id);
3673 
3674   -- Get the segments
3675   l_num_of_segments := FND_FLEX_EXT.BREAKUP_SEGMENTS(
3676                                       x_account, l_delimiter,
3677                                       l_dist_segments);
3678 
3679   -- Get the balancing segment number
3680   IF (NOT FND_FLEX_APIS.GET_QUALIFIER_SEGNUM(
3681                               101, 'GL#',
3682                               l_coa_id,
3683                               'GL_BALANCING',
3684                               l_flex_segment_num)) THEN
3685 
3686     RETURN (-1);
3687   END IF;
3688 
3689   IF l_flex_segment_num > 0 AND l_flex_segment_num <= l_num_of_segments THEN
3690         RETURN(l_dist_segments(l_flex_segment_num));
3691   ELSE
3692         RETURN(NULL);
3693   END IF;
3694 END Get_Balancing_Seg_from_acc;
3695 
3696 
3697 
3698 
3699   PROCEDURE Round_Biggest_Distribution(
3700           X_Base_Currency_Code IN VARCHAR2,
3701           X_Invoice_Id         IN NUMBER,
3702           X_Calling_Sequence   IN VARCHAR2) IS
3703 
3704     current_calling_sequence VARCHAR2(2000);
3705     debug_info               VARCHAR2(100);
3706 
3707   BEGIN
3708 
3709     -- Update current calling sequence
3710     --
3711     current_calling_sequence :=
3712     'AP_INVOICE_DISTRIBUTIONS_PKG.Round_Biggest_Distribution<-'
3713        ||X_Calling_Sequence;
3714 
3715     debug_info := 'Adjusting distribution amount in biggest distribution';
3716 
3717     -- bug 5052661 --  modified SELECT portion of SQL in where clause to go to base tables to avoid FTS
3718     UPDATE ap_invoice_distributions d1
3719        SET base_amount =
3720            (SELECT DECODE(SIGN(SUM(d2.base_amount) -
3721                             DECODE(max(f.minimum_accountable_unit), NULL,
3722                                    ROUND((SUM(d2.amount)
3723                                           * i.exchange_rate),MAX(f.precision)),
3724                                    ROUND((SUM(d2.amount) * i.exchange_rate)
3725                                          / MAX(f.minimum_accountable_unit)) *
3726                                    MAX(f.minimum_accountable_unit))),
3727                         1, d1.base_amount
3728                             - (SUM(d2.base_amount) -
3729                                DECODE(MAX(f.minimum_accountable_unit), NULL,
3730                                       ROUND((SUM(d2.amount)
3731                                              * i.exchange_rate),
3732                                             MAX(f.precision)),
3733                                       ROUND((SUM(d2.amount) * i.exchange_rate)
3734                                             / MAX(f.minimum_accountable_unit))*
3735                                       MAX(f.minimum_accountable_unit))),
3736                         -1, d1.base_amount
3737                              - (SUM(d2.base_amount) -
3738                                 DECODE(MAX(f.minimum_accountable_unit), NULL,
3739                                        ROUND((SUM(d2.amount) *
3740                                               i.exchange_rate),
3741                                              MAX(f.precision)),
3742                                        ROUND((SUM(d2.amount) * i.exchange_rate)
3743                                             /MAX(f.minimum_accountable_unit))*
3744                                        MAX(f.minimum_accountable_unit))),
3745                         d1.base_amount)
3746               FROM ap_invoices i, ap_invoice_distributions d2, fnd_currencies F
3747              WHERE d1.invoice_id = i.invoice_id
3748                AND d1.invoice_id = d2.invoice_id
3749                AND f.currency_code = X_Base_Currency_Code
3750              GROUP BY i.exchange_rate)
3751      WHERE d1.invoice_id = X_Invoice_Id
3752        AND d1.posted_flag = 'N'
3753        AND (d1.invoice_id, d1.distribution_line_number) IN
3754            (SELECT d5.invoice_id, MAX(d5.distribution_line_number)
3755               FROM ap_invoice_distributions_all d5
3756              WHERE (d5.invoice_id, abs(d5.amount)) IN
3757                 (SELECT i1.invoice_id , MAX(ABS(d3.amount))
3758                    FROM ap_invoices_all i1, ap_invoice_distributions_all d3
3759                   WHERE i1.invoice_id = X_Invoice_Id
3760                     AND i1.invoice_id = d3.invoice_id
3761                     AND d3.line_type_lookup_code NOT IN ('NONREC_TAX','REC_TAX','TRV','TERV','TIPV','IPV', 'ERV') -- Bug 11654030 <> 'TAX', Bug 12691958: Added excluding 'IPV' and 'ERV' lines
3762                     AND d3.related_id IS NULL -- Bug 13864403
3763                     AND NOT EXISTS
3764                       (SELECT d4.invoice_id
3765                          FROM ap_invoice_distributions_all d4
3766                         WHERE d4.invoice_id = X_Invoice_Id
3767                           AND (1 = DECODE(X_Base_Currency_Code,
3768                                       i1.invoice_currency_code,1,
3769                                       DECODE(d4.exchange_rate,null,1,0))
3770                            OR    1 = DECODE(X_Base_Currency_Code,
3771                                      i1.invoice_currency_code,
3772                                      1,DECODE(d4.base_amount,null,1,0))))
3773                   GROUP BY i1.invoice_id, i1.invoice_amount
3774                  HAVING nvl(i1.invoice_amount,0) = nvl(sum(d3.amount),0))
3775              GROUP BY d5.invoice_id);
3776 
3777 
3778   EXCEPTION
3779     WHEN OTHERS THEN
3780       IF (SQLCODE <> -20001) THEN
3781         FND_MESSAGE.SET_NAME('SQLAP', 'AP_DEBUG');
3782         FND_MESSAGE.SET_TOKEN('ERROR', SQLERRM);
3783         FND_MESSAGE.SET_TOKEN('CALLING_SEQUENCE', current_calling_sequence);
3784         FND_MESSAGE.SET_TOKEN('DEBUG_INFO', debug_info);
3785       END IF;
3786       APP_EXCEPTION.RAISE_EXCEPTION;
3787 
3788   END Round_Biggest_Distribution;
3789 
3790 
3791   -----------------------------------------------------------------------
3792   -- FUNCTION insert_single_dist_from_line inserts a record into
3793   -- ap_invoice_distributions given a line number number and/or line record.
3794   -- It returns FALSE if an error is encountered.
3795   -----------------------------------------------------------------------
3796   FUNCTION Insert_Single_Dist_From_Line(
3797            X_batch_id            IN         AP_INVOICES.BATCH_ID%TYPE,
3798            X_invoice_id          IN         NUMBER,
3799            X_invoice_date        IN         AP_INVOICES.INVOICE_DATE%TYPE,
3800            X_vendor_id           IN         AP_INVOICES.VENDOR_ID%TYPE,
3801            X_invoice_currency    IN         AP_INVOICES.INVOICE_CURRENCY_CODE%TYPE,
3802            X_exchange_rate       IN         AP_INVOICES.EXCHANGE_RATE%TYPE,
3803            X_exchange_rate_type  IN         AP_INVOICES.EXCHANGE_RATE_TYPE%TYPE,
3804            X_exchange_date       IN         AP_INVOICES.EXCHANGE_DATE%TYPE,
3805            X_line_number         IN         NUMBER,
3806            X_invoice_lines_rec   IN         AP_INVOICES_PKG.r_invoice_line_rec,
3807            X_line_source         IN         VARCHAR2,
3808            X_Generate_Permanent  IN         VARCHAR2 DEFAULT 'N',
3809            X_Validate_Info       IN         BOOLEAN DEFAULT TRUE,
3810            X_Error_Code          OUT NOCOPY VARCHAR2,
3811            X_Debug_Info          OUT NOCOPY VARCHAR2,
3812            X_Debug_Context       OUT NOCOPY VARCHAR2,
3813            X_Msg_Application     OUT NOCOPY VARCHAR2,
3814            X_Msg_Data            OUT NOCOPY VARCHAR2,
3815            X_Calling_Sequence    IN         VARCHAR2) RETURN BOOLEAN
3816   IS
3817 
3818   CURSOR line_rec IS
3819   SELECT INVOICE_ID,
3820       LINE_NUMBER,
3821       LINE_TYPE_LOOKUP_CODE,
3822       REQUESTER_ID,
3823       DESCRIPTION,
3824       LINE_SOURCE,
3825       ORG_ID,
3826       LINE_GROUP_NUMBER,
3827       INVENTORY_ITEM_ID,
3828       ITEM_DESCRIPTION,
3829       SERIAL_NUMBER,
3830       MANUFACTURER,
3831       MODEL_NUMBER,
3832       WARRANTY_NUMBER,
3833       GENERATE_DISTS,
3834       MATCH_TYPE,
3835       DISTRIBUTION_SET_ID,
3836       ACCOUNT_SEGMENT,
3837       BALANCING_SEGMENT,
3838       COST_CENTER_SEGMENT,
3839       OVERLAY_DIST_CODE_CONCAT,
3840       DEFAULT_DIST_CCID,
3841       PRORATE_ACROSS_ALL_ITEMS,
3842       ACCOUNTING_DATE,
3843       PERIOD_NAME,
3844       DEFERRED_ACCTG_FLAG,
3845       DEF_ACCTG_START_DATE,
3846       DEF_ACCTG_END_DATE,
3847       DEF_ACCTG_NUMBER_OF_PERIODS,
3848       DEF_ACCTG_PERIOD_TYPE,
3849       SET_OF_BOOKS_ID,
3850       AMOUNT,
3851       BASE_AMOUNT,
3852       ROUNDING_AMT,
3853       QUANTITY_INVOICED,
3854       UNIT_MEAS_LOOKUP_CODE,
3855       UNIT_PRICE,
3856       WFAPPROVAL_STATUS,
3857       DISCARDED_FLAG,
3858       ORIGINAL_AMOUNT,
3859       ORIGINAL_BASE_AMOUNT,
3860       ORIGINAL_ROUNDING_AMT,
3861       CANCELLED_FLAG,
3862       INCOME_TAX_REGION,
3863       TYPE_1099,
3864       STAT_AMOUNT,
3865       PREPAY_INVOICE_ID,
3866       PREPAY_LINE_NUMBER,
3867       INVOICE_INCLUDES_PREPAY_FLAG,
3868       CORRECTED_INV_ID,
3869       CORRECTED_LINE_NUMBER,
3870       PO_HEADER_ID,
3871       PO_LINE_ID,
3872       PO_RELEASE_ID,
3873       PO_LINE_LOCATION_ID,
3874       PO_DISTRIBUTION_ID,
3875       RCV_TRANSACTION_ID,
3876       FINAL_MATCH_FLAG,
3877       ASSETS_TRACKING_FLAG,
3878       ASSET_BOOK_TYPE_CODE,
3879       ASSET_CATEGORY_ID,
3880       PROJECT_ID,
3881       TASK_ID,
3882       EXPENDITURE_TYPE,
3883       EXPENDITURE_ITEM_DATE,
3884       EXPENDITURE_ORGANIZATION_ID,
3885       PA_QUANTITY,
3886       PA_CC_AR_INVOICE_ID,
3887       PA_CC_AR_INVOICE_LINE_NUM ,
3888       PA_CC_PROCESSED_CODE,
3889       AWARD_ID,
3890       AWT_GROUP_ID,
3891       REFERENCE_1,
3892       REFERENCE_2,
3893       RECEIPT_VERIFIED_FLAG,
3894       RECEIPT_REQUIRED_FLAG,
3895       RECEIPT_MISSING_FLAG,
3896       JUSTIFICATION,
3897       EXPENSE_GROUP,
3898       START_EXPENSE_DATE,
3899       END_EXPENSE_DATE,
3900       RECEIPT_CURRENCY_CODE,
3901       RECEIPT_CONVERSION_RATE,
3902       RECEIPT_CURRENCY_AMOUNT,
3903       DAILY_AMOUNT,
3904       WEB_PARAMETER_ID,
3905       ADJUSTMENT_REASON,
3906       MERCHANT_DOCUMENT_NUMBER,
3907       MERCHANT_NAME,
3908       MERCHANT_REFERENCE,
3909       MERCHANT_TAX_REG_NUMBER,
3910       MERCHANT_TAXPAYER_ID,
3911       COUNTRY_OF_SUPPLY,
3912       CREDIT_CARD_TRX_ID,
3913       COMPANY_PREPAID_INVOICE_ID,
3914       CC_REVERSAL_FLAG,
3915       CREATION_DATE,
3916       CREATED_BY,
3917       LAST_UPDATED_BY,
3918       LAST_UPDATE_DATE,
3919       LAST_UPDATE_LOGIN,
3920       PROGRAM_APPLICATION_ID,
3921       PROGRAM_ID,
3922       PROGRAM_UPDATE_DATE,
3923       REQUEST_ID,
3924       ATTRIBUTE_CATEGORY,
3925       ATTRIBUTE1,
3926       ATTRIBUTE2,
3927       ATTRIBUTE3,
3928       ATTRIBUTE4,
3929       ATTRIBUTE5,
3930       ATTRIBUTE6,
3931       ATTRIBUTE7,
3932       ATTRIBUTE8,
3933       ATTRIBUTE9,
3934       ATTRIBUTE10,
3935       ATTRIBUTE11,
3936       ATTRIBUTE12,
3937       ATTRIBUTE13,
3938       ATTRIBUTE14,
3939       ATTRIBUTE15,
3940       GLOBAL_ATTRIBUTE_CATEGORY,
3941       GLOBAL_ATTRIBUTE1,
3942       GLOBAL_ATTRIBUTE2,
3943       GLOBAL_ATTRIBUTE3,
3944       GLOBAL_ATTRIBUTE4,
3945       GLOBAL_ATTRIBUTE5,
3946       GLOBAL_ATTRIBUTE6,
3947       GLOBAL_ATTRIBUTE7,
3948       GLOBAL_ATTRIBUTE8,
3949       GLOBAL_ATTRIBUTE9,
3950       GLOBAL_ATTRIBUTE10,
3951       GLOBAL_ATTRIBUTE11,
3952       GLOBAL_ATTRIBUTE12,
3953       GLOBAL_ATTRIBUTE13,
3954       GLOBAL_ATTRIBUTE14,
3955       GLOBAL_ATTRIBUTE15,
3956       GLOBAL_ATTRIBUTE16,
3957       GLOBAL_ATTRIBUTE17,
3958       GLOBAL_ATTRIBUTE18,
3959       GLOBAL_ATTRIBUTE19,
3960       GLOBAL_ATTRIBUTE20,
3961       --ETAX: Invwkb, added included_tax_amount as modified the def
3962       --of ap_invoices_pkg.r_invoice_line_rec
3963       INCLUDED_TAX_AMOUNT,
3964       PRIMARY_INTENDED_USE,
3965       APPLICATION_ID,
3966       PRODUCT_TABLE,
3967       REFERENCE_KEY1,
3968       REFERENCE_KEY2,
3969       REFERENCE_KEY3,
3970       REFERENCE_KEY4,
3971       REFERENCE_KEY5,
3972       --bugfix:4674194
3973       SHIP_TO_LOCATION_ID,
3974       --bug7022001
3975       PAY_AWT_GROUP_ID
3976      FROM ap_invoice_lines_all
3977     WHERE invoice_id = X_invoice_id
3978       AND line_number = X_line_number;
3979 
3980 
3981   l_invoice_line_rec            AP_INVOICES_PKG.r_invoice_line_rec;
3982   l_invoice_attribute_rec       AP_UTILITIES_PKG.r_invoice_attribute_rec; --bug 8713737
3983 
3984   l_distribution_class
3985       AP_INVOICE_DISTRIBUTIONS.DISTRIBUTION_CLASS%TYPE;
3986   l_dist_ccid
3987       AP_INVOICE_DISTRIBUTIONS.DIST_CODE_COMBINATION_ID%TYPE;
3988   l_base_currency_code         AP_SYSTEM_PARAMETERS.BASE_CURRENCY_CODE%TYPE;
3989   l_chart_of_accounts_id       GL_SETS_OF_BOOKS.CHART_OF_ACCOUNTS_ID%TYPE;
3990   l_account_type               GL_CODE_COMBINATIONS.ACCOUNT_TYPE%TYPE;
3991   l_assets_tracking_flag
3992       AP_INVOICE_DISTRIBUTIONS.ASSETS_TRACKING_FLAG%TYPE;
3993   l_employee_id                AP_SUPPLIERS.EMPLOYEE_ID%TYPE;
3994   l_accounting_date            AP_INVOICE_LINES.ACCOUNTING_DATE%TYPE;
3995   l_open_gl_date               AP_INVOICE_LINES.ACCOUNTING_DATE%TYPE;
3996   l_open_period_name           AP_INVOICE_LINES.PERIOD_NAME%TYPE;
3997   user_id                      NUMBER;
3998   l_msg_application            VARCHAR2(25);
3999   l_msg_type                   VARCHAR2(25);
4000   l_msg_token1                 VARCHAR2(30);
4001   l_msg_token2                 VARCHAR2(30);
4002   l_msg_token3                 VARCHAR2(30);
4003   l_msg_count                  NUMBER;
4004   l_msg_data                   VARCHAR2(200); /*bug12612482 changed from 30 to 200*/
4005   l_billable_flag              VARCHAR2(25);
4006   l_pa_allows_overrides        VARCHAR2(1) := 'N';
4007   l_error_found                VARCHAR2(1) := 'N';
4008   l_existing_distributions     NUMBER := 0;
4009   l_unbuilt_flex               VARCHAR2(240):='';
4010   l_reason_unbuilt_flex        VARCHAR2(2000):='';
4011   current_calling_sequence     VARCHAR2(2000);
4012   debug_info                   VARCHAR2(2000);
4013   --bug 8980626, size should be 2000 as error messages are assigned to it
4014   debug_context                VARCHAR2(2000);
4015   l_dist_code_concat           VARCHAR2(2000);
4016   l_invoice_distribution_id
4017       ap_invoice_distributions.invoice_distribution_id%TYPE;
4018   l_invoice_type_lookup_code   ap_invoices_all.invoice_type_lookup_code%TYPE;
4019   l_sys_link_function          VARCHAR2(2); /* Bug 5102724 */
4020   l_web_parameter_id           number; --Bug5003249
4021   l_employee_ccid              number;
4022   l_message_text	       fnd_new_messages.message_text%type;
4023   l_copy_line_dff_flag         VARCHAR2(1); -- Bug 6837035
4024   l_copy_line_gdff_flag        VARCHAR2(1); -- Bug 8788072
4025 
4026   l_country_code               VARCHAR2(20);  --bug 9169915
4027 
4028   BEGIN
4029 
4030   --------------------------------------------------------------------------
4031   -- Step 1 - Update the calling sequence
4032   --------------------------------------------------------------------------
4033   current_calling_sequence :=
4034       'AP_INVOICE_DISTRIBUTIONS_PKG.insert_single_dist_from_line <-'||
4035       X_calling_sequence;
4036 
4037   --------------------------------------------------------------------------
4038   -- Step 2 - If calling module provided X_invoice_id / X_line_number, then
4039   -- we assume the calling module is not passing a line record.  Read the line
4040   -- record from the transaction tables.
4041   -------------------------------------------------------------------------
4042   debug_info := 'Verify line record';
4043   IF (X_invoice_id IS NOT NULL AND X_line_number IS NOT NULL) THEN
4044     BEGIN
4045       OPEN line_rec;
4046       FETCH line_rec INTO l_invoice_line_rec;
4047       IF (line_rec%NOTFOUND) THEN
4048         CLOSE line_rec;
4049         RAISE NO_DATA_FOUND;
4050       END IF;
4051       CLOSE line_Rec;
4052     EXCEPTION
4053       WHEN NO_DATA_FOUND THEN
4054         debug_info := debug_info ||': No valid line record was found.';
4055         X_debug_context := current_calling_sequence;
4056         X_debug_info := debug_info;
4057         return(FALSE);
4058     END;
4059   ELSE
4060     l_invoice_line_rec := X_invoice_lines_rec;
4061     IF (X_invoice_lines_rec.invoice_id IS NULL AND
4062         X_invoice_lines_rec.line_number is NULL ) THEN
4063       X_debug_info := debug_info || ': line not provided';
4064       X_debug_context := current_calling_sequence;
4065       RETURN (FALSE);
4066     END IF;
4067   END IF;
4068 
4069   ----------------------------------------------------------------------------
4070   -- Step 3 - Validate line does not contain other distributions
4071   ----------------------------------------------------------------------------
4072   IF (X_Validate_Info) then
4073     debug_info := 'Verify line does not contain distributions';
4074     BEGIN
4075       SELECT count(*)
4076       INTO l_existing_distributions
4077       FROM ap_invoice_distributions
4078      WHERE invoice_id = l_invoice_line_rec.invoice_id
4079        AND invoice_line_number = l_invoice_line_rec.line_number
4080 	   AND  rownum=1; --13507856 added the rownum condition to improve the performance
4081 
4082       IF (l_existing_distributions <> 0) then
4083         X_debug_info := debug_info || ': line already has distributions';
4084         X_debug_context := current_calling_sequence;
4085         RETURN(FALSE);
4086       END IF;
4087 
4088     EXCEPTION
4089       WHEN OTHERS THEN
4090       NULL;
4091     END;
4092   END IF; -- If calling module requested validation
4093 
4094   /* Bug  8713737 Begin */
4095   ---------------------------------------------------------------------------
4096   -- Step 3 b - Get the Invoice and Line DFF Info
4097   ---------------------------------------------------------------------------
4098   debug_info := 'Step 3 b - Get the Invoice and Line DFF Info';
4099   BEGIN
4100         select  attribute_category,
4101                 attribute1,
4102                 attribute2,
4103                 attribute3,
4104                 attribute4,
4105                 attribute5,
4106                 attribute6,
4107                 attribute7,
4108                 attribute8,
4109                 attribute9,
4110                 attribute10,
4111                 attribute11,
4112                 attribute12,
4113                 attribute13,
4114                 attribute14,
4115                 attribute15
4116         into    l_invoice_attribute_rec.attribute_category,
4117                 l_invoice_attribute_rec.attribute1,
4118                 l_invoice_attribute_rec.attribute2,
4119                 l_invoice_attribute_rec.attribute3,
4120                 l_invoice_attribute_rec.attribute4,
4121                 l_invoice_attribute_rec.attribute5,
4122                 l_invoice_attribute_rec.attribute6,
4123                 l_invoice_attribute_rec.attribute7,
4124                 l_invoice_attribute_rec.attribute8,
4125                 l_invoice_attribute_rec.attribute9,
4126                 l_invoice_attribute_rec.attribute10,
4127                 l_invoice_attribute_rec.attribute11,
4128                 l_invoice_attribute_rec.attribute12,
4129                 l_invoice_attribute_rec.attribute13,
4130                 l_invoice_attribute_rec.attribute14,
4131                 l_invoice_attribute_rec.attribute15
4132         from    ap_invoices
4133         where   invoice_id = l_invoice_line_rec.invoice_id;
4134   EXCEPTION
4135     WHEN NO_DATA_FOUND THEN
4136         debug_info := debug_info ||': Failed to fetch Invoice header DFF info.';
4137         X_debug_context := current_calling_sequence;
4138         X_debug_info := debug_info;
4139         return(FALSE);
4140   END;
4141     -- need to copy the line attributes to pass to PA APIs irrespective of
4142     -- whether these are copied to distribution or not.
4143 
4144     l_invoice_attribute_rec.line_attribute_category := l_invoice_line_rec.ATTRIBUTE_CATEGORY;
4145     l_invoice_attribute_rec.line_attribute1  := l_invoice_line_rec.ATTRIBUTE1 ;
4146     l_invoice_attribute_rec.line_attribute2  := l_invoice_line_rec.ATTRIBUTE2 ;
4147     l_invoice_attribute_rec.line_attribute3  := l_invoice_line_rec.ATTRIBUTE3 ;
4148     l_invoice_attribute_rec.line_attribute4  := l_invoice_line_rec.ATTRIBUTE4 ;
4149     l_invoice_attribute_rec.line_attribute5  := l_invoice_line_rec.ATTRIBUTE5 ;
4150     l_invoice_attribute_rec.line_attribute6  := l_invoice_line_rec.ATTRIBUTE6 ;
4151     l_invoice_attribute_rec.line_attribute7  := l_invoice_line_rec.ATTRIBUTE7 ;
4152     l_invoice_attribute_rec.line_attribute8  := l_invoice_line_rec.ATTRIBUTE8 ;
4153     l_invoice_attribute_rec.line_attribute9  := l_invoice_line_rec.ATTRIBUTE9 ;
4154     l_invoice_attribute_rec.line_attribute10 := l_invoice_line_rec.ATTRIBUTE10;
4155     l_invoice_attribute_rec.line_attribute11 := l_invoice_line_rec.ATTRIBUTE11;
4156     l_invoice_attribute_rec.line_attribute12 := l_invoice_line_rec.ATTRIBUTE12;
4157     l_invoice_attribute_rec.line_attribute13 := l_invoice_line_rec.ATTRIBUTE13;
4158     l_invoice_attribute_rec.line_attribute14 := l_invoice_line_rec.ATTRIBUTE14;
4159     l_invoice_attribute_rec.line_attribute15 := l_invoice_line_rec.ATTRIBUTE15;
4160   /* Bug  8713737 End */
4161 
4162   -- Bug 6837035 Retrieve the profile value to check if the DFF info should be
4163   -- copied onto distributions for imported lines.
4164   l_copy_line_dff_flag := NVL(fnd_profile.value('AP_COPY_INV_LINE_DFF'),'N');
4165   IF NVL(l_invoice_line_rec.line_source, 'DUMMY') <> 'IMPORTED' OR l_copy_line_dff_flag <> 'Y' THEN
4166     l_invoice_line_rec.ATTRIBUTE_CATEGORY := NULL;
4167     l_invoice_line_rec.ATTRIBUTE1 := NULL;
4168     l_invoice_line_rec.ATTRIBUTE2 := NULL;
4169     l_invoice_line_rec.ATTRIBUTE3 := NULL;
4170     l_invoice_line_rec.ATTRIBUTE4 := NULL;
4171     l_invoice_line_rec.ATTRIBUTE5 := NULL;
4172     l_invoice_line_rec.ATTRIBUTE6 := NULL;
4173     l_invoice_line_rec.ATTRIBUTE7 := NULL;
4174     l_invoice_line_rec.ATTRIBUTE8 := NULL;
4175     l_invoice_line_rec.ATTRIBUTE9 := NULL;
4176     l_invoice_line_rec.ATTRIBUTE10 := NULL;
4177     l_invoice_line_rec.ATTRIBUTE11 := NULL;
4178     l_invoice_line_rec.ATTRIBUTE12 := NULL;
4179     l_invoice_line_rec.ATTRIBUTE13 := NULL;
4180     l_invoice_line_rec.ATTRIBUTE14 := NULL;
4181     l_invoice_line_rec.ATTRIBUTE15 := NULL;
4182   END IF;
4183   -- Bug 6837035 End
4184 
4185   -- Bug 8788072 Start
4186   IF NVL(l_invoice_line_rec.line_source, 'DUMMY') = 'IMPORTED' THEN
4187     IF jg_globe_flex_val.Gdf_Context_Exists(l_invoice_line_rec.GLOBAL_ATTRIBUTE_CATEGORY) THEN
4188         l_copy_line_gdff_flag:='Y';
4189     ELSE
4190         l_copy_line_gdff_flag:='N';
4191     END IF;
4192   END IF;
4193   -- Bug 8788072 End
4194 
4195   ----------------------------------------------------------------------------
4196   -- Step 4 - Get GL Date and Period name.  Only if not called from the
4197   -- Open interface since Validation of the Import already verifies gl date
4198   -- nd period.
4199   ----------------------------------------------------------------------------
4200   IF (nvl(X_line_source, 'OTHERS') <> 'IMPORT') then
4201     debug_info := 'Get gl date from open period if line gl date is in' ||
4202                   'a closed one';
4203     BEGIN
4204       l_open_period_name := NULL;
4205 
4206       l_open_period_name :=
4207         AP_UTILITIES_PKG.GET_CURRENT_GL_DATE(
4208                 l_invoice_line_rec.accounting_date,
4209 	        l_invoice_line_rec.org_id);
4210 
4211       IF (l_open_period_name is NULL) then
4212         AP_UTILITIES_PKG.GET_OPEN_GL_DATE(l_invoice_line_rec.accounting_date,
4213                                           l_open_period_name,
4214                                           l_open_gl_date);
4215       --Invoice Lines: Distributions
4216       --For the case when the accounting_date on the line fell in an open
4217       --period, we were trying to insert NULL into a NOT NULL column
4218       --accounting_date, since the variable l_open_gl_date was not being
4219       --populated properly.
4220       ELSE
4221         l_open_gl_date := l_invoice_line_rec.accounting_date;
4222       END IF;
4223       IF (l_open_period_name is NULL) then
4224         X_error_code := 'AP_NO_OPEN_PERIOD';
4225         RETURN(FALSE);
4226       END IF;
4227     END;
4228   ELSE
4229     l_open_period_name := l_invoice_line_rec.period_name;
4230     l_open_gl_date := l_invoice_line_rec.accounting_date;
4231   END IF;
4232 
4233   --------------------------------------------------------------
4234   -- Step 5 - Get system level information necessary for
4235   -- validation and generation of distributions
4236   --------------------------------------------------------------
4237   debug_info := 'Get system information';
4238   BEGIN
4239     SELECT gsob.chart_of_accounts_id, ap.base_currency_code
4240       INTO l_chart_of_accounts_id, l_base_currency_code
4241       FROM ap_system_parameters ap, gl_sets_of_books gsob
4242      WHERE ap.set_of_books_id = gsob.set_of_books_id
4243        AND ap.set_of_books_id = l_invoice_line_rec.set_of_books_id
4244        AND ap.org_id = l_invoice_line_rec.org_id; -- Bug 13858818.
4245 
4246   EXCEPTION
4247     WHEN NO_DATA_FOUND THEN
4248       Debug_info := debug_info || ': No GL information was found';
4249       X_debug_context := current_calling_sequence;
4250       X_debug_info := debug_info;
4251     RETURN(FALSE);
4252   END;
4253 
4254 
4255   ----------------------------------------------------------------------------
4256   -- Step 6 - Get Expenditure Item Date if PA related and if validation
4257   -- requested validate PA information. Note that expenditure item date may
4258   -- already be populated when the process is called from the Interface Import
4259   -- in which case we bypass getting the expenditure item date.
4260 
4261   ----------------------------------------------------------------------------
4262   debug_info := 'Get expenditure item date and validate if PA related';
4263   IF (l_invoice_line_rec.project_id is not null) then
4264     IF (l_invoice_line_rec.expenditure_item_date is null) then
4265       l_invoice_line_rec.expenditure_item_date :=
4266            AP_INVOICES_PKG.get_expenditure_item_date(
4267                                          l_invoice_line_rec.invoice_id,
4268                                          X_invoice_date,
4269                                          l_open_GL_date,
4270                                          NULL,
4271                                          NULL,
4272                                          l_error_found);
4273       IF (l_error_found = 'Y') then
4274         Debug_info :=
4275           debug_info ||': cannot read expenditure item date information';
4276         X_debug_context := current_calling_sequence;
4277         X_debug_info := debug_info;
4278         RETURN(FALSE);
4279       END IF;
4280     END IF; -- Expenditure item date is null
4281     l_pa_allows_overrides :=
4282     FND_PROFILE.VALUE('PA_ALLOW_FLEXBUILDER_OVERRIDES');
4283 
4284     -- The Import process should make the call with X_Validate_Info  FALSE
4285     -- since The same validation should have been done in the Import Validation
4286 
4287     IF (X_validate_info) then
4288       user_id := to_number(FND_PROFILE.VALUE('USER_ID'));
4289 
4290       BEGIN
4291         SELECT employee_id
4292           INTO l_employee_id
4293           FROM ap_suppliers  /* bUg 4718054 */
4294          WHERE DECODE(SIGN(TO_DATE(TO_CHAR(START_DATE_ACTIVE,'DD-MM-YYYY'),
4295                'DD-MM-YYYY') - TO_DATE(TO_CHAR(SYSDATE,'DD-MM-YYYY'),'DD-MM-YYYY')),
4296                1, 'N', DECODE(SIGN(TO_DATE(TO_CHAR(END_DATE_ACTIVE ,'DD-MM-YYYY'),
4297                'DD-MM-YYYY') -  TO_DATE(TO_CHAR(SYSDATE,'DD-MM-YYYY'),'DD-MM-YYYY')),
4298                -1, 'N', 0, 'N', 'Y')) = 'Y'
4299            AND enabled_flag = 'Y'
4300            AND vendor_id = X_vendor_id;
4301       EXCEPTION
4302         WHEN no_data_found then
4303           l_employee_id := NULL;
4304         WHEN OTHERS then
4305           l_employee_id := NULL;
4306       END;
4307 
4308 --bug5003249
4309      Begin
4310         select default_code_comb_id
4311         into  l_employee_ccid
4312         from  PER_ASSIGNMENTS_F
4313         where person_id =  l_employee_id
4314         and   set_of_books_id =  l_invoice_line_rec.set_of_books_id
4315         and   trunc(sysdate) BETWEEN trunc(effective_start_date)
4316         and   nvl(trunc(effective_end_date), trunc(sysdate));
4317      EXCEPTION
4318          WHEN OTHERS then
4319           l_employee_ccid := NULL;
4320      End;
4321 
4322         select WEB_PARAMETER_ID
4323         into  l_web_parameter_id
4324         from  ap_invoice_lines
4325         where invoice_id = X_invoice_id
4326         AND line_number = X_line_number;
4327 
4328       /* Bug 5102724 */
4329       BEGIN
4330         SELECT invoice_type_lookup_code
4331         INTO   l_invoice_type_lookup_code
4332         FROM   ap_invoices_all
4333         WHERE  invoice_id = X_invoice_id;
4334       EXCEPTION
4335         WHEN no_data_found then
4336           NULL;
4337         WHEN OTHERS then
4338           NULL;
4339       END;
4340 
4341       If (l_invoice_type_lookup_code ='EXPENSE REPORT') Then
4342         l_sys_link_function :='ER' ;
4343       Else
4344         l_sys_link_function :='VI' ;
4345       End if;
4346 
4347 
4348     debug_info := 'Validate PA related information';
4349       PA_TRANSACTIONS_PUB.VALIDATE_TRANSACTION(
4350                     X_PROJECT_ID          => l_invoice_line_rec.project_id,
4351                     X_TASK_ID             => l_invoice_line_rec.task_id,
4352                     X_EI_DATE             => l_invoice_line_rec.expenditure_item_date,
4353                     X_EXPENDITURE_TYPE    => l_invoice_line_rec.expenditure_type,
4354                     X_NON_LABOR_RESOURCE  => null,
4355                     X_PERSON_ID           => l_employee_id,
4356                     X_QUANTITY            => nvl(l_invoice_line_rec.pa_quantity, '1'),
4357                     X_denom_currency_code => X_invoice_currency,
4358                     X_acct_currency_code  => l_base_currency_code,
4359                     X_denom_raw_cost      => l_invoice_line_rec.amount,
4360                     X_acct_raw_cost       => l_invoice_line_rec.base_amount,
4361                     X_acct_rate_type      => X_exchange_rate_type,
4362                     X_acct_rate_date      => X_exchange_date,
4363                     X_acct_exchange_rate  => X_exchange_rate,
4364                     X_TRANSFER_EI         => null,
4365                     X_INCURRED_BY_ORG_ID  => l_invoice_line_rec.expenditure_organization_id,
4366                     X_NL_RESOURCE_ORG_ID  => null,
4367                     X_TRANSACTION_SOURCE  => l_sys_link_function, /*bug 5102724 */
4368                     X_CALLING_MODULE      => 'apiindib.pls',
4369                     X_VENDOR_ID           => X_vendor_id,
4370                     X_ENTERED_BY_USER_ID  => user_id,
4371                     -- Bug 6837035 Start
4372                     X_ATTRIBUTE_CATEGORY  => l_invoice_line_rec.ATTRIBUTE_CATEGORY,
4373                     X_ATTRIBUTE1          => l_invoice_line_rec.ATTRIBUTE1,
4374                     X_ATTRIBUTE2          => l_invoice_line_rec.ATTRIBUTE2,
4375                     X_ATTRIBUTE3          => l_invoice_line_rec.ATTRIBUTE3,
4376                     X_ATTRIBUTE4          => l_invoice_line_rec.ATTRIBUTE4,
4377                     X_ATTRIBUTE5          => l_invoice_line_rec.ATTRIBUTE5,
4378                     X_ATTRIBUTE6          => l_invoice_line_rec.ATTRIBUTE6,
4379                     X_ATTRIBUTE7          => l_invoice_line_rec.ATTRIBUTE7,
4380                     X_ATTRIBUTE8          => l_invoice_line_rec.ATTRIBUTE8,
4381                     X_ATTRIBUTE9          => l_invoice_line_rec.ATTRIBUTE9,
4382                     X_ATTRIBUTE10         => l_invoice_line_rec.ATTRIBUTE10,
4383                     X_ATTRIBUTE11         => l_invoice_line_rec.ATTRIBUTE11,
4384                     X_ATTRIBUTE12         => l_invoice_line_rec.ATTRIBUTE12,
4385                     X_ATTRIBUTE13         => l_invoice_line_rec.ATTRIBUTE13,
4386                     X_ATTRIBUTE14         => l_invoice_line_rec.ATTRIBUTE14,
4387                     X_ATTRIBUTE15         => l_invoice_line_rec.ATTRIBUTE15,
4388                     -- Bug 6837035 End
4389                     X_msg_application     => l_msg_application,
4390                     X_msg_type            => l_msg_type,
4391                     X_msg_token1          => l_msg_token1,
4392                     X_msg_token2          => l_msg_token2,
4393                     X_msg_token3          => l_msg_token3,
4394                     X_msg_count           => l_msg_count,
4395                     X_msg_data            => l_msg_data,
4396                     X_BILLABLE_FLAG       => l_billable_flag);
4397         IF (l_msg_data is not null) THEN
4398           X_msg_application := l_msg_application;
4399           X_msg_data := l_msg_data;
4400 	  --bugfix:5725904
4401 	  Fnd_Message.Set_Name(l_msg_application, l_msg_data);
4402 	  /*bug 6682104 setting the token values*/
4403             IF (l_msg_token1 IS NOT NULL) THEN
4404 	       fnd_message.set_token('PATC_MSG_TOKEN1',l_msg_token1);
4405             ELSE
4406 	       fnd_message.set_token('PATC_MSG_TOKEN1',FND_API.G_MISS_CHAR);
4407 	    END IF;
4408 
4409             IF (l_msg_token2 IS NOT NULL) THEN
4410 	        fnd_message.set_token('PATC_MSG_TOKEN2',l_msg_token2);
4411             ELSE
4412 	       fnd_message.set_token('PATC_MSG_TOKEN2',FND_API.G_MISS_CHAR);
4413             END IF;
4414 
4415             IF (l_msg_token3 IS NOT NULL) THEN
4416 	         fnd_message.set_token('PATC_MSG_TOKEN3',l_msg_token3);
4417             ELSE
4418 	          fnd_message.set_token('PATC_MSG_TOKEN3',FND_API.G_MISS_CHAR);
4419             END IF;
4420 	  l_message_text := Fnd_Message.get;
4421 	  X_Error_Code := l_message_text;
4422 
4423           return(FALSE);
4424         END IF;
4425       END IF; -- X_validate_info is TRUE
4426     END IF; --l_project_id is not null
4427 
4428   ----------------------------------------------------------------------------
4429   -- Step 7 - Obtain final account and account related information.
4430   -- But only if calling module is not the Import since through the import
4431   -- The account should already be built.
4432   ----------------------------------------------------------------------------
4433   debug_info := 'Obtain account to be used in distribution';
4434   IF (nvl(X_line_source, 'OTHERS') <> 'IMPORT') then
4435     --Bug5003249 added condition on invoice type lookup code
4436 
4437     IF (l_invoice_line_rec.project_id is not null
4438         and l_invoice_type_lookup_code<>'PREPAYMENT') then
4439       -- Need to create a utility to flexbuild.  Look at import code.  Utility
4440       -- there is PA_FLEXBUILD
4441 
4442       debug_info := 'Billable Flag To PA FlexBuild '||l_billable_flag; --Bug6523162
4443 
4444       IF ( NOT (AP_UTILITIES_PKG.pa_flexbuild(
4445                     p_vendor_id                 => X_vendor_id,          --IN
4446                     p_employee_id               => l_employee_id,        --IN
4447                     p_set_of_books_id           =>
4448                       l_invoice_line_rec.set_of_books_id,                --IN
4449                     p_chart_of_accounts_id      =>
4450                       l_chart_of_accounts_id,                            --IN
4451                     p_base_currency_code        => l_base_currency_code, --IN
4452                     p_accounting_date           => l_open_GL_date,       --IN
4453                     p_award_id                  =>
4454                       l_invoice_line_rec.award_id,                       --IN
4455                     P_project_id                =>
4456                       l_invoice_line_rec.project_id,                     --IN
4457                     p_task_id                   =>
4458                       l_invoice_line_rec.task_id,                        --IN
4459                     p_expenditure_type          =>
4460                       l_invoice_line_rec.expenditure_type,
4461                     p_expenditure_org_id        =>
4462                       l_invoice_line_rec.expenditure_organization_id,
4463                     p_expenditure_item_date     =>
4464                       l_invoice_line_rec.expenditure_item_date,
4465                     p_invoice_attribute_rec     => l_invoice_attribute_rec, --bug 8713737
4466                     p_billable_flag             => l_billable_flag, --Bug6523162
4467                     p_employee_ccid             =>
4468                       l_employee_ccid,   --Bug5003249
4469                     p_web_parameter_id          =>
4470                       l_web_parameter_id,   --Bug5003249
4471                     p_invoice_type_lookup_code  =>
4472                       l_invoice_type_lookup_code, --Bug5003249
4473                     p_default_last_updated_by   => FND_GLOBAL.user_id,
4474                     p_default_last_update_login => FND_GLOBAL.login_id,
4475                     p_pa_default_dist_ccid      => l_dist_ccid,
4476                     p_pa_concatenated_segments  =>
4477                       l_dist_code_concat,                         --OUT NOCOPY
4478                     p_debug_Info                => debug_Info,    --OUT NOCOPY
4479                     p_debug_Context             => debug_Context, --OUT NOCOPY
4480                     p_calling_sequence          =>
4481                       'Get_Proj_And_Acc_For_Chrg_Dist' ,
4482                    p_default_dist_ccid         =>   l_invoice_line_rec.default_dist_ccid --IN bug 5386396
4483                   ))) THEN
4484         X_error_code := debug_Info; --Bug7598450
4485         debug_info := debug_info || ': Error encountered';
4486         debug_context := current_calling_sequence;
4487         RETURN(FALSE);
4488       END IF;
4489 
4490       IF (l_pa_allows_overrides = 'N') then
4491         IF ( NOT (AP_UTILITIES_PKG.IS_CCID_VALID(
4492                     l_dist_ccid,
4493                     l_chart_of_accounts_id,
4494                     l_open_gl_date,
4495                     current_calling_sequence))) then
4496           X_error_code := 'AP_INVALID_ACCOUNT';
4497           RETURN(FALSE);
4498         END IF;
4499       ELSE -- pa allows overrides is Y
4500         -- If the user provided an account at the line level,
4501         --  use it instead of the Account produced by PA
4502         IF (l_invoice_line_rec.default_dist_ccid is not null) then
4503          l_dist_ccid := l_invoice_line_rec.default_dist_ccid;
4504         END IF;
4505         IF (l_invoice_line_rec.overlay_dist_code_concat is NULL AND
4506             l_invoice_line_rec.balancing_segment is NULL AND
4507             l_invoice_line_rec.account_segment is NULL AND
4508             l_invoice_line_rec.cost_center_segment is NULL) then
4509           IF ( NOT (AP_UTILITIES_PKG.IS_CCID_VALID(
4510                        l_dist_ccid,
4511                        l_chart_of_accounts_id,
4512                        l_open_gl_date,
4513                        current_calling_sequence))) then
4514             X_error_code := 'AP_INVALID_ACCOUNT';
4515             RETURN(FALSE);
4516           END IF;
4517         ELSE
4518           IF ( NOT (AP_UTILITIES_PKG.OVERLAY_SEGMENTS (
4519                     l_invoice_line_rec.balancing_segment,
4520                     l_invoice_line_rec.cost_center_segment,
4521                     l_invoice_line_rec.account_segment,
4522                     l_invoice_line_rec.overlay_dist_code_concat,
4523                     l_dist_ccid,
4524                     l_invoice_line_rec.set_of_books_id,
4525                     'CREATE_COMB_NO_AT',
4526                     l_unbuilt_flex,
4527                     l_reason_unbuilt_flex,
4528                     FND_GLOBAL.RESP_APPL_ID,
4529                     FND_GLOBAL.RESP_ID,
4530                     FND_GLOBAL.USER_ID,
4531                     current_calling_sequence,
4532                     NULL,
4533                     l_open_gl_date))) THEN -- 7531219
4534             X_error_code := 'AP_CANNOT_OVERLAY';
4535             RETURN(FALSE);
4536           END IF;
4537         END IF; -- overlay information is null
4538       END IF; -- pa allows overrides
4539     ELSE -- project id is null
4540 
4541       l_dist_ccid := l_invoice_line_rec.default_dist_ccid;
4542       IF (l_invoice_line_rec.overlay_dist_code_concat is NULL AND
4543           l_invoice_line_rec.balancing_segment is NULL AND
4544           l_invoice_line_rec.account_segment is NULL AND
4545           l_invoice_line_rec.cost_center_segment is NULL) then
4546         IF ( NOT (AP_UTILITIES_PKG.IS_CCID_VALID(
4547                      l_dist_ccid,
4548                      l_chart_of_accounts_id,
4549                      l_open_gl_date,
4550                      current_calling_sequence))) THEN
4551           X_error_code := 'AP_INVALID_ACCOUNT';
4552           RETURN(FALSE);
4553         END IF;
4554       ELSE
4555         IF ( NOT (AP_UTILITIES_PKG.OVERLAY_SEGMENTS (
4556                     l_invoice_line_rec.balancing_segment,
4557                     l_invoice_line_rec.cost_center_segment,
4558                     l_invoice_line_rec.account_segment,
4559                     l_invoice_line_rec.overlay_dist_code_concat,
4560                     l_dist_ccid,
4561                     l_invoice_line_rec.set_of_books_id,
4562                     'CREATE_COMB_NO_AT',
4563                     l_unbuilt_flex,
4564                     l_reason_unbuilt_flex,
4565                     FND_GLOBAL.RESP_APPL_ID,
4566                     FND_GLOBAL.RESP_ID,
4567                     FND_GLOBAL.USER_ID,
4568                     current_calling_sequence,
4569                     NULL,
4570                     l_open_gl_date))) then --7531219
4571           X_error_code := 'AP_CANNOT_OVERLAY';
4572           RETURN(FALSE);
4573         END IF;
4574       END IF; -- overlay information is null
4575     END IF; -- project id is null
4576 
4577     IF (l_invoice_line_rec.project_id is not null) THEN
4578 
4579 	GMS_AP_API.validate_transaction
4580 			( x_project_id		  => l_invoice_line_rec.project_id,
4581 			  x_task_id		  => l_invoice_line_rec.task_id,
4582 			  x_award_id		  => l_invoice_line_rec.award_id,
4583 			  x_expenditure_type	  => l_invoice_line_rec.expenditure_type,
4584 			  x_expenditure_item_date => l_invoice_line_rec.expenditure_item_date,
4585 			  x_calling_sequence	  => 'AWARD_ID',
4586 			  x_msg_application       => l_msg_application,
4587 			  x_msg_type              => l_msg_type,
4588 			  x_msg_count             => l_msg_count,
4589 			  x_msg_data              => l_msg_data ) ;
4590 
4591 	IF (l_msg_data is not null) THEN
4592 	    x_msg_application := l_msg_application;
4593 	    x_msg_data := l_msg_data;
4594 	    X_error_code := X_msg_data;  -- bug 7936518
4595 	    return(FALSE);
4596 	END IF;
4597     END IF ;
4598 
4599   ELSE
4600 
4601     -- Need to assign the value from the pass in record
4602     l_dist_ccid := l_invoice_line_rec.default_dist_ccid;
4603 
4604   END IF; -- Calling module is other than the IMPORT
4605 
4606 
4607   ---------------------------------------------------------------------------
4608   -- Step 8 - Get account type.
4609   ---------------------------------------------------------------------------
4610   debug_info := 'Get account type for ccid' || l_dist_ccid;
4611     BEGIN
4612     SELECT account_type
4613       INTO l_account_type
4614       FROM gl_code_combinations
4615      WHERE code_combination_id = l_dist_ccid;
4616 
4617   EXCEPTION
4618     When no_data_found THEN
4619        Debug_info := debug_info || ': cannot read account type information';
4620        X_debug_context := current_calling_sequence;
4621        X_debug_info := debug_info;
4622        RETURN(FALSE);
4623   END;
4624   -- Obtain the assets tracking flag given the account type
4625   IF (l_account_type = 'A' OR
4626       (l_account_type = 'E' AND
4627        l_invoice_line_rec.assets_tracking_flag = 'Y')) then
4628     l_assets_tracking_flag := 'Y';
4629   ELSE
4630     l_assets_tracking_flag := 'N';
4631   END IF;
4632 
4633   ----------------------------------------------------------------------------
4634   -- Step 9 - Set distribution class value (Permanent or Candidate)
4635   ----------------------------------------------------------------------------
4636   if (X_Generate_Permanent = 'N') then
4637     l_distribution_class := 'CANDIDATE';
4638   else
4639     l_distribution_class := 'PERMANENT';
4640   end if;
4641 
4642 
4643   ---------------------------------------------------------------------------
4644   -- ETAX: Invwkb
4645   -- Step 10 - Exclude the included_tax_amount from the line_amount before
4646   --	       creating a item distribution.
4647   ---------------------------------------------------------------------------
4648   --bug6653070
4649 
4650   /*l_invoice_line_rec.amount := l_invoice_line_rec.amount -
4651   				   NVL(l_invoice_line_rec.included_tax_amount,0);*/
4652   l_invoice_line_rec.base_amount := ap_utilities_pkg.ap_round_currency(
4653   					l_invoice_line_rec.amount * x_exchange_rate,
4654 					l_base_currency_code);
4655 
4656   ----------------------------------------------------------------------------
4657   -- Step 11 - Generate distributions
4658   ----------------------------------------------------------------------------
4659   BEGIN
4660 
4661     INSERT INTO ap_invoice_distributions(
4662               batch_id,
4663               invoice_id,
4664               invoice_line_number,
4665               invoice_distribution_id,
4666               distribution_line_number,
4667               line_type_lookup_code,
4668               distribution_class,
4669               description,
4670               dist_match_type,
4671               org_id,
4672               dist_code_combination_id,
4673               accounting_date,
4674               period_name,
4675               accrual_posted_flag,
4676               cash_posted_flag,
4677               amount_to_post,
4678               base_amount_to_post,
4679               posted_amount,
4680               posted_base_amount,
4681               posted_flag,
4682               accounting_event_id,
4683               upgrade_posted_amt,
4684               upgrade_base_posted_amt,
4685               set_of_books_id,
4686               amount,
4687               base_amount,
4688               rounding_amt,
4689               quantity_variance,
4690               base_quantity_variance,
4691               match_status_flag,
4692               encumbered_flag,
4693               packet_id,
4694               reversal_flag,
4695               parent_reversal_id,
4696               cancellation_flag,
4697               income_tax_region,
4698               type_1099,
4699               stat_amount,
4700               charge_applicable_to_dist_id,
4701               prepay_amount_remaining,
4702               prepay_distribution_id,
4703               parent_invoice_id,
4704               corrected_invoice_dist_id,
4705               corrected_quantity,
4706               other_invoice_id,
4707               po_distribution_id,
4708               rcv_transaction_id,
4709               unit_price,
4710               matched_uom_lookup_code,
4711               quantity_invoiced,
4712               final_match_flag,
4713               related_id,
4714               assets_addition_flag,
4715               assets_tracking_flag,
4716               asset_book_type_code,
4717               asset_category_id,
4718               project_id,
4719               task_id,
4720               expenditure_type,
4721               expenditure_item_date,
4722               expenditure_organization_id,
4723               pa_quantity,
4724               pa_addition_flag,
4725               award_id,
4726               gms_burdenable_raw_cost,
4727               awt_flag,
4728               awt_group_id,
4729               awt_tax_rate_id,
4730               awt_gross_amount,
4731               awt_invoice_id,
4732               awt_origin_group_id,
4733               awt_invoice_payment_id,
4734               awt_withheld_amt,
4735               inventory_transfer_status,
4736               reference_1,
4737               reference_2,
4738               receipt_verified_flag,
4739               receipt_required_flag,
4740               receipt_missing_flag,
4741               justification,
4742               expense_group,
4743               start_expense_date,
4744               end_expense_date,
4745               receipt_currency_code,
4746               receipt_conversion_rate,
4747               receipt_currency_amount,
4748               daily_amount,
4749               web_parameter_id,
4750               adjustment_reason,
4751               merchant_document_number,
4752               merchant_name,
4753               merchant_reference,
4754               merchant_tax_reg_number,
4755               merchant_taxpayer_id,
4756               country_of_supply,
4757               credit_card_trx_id,
4758               company_prepaid_invoice_id,
4759               cc_reversal_flag,
4760               attribute_category,
4761               attribute1,
4762               attribute2,
4763               attribute3,
4764               attribute4,
4765               attribute5,
4766               attribute6,
4767               attribute7,
4768               attribute8,
4769               attribute9,
4770               attribute10,
4771               attribute11,
4772               attribute12,
4773               attribute13,
4774               attribute14,
4775               attribute15,
4776               global_attribute_category,
4777               global_attribute1,
4778               global_attribute2,
4779               global_attribute3,
4780               global_attribute4,
4781               global_attribute5,
4782               global_attribute6,
4783               global_attribute7,
4784               global_attribute8,
4785               global_attribute9,
4786               global_attribute10,
4787               global_attribute11,
4788               global_attribute12,
4789               global_attribute13,
4790               global_attribute14,
4791               global_attribute15,
4792               global_attribute16,
4793               global_attribute17,
4794               global_attribute18,
4795               global_attribute19,
4796               global_attribute20,
4797               created_by,
4798               creation_date,
4799               last_updated_by,
4800               last_update_date,
4801               last_update_login,
4802               program_application_id,
4803               program_id,
4804               program_update_date,
4805               request_id,
4806 	      --ETAX: Invwkb
4807 	      intended_use,
4808 	      --Freight and Special Charges
4809 	      rcv_charge_addition_flag,
4810 	      --bug7022001
4811 	      pay_awt_group_id)
4812     VALUES  (X_batch_id,                          -- batch_id
4813             l_invoice_line_rec.invoice_id,        -- invoice_id
4814             l_invoice_line_rec.line_number,       -- invoice_line_number
4815             ap_invoice_distributions_s.nextval,   -- invoice_distribution_id
4816             1,                                    -- distribution_line_number
4817             l_invoice_line_rec.line_type_lookup_code,  -- line_type_lookup_code
4818             l_distribution_class,                 -- distribution_class
4819             l_invoice_line_rec.description,       -- description
4820             'NOT_MATCHED',                        -- dist_match_type
4821             l_invoice_line_rec.org_id,            -- l_org_id
4822             l_dist_ccid,                          -- dist_code_combination_id
4823             l_open_gl_date,                       -- accounting_date
4824             l_open_period_name,                   -- period_name
4825             'N',                                  -- accrual_posted_flag
4826             'N',                                  -- cash_posted_flag
4827             NULL,                                 -- amount_to_post
4828             NULL,                                 -- base_amount_to_post
4829             NULL,                                 -- posted_amount
4830             NULL,                                 -- posted_base_amount
4831             'N',                                  -- posted_flag
4832             NULL,                                 -- accounting_event_id
4833             NULL,                                 -- upgrade_posted_amt
4834             NULL,                                 -- upgrade_base_posted_amt
4835             l_invoice_line_rec.set_of_books_id,   -- set_of_books_id
4836             l_invoice_line_rec.amount,            -- amount
4837             l_invoice_line_rec.base_amount,       -- base_amount
4838             l_invoice_line_rec.rounding_amt,      -- rounding_amt
4839             NULL,                                 -- quantity_variance
4840             NULL,                                 -- base_quantity_variance
4841 	    --Invoice Lines: Distributions, changed match_status_flag
4842             --to NULL from 'N'.
4843             NULl,                                 -- match_status_flag
4844             'N',                                  -- encumbered_flag
4845             NULL,                                 -- packet_id
4846          -- decode(l_invoice_line_rec.line_type_lookup_code,
4847             'N',                                  -- reversal_flag
4848             NULL,                                 -- parent_reversal_id
4849             'N',                                  -- cancellation_flag
4850             decode(l_invoice_line_rec.type_1099,null,null,
4851                   l_invoice_line_rec.income_tax_region),  -- income_tax_region
4852             l_invoice_line_rec.type_1099,         -- type_1099
4853             --Introduce below value for bug#10241241
4854 	    DECODE(GET_UOM(l_dist_ccid,l_chart_of_accounts_id),
4855                    NULL,NULL,
4856                    l_invoice_line_rec.stat_amount), --stat_amount
4857             NULL,                                 -- charge_applicable_to_dist_id
4858             NULL,                                 -- prepay_amount_remaining
4859             NULL,                                 -- prepay_distribution_id
4860             NULL,                                 -- parent_invoice_id
4861             NULL,                                 -- corrected_inv_dist_id
4862             NULL,                                 -- corrected_quantity
4863             NULL,                                 -- other_invoice_id
4864             NULL,                                 -- po_distribution_id
4865             NULL,                                 -- rcv_transaction_id
4866             NULL,                                 -- unit_price
4867             NULL,                                 -- matched_uom_lookup_code
4868             NULL,                                 -- quantity_invoiced
4869             NULL,                                 -- final_match_flag
4870             NULL,                                 -- related_id
4871             'U',                                  -- assets_addition_flag
4872             l_assets_tracking_flag,               -- assets_tracking_flag
4873             decode(l_assets_tracking_flag,'Y',
4874                  l_invoice_line_rec.asset_book_type_code, NULL),-- asset_book_type_code
4875             decode(l_assets_tracking_flag,'Y',
4876                     l_invoice_line_rec.asset_category_id, NULL),-- asset_category_id
4877             l_invoice_line_rec.project_id,                           -- project_id
4878             l_invoice_line_rec.task_id,                              -- task_id
4879             l_invoice_line_rec.expenditure_type,                     -- expenditure_type
4880             l_invoice_line_rec.expenditure_item_date,              -- expenditure_item_date
4881             l_invoice_line_rec.expenditure_organization_id,          -- expenditure_organization_id
4882             l_invoice_line_rec.pa_quantity,       -- pa_quantity
4883             decode(l_invoice_line_rec.project_id,NULL,'E', 'N'),     -- pa_addition_flag
4884             l_invoice_line_rec.award_id,                             -- award_id
4885             NULL,                                 -- gms_burdenable_raw_cost
4886             /*Added the following decode for bug#7695497 Start */
4887             decode(l_invoice_line_rec.line_type_lookup_code,
4888 	           'AWT', decode(l_invoice_line_rec.line_source ,'MANUAL LINE ENTRY','M', NULL),
4889 	           NULL),                                            -- awt_flag
4890             /*Added the above decode for bug#7695497 End */
4891             l_invoice_line_rec.awt_group_id,                         -- awt_group_id
4892             NULL,                                 -- awt_tax_rate_id
4893             NULL,                                 -- awt_gross_amount
4894             NULL,                                 -- awt_invoice_id
4895             NULL,                                 -- awt_origin_group_id
4896             NULL,                                 -- awt_invoice_payment_id
4897             NULL,                                 -- awt_withheld_amt
4898             'N',                                  -- inventory_transfer_status
4899 	    --Bug9296445
4900             l_invoice_line_rec.reference_1,       --NULL,   -- reference_1
4901             l_invoice_line_rec.reference_2,       --NULL,   -- reference_2
4902             NULL,                                 -- receipt_verified_flag
4903             NULL,                                 -- receipt_required_flag
4904             NULL,                                 -- receipt_missing_flag
4905             NULL,                                 -- justification
4906             NULL,                                 -- expense_group
4907             NULL,                                 -- start_expense_date
4908             NULL,                                 -- end_expense_date
4909             NULL,                                 -- receipt_currency_code
4910             NULL,                                 -- receipt_conversion_rate
4911             NULL,                                 -- receipt_currency_amount
4912             NULL,                                 -- daily_amount
4913             NULL,                                 -- web_parameter_id
4914             NULL,                                 -- adjustment_reason
4915             l_invoice_line_rec.merchant_document_number,  -- merchant_document_number --bug14335065 added merchant fields
4916             l_invoice_line_rec.merchant_name,             -- merchant_name
4917             l_invoice_line_rec.merchant_reference,        -- merchant_reference
4918             l_invoice_line_rec.merchant_tax_reg_number,   -- merchant_tax_reg_number
4919             l_invoice_line_rec.merchant_taxpayer_id,      -- merchant_taxpayer_id
4920             NULL,                                 -- country_of_supply
4921             NULL,                                 -- credit_card_trx_id
4922             NULL,                                 -- company_prepaid_invoice_id
4923             NULL,                                 -- cc_reversal_flag
4924             -- Bug 6837035 Start
4925             l_invoice_line_rec.attribute_category,-- attribute_category
4926             l_invoice_line_rec.attribute1,        -- attribute1
4927             l_invoice_line_rec.attribute2,        -- attribute2
4928             l_invoice_line_rec.attribute3,        -- attribute3
4929             l_invoice_line_rec.attribute4,        -- attribute4
4930             l_invoice_line_rec.attribute5,        -- attribute5
4931             l_invoice_line_rec.attribute6,        -- attribute6
4932             l_invoice_line_rec.attribute7,        -- attribute7
4933             l_invoice_line_rec.attribute8,        -- attribute8
4934             l_invoice_line_rec.attribute9,        -- attribute9
4935             l_invoice_line_rec.attribute10,        -- attribute10
4936             l_invoice_line_rec.attribute11,        -- attribute11
4937             l_invoice_line_rec.attribute12,        -- attribute12
4938             l_invoice_line_rec.attribute13,        -- attribute13
4939             l_invoice_line_rec.attribute14,        -- attribute14
4940             l_invoice_line_rec.attribute15,        -- attribute15
4941             -- Bug 6837035 End
4942             /* bug 8788072 changed from Null to decode */
4943             DECODE(l_copy_line_gdff_flag, 'Y', l_invoice_line_rec.global_attribute_category, NULL), -- global_attribute_category
4944             DECODE(l_copy_line_gdff_flag, 'Y', l_invoice_line_rec.global_attribute1, NULL), -- global_attribute1
4945             DECODE(l_copy_line_gdff_flag, 'Y', l_invoice_line_rec.global_attribute2, NULL), -- global_attribute2
4946 	    --bugfix:4674194
4947 	    Decode(AP_EXTENDED_WITHHOLDING_PKG.AP_EXTENDED_WITHHOLDING_OPTION,
4948 	           'Y',l_invoice_line_rec.ship_to_location_id,
4949             DECODE(l_copy_line_gdff_flag, 'Y', l_invoice_line_rec.global_attribute3, NULL)), --global_attribute3
4950             DECODE(l_copy_line_gdff_flag, 'Y', l_invoice_line_rec.global_attribute4, NULL), -- global_attribute4
4951             DECODE(l_copy_line_gdff_flag, 'Y', l_invoice_line_rec.global_attribute5, NULL), -- global_attribute5
4952             DECODE(l_copy_line_gdff_flag, 'Y', l_invoice_line_rec.global_attribute6, NULL), -- global_attribute6
4953             DECODE(l_copy_line_gdff_flag, 'Y', l_invoice_line_rec.global_attribute7, NULL), -- global_attribute7
4954             DECODE(l_copy_line_gdff_flag, 'Y', l_invoice_line_rec.global_attribute8, NULL), -- global_attribute8
4955             DECODE(l_copy_line_gdff_flag, 'Y', l_invoice_line_rec.global_attribute9, NULL), -- global_attribute9
4956             DECODE(l_copy_line_gdff_flag, 'Y', l_invoice_line_rec.global_attribute10, NULL), -- global_attribute10
4957             DECODE(l_copy_line_gdff_flag, 'Y', l_invoice_line_rec.global_attribute11, NULL), -- global_attribute11
4958             DECODE(l_copy_line_gdff_flag, 'Y', l_invoice_line_rec.global_attribute12, NULL), -- global_attribute12
4959             DECODE(l_copy_line_gdff_flag, 'Y', l_invoice_line_rec.global_attribute13, NULL), -- global_attribute13
4960             DECODE(l_copy_line_gdff_flag, 'Y', l_invoice_line_rec.global_attribute14, NULL), -- global_attribute14
4961             DECODE(l_copy_line_gdff_flag, 'Y', l_invoice_line_rec.global_attribute15, NULL), -- global_attribute15
4962             DECODE(l_copy_line_gdff_flag, 'Y', l_invoice_line_rec.global_attribute16, NULL), -- global_attribute16
4963             DECODE(l_copy_line_gdff_flag, 'Y', l_invoice_line_rec.global_attribute17, NULL), -- global_attribute17
4964             DECODE(l_copy_line_gdff_flag, 'Y', l_invoice_line_rec.global_attribute18, NULL), -- global_attribute18
4965             DECODE(l_copy_line_gdff_flag, 'Y', l_invoice_line_rec.global_attribute19, NULL), -- global_attribute19
4966             DECODE(l_copy_line_gdff_flag, 'Y', l_invoice_line_rec.global_attribute20, NULL), -- global_attribute20
4967             /* bug 8788072 */
4968             FND_GLOBAL.user_id,                   -- created_by
4969             SYSDATE,                              -- creation_date
4970             0,                                    -- last_updated_by
4971             SYSDATE,                              -- last_update_date
4972             FND_GLOBAL.login_id,                  -- last_update_login
4973             NULL,                                 -- program_application_id
4974             NULL,                                 -- program_id
4975             NULL,                                 -- program_update_date
4976             NULL,                                 -- request_id
4977 	    l_invoice_line_rec.primary_intended_use, -- intended_use
4978 	    'N',				  -- rcv_charge_addition_flag
4979             l_invoice_line_rec.pay_awt_group_id   --pay_awt_group_id  --bug7022001
4980 	    ) returning invoice_distribution_id into l_invoice_distribution_id;
4981 
4982 		   --bug 9169915 bug9737142
4983 		   SELECT JG_ZZ_SHARED_PKG.GET_COUNTRY(l_invoice_line_rec.org_id, null)
4984 			 INTO l_country_code
4985 			 FROM DUAL;
4986 
4987    		   IF l_country_code IN ('AR','CO') THEN
4988    	             JL_ZZ_AP_AWT_DEFAULT_PKG.SUPP_WH_DEF (l_invoice_line_rec.invoice_id,
4989 							l_invoice_line_rec.line_number,
4990 							l_invoice_distribution_id,
4991 							NULL);
4992                    END IF;
4993 	           --bug 9169915
4994 
4995 	    GMS_AP_API.CREATE_AWARD_DISTRIBUTIONS
4996 			( p_invoice_id		     => l_invoice_line_rec.invoice_id,
4997 			  p_distribution_line_number => 1,
4998 			  p_invoice_distribution_id  => l_invoice_distribution_id,
4999 			  p_award_id		     => l_invoice_line_rec.award_id,
5000 			  p_mode		     => 'AP',
5001 			  p_dist_set_id		     => NULL,
5002 			  p_dist_set_line_number     => NULL );
5003 
5004 
5005      EXCEPTION
5006       WHEN OTHERS THEN
5007         X_debug_info := debug_info || ': Error encountered during dist insert';
5008         X_debug_context := current_calling_sequence;
5009 	--Bugfix: 3859755, added the below stmt.
5010 	X_Error_Code := sqlerrm;
5011         return (FALSE);
5012     END;
5013 
5014     ----------------------------------------------------------------------------
5015   -- Step 10 - Update generate distributions flag in invoice line if generating
5016   -- permanent distributions.
5017   ----------------------------------------------------------------------------
5018   debug_info := 'Setting generate distributions flag to Done';
5019   IF (l_distribution_class = 'PERMANENT') then
5020     BEGIN
5021       UPDATE AP_INVOICE_LINES
5022          SET GENERATE_DISTS = 'D'
5023        WHERE invoice_id = X_invoice_id
5024          AND line_number = l_invoice_line_rec.line_number;
5025     EXCEPTION
5026       WHEN OTHERS THEN
5027         X_debug_info := debug_info || ': Error encountered';
5028         X_debug_context := current_calling_sequence;
5029         return (FALSE);
5030     END;
5031   END IF;
5032 
5033   RETURN(TRUE);
5034 
5035   EXCEPTION
5036     WHEN OTHERS THEN
5037     X_debug_info := 'Error encountered';
5038     X_debug_context := current_calling_sequence;
5039     RETURN (FALSE);
5040   END insert_single_dist_from_line;
5041 
5042 --Bug 8346277 Start
5043   -----------------------------------------------------------------------
5044   -- FUNCTION insert_AWT_dist_from_line inserts a record into
5045   -- ap_invoice_distributions given a line number number and/or line record.
5046   -- It returns FALSE if an error is encountered.
5047   -----------------------------------------------------------------------
5048 
5049 FUNCTION   Insert_AWT_Dist_From_Line(
5050            X_batch_id            IN         AP_INVOICES.BATCH_ID%TYPE,
5051            X_invoice_id          IN         NUMBER,
5052            X_invoice_date        IN         AP_INVOICES.INVOICE_DATE%TYPE,
5053            X_vendor_id           IN         AP_INVOICES.VENDOR_ID%TYPE,
5054            X_invoice_currency    IN         AP_INVOICES.INVOICE_CURRENCY_CODE%TYPE,
5055            X_exchange_rate       IN         AP_INVOICES.EXCHANGE_RATE%TYPE,
5056            X_exchange_rate_type  IN         AP_INVOICES.EXCHANGE_RATE_TYPE%TYPE,
5057            X_exchange_date       IN         AP_INVOICES.EXCHANGE_DATE%TYPE,
5058            X_line_number         IN         NUMBER,
5059            X_invoice_lines_rec   IN         AP_INVOICES_PKG.r_invoice_line_rec,
5060            X_line_source         IN         VARCHAR2,
5061            X_Generate_Permanent  IN         VARCHAR2 DEFAULT 'N',
5062            X_Validate_Info       IN         BOOLEAN DEFAULT TRUE,
5063            X_Error_Code          OUT NOCOPY VARCHAR2,
5064            X_Debug_Info          OUT NOCOPY VARCHAR2,
5065            X_Debug_Context       OUT NOCOPY VARCHAR2,
5066            X_Msg_Application     OUT NOCOPY VARCHAR2,
5067            X_Msg_Data            OUT NOCOPY VARCHAR2,
5068            X_Calling_Sequence    IN         VARCHAR2) RETURN BOOLEAN
5069    IS
5070 
5071 CURSOR line_rec IS
5072   SELECT INVOICE_ID
5073        , LINE_NUMBER
5074        , LINE_TYPE_LOOKUP_CODE
5075        , REQUESTER_ID
5076        , DESCRIPTION
5077        , LINE_SOURCE
5078        , ORG_ID
5079        , LINE_GROUP_NUMBER
5080        , INVENTORY_ITEM_ID
5081        , ITEM_DESCRIPTION
5082        , SERIAL_NUMBER
5083        , MANUFACTURER
5084        , MODEL_NUMBER
5085        , WARRANTY_NUMBER
5086        , GENERATE_DISTS
5087        , MATCH_TYPE
5088        , DISTRIBUTION_SET_ID
5089        , ACCOUNT_SEGMENT
5090        , BALANCING_SEGMENT
5091        , COST_CENTER_SEGMENT
5092        , OVERLAY_DIST_CODE_CONCAT
5093        , DEFAULT_DIST_CCID
5094        , PRORATE_ACROSS_ALL_ITEMS
5095        , ACCOUNTING_DATE
5096        , PERIOD_NAME
5097        , DEFERRED_ACCTG_FLAG
5098        , DEF_ACCTG_START_DATE
5099        , DEF_ACCTG_END_DATE
5100        , DEF_ACCTG_NUMBER_OF_PERIODS
5101        , DEF_ACCTG_PERIOD_TYPE
5102        , SET_OF_BOOKS_ID
5103        , AMOUNT
5104        , BASE_AMOUNT
5105        , ROUNDING_AMT
5106        , QUANTITY_INVOICED
5107        , UNIT_MEAS_LOOKUP_CODE
5108        , UNIT_PRICE
5109        , WFAPPROVAL_STATUS
5110        , DISCARDED_FLAG
5111        , ORIGINAL_AMOUNT
5112        , ORIGINAL_BASE_AMOUNT
5113        , ORIGINAL_ROUNDING_AMT
5114        , CANCELLED_FLAG
5115        , INCOME_TAX_REGION
5116        , TYPE_1099
5117        , STAT_AMOUNT
5118        , PREPAY_INVOICE_ID
5119        , PREPAY_LINE_NUMBER
5120        , INVOICE_INCLUDES_PREPAY_FLAG
5121        , CORRECTED_INV_ID
5122        , CORRECTED_LINE_NUMBER
5123        , PO_HEADER_ID
5124        , PO_LINE_ID
5125        , PO_RELEASE_ID
5126        , PO_LINE_LOCATION_ID
5127        , PO_DISTRIBUTION_ID
5128        , RCV_TRANSACTION_ID
5129        , FINAL_MATCH_FLAG
5130        , ASSETS_TRACKING_FLAG
5131        , ASSET_BOOK_TYPE_CODE
5132        , ASSET_CATEGORY_ID
5133        , PROJECT_ID
5134        , TASK_ID
5135        , EXPENDITURE_TYPE
5136        , EXPENDITURE_ITEM_DATE
5137        , EXPENDITURE_ORGANIZATION_ID
5138        , PA_QUANTITY
5139        , PA_CC_AR_INVOICE_ID
5140        , PA_CC_AR_INVOICE_LINE_NUM
5141        , PA_CC_PROCESSED_CODE
5142        , AWARD_ID
5143        , AWT_GROUP_ID
5144        , REFERENCE_1
5145        , REFERENCE_2
5146        , RECEIPT_VERIFIED_FLAG
5147        , RECEIPT_REQUIRED_FLAG
5148        , RECEIPT_MISSING_FLAG
5149        , JUSTIFICATION
5150        , EXPENSE_GROUP
5151        , START_EXPENSE_DATE
5152        , END_EXPENSE_DATE
5153        , RECEIPT_CURRENCY_CODE
5154        , RECEIPT_CONVERSION_RATE
5155        , RECEIPT_CURRENCY_AMOUNT
5156        , DAILY_AMOUNT
5157        , WEB_PARAMETER_ID
5158        , ADJUSTMENT_REASON
5159        , MERCHANT_DOCUMENT_NUMBER
5160        , MERCHANT_NAME
5161        , MERCHANT_REFERENCE
5162        , MERCHANT_TAX_REG_NUMBER
5163        , MERCHANT_TAXPAYER_ID
5164        , COUNTRY_OF_SUPPLY
5165        , CREDIT_CARD_TRX_ID
5166        , COMPANY_PREPAID_INVOICE_ID
5167        , CC_REVERSAL_FLAG
5168        , CREATION_DATE
5169        , CREATED_BY
5170        , LAST_UPDATED_BY
5171        , LAST_UPDATE_DATE
5172        , LAST_UPDATE_LOGIN
5173        , PROGRAM_APPLICATION_ID
5174        , PROGRAM_ID
5175        , PROGRAM_UPDATE_DATE
5176        , REQUEST_ID
5177        , ATTRIBUTE_CATEGORY
5178        , ATTRIBUTE1
5179        , ATTRIBUTE2
5180        , ATTRIBUTE3
5181        , ATTRIBUTE4
5182        , ATTRIBUTE5
5183        , ATTRIBUTE6
5184        , ATTRIBUTE7
5185        , ATTRIBUTE8
5186        , ATTRIBUTE9
5187        , ATTRIBUTE10
5188        , ATTRIBUTE11
5189        , ATTRIBUTE12
5190        , ATTRIBUTE13
5191        , ATTRIBUTE14
5192        , ATTRIBUTE15
5193        , GLOBAL_ATTRIBUTE_CATEGORY
5194        , GLOBAL_ATTRIBUTE1
5195        , GLOBAL_ATTRIBUTE2
5196        , GLOBAL_ATTRIBUTE3
5197        , GLOBAL_ATTRIBUTE4
5198        , GLOBAL_ATTRIBUTE5
5199        , GLOBAL_ATTRIBUTE6
5200        , GLOBAL_ATTRIBUTE7
5201        , GLOBAL_ATTRIBUTE8
5202        , GLOBAL_ATTRIBUTE9
5203        , GLOBAL_ATTRIBUTE10
5204        , GLOBAL_ATTRIBUTE11
5205        , GLOBAL_ATTRIBUTE12
5206        , GLOBAL_ATTRIBUTE13
5207        , GLOBAL_ATTRIBUTE14
5208        , GLOBAL_ATTRIBUTE15
5209        , GLOBAL_ATTRIBUTE16
5210        , GLOBAL_ATTRIBUTE17
5211        , GLOBAL_ATTRIBUTE18
5212        , GLOBAL_ATTRIBUTE19
5213        , GLOBAL_ATTRIBUTE20
5214        , INCLUDED_TAX_AMOUNT
5215        , PRIMARY_INTENDED_USE
5216        , APPLICATION_ID
5217        , PRODUCT_TABLE
5218        , REFERENCE_KEY1
5219        , REFERENCE_KEY2
5220        , REFERENCE_KEY3
5221        , REFERENCE_KEY4
5222        , REFERENCE_KEY5
5223        , SHIP_TO_LOCATION_ID
5224        , PAY_AWT_GROUP_ID
5225     FROM ap_invoice_lines_all
5226    WHERE invoice_id  = X_invoice_id
5227      AND line_number = X_line_number;
5228 
5229 
5230   l_invoice_line_rec           AP_INVOICES_PKG.r_invoice_line_rec;
5231 
5232   l_distribution_class         AP_INVOICE_DISTRIBUTIONS.DISTRIBUTION_CLASS%TYPE;
5233   l_dist_ccid                  AP_INVOICE_DISTRIBUTIONS.DIST_CODE_COMBINATION_ID%TYPE;
5234   l_base_currency_code         AP_SYSTEM_PARAMETERS.BASE_CURRENCY_CODE%TYPE;
5235   l_chart_of_accounts_id       GL_SETS_OF_BOOKS.CHART_OF_ACCOUNTS_ID%TYPE;
5236   l_account_type               GL_CODE_COMBINATIONS.ACCOUNT_TYPE%TYPE;
5237   l_assets_tracking_flag       AP_INVOICE_DISTRIBUTIONS.ASSETS_TRACKING_FLAG%TYPE;
5238   l_employee_id                AP_SUPPLIERS.EMPLOYEE_ID%TYPE;
5239   l_accounting_date            AP_INVOICE_LINES.ACCOUNTING_DATE%TYPE;
5240   l_open_gl_date               AP_INVOICE_LINES.ACCOUNTING_DATE%TYPE;
5241   l_open_period_name           AP_INVOICE_LINES.PERIOD_NAME%TYPE;
5242   user_id                      NUMBER;
5243   l_msg_application            VARCHAR2(25);
5244   l_msg_type                   VARCHAR2(25);
5245   l_msg_token1                 VARCHAR2(30);
5246   l_msg_token2                 VARCHAR2(30);
5247   l_msg_token3                 VARCHAR2(30);
5248   l_msg_count                  NUMBER;
5249   l_msg_data                   VARCHAR2(200); /*bug12612482 changed from 30 to 200*/
5250   l_billable_flag              VARCHAR2(25);
5251   l_pa_allows_overrides        VARCHAR2(1) := 'N';
5252   l_error_found                VARCHAR2(1) := 'N';
5253   l_existing_distributions     NUMBER := 0;
5254   l_unbuilt_flex               VARCHAR2(240):='';
5255   l_reason_unbuilt_flex        VARCHAR2(2000):='';
5256   current_calling_sequence     VARCHAR2(2000);
5257   debug_info                   VARCHAR2(2000); --Bug 8725625-Increased width
5258   debug_context                VARCHAR2(2000);
5259   l_dist_code_concat           VARCHAR2(2000);
5260   l_invoice_distribution_id    ap_invoice_distributions.invoice_distribution_id%TYPE;
5261   l_invoice_type_lookup_code   ap_invoices_all.invoice_type_lookup_code%TYPE;
5262   l_sys_link_function          VARCHAR2(2);
5263   l_web_parameter_id           number;
5264   l_employee_ccid              number;
5265   l_message_text	       fnd_new_messages.message_text%type;
5266   l_copy_line_dff_flag         VARCHAR2(1);
5267   l_Inc_AWT_For_Tax_Flag       Number :=1;
5268   l_dist_total number;
5269 
5270 /* bug 10201001 begins */
5271 --  l_accounting_event_id        ap_invoice_distributions.accounting_event_id%TYPE := -1;  --bug 9216708
5272   l_no_dists_exists               NUMBER := 0;   --bug 9216708
5273 
5274   cursor events_cur(p_invoice_id NUMBER,p_invoice_line_num NUMBER) is
5275   select distinct accounting_event_id
5276     from ap_invoice_distributions_all
5277    where invoice_id = p_invoice_id
5278      and invoice_line_number = p_invoice_line_num
5279      and posted_flag <> 'Y';
5280 
5281 TYPE EventTab IS TABLE OF ap_invoice_distributions.accounting_event_id%TYPE INDEX BY BINARY_INTEGER;
5282 l_accounting_event_id_list   EventTab;
5283 
5284 /* bug 10201001 ends */
5285   BEGIN
5286   --------------------------------------------------------------------------
5287   -- Step 1 - Update the calling sequence
5288   --------------------------------------------------------------------------
5289   current_calling_sequence :=
5290       'AP_INVOICE_DISTRIBUTIONS_PKG.insert_single_dist_from_line <-'||
5291       X_calling_sequence;
5292 
5293   --------------------------------------------------------------------------
5294   -- Step 2 - If calling module provided X_invoice_id / X_line_number, then
5295   -- we assume the calling module is not passing a line record.  Read the line
5296   -- record from the transaction tables.
5297   -------------------------------------------------------------------------
5298   debug_info := 'Verify line record';
5299   IF (X_invoice_id IS NOT NULL AND X_line_number IS NOT NULL) THEN
5300     BEGIN
5301       OPEN line_rec;
5302       FETCH line_rec INTO l_invoice_line_rec;
5303       IF (line_rec%NOTFOUND) THEN
5304         CLOSE line_rec;
5305         RAISE NO_DATA_FOUND;
5306       END IF;
5307       CLOSE line_Rec;
5308     EXCEPTION
5309       WHEN NO_DATA_FOUND THEN
5310         debug_info := debug_info ||': No valid line record was found.';
5311         X_debug_context := current_calling_sequence;
5312         X_debug_info := debug_info;
5313         return(FALSE);
5314     END;
5315   ELSE
5316     l_invoice_line_rec := X_invoice_lines_rec;
5317     IF (X_invoice_lines_rec.invoice_id IS NULL AND
5318         X_invoice_lines_rec.line_number is NULL ) THEN
5319       X_debug_info := debug_info || ': line not provided';
5320       X_debug_context := current_calling_sequence;
5321       RETURN (FALSE);
5322     END IF;
5323   END IF;
5324 
5325 
5326 
5327 
5328   SELECT DECODE(awt_include_tax_amt,'Y',1,'N',0,1)
5329          INTO l_Inc_AWT_For_Tax_Flag
5330     FROM ap_system_parameters_all
5331    WHERE org_id=l_invoice_line_rec.org_id
5332      AND rownum=1;
5333   ----------------------------------------------------------------------------
5334   -- Step 3 - Validate line does not contain other distributions
5335   ----------------------------------------------------------------------------
5336   IF (X_Validate_Info) then
5337     debug_info := 'Verify line does not contain distributions';
5338     BEGIN
5339       SELECT count(*)
5340       INTO l_existing_distributions
5341       FROM ap_invoice_distributions
5342      WHERE invoice_id = l_invoice_line_rec.invoice_id
5343        AND invoice_line_number = l_invoice_line_rec.line_number
5344        AND nvl(posted_flag,'N') <> 'N'
5345 	   AND rownum=1; --13507856 added the rownum condition to improve the performance
5346 
5347       IF (l_existing_distributions <> 0) then
5348         X_debug_info := debug_info || ': line already has posted distributions';
5349         X_debug_context := current_calling_sequence;
5350         RETURN(FALSE);
5351       END IF;
5352 
5353     EXCEPTION
5354       WHEN OTHERS THEN
5355       NULL;
5356     END;
5357   END IF; -- If calling module requested validation
5358 
5359   -- copied onto distributions for imported lines.
5360   l_copy_line_dff_flag := NVL(fnd_profile.value('AP_COPY_INV_LINE_DFF'),'N');
5361   IF NVL(l_invoice_line_rec.line_source, 'DUMMY') <> 'IMPORTED' OR l_copy_line_dff_flag <> 'Y' THEN
5362     l_invoice_line_rec.ATTRIBUTE_CATEGORY := NULL;
5363     l_invoice_line_rec.ATTRIBUTE1  := NULL;
5364     l_invoice_line_rec.ATTRIBUTE2  := NULL;
5365     l_invoice_line_rec.ATTRIBUTE3  := NULL;
5366     l_invoice_line_rec.ATTRIBUTE4  := NULL;
5367     l_invoice_line_rec.ATTRIBUTE5  := NULL;
5368     l_invoice_line_rec.ATTRIBUTE6  := NULL;
5369     l_invoice_line_rec.ATTRIBUTE7  := NULL;
5370     l_invoice_line_rec.ATTRIBUTE8  := NULL;
5371     l_invoice_line_rec.ATTRIBUTE9  := NULL;
5372     l_invoice_line_rec.ATTRIBUTE10 := NULL;
5373     l_invoice_line_rec.ATTRIBUTE11 := NULL;
5374     l_invoice_line_rec.ATTRIBUTE12 := NULL;
5375     l_invoice_line_rec.ATTRIBUTE13 := NULL;
5376     l_invoice_line_rec.ATTRIBUTE14 := NULL;
5377     l_invoice_line_rec.ATTRIBUTE15 := NULL;
5378   END IF;
5379 
5380   ----------------------------------------------------------------------------
5381   -- Step 4 - Get GL Date and Period name.  Only if not called from the
5382   -- Open interface since Validation of the Import already verifies gl date
5383   -- nd period.
5384   ----------------------------------------------------------------------------
5385   IF (nvl(X_line_source, 'OTHERS') <> 'IMPORT') then
5386     debug_info := 'Get gl date from open period if line gl date is in' ||
5387                   'a closed one';
5388     BEGIN
5389       l_open_period_name := NULL;
5390 
5391       l_open_period_name :=
5392         AP_UTILITIES_PKG.GET_CURRENT_GL_DATE(
5393                 l_invoice_line_rec.accounting_date,
5394 	        l_invoice_line_rec.org_id);
5395 
5396       IF (l_open_period_name is NULL) then
5397         AP_UTILITIES_PKG.GET_OPEN_GL_DATE(l_invoice_line_rec.accounting_date,
5398                                           l_open_period_name,
5399                                           l_open_gl_date);
5400       --Invoice Lines: Distributions
5401       --For the case when the accounting_date on the line fell in an open
5402       --period, we were trying to insert NULL into a NOT NULL column
5403       --accounting_date, since the variable l_open_gl_date was not being
5404       --populated properly.
5405       ELSE
5406         l_open_gl_date := l_invoice_line_rec.accounting_date;
5407       END IF;
5408       IF (l_open_period_name is NULL) then
5409         X_error_code := 'AP_NO_OPEN_PERIOD';
5410         RETURN(FALSE);
5411       END IF;
5412     END;
5413   ELSE
5414     l_open_period_name := l_invoice_line_rec.period_name;
5415     l_open_gl_date := l_invoice_line_rec.accounting_date;
5416   END IF;
5417 
5418   --------------------------------------------------------------
5419   -- Step 5 - Get system level information necessary for
5420   -- validation and generation of distributions
5421   --------------------------------------------------------------
5422   debug_info := 'Get system information';
5423   BEGIN
5424     SELECT gsob.chart_of_accounts_id, ap.base_currency_code
5425       INTO l_chart_of_accounts_id, l_base_currency_code
5426       FROM ap_system_parameters ap, gl_sets_of_books gsob
5427      WHERE ap.set_of_books_id = gsob.set_of_books_id
5428        AND ap.set_of_books_id = l_invoice_line_rec.set_of_books_id
5429        AND ap.org_id = l_invoice_line_rec.org_id; -- Bug 13858818
5430 
5431   EXCEPTION
5432     WHEN NO_DATA_FOUND THEN
5433       Debug_info := debug_info || ': No GL information was found';
5434       X_debug_context := current_calling_sequence;
5435       X_debug_info := debug_info;
5436     RETURN(FALSE);
5437   END;
5438 
5439 
5440 
5441   ----------------------------------------------------------------------------
5442   -- Step 7 - Obtain final account and account related information.
5443   -- But only if calling module is not the Import since through the import
5444   -- The account should already be built.
5445   ----------------------------------------------------------------------------
5446   debug_info := 'Obtain account to be used in distribution';
5447     -- Need to assign the value from the pass in record
5448     l_dist_ccid := l_invoice_line_rec.default_dist_ccid;
5449 
5450   ---------------------------------------------------------------------------
5451   -- Step 8 - Get account type.
5452   ---------------------------------------------------------------------------
5453   debug_info := 'Get account type for ccid ' || l_dist_ccid;
5454     BEGIN
5455     SELECT account_type
5456       INTO l_account_type
5457       FROM gl_code_combinations
5458      WHERE code_combination_id = l_dist_ccid;
5459 
5460   EXCEPTION
5461     WHEN no_data_found THEN
5462        Debug_info := debug_info || ': cannot read account type information';
5463        X_debug_context := current_calling_sequence;
5464        X_debug_info := debug_info;
5465        RETURN(FALSE);
5466   END;
5467 
5468 debug_info := 'Obtain the assets tracking flag given the account type';
5469   -- Obtain the assets tracking flag given the account type
5470   IF (l_account_type = 'A' OR
5471       (l_account_type = 'E' AND
5472        l_invoice_line_rec.assets_tracking_flag = 'Y')) then
5473     l_assets_tracking_flag := 'Y';
5474   ELSE
5475     l_assets_tracking_flag := 'N';
5476   END IF;
5477 debug_info := 'Before Step 9 - Set distribution class value (Permanent or Candidate)';
5478   ----------------------------------------------------------------------------
5479   -- Step 9 - Set distribution class value (Permanent or Candidate)
5480   ----------------------------------------------------------------------------
5481   if (X_Generate_Permanent = 'N') then
5482     l_distribution_class := 'CANDIDATE';
5483   else
5484     l_distribution_class := 'PERMANENT';
5485   end if;
5486 
5487 debug_info := 'After Step 9 - Set distribution class value (Permanent or Candidate)'||l_distribution_class;
5488   ---------------------------------------------------------------------------
5489   -- ETAX: Invwkb
5490   -- Step 10 - Exclude the included_tax_amount from the line_amount before
5491   --	       creating a item distribution.
5492   ---------------------------------------------------------------------------
5493 
5494         debug_info := 'Before Calc Inv line base amount'||l_invoice_line_rec.amount ||'Xrate '|| x_exchange_rate ||'l_base_currency_code '||l_base_currency_code;
5495 
5496         l_invoice_line_rec.base_amount := ap_utilities_pkg.ap_round_currency(
5497   					l_invoice_line_rec.amount * x_exchange_rate,
5498 					l_base_currency_code);
5499 
5500         debug_info := 'After Calc Inv line base amount'||l_invoice_line_rec.amount ||'Xrate ' || x_exchange_rate ||'l_base_currency_code '||l_base_currency_code;
5501 
5502   ----------------------------------------------------------------------------
5503   -- Step 11 - Generate distributions
5504   ----------------------------------------------------------------------------
5505   BEGIN
5506 	l_dist_total:=0;
5507 
5508 	debug_info  := 'Dist Total - '  ||l_dist_total ;
5509 
5510 
5511           SELECT SUM(AMOUNT)
5512             INTO l_dist_total
5513             FROM ap_invoice_distributions_all aid
5514            WHERE aid.invoice_id             = l_invoice_line_rec.invoice_id
5515              AND line_type_lookup_code NOT IN('AWT' , 'PREPAY','ERV','TERV')
5516 			 AND NOT (aid.line_type_lookup_code IN ('REC_TAX' , 'NONREC_TAX', 'TIPV', 'TRV')
5517 		     AND aid.prepay_distribution_id is not null)  /*Bug11937214*/
5518              AND(l_Inc_AWT_For_Tax_Flag = 1
5519                  OR (aid.line_type_lookup_code NOT IN('REC_TAX' , 'NONREC_TAX' , 'TIPV' , 'TRV'))
5520                 ) ;
5521 
5522 	IF l_dist_total <> 0 THEN
5523 
5524 /* bug 10201001 begins */
5525 /*	  commented the following code
5526           -- bug 9216708 start
5527 	  select count(*)
5528             into l_dists_exists
5529 	    from ap_invoice_distributions_all
5530 	   where invoice_id = l_invoice_line_rec.invoice_id
5531 	     and accounting_event_id is NOT NULL
5532 	     and line_type_lookup_code = 'AWT'
5533 	     and awt_flag = 'M'
5534 	     and nvl(posted_flag,'N') <> 'Y';
5535 
5536 	IF l_dists_exists > 0 THEN
5537   	  SELECT nvl(max(aid.accounting_event_id),-1)
5538 	    INTO l_accounting_event_id
5539 	    FROM ap_invoice_distributions_all aid
5540            WHERE aid.invoice_id = l_invoice_line_rec.invoice_id
5541 	     AND aid.line_type_lookup_code = 'AWT'
5542 	     AND aid.awt_flag = 'M'
5543              AND NVL(posted_flag , 'N') <> 'Y';
5544 	END IF;
5545 */
5546 
5547          OPEN events_cur (l_invoice_line_rec.invoice_id,l_invoice_line_rec.line_number);
5548          FETCH events_cur BULK COLLECT INTO l_accounting_event_id_list;
5549 	 CLOSE events_cur;
5550 
5551 /* bug 10201001 end */
5552           DELETE FROM ap_invoice_distributions_all aid
5553            WHERE invoice_id              = l_invoice_line_rec.invoice_id
5554              AND invoice_line_number     = l_invoice_line_rec.line_number
5555              AND NVL(posted_flag , 'N') <> 'Y';
5556 
5557 /* bug 10201001 begins */
5558           FOR i in 1..l_accounting_event_id_list.count LOOP
5559 
5560 	    SELECT count(*)
5561 	      INTO l_no_dists_exists
5562 	      FROM xla_events xe
5563 	     WHERE xe.event_id = l_accounting_event_id_list(i)
5564 	       AND xe.event_status_code <> 'P'
5565 	       AND xe.application_id = 200
5566 	       AND NOT EXISTS (SELECT 'No self assessed tax rows exists for this event'
5567                                  FROM ap_self_assessed_tax_dist_all asatd
5568                                 WHERE asatd.invoice_id = l_invoice_line_rec.invoice_id
5569 				  AND asatd.accounting_event_id = xe.event_id)
5570 	       AND NOT EXISTS (SELECT 'No Invoice rows exist for this event'
5571 	                         FROM ap_invoice_distributions_all aid
5572                                 WHERE aid.invoice_id = l_invoice_line_rec.invoice_id
5573 				  AND aid.accounting_event_id = xe.event_id)
5574 	       AND NOT EXISTS (SELECT 'No payment rows exist for this event'
5575 	                         FROM ap_invoice_payments_all aip,
5576 				      ap_payment_history_all aph
5577 				WHERE aip.invoice_id = l_invoice_line_rec.invoice_id
5578 				  AND aip.check_id = aph.check_id
5579 				  AND aph.accounting_event_id = xe.event_id)
5580 	       AND NOT EXISTS (SELECT 'No prepayment rows exist for this event'
5581 	                         FROM ap_prepay_history_all aprh
5582 				WHERE aprh.invoice_id = l_invoice_line_rec.invoice_id
5583 				  AND aprh.accounting_event_id = xe.event_id);
5584 
5585             IF (l_no_dists_exists <> 0) THEN
5586                AP_ACCOUNTING_EVENTS_PKG.delete_invoice_event(l_accounting_event_id_list(i),
5587 	                                                  l_invoice_line_rec.invoice_id,
5588                                                           current_calling_sequence);
5589             END IF;
5590 	  END LOOP;
5591  /* bug 10201001 end */
5592         debug_info := ' Before Insert AwT Distributions ';
5593 
5594           INSERT INTO ap_invoice_distributions_all
5595                ( batch_id
5596                , invoice_id
5597                , invoice_line_number
5598                , invoice_distribution_id
5599                , distribution_line_number
5600                , line_type_lookup_code
5601                , distribution_class
5602                , description
5603                , dist_match_type
5604                , org_id
5605                , dist_code_combination_id
5606                , accounting_date
5607                , period_name
5608                , accrual_posted_flag
5609                , cash_posted_flag
5610                , amount_to_post
5611                , base_amount_to_post
5612                , posted_amount
5613                , posted_base_amount
5614                , posted_flag
5615                , accounting_event_id
5616                , upgrade_posted_amt
5617                , upgrade_base_posted_amt
5618                , set_of_books_id
5619                , amount
5620                , base_amount
5621                , rounding_amt
5622                , quantity_variance
5623                , base_quantity_variance
5624                , match_status_flag
5625                , encumbered_flag
5626                , packet_id
5627                , reversal_flag
5628                , parent_reversal_id
5629                , cancellation_flag
5630                , income_tax_region
5631                , type_1099
5632                , stat_amount
5633                , charge_applicable_to_dist_id
5634                , prepay_amount_remaining
5635                , prepay_distribution_id
5636                , parent_invoice_id
5637                , corrected_invoice_dist_id
5638                , corrected_quantity
5639                , other_invoice_id
5640                , po_distribution_id
5641                , rcv_transaction_id
5642                , unit_price
5643                , matched_uom_lookup_code
5644                , quantity_invoiced
5645                , final_match_flag
5646                , related_id
5647                , assets_addition_flag
5648                , assets_tracking_flag
5649                , asset_book_type_code
5650                , asset_category_id
5651                , project_id
5652                , task_id
5653                , expenditure_type
5654                , expenditure_item_date
5655                , expenditure_organization_id
5656                , pa_quantity
5657                , pa_addition_flag
5658                , award_id
5659                , gms_burdenable_raw_cost
5660                , awt_flag
5661                , awt_group_id
5662                , awt_tax_rate_id
5663                , awt_gross_amount
5664                , awt_invoice_id
5665                , awt_origin_group_id
5666                , awt_invoice_payment_id
5667                , awt_withheld_amt
5668                , inventory_transfer_status
5669                , reference_1
5670                , reference_2
5671                , receipt_verified_flag
5672                , receipt_required_flag
5673                , receipt_missing_flag
5674                , justification
5675                , expense_group
5676                , start_expense_date
5677                , end_expense_date
5678                , receipt_currency_code
5679                , receipt_conversion_rate
5680                , receipt_currency_amount
5681                , daily_amount
5682                , web_parameter_id
5683                , adjustment_reason
5684                , merchant_document_number
5685                , merchant_name
5686                , merchant_reference
5687                , merchant_tax_reg_number
5688                , merchant_taxpayer_id
5689                , country_of_supply
5690                , credit_card_trx_id
5691                , company_prepaid_invoice_id
5692                , cc_reversal_flag
5693                , attribute_category
5694                , attribute1
5695                , attribute2
5696                , attribute3
5697                , attribute4
5698                , attribute5
5699                , attribute6
5700                , attribute7
5701                , attribute8
5702                , attribute9
5703                , attribute10
5704                , attribute11
5705                , attribute12
5706                , attribute13
5707                , attribute14
5708                , attribute15
5709                , global_attribute_category
5710                , global_attribute1
5711                , global_attribute2
5712                , global_attribute3
5713                , global_attribute4
5714                , global_attribute5
5715                , global_attribute6
5716                , global_attribute7
5717                , global_attribute8
5718                , global_attribute9
5719                , global_attribute10
5720                , global_attribute11
5721                , global_attribute12
5722                , global_attribute13
5723                , global_attribute14
5724                , global_attribute15
5725                , global_attribute16
5726                , global_attribute17
5727                , global_attribute18
5728                , global_attribute19
5729                , global_attribute20
5730                , created_by
5731                , creation_date
5732                , last_updated_by
5733                , last_update_date
5734                , last_update_login
5735                , program_application_id
5736                , program_id
5737                , program_update_date
5738                , request_id
5739                , intended_use
5740                , rcv_charge_addition_flag
5741                , pay_awt_group_id
5742                , awt_related_id
5743                )
5744           SELECT X_batch_id batch_id
5745                , l_invoice_line_rec.invoice_id invoice_id
5746                , l_invoice_line_rec.line_number invoice_line_number
5747                , ap_invoice_distributions_s.nextval invoice_distribution_id
5748                , rownum distribution_line_number
5749                , 'AWT' line_type_lookup_code
5750                , l_distribution_class distribution_class
5751                , l_invoice_line_rec.description description
5752                , 'NOT_MATCHED' dist_match_type
5753                , l_invoice_line_rec.org_id l_org_id
5754                , l_dist_ccid dist_code_combination_id
5755                , l_open_gl_date accounting_date
5756                , l_open_period_name period_name
5757                , 'N' accrual_posted_flag
5758                , 'N' cash_posted_flag
5759                , NULL amount_to_post
5760                , NULL base_amount_to_post
5761                , NULL posted_amount
5762                , NULL posted_base_amount
5763                , 'N' posted_flag
5764 	       /* bug 10201001
5765                , DECODE(l_accounting_event_id,-1,NULL,
5766 			            l_accounting_event_id) accounting_event_id  bug 9216708 */
5767                , NULL accounting_event_id
5768                , NULL upgrade_posted_amt
5769                , NULL upgrade_base_posted_amt
5770                , l_invoice_line_rec.set_of_books_id set_of_books_id
5771                , ap_utilities_pkg.ap_round_currency
5772                              (l_invoice_line_rec.amount * aid.amount / l_dist_total
5773                              , X_invoice_currency) amount
5774                , DECODE(X_exchange_rate_type
5775                         , NULL , NULL
5776                         , ap_utilities_pkg.ap_round_currency(
5777                                        (l_invoice_line_rec.amount * aid.amount / l_dist_total) * X_exchange_rate
5778                                        , X_invoice_currency)) base_amount
5779                , 0 rounding_amt
5780                , NULL quantity_variance
5781                , NULL base_quantity_variance
5782                , NULL match_status_flag
5783                , 'N' encumbered_flag
5784                , NULL packet_id
5785                , 'N' reversal_flag
5786                , NULL parent_reversal_id
5787                , 'N' cancellation_flag
5788                , DECODE(l_invoice_line_rec.type_1099
5789                        , NULL , NULL
5790                        , l_invoice_line_rec.income_tax_region) income_tax_region
5791                , l_invoice_line_rec.type_1099 type_1099
5792 	       , NULL stat_amount
5793                , NULL charge_applicable_to_dist_id
5794                , NULL prepay_amount_remaining
5795                , NULL prepay_distribution_id
5796                , NULL parent_invoice_id
5797                , NULL corrected_inv_dist_id
5798                , NULL corrected_quantity
5799                , NULL other_invoice_id
5800                , NULL po_distribution_id
5801                , NULL rcv_transaction_id
5802                , NULL unit_price
5803                , NULL matched_uom_lookup_code
5804                , NULL quantity_invoiced
5805                , NULL final_match_flag
5806                , NULL related_id
5807                , 'U' assets_addition_flag
5808                , l_assets_tracking_flag assets_tracking_flag
5809                , DECODE(l_assets_tracking_flag
5810                        , 'Y' , l_invoice_line_rec.asset_book_type_code
5811                        , NULL) asset_book_type_code
5812                , DECODE(l_assets_tracking_flag
5813                        , 'Y' , l_invoice_line_rec.asset_category_id
5814                        , NULL) asset_category_id
5815                , l_invoice_line_rec.project_id project_id
5816                , l_invoice_line_rec.task_id task_id
5817                , l_invoice_line_rec.expenditure_type expenditure_type
5818                , l_invoice_line_rec.expenditure_item_date expenditure_item_date
5819                , l_invoice_line_rec.expenditure_organization_id expenditure_organization_id
5820                , l_invoice_line_rec.pa_quantity pa_quantity
5821                , DECODE(l_invoice_line_rec.project_id , NULL , 'E' , 'N') pa_addition_flag
5822                , l_invoice_line_rec.award_id award_id
5823                , NULL gms_burdenable_raw_cost
5824                , 'M' awt_flag
5825                , l_invoice_line_rec.awt_group_id awt_group_id
5826                , NULL awt_tax_rate_id
5827                , NULL awt_gross_amount
5828                , NULL awt_invoice_id
5829                , NULL awt_origin_group_id
5830                , NULL awt_invoice_payment_id
5831                , NULL awt_withheld_amt
5832                , 'N' inventory_transfer_status
5833                , l_invoice_line_rec.reference_1  reference_1 --NULL Bug9296445
5834                , l_invoice_line_rec.reference_2  reference_2 --NULL Bug9296445,
5835                , NULL receipt_verified_flag
5836                , NULL receipt_required_flag
5837                , NULL receipt_missing_flag
5838                , NULL justification
5839                , NULL expense_group
5840                , NULL start_expense_date
5841                , NULL end_expense_date
5842                , NULL receipt_currency_code
5843                , NULL receipt_conversion_rate
5844                , NULL receipt_currency_amount
5845                , NULL daily_amount
5846                , NULL web_parameter_id
5847                , NULL adjustment_reason
5848                , NULL merchant_document_number
5849                , NULL merchant_name
5850                , NULL merchant_reference
5851                , NULL merchant_tax_reg_number
5852                , NULL merchant_taxpayer_id
5853                , NULL country_of_supply
5854                , NULL credit_card_trx_id
5855                , NULL company_prepaid_invoice_id
5856                , NULL cc_reversal_flag
5857                , l_invoice_line_rec.attribute_category attribute_category
5858                , l_invoice_line_rec.attribute1 attribute1
5859                , l_invoice_line_rec.attribute2 attribute2
5860                , l_invoice_line_rec.attribute3 attribute3
5861                , l_invoice_line_rec.attribute4 attribute4
5862                , l_invoice_line_rec.attribute5 attribute5
5863                , l_invoice_line_rec.attribute6 attribute6
5864                , l_invoice_line_rec.attribute7 attribute7
5865                , l_invoice_line_rec.attribute8 attribute8
5866                , l_invoice_line_rec.attribute9 attribute9
5867                , l_invoice_line_rec.attribute10 attribute10
5868                , l_invoice_line_rec.attribute11 attribute11
5869                , l_invoice_line_rec.attribute12 attribute12
5870                , l_invoice_line_rec.attribute13 attribute13
5871                , l_invoice_line_rec.attribute14 attribute14
5872                , l_invoice_line_rec.attribute15 attribute15
5873                , NULL global_attribute_category
5874                , NULL global_attribute1
5875                , NULL global_attribute2
5876                , DECODE(AP_EXTENDED_WITHHOLDING_PKG.AP_EXTENDED_WITHHOLDING_OPTION
5877                        , 'Y' , l_invoice_line_rec.ship_to_location_id
5878                        , '') global_attribute3
5879                , NULL global_attribute4
5880                , NULL global_attribute5
5881                , NULL global_attribute6
5882                , NULL global_attribute7
5883                , NULL global_attribute8
5884                , NULL global_attribute9
5885                , NULL global_attribute10
5886                , NULL global_attribute11
5887                , NULL global_attribute12
5888                , NULL global_attribute13
5889                , NULL global_attribute14
5890                , NULL global_attribute15
5891                , NULL global_attribute16
5892                , NULL global_attribute17
5893                , NULL global_attribute18
5894                , NULL global_attribute19
5895                , NULL global_attribute20
5896                , FND_GLOBAL.user_id created_by
5897                , SYSDATE creation_date
5898                , 0 last_updated_by
5899                , SYSDATE last_update_date
5900                , FND_GLOBAL.login_id last_update_login
5901                , NULL program_application_id
5902                , NULL program_id
5903                , NULL program_update_date
5904                , NULL request_id
5905                , l_invoice_line_rec.primary_intended_use intended_use
5906                , 'N' rcv_charge_addition_flag
5907                , l_invoice_line_rec.pay_awt_group_id pay_awt_group_id
5908                , aid.invoice_distribution_id awt_related_id
5909             FROM ap_invoice_distributions_all aid
5910            WHERE aid.invoice_id                 = l_invoice_line_rec.invoice_id
5911              AND aid.line_type_lookup_code NOT IN('AWT' , 'PREPAY','ERV','TERV')
5912 			 AND NOT (aid.line_type_lookup_code IN ('REC_TAX' , 'NONREC_TAX', 'TIPV', 'TRV')
5913 		     AND aid.prepay_distribution_id is not null)  /*Bug11937214*/
5914              AND (  l_Inc_AWT_For_Tax_Flag      = 1
5915                      OR ( aid.line_type_lookup_code NOT IN('REC_TAX' , 'NONREC_TAX' , 'TIPV' , 'TRV'))
5916                  ) ;
5917 
5918 
5919 	debug_info := ' After Insert AwT Distributions ';
5920 	end if;
5921 
5922 	  UPDATE ap_invoice_distributions_all aid
5923 	     SET aid.amount = aid.amount -
5924 		 ((
5925 		   SELECT SUM(aid1.amount)
5926 		     FROM ap_invoice_distributions_all aid1
5927 		    WHERE aid1.invoice_id          = aid.invoice_id
5928 		      AND aid1.invoice_line_number = aid.invoice_line_number
5929 		 )- l_invoice_line_rec.amount)
5930 	   WHERE aid.invoice_id          = l_invoice_line_rec.invoice_id
5931 	     AND aid.invoice_line_number = l_invoice_line_rec.line_number
5932 	     AND ABS(aid.amount)         =
5933 		 ( SELECT MAX(ABS(aid1.amount))
5934 		     FROM ap_invoice_distributions_all aid1
5935 		    WHERE aid1.invoice_id          = aid.invoice_id
5936 		      AND aid1.invoice_line_number = aid.invoice_line_number)
5937 	     AND rownum = 1;
5938 
5939 	IF X_exchange_rate_type is not null then
5940 
5941 	  UPDATE ap_invoice_distributions_all aid
5942 	     SET aid.base_amount = aid.base_amount -
5943 		 ((
5944 		   SELECT SUM(aid1.base_amount)
5945 		     FROM ap_invoice_distributions_all aid1
5946 		    WHERE aid1.invoice_id          = aid.invoice_id
5947 		      AND aid1.invoice_line_number = aid.invoice_line_number
5948 		 )- l_invoice_line_rec.base_amount)
5949 	   WHERE aid.invoice_id          = l_invoice_line_rec.invoice_id
5950 	     AND aid.invoice_line_number = l_invoice_line_rec.line_number
5951 	     AND ABS(aid.base_amount)         =
5952 		 ( SELECT MAX(ABS(aid1.base_amount))
5953 		     FROM ap_invoice_distributions_all aid1
5954 		    WHERE aid1.invoice_id          = aid.invoice_id
5955 		      AND aid1.invoice_line_number = aid.invoice_line_number)
5956 	     AND rownum = 1;
5957 
5958 	END IF;
5959 
5960 
5961     GMS_AP_API.CREATE_AWARD_DISTRIBUTIONS
5962                 ( p_invoice_id		     => l_invoice_line_rec.invoice_id,
5963                   p_distribution_line_number => 1,
5964                   p_invoice_distribution_id  => l_invoice_distribution_id,
5965                   p_award_id		     => l_invoice_line_rec.award_id,
5966                   p_mode		     => 'AP',
5967                   p_dist_set_id		     => NULL,
5968                   p_dist_set_line_number     => NULL );
5969 
5970 
5971      EXCEPTION
5972       WHEN OTHERS THEN
5973         X_debug_info := debug_info || ': Error encountered during dist insert';
5974         X_debug_context := current_calling_sequence;
5975         --Bugfix: 3859755, added the below stmt.
5976         X_Error_Code := SQLERRM;
5977         RETURN (FALSE);
5978     END;
5979 
5980     ----------------------------------------------------------------------------
5981   -- Step 10 - Update generate distributions flag in invoice line if generating
5982   -- permanent distributions.
5983   ----------------------------------------------------------------------------
5984   debug_info := 'Setting generate distributions flag to Done';
5985   IF (l_distribution_class = 'PERMANENT') then
5986     BEGIN
5987       UPDATE AP_INVOICE_LINES
5988          SET GENERATE_DISTS = 'D'
5989        WHERE invoice_id = X_invoice_id
5990          AND line_number = l_invoice_line_rec.line_number;
5991     EXCEPTION
5992       WHEN OTHERS THEN
5993         X_debug_info := debug_info || ': Error encountered';
5994         X_debug_context := current_calling_sequence;
5995         return (FALSE);
5996     END;
5997   END IF;
5998 
5999   RETURN(TRUE);
6000 
6001 EXCEPTION
6002     WHEN OTHERS THEN
6003     X_debug_info := 'Error encountered' ||debug_info;
6004     X_debug_context := current_calling_sequence;
6005     RETURN (FALSE);
6006 END Insert_AWT_Dist_From_Line;
6007 
6008 --Bug 8346277 End
6009 
6010 
6011 
6012   ----------------------------------------------------------------------
6013   -- PRIVATE FUNCTION get_project_and_account_for_chrg_dist encapsulates the
6014   -- logic for obtaining the project and account information for a
6015   -- distribution created for a charge line that is allocated to one
6016   -- or more lines in an invoice.
6017   -- Returns FALSE if an error is encountered and an specific error
6018   -- code for invalid PA, invalid account or if it is unable to overlay.
6019   --------------------------------------------------------------------------
6020 
6021   FUNCTION Get_Proj_And_Acc_For_Chrg_Dist(
6022   X_invoice_id             IN         NUMBER,
6023   X_invoice_date           IN         AP_INVOICES.INVOICE_DATE%TYPE,
6024   X_vendor_id              IN         NUMBER,
6025   X_invoice_currency_code  IN         AP_INVOICES.INVOICE_CURRENCY_CODE%TYPE,
6026   X_sob_id                 IN         AP_INVOICE_LINES.SET_OF_BOOKS_ID%TYPE,
6027   X_chart_of_accounts_id   IN         GL_SETS_OF_BOOKS.CHART_OF_ACCOUNTS_ID%TYPE,
6028   X_base_currency_code     IN         AP_SYSTEM_PARAMETERS.BASE_CURRENCY_CODE%TYPE,
6029   X_amount                 IN         AP_INVOICE_DISTRIBUTIONS.AMOUNT%TYPE,
6030   X_base_amount            IN         AP_INVOICE_DISTRIBUTIONS.BASE_AMOUNT%TYPE,
6031   X_exchange_rate_type     IN         AP_INVOICES.EXCHANGE_RATE_TYPE%TYPE,
6032   X_exchange_date          IN         AP_INVOICES.EXCHANGE_DATE%TYPE,
6033   X_exchange_rate          IN         AP_INVOICES.EXCHANGE_RATE%TYPE,
6034   X_line_number            IN         NUMBER,
6035   X_GL_Date                IN         AP_INVOICE_LINES.ACCOUNTING_DATE%TYPE,
6036   X_Period_Name            IN         AP_INVOICE_LINES.PERIOD_NAME%TYPE,
6037   X_chrg_line_project_id   IN         AP_INVOICE_LINES.PROJECT_ID%TYPE,
6038   X_chrg_line_task_id      IN         AP_INVOICE_LINES.TASK_ID%TYPE,
6039   X_chrg_line_award_id	   IN	      AP_INVOICE_LINES.award_ID%TYPE,
6040   X_chrg_line_expenditure_type IN         AP_INVOICE_LINES.EXPENDITURE_TYPE%TYPE,
6041   X_chrg_line_exp_org_id   IN         AP_INVOICE_LINES.EXPENDITURE_ORGANIZATION_ID%TYPE,
6042   X_chrg_assets_track_flag IN         AP_INVOICE_LINES.ASSETS_TRACKING_FLAG%TYPE,
6043   X_chrg_asset_book_type_code  IN         AP_INVOICE_LINES.ASSET_BOOK_TYPE_CODE%TYPE,
6044   X_chrg_asset_category_id IN         AP_INVOICE_LINES.ASSET_CATEGORY_ID%TYPE,
6045   X_item_dist_project_id   IN         AP_INVOICE_DISTRIBUTIONS.PROJECT_ID%TYPE,
6046   X_item_dist_task_id      IN         AP_INVOICE_DISTRIBUTIONS.TASK_ID%TYPE,
6047   X_item_dist_award_id	   IN	      AP_INVOICE_DISTRIBUTIONS.award_ID%TYPE,
6048   X_item_dist_expenditure_type IN         AP_INVOICE_DISTRIBUTIONS.EXPENDITURE_TYPE%TYPE,
6049   X_item_dist_exp_org_id   IN         AP_INVOICE_DISTRIBUTIONS.EXPENDITURE_ORGANIZATION_ID%TYPE,
6050   X_item_assets_track_flag IN         AP_INVOICE_DISTRIBUTIONS.ASSETS_TRACKING_FLAG%TYPE,
6051   X_item_asset_book_type_code  IN         AP_INVOICE_DISTRIBUTIONS.ASSET_BOOK_TYPE_CODE%TYPE,
6052   X_item_asset_category_id IN         AP_INVOICE_DISTRIBUTIONS.ASSET_CATEGORY_ID%TYPE,
6053   X_chrg_line_default_ccid IN         NUMBER,
6054   X_overlay_dist_code_concat   IN         AP_INVOICE_LINES.OVERLAY_DIST_CODE_CONCAT%TYPE,
6055   X_balancing_segment      IN         AP_INVOICE_LINES.BALANCING_SEGMENT%TYPE,
6056   X_account_segment        IN         AP_INVOICE_LINES.ACCOUNT_SEGMENT%TYPE,
6057   X_cost_center_segment    IN         AP_INVOICE_LINES.COST_CENTER_SEGMENT%TYPE,
6058   X_item_dist_ccid         IN         AP_INVOICE_DISTRIBUTIONS.DIST_CODE_COMBINATION_ID%TYPE,
6059   X_item_po_dist_id        IN         AP_INVOICE_DISTRIBUTIONS.PO_DISTRIBUTION_ID%TYPE,
6060   X_item_rcv_trx_id        IN         AP_INVOICE_DISTRIBUTIONS.RCV_TRANSACTION_ID%TYPE,
6061   X_pa_allows_overrides    IN         VARCHAR2,
6062   X_allow_po_override      IN         VARCHAR2,
6063   X_project_id             OUT NOCOPY AP_INVOICE_DISTRIBUTIONS.PROJECT_ID%TYPE,
6064   X_task_id                OUT NOCOPY AP_INVOICE_DISTRIBUTIONS.TASK_ID%TYPE,
6065   X_award_id		   OUT NOCOPY AP_INVOICE_LINES.award_ID%TYPE,
6066   X_expenditure_type       OUT NOCOPY AP_INVOICE_DISTRIBUTIONS.EXPENDITURE_TYPE%TYPE,
6067   X_expenditure_org_id     OUT NOCOPY AP_INVOICE_DISTRIBUTIONS.EXPENDITURE_ORGANIZATION_ID%TYPE,
6068   X_expenditure_item_date  OUT NOCOPY AP_INVOICE_DISTRIBUTIONS.EXPENDITURE_ITEM_DATE%TYPE,
6069   X_pa_addition_flag       OUT NOCOPY AP_INVOICE_DISTRIBUTIONS.PA_ADDITION_FLAG%TYPE,
6070   X_account_for_dist       OUT NOCOPY NUMBER,
6071   X_assets_tracking_flag   OUT NOCOPY AP_INVOICE_DISTRIBUTIONS.ASSETS_TRACKING_FLAG%TYPE,
6072   X_asset_book_typ_code    OUT NOCOPY AP_INVOICE_DISTRIBUTIONS.ASSET_BOOK_TYPE_CODE%TYPE,
6073   X_asset_category_id      OUT NOCOPY AP_INVOICE_DISTRIBUTIONS.ASSET_CATEGORY_ID%TYPE,
6074   X_error_code             OUT NOCOPY VARCHAR2,
6075   X_msg_application        OUT NOCOPY VARCHAR2,
6076   X_msg_data               OUT NOCOPY VARCHAR2,
6077   X_default_dist_ccid      IN   AP_INVOICE_LINES.DEFAULT_DIST_CCID%TYPE) --bug 5386396
6078   RETURN BOOLEAN
6079 IS
6080 
6081   l_po_accrue_on_receipt_flag PO_DISTRIBUTIONS.ACCRUE_ON_RECEIPT_FLAG%TYPE;
6082   l_po_ccid                   PO_DISTRIBUTIONS.CODE_COMBINATION_ID%TYPE;
6083   l_dist_ccid                 AP_INVOICE_DISTRIBUTIONS.DIST_CODE_COMBINATION_ID%TYPE;
6084   l_dist_code_concat          VARCHAR2(2000);
6085   l_employee_id               AP_SUPPLIERS.EMPLOYEE_ID%TYPE;
6086   l_account_type              GL_CODE_COMBINATIONS.ACCOUNT_TYPE%TYPE;
6087   user_id                     NUMBER;
6088   l_msg_application         VARCHAR2(25);
6089   l_msg_type              VARCHAR2(25);
6090   l_msg_token1               VARCHAR2(30);
6091   l_msg_token2               VARCHAR2(30);
6092   l_msg_token3               VARCHAR2(30);
6093   l_msg_count              NUMBER;
6094   l_msg_data              VARCHAR2(200); /*bug12612482 changed from 30 to 200*/
6095   l_billable_flag             VARCHAR2(25);
6096   l_unbuilt_flex              VARCHAR2(240):='';
6097   l_reason_unbuilt_flex       VARCHAR2(2000):='';
6098   l_error_found               VARCHAR2(1) := 'N';
6099   l_vendor_id                 AP_INVOICES.VENDOR_ID%TYPE;
6100   current_calling_sequence            VARCHAR2(200);
6101   debug_context               VARCHAR2(2000);
6102   debug_info                  VARCHAR2(100);
6103   l_invoice_type_lookup_code   ap_invoices_all.invoice_type_lookup_code%TYPE;
6104   l_sys_link_function          VARCHAR2(2); /* Bug 5102724 */
6105   l_web_parameter_id           number; --Bug5003249
6106   l_employee_ccid              number;
6107   l_message_text	       fnd_new_messages.message_text%TYPE;
6108   l_invoice_attribute_rec       AP_UTILITIES_PKG.r_invoice_attribute_rec; --bug 8713737
6109 
6110 BEGIN
6111 
6112   -------------------------------------------------------------------
6113   -- Step 1 - Gather whether distribution is project related and at
6114   -- which level.
6115   -------------------------------------------------------------------
6116   IF (X_item_dist_project_id IS NOT NULL) THEN
6117     X_project_id := X_item_dist_project_id;
6118     X_task_id := X_item_dist_task_id;
6119     X_expenditure_type := X_item_dist_expenditure_type;
6120     X_expenditure_org_id := X_item_dist_exp_org_id;
6121     X_pa_addition_flag := 'N';
6122   ELSIF (X_chrg_line_project_id is not null) then
6123     X_project_id := X_chrg_line_project_id;
6124     X_task_id := X_chrg_line_task_id;
6125     X_expenditure_type := X_chrg_line_expenditure_type;
6126     X_expenditure_org_id := X_chrg_line_exp_org_id;
6127     X_pa_addition_flag := 'N';
6128   ELSE
6129     X_project_id := NULL;
6130     X_task_id := NULL;
6131     X_expenditure_type := NULL;
6132     X_expenditure_org_id := NULL;
6133     X_pa_addition_flag := 'E';
6134   END IF;
6135 
6136   -------------------------------------------------------------------
6137   -- Step 2 - Validate PA information
6138   -------------------------------------------------------------------
6139   IF (X_project_id IS NOT NULL AND X_item_dist_project_id IS NOT NULL) then
6140     user_id := TO_NUMBER(FND_PROFILE.VALUE('USER_ID'));
6141 
6142     X_expenditure_item_date := AP_INVOICES_PKG.get_expenditure_item_date(
6143                                                    X_invoice_id,
6144                                                    X_invoice_date,
6145                                                    X_GL_date,
6146                                                    X_item_po_dist_id,
6147                                                    X_item_rcv_trx_id,
6148                                                    l_error_found);
6149     if (l_error_found = 'Y') then
6150       X_error_code := 'AP_CANNOT_READ_EXP_DATE';
6151       RETURN(FALSE);
6152     END IF;
6153 
6154     BEGIN
6155     SELECT employee_id
6156     INTO l_employee_id
6157         FROM ap_suppliers /* bUg 4718054 */
6158        WHERE DECODE(SIGN(TO_DATE(TO_CHAR(START_DATE_ACTIVE,'DD-MM-YYYY'),
6159                'DD-MM-YYYY') - TO_DATE(TO_CHAR(SYSDATE,'DD-MM-YYYY'),'DD-MM-YYYY')),
6160                1, 'N', DECODE(SIGN(TO_DATE(TO_CHAR(END_DATE_ACTIVE ,'DD-MM-YYYY'),
6161                'DD-MM-YYYY') -  TO_DATE(TO_CHAR(SYSDATE,'DD-MM-YYYY'),'DD-MM-YYYY')),
6162                -1, 'N', 0, 'N', 'Y')) = 'Y'
6163          AND enabled_flag = 'Y'
6164          AND vendor_id = l_vendor_id;
6165     EXCEPTION
6166       WHEN no_data_found then
6167         l_employee_id := NULL;
6168       WHEN OTHERS then
6169         l_employee_id := NULL;
6170     END;
6171 
6172 --bug5003249
6173      Begin
6174         select default_code_comb_id
6175         into  l_employee_ccid
6176         from  PER_ASSIGNMENTS_F
6177         where person_id =  l_employee_id
6178         and   set_of_books_id =  x_sob_id
6179         and   trunc(sysdate) BETWEEN trunc(effective_start_date)
6180         and   nvl(trunc(effective_end_date), trunc(sysdate));
6181      EXCEPTION
6182          WHEN OTHERS then
6183           l_employee_ccid := NULL;
6184      End;
6185 
6186         select  WEB_PARAMETER_ID,   /* Bug 8713737 - added DFF columns*/
6187                 attribute_category,
6188                 attribute1,
6189                 attribute2,
6190                 attribute3,
6191                 attribute4,
6192                 attribute5,
6193                 attribute6,
6194                 attribute7,
6195                 attribute8,
6196                 attribute9,
6197                 attribute10,
6198                 attribute11,
6199                 attribute12,
6200                 attribute13,
6201                 attribute14,
6202                 attribute15
6203         into  l_web_parameter_id,
6204             l_invoice_attribute_rec.line_attribute_category,
6205             l_invoice_attribute_rec.line_attribute1 ,
6206             l_invoice_attribute_rec.line_attribute2 ,
6207             l_invoice_attribute_rec.line_attribute3 ,
6208             l_invoice_attribute_rec.line_attribute4 ,
6209             l_invoice_attribute_rec.line_attribute5 ,
6210             l_invoice_attribute_rec.line_attribute6 ,
6211             l_invoice_attribute_rec.line_attribute7 ,
6212             l_invoice_attribute_rec.line_attribute8 ,
6213             l_invoice_attribute_rec.line_attribute9 ,
6214             l_invoice_attribute_rec.line_attribute10,
6215             l_invoice_attribute_rec.line_attribute11,
6216             l_invoice_attribute_rec.line_attribute12,
6217             l_invoice_attribute_rec.line_attribute13,
6218             l_invoice_attribute_rec.line_attribute14,
6219             l_invoice_attribute_rec.line_attribute15
6220         from  ap_invoice_lines
6221         where invoice_id = X_invoice_id
6222         AND line_number = X_line_number;
6223 
6224      /* Bug 5102724 */
6225       BEGIN
6226         SELECT  invoice_type_lookup_code, /* Bug 8713737 - added DFF columns*/
6227                 attribute_category,
6228                 attribute1,
6229                 attribute2,
6230                 attribute3,
6231                 attribute4,
6232                 attribute5,
6233                 attribute6,
6234                 attribute7,
6235                 attribute8,
6236                 attribute9,
6237                 attribute10,
6238                 attribute11,
6239                 attribute12,
6240                 attribute13,
6241                 attribute14,
6242                 attribute15
6243         INTO    l_invoice_type_lookup_code,
6244                 l_invoice_attribute_rec.attribute_category,
6245                 l_invoice_attribute_rec.attribute1,
6246                 l_invoice_attribute_rec.attribute2,
6247                 l_invoice_attribute_rec.attribute3,
6248                 l_invoice_attribute_rec.attribute4,
6249                 l_invoice_attribute_rec.attribute5,
6250                 l_invoice_attribute_rec.attribute6,
6251                 l_invoice_attribute_rec.attribute7,
6252                 l_invoice_attribute_rec.attribute8,
6253                 l_invoice_attribute_rec.attribute9,
6254                 l_invoice_attribute_rec.attribute10,
6255                 l_invoice_attribute_rec.attribute11,
6256                 l_invoice_attribute_rec.attribute12,
6257                 l_invoice_attribute_rec.attribute13,
6258                 l_invoice_attribute_rec.attribute14,
6259                 l_invoice_attribute_rec.attribute15
6260         FROM   ap_invoices_all
6261         WHERE  invoice_id = X_invoice_id;
6262       EXCEPTION
6263         WHEN no_data_found then
6264           NULL;
6265         WHEN OTHERS then
6266           NULL;
6267       END;
6268 
6269       If (l_invoice_type_lookup_code ='EXPENSE REPORT') Then
6270         l_sys_link_function :='ER' ;
6271       Else
6272         l_sys_link_function :='VI' ;
6273       End if;
6274 
6275     PA_TRANSACTIONS_PUB.VALIDATE_TRANSACTION(
6276                 X_PROJECT_ID          => X_project_id,
6277                 X_TASK_ID             => X_task_id,
6278                 X_EI_DATE             => X_expenditure_item_date,
6279                 X_EXPENDITURE_TYPE    => X_expenditure_type,
6280                 X_NON_LABOR_RESOURCE  => null,
6281                 X_PERSON_ID           => l_employee_id,
6282                 X_QUANTITY            => '1',
6283                 X_denom_currency_code => X_invoice_currency_code,
6284                 X_acct_currency_code  => X_base_currency_code,
6285                 X_denom_raw_cost      => X_amount,
6286                 X_acct_raw_cost       => X_base_amount,
6287                 X_acct_rate_type      => X_exchange_rate_type,
6288                 X_acct_rate_date      => X_exchange_date,
6289                 X_acct_exchange_rate  => X_exchange_rate,
6290                 X_TRANSFER_EI         => null,
6291                 X_INCURRED_BY_ORG_ID  => X_expenditure_org_id,
6292                 X_NL_RESOURCE_ORG_ID  => null,
6293                 X_TRANSACTION_SOURCE  => l_sys_link_function,  /* bug 5102724 */
6294                 X_CALLING_MODULE      => 'apiindib.pls',
6295                 X_VENDOR_ID           => X_vendor_id,
6296                 X_ENTERED_BY_USER_ID  => user_id,
6297                 X_ATTRIBUTE_CATEGORY  => NULL,
6298                 X_ATTRIBUTE1          => NULL,
6299                 X_ATTRIBUTE2          => NULL,
6300                 X_ATTRIBUTE3          => NULL,
6301                 X_ATTRIBUTE4          => NULL,
6302                 X_ATTRIBUTE5          => NULL,
6303                 X_ATTRIBUTE6          => NULL,
6304                 X_ATTRIBUTE7          => NULL,
6305                 X_ATTRIBUTE8          => NULL,
6306                 X_ATTRIBUTE9          => NULL,
6307                 X_ATTRIBUTE10         => NULL,
6308                 X_ATTRIBUTE11         => NULL,
6309                 X_ATTRIBUTE12         => NULL,
6310                 X_ATTRIBUTE13         => NULL,
6311                 X_ATTRIBUTE14         => NULL,
6312                 X_ATTRIBUTE15         => NULL,
6313                 X_msg_application     => l_msg_application,
6314                 X_msg_type            => l_msg_type,
6315                 X_msg_token1          => l_msg_token1,
6316                 X_msg_token2          => l_msg_token2,
6317                 X_msg_token3          => l_msg_token3,
6318                 X_msg_count           => l_msg_count,
6319                 X_msg_data            => l_msg_data,
6320                 X_BILLABLE_FLAG       => l_billable_flag);
6321 
6322     if (l_msg_data is not null) then
6323       X_msg_application := l_msg_application;
6324       X_msg_data := l_msg_data;
6325       --bugfix:5725904
6326       Fnd_Message.Set_Name(l_msg_application, l_msg_data);
6327       /*bug 6682104 setting the token values*/
6328             IF (l_msg_token1 IS NOT NULL) THEN
6329 	       fnd_message.set_token('PATC_MSG_TOKEN1',l_msg_token1);
6330             ELSE
6331 	       fnd_message.set_token('PATC_MSG_TOKEN1',FND_API.G_MISS_CHAR);
6332 	    END IF;
6333 
6334             IF (l_msg_token2 IS NOT NULL) THEN
6335 	        fnd_message.set_token('PATC_MSG_TOKEN2',l_msg_token2);
6336             ELSE
6337 	       fnd_message.set_token('PATC_MSG_TOKEN2',FND_API.G_MISS_CHAR);
6338             END IF;
6339 
6340             IF (l_msg_token3 IS NOT NULL) THEN
6341 	         fnd_message.set_token('PATC_MSG_TOKEN3',l_msg_token3);
6342             ELSE
6343 	          fnd_message.set_token('PATC_MSG_TOKEN3',FND_API.G_MISS_CHAR);
6344             END IF;
6345       l_message_text := Fnd_Message.get;
6346       x_error_code := l_message_text;
6347 
6348       return(FALSE);
6349 
6350     end if;
6351 
6352   end if;
6353 
6354 
6355   --------------------------------------------------------------------------
6356   -- Step 3 - Gather the source of the account. Possible values are
6357   -- a) Account from item distribution (if no PA information)
6358   -- b) Account from item distribution (if PA information from dist)
6359   -- c) Account from PO if accrue on receipt and dist PO matched
6360   -- d) Account from PA if PA information from line
6361   -- Also, the accounts above may be overlayed with overlay information if:
6362   -- 1) Overlay information available
6363   -- 2) If PO matched and account not from line PA info and PO allows overrides
6364   -- 3) If account from line PA info and PA allows overrides
6365   -- 4) If account from item dist, (not PO matched but PA related) and
6366   --    PA allows overrides
6367   -- 5) If account from item dist (not PO matched and not PA related)
6368   ----------------------------------------------------------------------------
6369     --Bug5003249 added condition on invoice type lookup code
6370   IF (X_project_id IS NOT NULL AND X_item_dist_project_id IS NULL
6371       AND l_invoice_type_lookup_code<>'PREPAYMENT') THEN
6372     -- l_dist_ccid := AP_UTILITIES_PKG.PA_FLEXBUILD
6373 
6374     debug_info := 'Billable Flag To PA FlexBuild '||l_billable_flag; --Bug6523162
6375 
6376     IF ( NOT (AP_UTILITIES_PKG.pa_flexbuild(
6377                p_vendor_id          =>  X_vendor_id,          --IN
6378                p_employee_id        =>  l_employee_id,        --IN
6379                p_set_of_books_id    =>  X_sob_id,             --IN
6380                p_chart_of_accounts_id => X_chart_of_accounts_id, -- IN
6381                p_base_currency_code    =>  X_base_currency_code, --IN
6382                p_accounting_date       =>  X_GL_Date,            --IN
6383                p_award_id              =>  X_award_id,           --IN
6384                P_project_id             => X_project_id,
6385                p_task_id                => X_task_id,
6386                p_expenditure_type       => X_expenditure_type,
6387                p_expenditure_org_id     => X_expenditure_org_id,
6388                p_expenditure_item_date  => X_expenditure_item_date,
6389                p_invoice_attribute_rec  => l_invoice_attribute_rec, -- bug 8713737
6390                p_billable_flag             => l_billable_flag, --Bug6523162
6391                p_employee_ccid             =>
6392                       l_employee_ccid,   --Bug5003249
6393                p_web_parameter_id          =>
6394                       l_web_parameter_id,   --Bug5003249
6395                p_invoice_type_lookup_code  =>
6396                       l_invoice_type_lookup_code, --Bug5003249
6397                p_default_last_updated_by => FND_GLOBAL.user_id,
6398                p_default_last_update_login  => FND_GLOBAL.login_id,
6399                p_pa_default_dist_ccid       => l_dist_ccid,
6400                p_pa_concatenated_segments   => l_dist_code_concat, --OUT NOCOPY
6401                p_debug_Info                 => debug_Info, -- OUT  NOCOPY
6402                p_debug_Context             =>  debug_Context, --OUT  NOCOPY
6403                p_calling_sequence          => 'Get_Proj_And_Acc_For_Chrg_Dist' ,
6404                p_default_dist_ccid         =>  X_default_dist_ccid  --IN  bug 5386396
6405                ))) THEN
6406        debug_info := debug_info || ': Error encountered';
6407        debug_context := current_calling_sequence;
6408        RETURN(FALSE);
6409     END IF;
6410     IF (X_pa_allows_overrides = 'Y' AND
6411         (X_overlay_dist_code_concat   IS NOT NULL OR
6412          X_balancing_segment   IS NOT NULL OR
6413          X_account_segment     IS NOT NULL OR
6414          X_cost_center_segment IS NOT NULL)) THEN
6415 
6416       IF ( NOT (AP_UTILITIES_PKG.OVERLAY_SEGMENTS (
6417                    X_balancing_segment,
6418                    X_cost_center_segment,
6419                    X_account_segment,
6420                    X_overlay_dist_code_concat,
6421                    l_dist_ccid,
6422                    X_sob_id,
6423                    'CREATE_COMB_NO_AT',
6424                    l_unbuilt_flex,
6425                    l_reason_unbuilt_flex,
6426                    FND_GLOBAL.RESP_APPL_ID,
6427                    FND_GLOBAL.RESP_ID,
6428                    FND_GLOBAL.USER_ID,
6429                    'Create Charge Account',
6430                    NULL,
6431                    X_GL_Date))) then --7531219
6432         X_error_code := 'AP_CANNOT_OVERLAY';
6433         RETURN(FALSE);
6434       END IF;
6435     END IF;
6436 
6437   ELSIF (X_item_po_dist_id IS NOT NULL) THEN
6438     BEGIN
6439       SELECT code_combination_id,
6440              accrue_on_receipt_flag
6441         INTO l_po_ccid,
6442              l_po_accrue_on_receipt_flag
6443         FROM po_distributions
6444        WHERE po_distribution_id = X_item_po_dist_id;
6445 
6446     EXCEPTION
6447       When no_data_found then
6448         return(FALSE);
6449     END;
6450 
6451     IF (l_po_accrue_on_receipt_flag = 'Y') THEN
6452       l_dist_ccid := l_po_ccid;
6453     ELSE
6454       l_dist_ccid := X_item_dist_ccid;
6455     END IF;
6456 
6457 
6458     IF (((X_item_dist_project_id is null and
6459           X_allow_po_override = 'Y' ) OR
6460          (X_item_dist_project_id IS NOT NULL AND
6461           X_pa_allows_overrides = 'Y' AND
6462           X_allow_po_override = 'Y')) AND
6463         (X_overlay_dist_code_concat   IS NOT NULL OR
6464          X_balancing_segment          IS NOT NULL OR
6465          X_account_segment            IS NOT NULL OR
6466          X_cost_center_segment        IS NOT NULL)
6467 
6468          ) THEN
6469 
6470       IF ( NOT (AP_UTILITIES_PKG.OVERLAY_SEGMENTS (
6471                    X_balancing_segment,
6472                    X_cost_center_segment,
6473                    X_account_segment,
6474                    X_overlay_dist_code_concat,
6475                    l_dist_ccid,
6476                    X_sob_id,
6477                    'CREATE_COMB_NO_AT',
6478                    l_unbuilt_flex,
6479                    l_reason_unbuilt_flex,
6480                    FND_GLOBAL.RESP_APPL_ID,
6481                    FND_GLOBAL.RESP_ID,
6482                    FND_GLOBAL.USER_ID,
6483                    'Create Charge Account',
6484                    NULL,
6485                    X_GL_Date))) THEN --7531219
6486         X_error_code := 'AP_CANNOT_OVERLAY';
6487         RETURN(FALSE);
6488       END IF;
6489 
6490     ELSE
6491       IF ( NOT (AP_UTILITIES_PKG.IS_CCID_VALID(
6492                   l_dist_ccid,
6493                   X_chart_of_accounts_id,
6494                   X_GL_date,
6495                   'Create Charge Account'))) THEN
6496         X_error_code := 'AP_INVALID_ACCOUNT';
6497         RETURN(FALSE);
6498       END IF;
6499 
6500     END IF;
6501 
6502   ELSE
6503     l_dist_ccid := X_item_dist_ccid;
6504     if (X_overlay_dist_code_concat IS NOT NULL OR
6505         X_balancing_segment   IS NOT NULL OR
6506         X_account_segment     IS NOT NULL OR
6507         X_cost_center_segment IS NOT NULL) THEN
6508 
6509       IF ( NOT (AP_UTILITIES_PKG.OVERLAY_SEGMENTS (
6510                   X_balancing_segment,
6511                   X_cost_center_segment,
6512                   X_account_segment,
6513                   X_overlay_dist_code_concat,
6514                   l_dist_ccid,
6515                   X_sob_id,
6516                   'CREATE_COMB_NO_AT',
6517                   l_unbuilt_flex,
6518                   l_reason_unbuilt_flex,
6519                   FND_GLOBAL.RESP_APPL_ID,
6520                   FND_GLOBAL.RESP_ID,
6521                   FND_GLOBAL.USER_ID,
6522                   'Create Charge Account',
6523                   NULL,
6524                   X_GL_Date))) then --7531219
6525         X_error_code := 'AP_CANNOT_OVERLAY';
6526         RETURN(FALSE);
6527       END IF;
6528     ELSE
6529       IF ( NOT (AP_UTILITIES_PKG.IS_CCID_VALID(l_dist_ccid,
6530                                                X_chart_of_accounts_id,
6531                                                X_GL_date,
6532                                                'Create Charge Account'))) then
6533         X_error_code := 'AP_INVALID_ACCOUNT';
6534         RETURN(FALSE);
6535       END IF;
6536     END IF;
6537   END IF;
6538 
6539   X_account_for_dist := l_dist_ccid;
6540 
6541   -------------------------------------------------------------------
6542   -- Step 4 - Get account type and asset information
6543   -------------------------------------------------------------------
6544   BEGIN
6545     SELECT account_type
6546       INTO l_account_type
6547       FROM gl_code_combinations
6548      WHERE code_combination_id = l_dist_ccid;
6549 
6550   EXCEPTION
6551     WHEN no_data_found THEN
6552        RETURN(FALSE);
6553   END;
6554 
6555   IF (l_account_type = 'A') THEN
6556     X_assets_tracking_flag := 'Y';
6557     X_asset_book_typ_code := nvl(X_item_asset_book_type_code,
6558                                   X_chrg_asset_book_type_code);
6559     X_asset_category_id := nvl(X_item_asset_category_id,
6560                                       X_chrg_asset_category_id);
6561   ELSIF (l_account_type = 'E' AND
6562          X_chrg_assets_track_flag = 'Y') THEN
6563     X_assets_tracking_flag := 'Y';
6564     X_asset_book_typ_code := X_chrg_asset_book_type_code;
6565     X_asset_category_id := X_chrg_asset_category_id;
6566   ELSE
6567     X_assets_tracking_flag := 'N';
6568     X_asset_book_typ_code := NULL;
6569     X_asset_category_id := NULL;
6570   END IF;
6571 
6572   IF (X_item_dist_award_id IS NOT NULL) THEN
6573       gms_ap_api.get_distribution_award
6574 			(p_invoice_id		    => NULL,
6575 			 p_distribution_line_number => NULL,
6576 			 p_invoice_distribution_id  => NULL,
6577 			 p_award_set_id             => x_item_dist_award_id,
6578 			 p_award_id		    => x_award_id);
6579 
6580   ELSIF (X_chrg_line_award_id is not null) then
6581     x_award_id := X_chrg_line_award_id;
6582   ELSE
6583     x_award_id := NULL;
6584   END IF;
6585 
6586   IF (X_award_id IS NOT NULL AND X_item_dist_award_id IS NOT NULL) then
6587 
6588 	current_calling_sequence := 'AWARD_ID'; -- Bug 8600813: required when award_id is passed
6589 
6590 	GMS_AP_API.validate_transaction
6591 			( x_project_id		  => X_project_id,
6592 			  x_task_id		  => X_task_id,
6593 			  x_award_id		  => X_award_id,
6594 			  x_expenditure_type	  => X_expenditure_type,
6595  			  x_expenditure_item_date => X_expenditure_item_date,
6596 			  x_calling_sequence	  => current_calling_sequence,
6597 			  x_msg_application       => l_msg_application,
6598 			  x_msg_type              => l_msg_type,
6599 			  x_msg_count             => l_msg_count,
6600 			  x_msg_data              => l_msg_data );
6601 
6602 	IF (l_msg_data is not null) THEN
6603 	    X_msg_application := l_msg_application;
6604 	    X_msg_data := l_msg_data;
6605 	    X_error_code := X_msg_data;  -- bug 7936518
6606 	    Return(FALSE);
6607 	END IF;
6608   END IF;
6609 
6610   RETURN(TRUE);
6611 
6612 END get_proj_and_acc_for_chrg_dist;
6613 
6614 
6615   -----------------------------------------------------------------------
6616   -- FUNCTION insert_charge_from_alloc inserts charge distributions based
6617   -- on the defined allocations for the parent line.
6618   -- It returns FALSE if an error is encountered.
6619   -----------------------------------------------------------------------
6620   FUNCTION Insert_Charge_From_Alloc(
6621            X_invoice_id          IN         NUMBER,
6622            X_line_number         IN         NUMBER,
6623            X_Generate_Permanent  IN         VARCHAR2 DEFAULT 'N',
6624            X_Validate_Info       IN         BOOLEAN DEFAULT TRUE,
6625            X_Error_Code          OUT NOCOPY VARCHAR2,
6626            X_Debug_Info          OUT NOCOPY VARCHAR2,
6627            X_Debug_Context       OUT NOCOPY VARCHAR2,
6628            X_Msg_Application     OUT NOCOPY VARCHAR2,
6629            X_Msg_Data            OUT NOCOPY VARCHAR2,
6630            X_Calling_Sequence    IN         VARCHAR2) RETURN BOOLEAN
6631   IS
6632 
6633   CURSOR alloc_rule_lines_cur IS
6634   SELECT ARL.to_invoice_line_number,
6635          ARL.percentage,
6636          ARL.amount,
6637          Sum(AID.amount)
6638     FROM AP_Allocation_Rule_Lines ARL,
6639          AP_invoice_distributions_all AID
6640     WHERE ARL.invoice_id = X_invoice_id
6641       AND AID.invoice_id = X_invoice_id
6642       AND ARL.chrg_invoice_line_number = X_line_number
6643       AND AID.invoice_line_number = ARL.to_invoice_line_number
6644       AND AID.line_type_lookup_code in ('ITEM', 'ACCRUAL', 'IPV', 'ERV')
6645   --Invoice Lines: Distributions,  Added the ARL.amount, ARL.percentage
6646   --to the GROUP BY , without those cursor is INVALID
6647   GROUP BY ARL.to_invoice_line_number, ARL.amount,ARL.percentage
6648   ORDER BY ARL.to_invoice_line_number;
6649 
6650 
6651   CURSOR applicable_lines_cur IS
6652     SELECT AIL.line_number,
6653            AIL.amount,
6654            sum(AID.amount)
6655       FROM AP_invoice_lines AIL,
6656            AP_invoice_distributions_all AID
6657      WHERE AIL.invoice_id = X_invoice_id
6658        AND nvl(AIL.discarded_flag, 'N') = 'N'
6659        AND nvl(AIL.cancelled_flag, 'N') = 'N'
6660        AND AIL.amount <> 0
6661        AND AIL.line_type_lookup_code = 'ITEM'
6662        AND nvl(AIL.match_type,'NOT_MATCHED') NOT IN
6663  	      ('PRICE_CORRECTION', 'QTY_CORRECTION','LINE_CORRECTION','AMOUNT_CORRECTION')
6664        AND AID.invoice_line_number = AIL.line_number
6665        AND AID.invoice_id = X_invoice_id
6666        AND AID.line_type_lookup_code IN ('ITEM', 'ACCRUAL', 'IPV', 'ERV')
6667   --Invoice Lines: Distributions, added AIL.amount to the GROUPBY clause
6668   GROUP BY AIL.line_number,AIL.amount
6669   ORDER BY AIL.line_number;
6670 
6671   CURSOR applicable_dists_cur (P_line_number IN NUMBER) IS
6672     SELECT AID.invoice_distribution_id,
6673            AID.po_distribution_id,
6674            AID.rcv_transaction_id,
6675            AID.project_id,
6676            AID.task_id,
6677 	   AID.pa_quantity,   -- bug6699834
6678            AID.expenditure_type,
6679            AID.expenditure_organization_id,
6680            AID.award_id,
6681 	   AP_INVOICE_DISTRIBUTIONS_PKG.GET_TOTAL_DIST_AMOUNT(
6682 			aid.invoice_distribution_id),
6683            AID.dist_code_combination_id,
6684            AID.assets_tracking_flag,
6685            AID.asset_book_type_code,
6686            AID.asset_category_id,
6687            AID.description
6688       FROM ap_invoice_distributions_all AID
6689      WHERE AID.invoice_id = X_invoice_id
6690        AND AID.invoice_line_number = P_line_number
6691        AND AID.line_type_lookup_code in ('ITEM', 'ACCRUAL')
6692   ORDER BY AID.distribution_line_number;
6693 
6694 
6695   l_batch_id               AP_INVOICE_DISTRIBUTIONS.BATCH_ID%TYPE;
6696   l_distribution_class     AP_INVOICE_DISTRIBUTIONS.DISTRIBUTION_CLASS%TYPE;
6697   l_org_id                 AP_INVOICE_LINES.ORG_ID%TYPE;
6698   l_sob_id                 AP_INVOICE_LINES.SET_OF_BOOKS_ID%TYPE;
6699   l_base_currency_code     AP_SYSTEM_PARAMETERS.BASE_CURRENCY_CODE%TYPE;
6700   l_chart_of_accounts_id   GL_SETS_OF_BOOKS.CHART_OF_ACCOUNTS_ID%TYPE;
6701   l_account_type           GL_CODE_COMBINATIONS.ACCOUNT_TYPE%TYPE;
6702   l_invoice_date           AP_INVOICES.INVOICE_DATE%TYPE;
6703   l_vendor_id              AP_INVOICES.VENDOR_ID%TYPE;
6704   l_invoice_amount         AP_INVOICES.INVOICE_AMOUNT%TYPE;
6705   l_exchange_rate          AP_INVOICES.EXCHANGE_RATE%TYPE;
6706   l_exchange_rate_type     AP_INVOICES.EXCHANGE_RATE_TYPE%TYPE;
6707   l_exchange_date          AP_INVOICES.EXCHANGE_DATE%TYPE;
6708   l_invoice_currency_code  AP_INVOICES.INVOICE_CURRENCY_CODE%TYPE;
6709   l_assets_tracking_flag   AP_INVOICE_LINES.ASSETS_TRACKING_FLAG%TYPE;
6710   l_asset_book_type_code   AP_INVOICE_LINES.ASSET_BOOK_TYPE_CODE%TYPE;
6711   l_asset_category_id      AP_INVOICE_LINES.ASSET_CATEGORY_ID%TYPE;
6712   l_line_amount            AP_INVOICE_LINES.AMOUNT%TYPE;
6713   l_line_base_amount       AP_INVOICE_LINES.BASE_AMOUNT%TYPE;
6714   l_line_type_lookup_code  AP_INVOICE_LINES.LINE_TYPE_LOOKUP_CODE%TYPE;
6715   l_line_description       AP_INVOICE_LINES.DESCRIPTION%TYPE;
6716   l_sum_lines_amount       AP_INVOICE_LINES.AMOUNT%TYPE;
6717   l_default_dist_ccid      AP_INVOICE_LINES.DEFAULT_DIST_CCID%TYPE;
6718   l_overlay_dist_concat    AP_INVOICE_LINES.OVERLAY_DIST_CODE_CONCAT%TYPE;
6719   l_balancing_segment      AP_INVOICE_LINES.BALANCING_SEGMENT%TYPE;
6720   l_account_segment        AP_INVOICE_LINES.ACCOUNT_SEGMENT%TYPE;
6721   l_cost_center_segment    AP_INVOICE_LINES.COST_CENTER_SEGMENT%TYPE;
6722   l_project_id             AP_INVOICE_LINES.PROJECT_ID%TYPE;
6723   l_task_id                AP_INVOICE_LINES.TASK_ID%TYPE;
6724   l_award_id		   AP_INVOICE_LINES.AWARD_ID%TYPE;
6725   l_expenditure_type       AP_INVOICE_LINES.EXPENDITURE_TYPE%TYPE;
6726   l_expenditure_organization_id
6727     AP_INVOICE_LINES.EXPENDITURE_ORGANIZATION_ID%TYPE;
6728   l_accounting_date        AP_INVOICE_LINES.ACCOUNTING_DATE%TYPE;
6729   l_created_by             AP_INVOICE_LINES.CREATED_BY%TYPE;
6730   l_last_update_login      AP_INVOICE_LINES.LAST_UPDATE_LOGIN%TYPE;
6731   l_awt_group_id           AP_INVOICE_LINES.AWT_GROUP_ID%TYPE;
6732 
6733 l_pay_awt_group_id           AP_INVOICE_LINES.PAY_AWT_GROUP_ID%TYPE;	---7022001
6734 
6735   l_type_1099              AP_INVOICE_LINES.TYPE_1099%TYPE;
6736   l_income_tax_region      AP_INVOICE_LINES.INCOME_TAX_REGION%TYPE;
6737   l_open_gl_date           AP_INVOICE_LINES.ACCOUNTING_DATE%TYPE;
6738   l_open_period_name       AP_INVOICE_LINES.PERIOD_NAME%TYPE;
6739   l_invoice_distribution_id
6740     AP_INVOICE_DISTRIBUTIONS.INVOICE_DISTRIBUTION_ID%TYPE;
6741   l_po_distribution_id     AP_INVOICE_DISTRIBUTIONS.PO_DISTRIBUTION_ID%TYPE;
6742   l_rcv_transaction_id     AP_INVOICE_DISTRIBUTIONS.RCV_TRANSACTION_ID%TYPE;
6743   l_dist_project_id        AP_INVOICE_DISTRIBUTIONS.PROJECT_ID%TYPE;
6744   l_dist_task_id           AP_INVOICE_DISTRIBUTIONS.TASK_ID%TYPE;
6745   l_dist_pa_quantity       AP_INVOICE_DISTRIBUTIONS.PA_QUANTITY%TYPE; --6699834
6746   l_dist_award_id          AP_INVOICE_DISTRIBUTIONS.AWARD_ID%TYPE;
6747   l_dist_expenditure_type  AP_INVOICE_DISTRIBUTIONS.EXPENDITURE_TYPE%TYPE;
6748   l_dist_expenditure_org_id
6749     AP_INVOICE_DISTRIBUTIONS.EXPENDITURE_ORGANIZATION_ID%TYPE;
6750   l_dist_amount            AP_INVOICE_DISTRIBUTIONS.AMOUNT%TYPE;
6751   l_dist_base_amount       AP_INVOICE_DISTRIBUTIONS.BASE_AMOUNT%TYPE;
6752   l_dist_code_combination_id
6753     AP_INVOICE_DISTRIBUTIONS.DIST_CODE_COMBINATION_ID%TYPE;
6754   l_dist_assets_tracking_flag
6755     AP_INVOICE_DISTRIBUTIONS.ASSETS_TRACKING_FLAG%TYPE;
6756   l_dist_asset_book_type_code
6757     AP_INVOICE_DISTRIBUTIONS.ASSET_BOOK_TYPE_CODE%TYPE;
6758   l_dist_asset_category_id
6759     AP_INVOICE_DISTRIBUTIONS.ASSET_CATEGORY_ID%TYPE;
6760   l_dist_description       AP_INVOICE_DISTRIBUTIONS.DESCRIPTION%TYPE;
6761   l_dist_tab               AP_INVOICE_LINES_PKG.dist_tab_type;
6762   l_alloc_line_tab         AP_INVOICE_LINES_PKG.alloc_line_tab_type;
6763   l_rule_type              AP_ALLOCATION_RULES.RULE_TYPE%TYPE;
6764   l_rule_status            AP_ALLOCATION_RULES.STATUS%TYPE;
6765   l_alloc_rule_line_percent AP_ALLOCATION_RULE_LINES.PERCENTAGE%TYPE := 0;
6766   l_alloc_rule_line_amount AP_ALLOCATION_RULE_LINES.AMOUNT%TYPE := 0;
6767   l_alloc_rule_line_number
6768     AP_ALLOCATION_RULE_LINES.TO_INVOICE_LINE_NUMBER%TYPE;
6769   l_applicable_line_number AP_INVOICE_LINES.LINE_NUMBER%TYPE;
6770   l_applicable_line_amount AP_INVOICE_LINES.AMOUNT%TYPE := 0;
6771   l_sum_applic_lines       AP_INVOICE_LINES.AMOUNT%TYPE := 0;
6772   l_sum_dists_applic_line  AP_INVOICE_DISTRIBUTIONS.AMOUNT%TYPE := 0;
6773   l_running_total_alloc    AP_INVOICE_LINES.AMOUNT%TYPE := 0;
6774   l_running_total_base_amt AP_INVOICE_LINES.BASE_AMOUNT%TYPE := 0;
6775   l_max_alloc              AP_INVOICE_LINES.AMOUNT%TYPE := 0;
6776   l_max_base_alloc         AP_INVOICE_LINES.BASE_AMOUNT%TYPE := 0;
6777   --Bug9296445
6778   l_reference_1	           AP_INVOICE_LINES.REFERENCE_1%TYPE;
6779   l_reference_2		   AP_INVOICE_LINES.REFERENCE_2%TYPE;
6780 
6781   l_msg_application      VARCHAR2(25);
6782   l_msg_data           VARCHAR2(200);  /*bug12612482 changed from 30 to 200*/
6783   i                        BINARY_INTEGER := 0;
6784   t                        BINARY_INTEGER := 0;
6785   l_max_i                  BINARY_INTEGER := 0;
6786   l_max_base_i             BINARY_INTEGER := 0;
6787   l_max_t                  BINARY_INTEGER := 0;
6788   l_pa_allows_overrides    VARCHAR2(1) := 'N';
6789   l_allow_po_override      AP_SYSTEM_PARAMETERS.ALLOW_FLEX_OVERRIDE_FLAG%TYPE;
6790   l_error_found            VARCHAR2(1) := 'N';
6791   l_error_code             VARCHAR2(4000); --bug13436794, changed length to 4000 from 80
6792   l_existing_distributions NUMBER := 0;
6793   l_count_undistributed_lines NUMBER := 1;
6794   l_count_applicable_dists NUMBER := 0;
6795   current_calling_sequence VARCHAR2(2000);
6796   debug_info               VARCHAR2(1000);
6797 
6798   l_inv_dist_id		   AP_INVOICE_DISTRIBUTIONS.INVOICE_DISTRIBUTION_ID%TYPE;
6799 
6800   -- Bug 5114543
6801   l_max_dist_line_num	   NUMBER :=0;
6802   l_chrg_line_rec	   ap_invoice_lines_all%rowtype;
6803   l_dummy		   VARCHAR2(30);
6804 
6805   l_country_code VARCHAR2(20);   --bug 9169915
6806   l_stat_amount AP_INVOICE_LINES.STAT_AMOUNT%TYPE; --Bug#10241241
6807   l_dist_updated  NUMBER;  --Bug#10241241
6808   -- Bug 13841774. Start.
6809   l_copy_line_dff_flag     VARCHAR2(1);
6810   l_line_source            AP_INVOICE_LINES.LINE_SOURCE%TYPE;
6811   l_attribute_category     AP_INVOICE_LINES.ATTRIBUTE_CATEGORY%TYPE;
6812   l_attribute1             AP_INVOICE_LINES.ATTRIBUTE1%TYPE;
6813   l_attribute2             AP_INVOICE_LINES.ATTRIBUTE2%TYPE;
6814   l_attribute3             AP_INVOICE_LINES.ATTRIBUTE3%TYPE;
6815   l_attribute4             AP_INVOICE_LINES.ATTRIBUTE4%TYPE;
6816   l_attribute5             AP_INVOICE_LINES.ATTRIBUTE5%TYPE;
6817   l_attribute6             AP_INVOICE_LINES.ATTRIBUTE6%TYPE;
6818   l_attribute7             AP_INVOICE_LINES.ATTRIBUTE7%TYPE;
6819   l_attribute8             AP_INVOICE_LINES.ATTRIBUTE8%TYPE;
6820   l_attribute9             AP_INVOICE_LINES.ATTRIBUTE9%TYPE;
6821   l_attribute10            AP_INVOICE_LINES.ATTRIBUTE10%TYPE;
6822   l_attribute11            AP_INVOICE_LINES.ATTRIBUTE11%TYPE;
6823   l_attribute12            AP_INVOICE_LINES.ATTRIBUTE12%TYPE;
6824   l_attribute13            AP_INVOICE_LINES.ATTRIBUTE13%TYPE;
6825   l_attribute14            AP_INVOICE_LINES.ATTRIBUTE14%TYPE;
6826   l_attribute15            AP_INVOICE_LINES.ATTRIBUTE15%TYPE;
6827   -- Bug 13841774. End.
6828 
6829 BEGIN
6830 
6831 
6832   ---------------------------------------------------------------------------
6833   -- Step 1 - Update the calling sequence
6834   ---------------------------------------------------------------------------
6835   current_calling_sequence :=
6836     'AP_INVOICE_DISTRIBUTIONS_PKG.insert_charge_from_alloc <-'
6837     ||X_calling_sequence;
6838 
6839   --------------------------------------------------------------------------
6840   -- Step 2 - Validate the line exists and get line level information
6841   --------------------------------------------------------------------------
6842   debug_info := 'Verify valid invoice line provided';
6843   BEGIN
6844     SELECT org_id,
6845            set_of_books_id,
6846            default_dist_ccid,
6847            overlay_dist_code_concat,
6848            balancing_segment,
6849            account_segment,
6850            cost_center_segment,
6851            project_id,
6852            task_id,
6853 	   award_id,
6854            expenditure_type,
6855            expenditure_organization_id,
6856            assets_tracking_flag,
6857            asset_book_type_code,
6858            asset_category_id,
6859            accounting_date,
6860            amount,
6861            base_amount,
6862            line_type_lookup_code,
6863            description,
6864            awt_group_id,
6865            type_1099,
6866            income_tax_region,
6867            created_by,
6868            last_update_login,
6869            pay_awt_group_id,
6870 	   --Bug9296445
6871 	   reference_1,
6872 	   reference_2,
6873 	   stat_amount, --10241241
6874 	   -- Bug 13841774. Start.
6875 	   NVL(line_source, 'DUMMY'),
6876 	   attribute_category,
6877 	   attribute1,
6878            attribute2,
6879            attribute3,
6880            attribute4,
6881            attribute5,
6882 	   attribute6,
6883 	   attribute7,
6884 	   attribute8,
6885 	   attribute9,
6886 	   attribute10,
6887 	   attribute11,
6888 	   attribute12,
6889 	   attribute13,
6890 	   attribute14,
6891 	   attribute15
6892 	   -- Bug 13841774. End.
6893       INTO l_org_id,
6894            l_sob_id,
6895            l_default_dist_ccid,
6896            l_overlay_dist_concat,
6897            l_balancing_segment,
6898            l_account_segment,
6899            l_cost_center_segment,
6900            l_project_id,
6901            l_task_id,
6902 	   l_award_id,
6903            l_expenditure_type,
6904            l_expenditure_organization_id,
6905            l_assets_tracking_flag,
6906            l_asset_book_type_code,
6907            l_asset_category_id,
6908            l_accounting_date,
6909            l_line_amount,
6910            l_line_base_amount,
6911            l_line_type_lookup_code,
6912            l_line_description,
6913            l_awt_group_id,
6914            l_type_1099,
6915            l_income_tax_region,
6916            l_created_by,
6917            l_last_update_login,
6918            l_pay_awt_group_id,
6919            --Bug9296445
6920 	   l_reference_1,
6921 	   l_reference_2,
6922 	   l_stat_amount, --10241241
6923 	   -- Bug 13841774. Start.
6924            l_line_source,
6925            l_attribute_category,
6926            l_attribute1,
6927            l_attribute2,
6928            l_attribute3,
6929            l_attribute4,
6930            l_attribute5,
6931            l_attribute6,
6932            l_attribute7,
6933            l_attribute8,
6934            l_attribute9,
6935 	   l_attribute10,
6936 	   l_attribute11,
6937 	   l_attribute12,
6938 	   l_attribute13,
6939 	   l_attribute14,
6940 	   l_attribute15
6941 	   -- Bug 13841774. End.
6942       FROM ap_invoice_lines
6943      WHERE invoice_id = X_invoice_id
6944        AND line_number = X_line_number;
6945 
6946   EXCEPTION
6947     WHEN NO_DATA_FOUND THEN
6948       X_debug_info := debug_info || ': line not found';
6949       X_debug_context := current_calling_sequence;
6950       RETURN (FALSE);
6951 
6952   END;
6953   --------------------------------------------------------------------------
6954   -- Step 3 - Validate line does not contain other distributions
6955   --------------------------------------------------------------------------
6956   IF (X_Validate_Info) then
6957     debug_info := 'Verify line does not contain distributions';
6958     BEGIN
6959       SELECT count(*)
6960         INTO l_existing_distributions
6961         FROM ap_invoice_distributions
6962        WHERE invoice_id = X_invoice_id
6963          AND invoice_line_number = X_line_number
6964 		 AND rownum=1; --13507856 added the rownum condition to improve the performance
6965 
6966       IF (l_existing_distributions <> 0) then
6967           -- X_debug_info := debug_info || ': line already has distributions';
6968           -- X_debug_context := current_calling_sequence;
6969           -- RETURN(FALSE);
6970 
6971           -- Bug 5114543
6972 	  -- Instead of returning a failure, reverse any open inv distributions and
6973 	  -- continue with creation of charge distributions based on the allocation.
6974 
6975 	  select ail.*
6976             into l_chrg_line_rec
6977 	    from ap_invoice_lines_all ail
6978 	   where invoice_id  = X_invoice_id
6979 	     and line_number = X_line_number;
6980 
6981           if not ap_invoice_lines_pkg.reverse_charge_distributions
6982 		                        (p_inv_line_rec         => l_chrg_line_rec
6983 		                        ,p_calling_mode         => l_dummy
6984 		                        ,x_error_code           => x_error_code
6985 		                        ,x_debug_info           => debug_info
6986 		                        ,p_calling_sequence     => current_calling_sequence) then
6987 
6988 	     x_debug_info := debug_info || ': unable to reverse charge distributions';
6989 	     x_debug_context := current_calling_sequence;
6990 	     return (false);
6991 
6992           end if;
6993       END IF;
6994 
6995     EXCEPTION
6996       WHEN OTHERS THEN
6997         NULL;
6998     END;
6999   END IF;
7000 
7001   --------------------------------------------------------------------------
7002   -- Step 4 - Get invoice information
7003   --------------------------------------------------------------------------
7004   debug_info := 'Get invoice information';
7005   BEGIN
7006     SELECT batch_id,
7007            invoice_date,
7008            vendor_id,
7009            exchange_rate,
7010            exchange_rate_type,
7011            exchange_date,
7012            invoice_currency_code,
7013            invoice_amount
7014       INTO l_batch_id,
7015            l_invoice_date,
7016            l_vendor_id,
7017            l_exchange_rate,
7018            l_exchange_rate_type,
7019            l_exchange_date,
7020            l_invoice_currency_code,
7021            l_invoice_amount
7022       FROM ap_invoices
7023      WHERE invoice_id = X_invoice_id;
7024 
7025   EXCEPTION
7026     When no_data_found then
7027       X_debug_info := debug_info || ': cannot read invoice';
7028       X_debug_context := current_calling_sequence;
7029       RETURN (FALSE);
7030   END;
7031 
7032   ---------------------------------------------------------------------------
7033   -- Step 5 - Validate all lines charge is allocated to have been distributed
7034   ---------------------------------------------------------------------------
7035   debug_info := 'Verify all lines to allocate against are distributed';
7036 
7037   BEGIN
7038     SELECT rule_type, status
7039       INTO l_rule_type, l_rule_status
7040       FROM ap_allocation_rules
7041      WHERE invoice_id = X_invoice_id
7042        AND chrg_invoice_line_number = X_line_number;
7043 
7044   EXCEPTION
7045     WHEN no_data_found THEN
7046       X_error_code := 'AP_NO_ALLOCATION_RULE_FOUND';
7047       RETURN(FALSE);
7048   END;
7049 
7050   IF (l_rule_status = 'EXECUTED') then
7051     X_error_code := 'AP_ALLOCATION_ALREADY_EXECUTED';
7052     RETURN(FALSE);
7053   END IF;
7054 
7055   IF (l_rule_type = 'PRORATION') then
7056     BEGIN
7057       --Bug 5558693
7058       SELECT DECODE(NVL(ai.net_of_retainage_flag, 'N'),
7059                    'Y', (SUM(NVL(ail.amount, 0)) + SUM(NVL(retained_amount,0))),
7060                     SUM(ail.amount) )
7061         INTO l_sum_lines_amount
7062         FROM ap_invoice_lines_all ail,
7063              ap_invoices_all ai
7064        WHERE ai.invoice_id = ail.invoice_id
7065          AND ail.invoice_id = X_invoice_id
7066          AND ail.line_type_lookup_code NOT IN ('AWT')
7067 	 /*bugfix:5685469*/
7068 	 AND    ((AIL.line_type_lookup_code <> 'TAX'
7069 	          and (AIL.line_type_lookup_code NOT IN ('PREPAY')
7070 		       or NVL(AIL.invoice_includes_prepay_flag,'N') = 'Y'
7071 		      )
7072 		 OR
7073 		 (AIL.line_type_lookup_code = 'TAX'
7074                   and (AIL.prepay_invoice_id IS NULL
7075                       or (AIL.prepay_invoice_id is not null
7076                           and NVL(AIL.invoice_includes_prepay_flag, 'N') = 'Y'
7077 			 )
7078 	       	      )
7079 		 )
7080 		)
7081 	       )
7082           group by ai.net_of_retainage_flag;
7083 
7084     EXCEPTION
7085       When no_data_found then
7086         X_debug_info := debug_info || ': cannot read lines for invoice';
7087         X_debug_context := current_calling_sequence;
7088         RETURN(FALSE);
7089     END;
7090 
7091     IF (l_invoice_amount <> l_sum_lines_amount) then
7092       X_error_code := 'AP_NON_FULL_INVOICE';
7093       RETURN(FALSE);
7094     END IF;
7095 
7096     BEGIN
7097       SELECT count(*)
7098         INTO l_count_undistributed_lines
7099         FROM ap_invoice_lines_all AIL
7100        WHERE AIL.invoice_id = X_invoice_id
7101          AND AIL.line_type_lookup_code = 'ITEM'
7102          AND NVL(AIL.match_type,'NOT_MATCHED') NOT IN
7103 		('PRICE_CORRECTION', 'QTY_CORRECTION','LINE_CORRECTION','AMOUNT_CORRECTION')
7104          --Bug 5558693
7105          AND amount  <>
7106                (SELECT NVL(SUM(NVL(aid.amount,0)),0)
7107                           FROM ap_invoice_distributions_all AID
7108                          WHERE AID.invoice_id = ail.invoice_id
7109                            AND AID.invoice_line_number = AIL.line_number
7110                            AND (AID.line_type_lookup_code NOT IN ('RETAINAGE','PREPAY')
7111                                 OR (AID.prepay_distribution_id IS NOT NULL
7112                                      AND AID.line_type_lookup_code IN ('REC_TAX', 'NONREC_TAX', 'TIPV', 'TRV', 'TERV')))
7113                 );
7114 
7115       IF (l_count_undistributed_lines <> 0) then
7116         X_error_code := 'AP_UNDISTRIBUTED_LINE_EXISTS';
7117         RETURN(FALSE);
7118       END IF;
7119     EXCEPTION
7120       WHEN no_data_found THEN
7121         X_debug_info := debug_info || ': cannot read lines for invoice';
7122         X_debug_context := current_calling_sequence;
7123     END;
7124 
7125   ELSE
7126     BEGIN
7127 
7128       SELECT count(*)
7129         INTO l_count_undistributed_lines
7130         FROM ap_invoice_lines AIL, ap_allocation_rule_lines ARL
7131        WHERE AIL.invoice_id = X_invoice_id
7132          AND ARL.invoice_id = X_invoice_id
7133          AND ARL.chrg_invoice_line_number = X_line_number
7134          AND ARL.to_invoice_line_number = AIL.line_number
7135          --Bug 5558693
7136          AND AIL.amount <> (SELECT NVL(SUM(nvl(amount,0)),0)
7137                               FROM ap_invoice_distributions AID
7138                              WHERE AID.invoice_id = AIL.invoice_id
7139                                AND AID.invoice_line_number = AIL.line_number
7140                                AND (AID.line_type_lookup_code NOT IN ('RETAINAGE','PREPAY')
7141                                 OR (AID.prepay_distribution_id IS NOT NULL
7142                                      AND AID.line_type_lookup_code IN ('REC_TAX', 'NONREC_TAX', 'TIPV', 'TRV', 'TERV')))
7143                            );
7144 
7145       IF (l_count_undistributed_lines <> 0) then
7146         X_error_code := 'AP_UNDISTRIBUTED_LINE_EXISTS';
7147         RETURN(FALSE);
7148       END IF;
7149     EXCEPTION
7150       WHEN NO_DATA_FOUND THEN
7151         X_debug_info := debug_info || ': cannot read lines for invoice';
7152         X_debug_context := current_calling_sequence;
7153     END;
7154   END IF;
7155 
7156   ---------------------------------------------------------------------------
7157   -- Step 6 - Get GL Date and Period name.
7158   ---------------------------------------------------------------------------
7159   debug_info :=
7160     'Get gl date from open period if line gl date is in a closed one';
7161   BEGIN
7162     l_open_period_name := NULL;
7163     l_open_period_name := AP_UTILITIES_PKG.GET_CURRENT_GL_DATE(
7164                                     l_accounting_date,
7165 				    l_org_id);
7166 
7167     IF (l_open_period_name is NULL) then
7168       AP_UTILITIES_PKG.GET_OPEN_GL_DATE(l_accounting_date, l_open_period_name,
7169                                         l_open_gl_date,l_org_id);
7170     --Invoice Lines: Distributions, added the ELSE part of the IF condition
7171     ELSE
7172       l_open_gl_date := l_accounting_date;
7173     END IF;
7174 
7175     IF (l_open_period_name is NULL) THEN
7176       X_error_code := 'AP_NO_OPEN_PERIOD';
7177       RETURN(FALSE);
7178     END IF;
7179   END;
7180 
7181 
7182   --------------------------------------------------------------
7183   -- Step 7 - Get system level information necessary for
7184   -- validation and generation of distributions
7185   --------------------------------------------------------------
7186   debug_info := 'Get system information';
7187   BEGIN
7188     SELECT gsob.chart_of_accounts_id, ap.base_currency_code,
7189            ap.allow_flex_override_flag
7190       INTO l_chart_of_accounts_id, l_base_currency_code,
7191            l_allow_po_override
7192       FROM ap_system_parameters ap, gl_sets_of_books gsob
7193      WHERE ap.set_of_books_id = gsob.set_of_books_id
7194            AND ap.org_id = l_org_id; -- Bug 13858818
7195 
7196   l_pa_allows_overrides :=
7197     FND_PROFILE.VALUE('PA_ALLOW_FLEXBUILDER_OVERRIDES');
7198 
7199   EXCEPTION
7200   WHEN no_data_found THEN
7201     Debug_info := debug_info || ': No GL information was found';
7202     X_debug_context := current_calling_sequence;
7203     X_debug_info := debug_info;
7204     RETURN(FALSE);
7205   END;
7206 
7207 
7208   --------------------------------------------------------------------------
7209   -- Step 8 - Commence proration to all applicable lines.
7210   -- Verify per line that we may not divide by 0 (which could happen
7211   -- if all distributions for a line are of type other than ITEM or
7212   -- ACCRUAL (IPV and ERV included).  Will divide sql into the 3 rule types.
7213   --------------------------------------------------------------------------
7214   debug_info := 'Commence proration';
7215   BEGIN
7216     IF (l_rule_type = 'PRORATION') THEN
7217       t := 0;
7218       BEGIN
7219         OPEN applicable_lines_cur;
7220         LOOP
7221           FETCH applicable_lines_cur
7222            INTO l_applicable_line_number,
7223                 l_applicable_line_amount,
7224                 l_sum_dists_applic_line;
7225 
7226           EXIT WHEN applicable_lines_cur%NOTFOUND;
7227 
7228           IF (l_sum_dists_applic_line <> 0) THEN
7229             l_sum_applic_lines :=
7230               l_sum_applic_lines + l_applicable_line_amount;
7231             l_alloc_line_tab(t).invoice_line_number :=
7232               l_applicable_line_number;
7233             l_alloc_line_tab(t).amount := l_applicable_line_amount;
7234             l_alloc_line_tab(t).sum_amount_dists := l_sum_dists_applic_line;
7235             t := t+1;
7236           END IF;
7237         END LOOP;
7238         CLOSE applicable_lines_cur;
7239 
7240         FOR t IN 0..l_alloc_line_tab.COUNT-1
7241         LOOP
7242           l_alloc_line_tab(t).amount :=
7243              AP_UTILITIES_PKG.Ap_Round_Currency(
7244                (l_alloc_line_tab(t).amount * l_line_amount) /
7245                 l_sum_applic_lines,
7246                 l_invoice_currency_code);
7247           IF (ABS(l_alloc_line_tab(t).amount) >= ABS(nvl(l_max_alloc,0)) OR
7248               t = 0) then
7249             l_max_alloc := l_alloc_line_tab(t).amount;
7250             l_max_t := t;
7251           END IF;
7252           l_running_total_alloc :=
7253             nvl(l_running_total_alloc, 0) + l_alloc_line_tab(t).amount;
7254         END LOOP;
7255 
7256 	--Invoice Lines: Distributions
7257 	--Basically for the case when user allocates the charge line
7258 	--to items lines which have no item distributions, this can
7259 	--result in l_alloca_line_tab having no records in the table.
7260 
7261         l_count_applicable_dists := l_alloc_line_tab.COUNT;
7262         IF (l_count_applicable_dists = 0) THEN
7263            x_error_code := 'NO_APPLICABLE_DISTS';
7264            RETURN(FALSE);
7265         END IF;
7266 
7267       EXCEPTION
7268         WHEN OTHERS THEN
7269           CLOSE applicable_lines_cur;
7270           X_debug_info := debug_info || ': Error encountered';
7271           X_debug_context := current_calling_sequence;
7272           RETURN(FALSE);
7273       END;
7274 
7275       IF (l_line_amount <> l_running_total_alloc) then
7276         l_alloc_line_tab(l_max_t).amount :=
7277             l_alloc_line_tab(l_max_t).amount +
7278            (l_line_amount - l_running_total_alloc);
7279       END IF;
7280 
7281     ELSIF (l_rule_type = 'PERCENTAGE') then
7282       t := 0;
7283       BEGIN
7284         OPEN alloc_rule_lines_cur;
7285         LOOP
7286           FETCH alloc_rule_lines_cur
7287            INTO l_alloc_rule_line_number,
7288                 l_alloc_rule_line_percent,
7289                 l_alloc_rule_line_amount,
7290                 l_sum_dists_applic_line;
7291 
7292           EXIT WHEN alloc_rule_lines_cur%NOTFOUND;
7293 
7294           IF (l_sum_dists_applic_line = 0) then
7295             X_error_code := 'AP_IMPROPER_LINE_IN_ALLOC_RULE';
7296             CLOSE alloc_rule_lines_cur;
7297             RETURN(FALSE);
7298           ELSE
7299             l_alloc_line_tab(t).invoice_line_number :=
7300                                        l_alloc_rule_line_number;
7301             l_alloc_line_tab(t).percentage := l_alloc_rule_line_percent;
7302             l_alloc_line_tab(t).amount :=
7303               AP_UTILITIES_PKG.Ap_Round_Currency(
7304                  (l_line_amount * l_alloc_rule_line_percent) / 100,
7305                   l_invoice_currency_code);
7306             l_alloc_line_tab(t).sum_amount_dists := l_sum_dists_applic_line;
7307 
7308             IF (ABS(l_alloc_line_tab(t).amount) >= ABS(nvl(l_max_alloc,0)) OR
7309                 t = 0) THEN
7310               l_max_alloc := l_alloc_line_tab(t).amount;
7311               l_max_t := t;
7312             END IF;
7313             l_running_total_alloc :=
7314                  nvl(l_running_total_alloc, 0) + l_alloc_line_tab(t).amount;
7315             t := t+1;
7316           END IF;
7317         END LOOP;
7318         CLOSE alloc_rule_lines_Cur;
7319 
7320 	--Invoice Lines: Distributions
7321 	l_count_applicable_dists := l_alloc_line_tab.COUNT;
7322         IF (l_count_applicable_dists = 0) THEN
7323            x_error_code := 'NO_APPLICABLE_DISTS';
7324            RETURN(FALSE);
7325         END IF;
7326 
7327         IF (l_line_amount <> l_running_total_alloc) THEN
7328           l_alloc_line_tab(l_max_t).amount :=
7329             l_alloc_line_tab(l_max_t).amount +
7330                (l_line_amount - l_running_total_alloc);
7331         END IF;
7332 
7333       EXCEPTION
7334         WHEN OTHERS THEN
7335           CLOSE alloc_rule_lines_cur;
7336           X_debug_info := debug_info || ': Error encountered';
7337           X_debug_context := current_calling_sequence;
7338           RETURN(FALSE);
7339       END;
7340 
7341 
7342     ELSE /* rule type is AMOUNT */
7343       t := 0;
7344       BEGIN
7345         OPEN alloc_rule_lines_cur;
7346         LOOP
7347           FETCH alloc_rule_lines_cur
7348            INTO l_alloc_rule_line_number,
7349                 l_alloc_rule_line_percent,
7350                 l_alloc_rule_line_amount,
7351                 l_sum_dists_applic_line;
7352 
7353           EXIT WHEN alloc_rule_lines_cur%NOTFOUND;
7354 
7355           IF (l_sum_dists_applic_line = 0) then
7356             X_error_code := 'AP_IMPROPER_LINE_IN_ALLOC_RULE';
7357             CLOSE alloc_rule_lines_cur;
7358             RETURN(FALSE);
7359           ELSE
7360             l_alloc_line_tab(t).invoice_line_number :=
7361               l_alloc_rule_line_number;
7362             l_alloc_line_tab(t).amount := l_alloc_rule_line_amount;
7363             l_alloc_line_tab(t).sum_amount_dists := l_sum_dists_applic_line;
7364             t := t + 1;
7365           END IF;
7366         END LOOP;
7367         CLOSE alloc_rule_lines_Cur;
7368 
7369 	--Invoice Lines: Distributions
7370 	l_count_applicable_dists := l_alloc_line_tab.COUNT;
7371         IF (l_count_applicable_dists = 0) THEN
7372            x_error_code := 'NO_APPLICABLE_DISTS';
7373            RETURN(FALSE);
7374         END IF;
7375 
7376       EXCEPTION
7377         WHEN OTHERS THEN
7378           CLOSE alloc_rule_lines_cur;
7379           X_debug_info := debug_info || ': Error encountered';
7380           X_debug_context := current_calling_sequence;
7381           RETURN(FALSE);
7382       END;
7383 
7384     END IF;
7385 
7386   EXCEPTION
7387     WHEN OTHERS THEN
7388       X_debug_info := debug_info || ': Error encountered';
7389       X_debug_context := current_calling_sequence;
7390       RETURN(FALSE);
7391   END;
7392 
7393 
7394   --------------------------------------------------------------
7395   -- Step 9 - Commence proration to all applicable distributions.
7396   --------------------------------------------------------------
7397   debug_info := 'Commence proration to distributions';
7398   BEGIN
7399     i := 0;
7400     l_max_base_i := 0;
7401     l_max_base_alloc := 0;
7402     l_running_total_base_amt := 0;
7403 
7404     -- Bug 5114543
7405     l_max_dist_line_num := AP_INVOICE_LINES_PKG.get_max_dist_line_num
7406 					(x_invoice_id, x_line_number) + 1;
7407 
7408     FOR t IN 0..l_alloc_line_tab.COUNT-1 LOOP
7409       l_running_total_alloc := 0;
7410       l_max_alloc := 0;
7411       l_max_i := -1;
7412 
7413       OPEN applicable_dists_cur(l_alloc_line_tab(t).invoice_line_number);
7414       LOOP
7415         FETCH applicable_dists_cur
7416          INTO l_invoice_distribution_id,
7417               l_po_distribution_id,
7418               l_rcv_transaction_id,
7419               l_dist_project_id,
7420               l_dist_task_id,
7421 	      l_dist_pa_quantity,   -- bug6699834
7422               l_dist_expenditure_type,
7423               l_dist_expenditure_org_id,
7424               l_dist_award_id,
7425               l_dist_amount,
7426               l_dist_code_combination_id,
7427               l_dist_assets_tracking_flag,
7428               l_dist_asset_book_type_code,
7429               l_dist_asset_category_id,
7430               l_dist_description;
7431 
7432         EXIT WHEN applicable_dists_cur%NOTFOUND;
7433 
7434 	-- Bug 5114543
7435         l_dist_tab(i).dist_line_num := l_max_dist_line_num;
7436 
7437         l_dist_tab(i).description := l_line_description;
7438         l_dist_tab(i).charge_applicable_to_dist := l_invoice_distribution_id;
7439         l_dist_tab(i).award_id := l_dist_award_id;
7440 	l_dist_tab(i).pa_quantity := l_dist_pa_quantity; -- bug6699834
7441         l_dist_tab(i).attribute_category := NULL;
7442         l_dist_tab(i).attribute1 := NULL;
7443         l_dist_tab(i).attribute2 := NULL;
7444         l_dist_tab(i).attribute3 := NULL;
7445         l_dist_tab(i).attribute4 := NULL;
7446         l_dist_tab(i).attribute5 := NULL;
7447         l_dist_tab(i).attribute6 := NULL;
7448         l_dist_tab(i).attribute7 := NULL;
7449         l_dist_tab(i).attribute8 := NULL;
7450         l_dist_tab(i).attribute9 := NULL;
7451         l_dist_tab(i).attribute10 := NULL;
7452         l_dist_tab(i).attribute11 := NULL;
7453         l_dist_tab(i).attribute12 := NULL;
7454         l_dist_tab(i).attribute13 := NULL;
7455         l_dist_tab(i).attribute14 := NULL;
7456         l_dist_tab(i).attribute15 := NULL;
7457         l_dist_tab(i).type_1099   := l_type_1099;
7458         l_dist_tab(i).income_tax_region := l_income_tax_region;
7459         l_dist_tab(i).amount:=
7460           AP_UTILITIES_PKG.Ap_Round_Currency(
7461             (l_alloc_line_tab(t).amount * l_dist_amount) /
7462              l_alloc_line_tab(t).sum_amount_dists,
7463              l_invoice_currency_code);
7464         l_dist_tab(i).base_amount :=
7465           AP_UTILITIES_PKG.Ap_Round_Currency(
7466           NVL(l_dist_tab(i).amount, 0) * l_exchange_rate ,
7467           l_base_currency_code);
7468         l_dist_tab(i).rounding_amt := 0;
7469 
7470         -- Get project and account information
7471         --
7472         IF (NOT (
7473                 Get_Proj_And_Acc_For_Chrg_Dist(
7474                  X_invoice_id,
7475                  l_invoice_date,
7476                  l_vendor_id,
7477                  l_invoice_currency_code,
7478                  l_sob_id,
7479                  l_chart_of_accounts_id,
7480                  l_base_currency_code,
7481                  l_dist_tab(i).amount,
7482                  l_dist_tab(i).base_amount,
7483                  l_exchange_rate_type,
7484                  l_exchange_date,
7485                  l_exchange_rate,
7486                  X_line_number,
7487                  l_open_gl_date,
7488                  l_open_period_name,
7489                  l_project_id,
7490                  l_task_id,
7491 		 l_award_id,
7492                  l_expenditure_type,
7493                  l_expenditure_organization_id,
7494                  l_assets_tracking_flag,
7495                  l_asset_book_type_code,
7496                  l_asset_category_id,
7497                  l_dist_project_id,
7498                  l_dist_task_id,
7499 		 l_dist_award_id,
7500                  l_dist_expenditure_type,
7501                  l_dist_expenditure_org_id,
7502                  l_dist_assets_tracking_flag,
7503                  l_dist_asset_book_type_code,
7504                  l_dist_asset_category_id,
7505                  l_default_dist_ccid,
7506                  l_overlay_dist_concat,
7507                  l_balancing_segment,
7508                  l_account_segment,
7509                  l_cost_center_segment,
7510                  l_dist_code_combination_id,
7511                  l_po_distribution_id,
7512                  l_rcv_transaction_id,
7513                  l_pa_allows_overrides,
7514                  l_allow_po_override,
7515                  l_dist_tab(i).project_id,
7516                  l_dist_tab(i).task_id,
7517                  l_dist_tab(i).award_id,
7518                  l_dist_tab(i).expenditure_type,
7519                  l_dist_tab(i).expenditure_organization_id,
7520                  l_dist_tab(i).expenditure_item_date,
7521                  l_dist_tab(i).pa_addition_flag,
7522                  l_dist_tab(i).dist_ccid,
7523                  l_dist_tab(i).assets_tracking_flag,
7524                  l_dist_tab(i).asset_book_type_code,
7525                  l_dist_tab(i).asset_category_id,
7526                  l_error_code,
7527                  l_msg_application,
7528                  l_msg_data,
7529                  l_default_dist_ccid --bug 5386396
7530             ))) THEN
7531 
7532           CLOSE applicable_dists_cur;
7533 
7534           IF (l_error_code is not null) then
7535             X_error_code := l_error_code;
7536             RETURN(FALSE);
7537           ELSIF (l_msg_data is not null) then
7538             X_msg_application := l_msg_application;
7539             X_msg_data := l_msg_data;
7540             RETURN(FALSE);
7541           ELSE
7542             X_debug_info := debug_info
7543                             ||': Error encountered while reading account info';
7544             X_debug_context := current_calling_sequence;
7545             RETURN(FALSE);
7546           END IF;
7547         END IF;
7548 
7549        -- l_dist_tab(i).assets_tracking_flag :=
7550         IF (l_dist_tab(i).assets_tracking_flag = 'Y') THEN
7551           l_dist_tab(i).asset_book_type_code := l_asset_book_type_code;
7552           l_dist_tab(i).asset_category_id := l_asset_category_id;
7553         END IF;
7554 
7555         IF (l_max_i = -1 OR ABS(nvl(l_max_alloc, 0)) <=
7556              ABS(l_dist_tab(i).amount)) then
7557           l_max_i := i;
7558           l_max_alloc := l_dist_tab(i).amount;
7559         END IF;
7560         IF (i = 0 OR ABS(nvl(l_max_base_alloc, 0)) <=
7561              ABS(l_dist_tab(i).base_amount)) THEN
7562           l_max_base_i := i;
7563           l_max_base_alloc := l_dist_tab(i).base_amount;
7564         END IF;
7565         l_running_total_alloc := nvl(l_running_total_alloc, 0) +
7566                                  l_dist_tab(i).amount;
7567         l_running_total_base_amt := nvl(l_running_total_base_amt, 0) +
7568                                     l_dist_tab(i).base_amount;
7569 
7570         i := i+1;
7571 
7572 	-- Bug 5114543
7573 	l_max_dist_line_num := l_max_dist_line_num +1;
7574 
7575       END LOOP; -- Loop through distributions within line
7576 
7577       CLOSE applicable_dists_cur;
7578 
7579       if (l_alloc_line_tab(t).amount <> l_running_total_alloc) then
7580         l_dist_tab(l_max_i).amount :=
7581             l_dist_tab(l_max_i).amount + (l_alloc_line_tab(t).amount -
7582                                              l_running_total_alloc);
7583         l_running_total_base_amt := l_running_total_base_amt -
7584                                       l_dist_tab(l_max_I).base_amount;
7585         l_dist_tab(l_max_i).base_amount :=
7586           AP_UTILITIES_PKG.Ap_Round_Currency(
7587             NVL(l_dist_tab(l_max_i).amount, 0) * l_exchange_rate ,
7588             l_base_currency_code);
7589         l_running_total_base_amt := l_running_total_base_amt +
7590                                     l_dist_tab(l_max_i).base_amount;
7591       end if;
7592       if (ABS(nvl(l_max_base_alloc, 0)) <=
7593           ABS(l_dist_tab(l_max_i).base_amount)) then
7594         l_max_base_i := l_max_i;
7595         l_max_base_alloc := l_dist_tab(l_max_i).base_amount;
7596       end if;
7597 
7598     END LOOP;  -- Loop through lines
7599 
7600     if (l_running_total_base_amt <> l_line_base_amount) then
7601       l_dist_tab(l_max_base_i).rounding_amt := l_line_base_amount -
7602                                                 l_running_total_base_amt;
7603       l_dist_tab(l_max_base_i).base_amount :=
7604         l_dist_tab(l_max_base_i).base_amount + l_line_base_amount -
7605             l_running_total_base_amt;
7606     end if;
7607 
7608   END;
7609 
7610   ----------------------------------------------------------------------------
7611   -- Step 10 - Set distribution class value (Permanent or Candidate)
7612   ----------------------------------------------------------------------------
7613   if (X_Generate_Permanent = 'N') then
7614     l_distribution_class := 'CANDIDATE';
7615   else
7616     l_distribution_class := 'PERMANENT';
7617   end if;
7618 
7619    --bug 9169915
7620    SELECT JG_ZZ_SHARED_PKG.GET_COUNTRY(l_org_id, null)
7621      INTO l_country_code
7622      FROM DUAL;
7623    --bug 9169915
7624 
7625   ----------------------------------------------------------------------------
7626   -- Step 11 - Generate distributions
7627   ----------------------------------------------------------------------------
7628 
7629    l_dist_updated := 0;  --Bug#10241241
7630    -- Bug 13841774. Start.
7631    l_copy_line_dff_flag := NVL(fnd_profile.value('AP_COPY_INV_LINE_DFF'),'N');
7632 
7633    IF (l_line_source <> 'IMPORTED' OR l_copy_line_dff_flag <> 'Y') THEN
7634        l_attribute_category  := NULL ;
7635        l_attribute1          := NULL ;
7636        l_attribute2          := NULL ;
7637        l_attribute3          := NULL ;
7638        l_attribute4          := NULL ;
7639        l_attribute5          := NULL ;
7640        l_attribute6          := NULL ;
7641        l_attribute7          := NULL ;
7642        l_attribute8          := NULL ;
7643        l_attribute9          := NULL ;
7644        l_attribute10         := NULL ;
7645        l_attribute11         := NULL ;
7646        l_attribute12         := NULL ;
7647        l_attribute13         := NULL ;
7648        l_attribute14         := NULL ;
7649        l_attribute15         := NULL ;
7650    END IF;
7651    -- Bug 13841774. End.
7652 
7653    FOR i in nvl(l_dist_tab.FIRST, 0) .. nvl(l_dist_tab.LAST, -1)  LOOP
7654 
7655      SELECT ap_invoice_distributions_s.nextval INTO l_inv_dist_id FROM DUAL;
7656 
7657      INSERT INTO ap_invoice_distributions(
7658               batch_id,
7659               invoice_id,
7660               invoice_line_number,
7661               invoice_distribution_id,
7662               distribution_line_number,
7663               line_type_lookup_code,
7664               distribution_class,
7665               description,
7666               dist_match_type,
7667               org_id,
7668               dist_code_combination_id,
7669               accounting_date,
7670               period_name,
7671               accrual_posted_flag,
7672               cash_posted_flag,
7673               amount_to_post,
7674               base_amount_to_post,
7675               posted_amount,
7676               posted_base_amount,
7677               posted_flag,
7678               accounting_event_id,
7679               upgrade_posted_amt,
7680               upgrade_base_posted_amt,
7681               set_of_books_id,
7682               amount,
7683               base_amount,
7684               rounding_amt,
7685               quantity_variance,
7686               base_quantity_variance,
7687               match_status_flag,
7688               encumbered_flag,
7689               packet_id,
7690               reversal_flag,
7691               parent_reversal_id,
7692               cancellation_flag,
7693               income_tax_region,
7694               type_1099,
7695               stat_amount,
7696               charge_applicable_to_dist_id,
7697               prepay_amount_remaining,
7698               prepay_distribution_id,
7699               parent_invoice_id,
7700               corrected_invoice_dist_id,
7701               corrected_quantity,
7702               other_invoice_id,
7703               po_distribution_id,
7704               rcv_transaction_id,
7705               unit_price,
7706               matched_uom_lookup_code,
7707               quantity_invoiced,
7708               final_match_flag,
7709               related_id,
7710               assets_addition_flag,
7711               assets_tracking_flag,
7712               asset_book_type_code,
7713               asset_category_id,
7714               project_id,
7715               task_id,
7716               expenditure_type,
7717               expenditure_item_date,
7718               expenditure_organization_id,
7719               pa_quantity,
7720               pa_addition_flag,
7721               award_id,
7722               gms_burdenable_raw_cost,
7723               awt_flag,
7724               awt_group_id,
7725               awt_tax_rate_id,
7726               awt_gross_amount,
7727               awt_invoice_id,
7728               awt_origin_group_id,
7729               awt_invoice_payment_id,
7730               awt_withheld_amt,
7731               inventory_transfer_status,
7732               reference_1,
7733               reference_2,
7734               receipt_verified_flag,
7735               receipt_required_flag,
7736               receipt_missing_flag,
7737               justification,
7738               expense_group,
7739               start_expense_date,
7740               end_expense_date,
7741               receipt_currency_code,
7742               receipt_conversion_rate,
7743               receipt_currency_amount,
7744               daily_amount,
7745               web_parameter_id,
7746               adjustment_reason,
7747               merchant_document_number,
7748               merchant_name,
7749               merchant_reference,
7750               merchant_tax_reg_number,
7751               merchant_taxpayer_id,
7752               country_of_supply,
7753               credit_card_trx_id,
7754               company_prepaid_invoice_id,
7755               cc_reversal_flag,
7756               attribute_category,
7757               attribute1,
7758               attribute2,
7759               attribute3,
7760               attribute4,
7761               attribute5,
7762               attribute6,
7763               attribute7,
7764               attribute8,
7765               attribute9,
7766               attribute10,
7767               attribute11,
7768               attribute12,
7769               attribute13,
7770               attribute14,
7771               attribute15,
7772               global_attribute_category,
7773               global_attribute1,
7774               global_attribute2,
7775               global_attribute3,
7776               global_attribute4,
7777               global_attribute5,
7778               global_attribute6,
7779               global_attribute7,
7780               global_attribute8,
7781               global_attribute9,
7782               global_attribute10,
7783               global_attribute11,
7784               global_attribute12,
7785               global_attribute13,
7786               global_attribute14,
7787               global_attribute15,
7788               global_attribute16,
7789               global_attribute17,
7790               global_attribute18,
7791               global_attribute19,
7792               global_attribute20,
7793               created_by,
7794               creation_date,
7795               last_updated_by,
7796               last_update_date,
7797               last_update_login,
7798               program_application_id,
7799               program_id,
7800               program_update_date,
7801               request_id,
7802 	      --ETAX: Invwkb
7803 	      intended_use,
7804 	      --Freight and Special Charges
7805 	      rcv_charge_addition_flag,
7806 	---7022001
7807 	pay_awt_group_id)
7808     SELECT    l_batch_id,                       -- batch_id
7809               X_invoice_id,                     -- invoice_id
7810               X_line_number,                    -- invoice_line_number
7811               l_inv_dist_id,           		-- invoice_distribution_id
7812               l_dist_tab(i).dist_line_num,      -- distribution_line_number
7813               l_line_type_lookup_code,          -- line_type_lookup_code
7814               l_distribution_class,             -- distribution_class
7815               l_dist_tab(i).description,        -- description
7816               'NOT_MATCHED',                    -- dist_match_type
7817               l_org_id,                         -- l_org_id
7818               l_dist_tab(i).dist_ccid,          -- dist_code_combination_id
7819               l_open_gl_date,                   -- accounting_date
7820               l_open_period_name,               -- period_name
7821               'N',                              -- accrual_posted_flag
7822               'N',                              -- cash_posted_flag
7823               NULL,                             -- amount_to_post
7824               NULL,                             -- base_amount_to_post
7825               NULL,                             -- posted_amount
7826               NULL,                             -- posted_base_amount
7827               'N',                              -- posted_flag
7828               NULL,                             -- accounting_event_id
7829               NULL,                             -- upgrade_posted_amt
7830               NULL,                             -- upgrade_base_posted_amt
7831               l_sob_id,                         -- set_of_books_id
7832               l_dist_tab(i).amount,             -- amount
7833               l_dist_tab(i).base_amount,        -- base_amount
7834               l_dist_tab(i).rounding_amt,       -- rounding_amt
7835               NULL,                             -- quantity_variance
7836               NULL,                             -- base_quantity_variance
7837 	      --Invoice Lines: Distributions, changed match_status_flag
7838 	      --to NULL from 'N'.
7839               NULL,                             -- match_status_flag
7840               'N',                              -- encumbered_flag
7841               NULL,                             -- packet_id
7842               'N',                              -- reversal_flag
7843               NULL,                             -- parent_reversal_id
7844               'N',                              -- cancellation_flag
7845               decode(l_type_1099,null,null,l_income_tax_region),
7846                                                 -- income_tax_region
7847               l_type_1099,                      -- type_1099
7848 	      NULL,                             -- stat_amount
7849               l_dist_tab(i).charge_applicable_to_dist, -- charge_applicable_to_dist_id
7850               NULL,                             -- prepay_amount_remaining
7851               NULL,                             -- prepay_distribution_id
7852               NULL,                             -- parent_invoice_id
7853               NULL,                             -- corrected_inv_dist_id
7854               NULL,                             -- corrected_quantity
7855               NULL,                             -- other_invoice_id
7856               NULL,                             -- po_distribution_id
7857               NULL,                             -- rcv_transaction_id
7858               NULL,                             -- unit_price
7859               NULL,                             -- matched_uom_lookup_code
7860               NULL,                             -- quantity_invoiced
7861               NULL,                             -- final_match_flag
7862               NULL,                             -- related_id
7863               'U',                              -- assets_addition_flag
7864               l_dist_tab(i).assets_tracking_flag,   -- assets_tracking_flag
7865               l_dist_tab(i).asset_book_type_code,   -- asset_book_type_code
7866               l_dist_tab(i).asset_category_id,  -- asset_category_id
7867               l_dist_tab(i).project_id,         -- project_id
7868               l_dist_tab(i).task_id,            -- task_id
7869               l_dist_tab(i).expenditure_type,   -- expenditure_type
7870               l_dist_tab(i).expenditure_item_date,  -- expenditure_item_date
7871               l_dist_tab(i).expenditure_organization_id,  -- expenditure_organization_id
7872 /* commented for Bug fix 6699834. added below line as replacement                             NULL,                             -- pa_quantity  */
7873               l_dist_tab(i).pa_quantity,        -- pa_quantity  -- bug6699834
7874               l_dist_tab(i).pa_addition_flag,   -- pa_addition_flag
7875               NULL,                             -- award_id
7876               NULL,                             -- gms_burdenable_raw_cost
7877               NULL,                             -- awt_flag
7878               l_awt_group_id,                   -- awt_group_id
7879               NULL,                             -- awt_tax_rate_id
7880               NULL,                             -- awt_gross_amount
7881               NULL,                             -- awt_invoice_id
7882               NULL,                             -- awt_origin_group_id
7883               NULL,                             -- awt_invoice_payment_id
7884               NULL,                             -- awt_withheld_amt
7885               'N',                              -- inventory_transfer_status
7886               l_reference_1,                    -- NULL   --reference_1 --Bug9296445
7887               l_reference_2,                    -- NULL   --reference_2 --Bug9296445
7888               NULL,                             -- receipt_verified_flag
7889               NULL,                             -- receipt_required_flag
7890               NULL,                             -- receipt_missing_flag
7891               NULL,                             -- justification
7892               NULL,                             -- expense_group
7893               NULL,                             -- start_expense_date
7894               NULL,                             -- end_expense_date
7895               NULL,                             -- receipt_currency_code
7896               NULL,                             -- receipt_conversion_rate
7897               NULL,                             -- receipt_currency_amount
7898               NULL,                             -- daily_amount
7899               NULL,                             -- web_parameter_id
7900               NULL,                             -- adjustment_reason
7901               NULL,                             -- merchant_document_number
7902               NULL,                             -- merchant_name
7903               NULL,                             -- merchant_reference
7904               NULL,                             -- merchant_tax_reg_number
7905               NULL,                             -- merchant_taxpayer_id
7906               NULL,                             -- country_of_supply
7907               NULL,                             -- credit_card_trx_id
7908               NULL,                             -- company_prepaid_invoice_id
7909               NULL,                             -- cc_reversal_flag
7910               -- Bug 13841774. Start.
7911               l_attribute_category,             -- attribute_category
7912               l_attribute1,                     -- attribute1
7913               l_attribute2,                     -- attribute2
7914               l_attribute3,                     -- attribute3
7915               l_attribute4,                     -- attribute4
7916               l_attribute5,                     -- attribute5
7917               l_attribute6,                     -- attribute6
7918               l_attribute7,                     -- attribute7
7919               l_attribute8,                     -- attribute8
7920               l_attribute9,                     -- attribute9
7921               l_attribute10,                    -- attribute10
7922               l_attribute11,                    -- attribute11
7923               l_attribute12,                    -- attribute12
7924               l_attribute13,                    -- attribute13
7925               l_attribute14,                    -- attribute14
7926               l_attribute15,                    -- attribute15
7927               -- Bug 13841774. End.
7928               NULL,                             -- global_attribute_category
7929               NULL,                             -- global_attribute1
7930               NULL,                             -- global_attribute2
7931 	      --bugfix:4674194
7932 	      decode(AP_EXTENDED_WITHHOLDING_PKG.AP_EXTENDED_WITHHOLDING_OPTION,
7933 	             'Y',ail1.ship_to_location_id,''), --global_attribute3
7934               NULL,                             -- global_attribute4
7935               NULL,                             -- global_attribute5
7936               NULL,                             -- global_attribute6
7937               NULL,                             -- global_attribute7
7938               NULL,                             -- global_attribute8
7939               NULL,                             -- global_attribute9
7940               NULL,                             -- global_attribute10
7941               NULL,                             -- global_attribute11
7942               NULL,                             -- global_attribute12
7943               NULL,                             -- global_attribute13
7944               NULL,                             -- global_attribute14
7945               NULL,                             -- global_attribute15
7946               NULL,                             -- global_attribute16
7947               NULL,                             -- global_attribute17
7948               NULL,                             -- global_attribute18
7949               NULL,                             -- global_attribute19
7950               NULL,                             -- global_attribute20
7951               l_created_by,                     -- created_by
7952               sysdate,                          -- creation_date
7953               0,                                -- last_updated_by
7954               sysdate,                          -- last_update_date
7955               l_last_update_login,              -- last_update_login
7956               NULL,                             -- program_application_id
7957               NULL,                             -- program_id
7958               NULL,                             -- program_update_date
7959               NULL,                             -- request_id
7960 	      --ETAX: Invwkb
7961 	      ail.primary_intended_use,		-- intended_use
7962 	      'N',				-- rcv_charge_addition_flag
7963 	 l_pay_awt_group_id                   -- pay_awt_group_id 7022001
7964          FROM ap_invoice_lines AIL, --Charge line
7965 	      ap_invoice_lines AIL1, --ITEM Line
7966 	      ap_invoice_distributions aid
7967          WHERE ail.invoice_id = X_invoice_id
7968          AND ail.line_number = X_line_number
7969 	 AND aid.invoice_id = ail.invoice_id
7970 	 AND aid.invoice_distribution_id = l_dist_tab(i).charge_applicable_to_dist
7971 	 AND ail1.invoice_id = ail.invoice_id
7972 	 AND ail1.line_number = aid.invoice_line_number;
7973 
7974 	 --bug 9169915 bug9737142
7975 	 IF l_country_code IN ('AR','CO') THEN
7976    	   JL_ZZ_AP_AWT_DEFAULT_PKG.SUPP_WH_DEF (X_invoice_id,
7977 	                                         X_line_number,
7978 						 l_inv_dist_id,
7979 						 NULL);
7980          END IF;
7981 	 --bug 9169915
7982 
7983 	 GMS_AP_API.CREATE_AWARD_DISTRIBUTIONS
7984 			( p_invoice_id		     => X_invoice_id,
7985 			  p_distribution_line_number => l_dist_tab(i).dist_line_num,
7986 			  p_invoice_distribution_id  => l_inv_dist_id,
7987 			  p_award_id		     => l_dist_tab(i).award_id,
7988 			  p_mode		     => 'AP',
7989 			  p_dist_set_id		     => NULL,
7990 			  p_dist_set_line_number     => NULL);
7991 
7992           --Bug#10241241
7993 	   IF (l_dist_updated = 0 and
7994 	       l_stat_amount is not null and
7995 	       GET_UOM(l_dist_tab(i).dist_ccid,l_chart_of_accounts_id) is not null) THEN
7996 
7997 	   Update ap_invoice_distributions
7998 	   set stat_amount =   l_stat_amount
7999 	   where invoice_id  = X_invoice_id
8000              and invoice_line_number= X_line_number
8001 	     and distribution_line_number = l_dist_tab(i).dist_line_num;
8002 
8003              l_dist_updated := 1;
8004 
8005            END IF;
8006 	 --Bug#10241241
8007 
8008   END LOOP;
8009 
8010 
8011 ----------------------------------------------------------------------------
8012   -- Step 12 - Update generate distributions flag in invoice line if generating
8013   -- permanent distributions.
8014   ----------------------------------------------------------------------------
8015   debug_info := 'Setting generate distributions flag to Done';
8016   if (l_distribution_class = 'PERMANENT') then
8017 
8018     -- Bug 5114543
8019     -- generate_dists on the charge line should be set to 'Done'
8020     -- when the line amount equals the distributions total.
8021 
8022     BEGIN
8023       UPDATE AP_INVOICE_LINES
8024          SET GENERATE_DISTS = 'D'
8025        WHERE invoice_id = X_invoice_id
8026          AND line_number = X_line_number
8027 	 AND amount = (select sum(amount)
8028 			 from ap_invoice_distributions
8029 			where invoice_id = x_invoice_id
8030 			  and invoice_line_number = x_line_number);
8031     EXCEPTION
8032       WHEN OTHERS THEN
8033          X_debug_info := debug_info || ': Error encountered';
8034          X_debug_context := current_calling_sequence;
8035          return (FALSE);
8036     END;
8037   end if;
8038 
8039   ----------------------------------------------------------------------------
8040   -- Step 13 - Update status of allocation rule type if the distributions were
8041   -- generated in permanent mode.
8042   ----------------------------------------------------------------------------
8043   debug_info := 'Setting status of allocation rule to Executed';
8044   if (l_distribution_class = 'PERMANENT') then
8045 
8046     -- Bug 5114543
8047     -- allocation rule status should be set to 'Executed' when the associated
8048     -- charge line amount equals its distributions total.
8049 
8050     BEGIN
8051       UPDATE AP_ALLOCATION_RULES
8052          SET STATUS = 'EXECUTED'
8053        WHERE invoice_id = X_invoice_id
8054          AND chrg_invoice_line_number = X_line_number
8055 	 AND exists
8056 		(select 'Line Amount Equals Distribution Total'
8057 		 from   ap_invoice_lines_all ail,
8058 			ap_invoice_distributions_all aid
8059 		 where  ail.invoice_id  = aid.invoice_id
8060 		 and	ail.line_number = aid.invoice_line_number
8061 		 and	ail.invoice_id  = X_invoice_id
8062 		 and	ail.line_number = X_line_number
8063 		 group by ail.line_number, ail.amount
8064 		 having ail.amount = sum(aid.amount));
8065 
8066     EXCEPTION
8067       WHEN OTHERS THEN
8068          X_debug_info := debug_info || ': Error encountered';
8069          X_debug_context := current_calling_sequence;
8070          RETURN (FALSE);
8071     END;
8072   END IF;
8073 
8074   RETURN(TRUE);
8075 
8076   EXCEPTION
8077      WHEN OTHERS THEN
8078        X_debug_info := debug_info || 'Error encountered';
8079        X_debug_context := current_calling_sequence;
8080        X_error_code := sqlerrm;
8081        return (FALSE);
8082 
8083 END insert_charge_from_alloc;
8084 
8085   -----------------------------------------------------------------------
8086   -- FUNCTION get_total_dist_amount returns the total of the original
8087   -- ITEM or ACCRUAL distribution when the same has been split into
8088   -- ITEM/ACCRUAL, IPV and ERV.  It may also be called in Price
8089   -- Corrections where there was no original ITEM/ACCRUAL. It returns
8090   -- NULL if an error is found.
8091   -----------------------------------------------------------------------
8092   FUNCTION Get_Total_Dist_Amount(
8093          X_invoice_distribution_id IN       NUMBER) RETURN NUMBER
8094   IS
8095 
8096   l_original_amount    AP_INVOICE_DISTRIBUTIONS.AMOUNT%TYPE := 0;
8097 
8098   BEGIN
8099 
8100     SELECT sum(nvl(AID.amount,0))
8101       INTO l_original_amount
8102       FROM ap_invoice_distributions_all  AID
8103      WHERE AID.invoice_distribution_id = X_invoice_distribution_id
8104         OR AID.related_id = X_invoice_distribution_id;
8105 
8106 
8107     RETURN(l_original_amount);
8108 
8109 EXCEPTION
8110   WHEN no_data_found THEN
8111     RETURN(l_original_amount) ;
8112   WHEN OTHERS THEN
8113     RETURN(l_original_amount);
8114 
8115 END get_total_dist_amount;
8116 
8117 
8118  -----------------------------------------------------------------------
8119   -- Function get_dist_line_num returns the distribution line
8120   -- number of invoice distributions belonging to P_invoice_dist_id
8121   -----------------------------------------------------------------------
8122   FUNCTION GET_DIST_LINE_NUM(
8123           X_invoice_dist_id      IN NUMBER)
8124   RETURN NUMBER
8125   IS
8126       l_dist_line_num number := 0;
8127   BEGIN
8128 
8129     SELECT nvl(distribution_line_number,0)
8130       INTO l_dist_line_num
8131       FROM ap_invoice_distributions
8132      WHERE invoice_distribution_id = X_invoice_dist_id;
8133 
8134     RETURN(l_dist_line_num);
8135 
8136   END GET_DIST_LINE_NUM;
8137 
8138 
8139   -----------------------------------------------------------------------
8140   -- Function get_inv_line_num returns the invoice line
8141   -- number of invoice distribution belonging to P_invoice_dist_id
8142   -----------------------------------------------------------------------
8143   FUNCTION GET_INV_LINE_NUM(
8144           X_invoice_dist_id      IN NUMBER )
8145   RETURN NUMBER
8146   IS
8147       l_inv_line_num number := 0;
8148   BEGIN
8149 
8150     SELECT nvl(invoice_line_number,0)
8151       INTO l_inv_line_num
8152       FROM ap_invoice_distributions
8153      WHERE invoice_distribution_id = X_invoice_dist_id;
8154 
8155     RETURN(l_inv_line_num);
8156 
8157   END GET_INV_LINE_NUM;
8158 
8159   -----------------------------------------------------------------------
8160   -- Function get_invoice_num returns the parent invoice
8161   -- number of invoice distribution belonging to P_invoice_dist_id
8162   -----------------------------------------------------------------------
8163   FUNCTION GET_INVOICE_NUM(
8164           X_invoice_dist_id      IN NUMBER )
8165   RETURN VARCHAR2
8166   IS
8167       l_inv_num VARCHAR2(50);
8168   BEGIN
8169 
8170     SELECT nvl(ai.invoice_num,0)
8171       INTO l_inv_num
8172       FROM ap_invoice_distributions aid,
8173            ap_invoices ai
8174      WHERE aid.invoice_distribution_id = X_invoice_dist_id
8175        AND aid.invoice_id = ai.invoice_id;
8176 
8177     RETURN(l_inv_num);
8178 
8179   END GET_INVOICE_NUM;
8180 
8181 
8182   -----------------------------------------------------------------------
8183   -- Function GET_REVERSAL_RELATED_ID returns the ditribution id value
8184   -- that should populates the related_id column when distribution line
8185   -- is reversed and invoice line is discarded.
8186   -----------------------------------------------------------------------
8187   FUNCTION GET_REVERSAL_RELATED_ID(
8188           X_related_dist_id    IN  NUMBER )
8189   RETURN NUMBER
8190   IS
8191       l_distribution_id  ap_invoice_distributions.invoice_distribution_id%TYPE;
8192   BEGIN
8193 
8194     BEGIN
8195       SELECT invoice_distribution_id
8196         INTO l_distribution_id
8197         FROM ap_invoice_distributions
8198        WHERE parent_reversal_id = X_related_dist_id;
8199     EXCEPTION
8200       WHEN no_data_found THEN
8201         l_distribution_id := null;
8202       WHEN TOO_MANY_ROWS THEN       -- added for 9590980
8203         l_distribution_id := null;
8204     END;
8205 
8206     RETURN(l_distribution_id);
8207 
8208   END GET_REVERSAL_RELATED_ID;
8209 
8210 
8211  --Invoice Lines: Distributions
8212  -----------------------------------------------------------------------
8213   -- Function GET_REVERSING_DIST_NUM returns the ditribution num value
8214   -- of the invoice distribution that is reversing the invoice distribution
8215   --identified by x_invoice_dist_id.
8216   -----------------------------------------------------------------------
8217  FUNCTION GET_REVERSING_DIST_NUM(X_Invoice_Dist_Id NUMBER) RETURN NUMBER IS
8218     l_reversing_dist_num ap_invoice_distributions.distribution_line_number%TYPE;
8219  BEGIN
8220 
8221    BEGIN
8222       SELECT distribution_line_number
8223       INTO l_reversing_dist_num
8224       FROM ap_invoice_distributions
8225       WHERE parent_reversal_id = x_invoice_dist_id;
8226 
8227    EXCEPTION WHEN NO_DATA_FOUND THEN
8228      l_reversing_dist_num := NULL;
8229      WHEN TOO_MANY_ROWS THEN     -- added for 9590980
8230       l_reversing_dist_num := null;
8231    END;
8232 
8233    RETURN(l_reversing_dist_num);
8234 
8235  END GET_REVERSING_DIST_NUM;
8236 
8237 
8238 /*=============================================================================
8239  |  PUBLIC PROCEDURE Calculate_Variance
8240  |
8241  |  DESCRIPTION
8242  |   Procedure that calculates the IPV/ERV for an distribution line which
8243  |   could be ITEM, ACCRUAL, RETROEXPENSE, RETROACCRUAL or IPV type. It
8244  |   returns TRUE if there is no error or exception. It returns True if no
8245  |   error.
8246  |
8247  |  PARAMETERS
8248  |    x_distribution_id - Distributions which could be ITEM, ACCRUAL and IPV
8249  |    x_reporting_ledger_id - reporting set of books id value for MRC
8250  |    x_distribution_amt - Out parameter as updated value for this dist line
8251  |    x_dist_base_amt - Out parameter as updated value for this dist line
8252  |    x_ipv - Out parameter as calculated ipv
8253  |    x_bipv - Out parameter as calculated base amount for ipv
8254  |    x_erv - Out parameter as calculated erv in base currency code
8255  |    x_calling_sequence - calling sequence for debug purpose
8256  |    x_debug_switch - a control to log debug information
8257  |
8258  |  PROGRAM FLOW
8259  |
8260  |  KNOWN ISSUES
8261  |
8262  |  NOTES
8263  |
8264  |  MODIFICATION HISTORY
8265  |  Date         Author             Description of Change
8266  |
8267  *============================================================================*/
8268 
8269 FUNCTION Calculate_Variance(
8270              X_DISTRIBUTION_ID      IN            NUMBER,
8271              X_REPORTING_LEDGER_ID  IN            NUMBER,
8272              X_DISTRIBUTION_AMT        OUT NOCOPY NUMBER,
8273              X_DIST_BASE_AMT           OUT NOCOPY NUMBER,
8274              X_IPV                  IN OUT NOCOPY NUMBER,
8275              X_BIPV                 IN OUT NOCOPY NUMBER,
8276              X_ERV                  IN OUT NOCOPY NUMBER,
8277              X_DEBUG_INFO           IN OUT NOCOPY VARCHAR2,
8278              X_DEBUG_CONTEXT        IN OUT NOCOPY VARCHAR2,
8279              X_CALLING_SEQUENCE     IN OUT NOCOPY VARCHAR2) Return Boolean
8280 
8281 IS
8282   l_inv_currency_code        ap_invoices.invoice_currency_code%TYPE;
8283   l_base_currency_code       ap_system_parameters.base_currency_code%TYPE;
8284   l_dist_line_type           VARCHAR2(25);
8285   l_inv_price                ap_invoice_distributions.unit_price%TYPE;
8286   l_qty_invoiced             NUMBER;
8287   l_po_qty                   NUMBER;
8288   l_po_price                 po_line_locations.price_override%TYPE;
8289   l_po_rate                  NUMBER;
8290   l_rtxn_rate                NUMBER;
8291   l_inv_rate                 ap_invoices.exchange_rate%TYPE;
8292   l_match_option             po_line_locations.match_option%TYPE;
8293   l_rtxn_uom                 VARCHAR2(25);
8294   l_rtxn_item_id             rcv_shipment_lines.item_id%TYPE;
8295   l_po_uom                   po_line_locations.unit_meas_lookup_code%TYPE;
8296   l_distribution_amt         ap_invoice_distributions.amount%TYPE;
8297   l_dist_base_amt            ap_invoice_distributions.base_amount%TYPE;
8298   l_dist_match_type          ap_invoice_distributions.dist_match_type%TYPE;
8299   l_corrected_inv_dist_id    NUMBER(15);
8300   l_corrected_qty            NUMBER;
8301   l_uom_conv_rate            NUMBER;
8302   l_rate_diff                NUMBER;
8303   l_price_diff               NUMBER;
8304 
8305   l_original_dist_base_amt   NUMBER;
8306   l_original_dist_amt        NUMBER;
8307 
8308   l_corrected_inv_rate       ap_invoices.exchange_rate%TYPE;
8309   current_calling_sequence   VARCHAR2(2000);
8310   l_debug_info               VARCHAR2(100);
8311 
8312   l_match_basis              po_line_types.matching_basis%TYPE;  -- Amount Based Matching
8313   l_line_source              ap_invoice_lines.line_source%TYPE;  --Bug#10416960
8314 
8315   cursor invoice_dist_cursor is
8316   SELECT AI.invoice_currency_code,              -- l_inv_currency_code
8317          ASP.base_currency_code,                -- l_base_currency_code
8318          D.line_type_lookup_code,               -- l_dist_line_type
8319          D.unit_price,                          -- l_inv_price
8320          nvl(D.quantity_invoiced, 0),           -- l_quantity_invoiced
8321          nvl(PD.quantity_ordered,0) -
8322               nvl(PD.quantity_cancelled,0),     -- l_po_qty
8323          nvl(PLL.price_override, 0),            -- l_po_price
8324          decode(AI.invoice_currency_code,
8325                 ASP.base_currency_code, 1,
8326                 PD.rate), -- l_po_rate
8327          decode (AI.invoice_currency_code,
8328                  ASP.base_currency_code, 1 ,
8329                  RTXN.currency_conversion_rate),  -- l_rtxn_rate
8330          nvl(AI.exchange_rate,1),  -- l_inv_rate
8331          nvl(PLL.match_option, 'P'),            -- l_match_option
8332          D.matched_uom_lookup_code,             -- l_rtxn_uom
8333          RSL.item_id,                           -- l_rtxn_item_id
8334          PL.unit_meas_lookup_code,              -- l_po_uom
8335          D.amount,                              -- l_distribution_amt
8336          decode(AI.invoice_currency_code,
8337                 ASP.base_currency_code, nvl(D.amount,0),
8338                                     nvl(D.base_amount,0)),  -- l_dist_base_amt
8339          D.dist_match_type,                     -- l_dist_match_type
8340          D.corrected_invoice_dist_id,           -- l_corrected_invoice_dist_id
8341          D.corrected_quantity,                  -- l_corrected_quantity
8342          PLL.matching_basis,                     -- l_match_basis /* Amount Based Matching */
8343 	 ail.line_source                  --Bug#10416960
8344   FROM   ap_invoices_all AI,
8345          ap_system_parameters_all ASP,
8346          ap_invoice_distributions D,
8347          po_distributions PD,
8348          po_lines PL,
8349          po_line_types PLT,                     -- Amount Based Matching
8350          po_line_locations PLL,
8351          rcv_transactions RTXN,
8352          rcv_shipment_lines RSL,
8353 	 AP_INVOICE_LINES_ALL ail --bug#10416960
8354   WHERE  AI.invoice_id = D.invoice_id
8355     AND  D.invoice_distribution_id = X_distribution_id
8356     AND  AIL.invoice_id = D.invoice_id
8357     AND  AIL.line_number=D.invoice_line_number
8358     AND  nvl(ASP.org_id, -999) = nvl(AI.org_id,-999)
8359     AND  nvl(AI.org_id,-999) = nvl(D.org_id,-999)
8360     AND  D.po_distribution_id = PD.po_distribution_id
8361     AND  PL.po_header_id = PD.po_header_id
8362     AND  PL.po_line_id = PD.po_line_id
8363     AND  PL.line_type_id = PLT.line_type_id     -- Amount Based Matching
8364     AND  PD.line_location_id = PLL.line_location_id
8365     AND  D.rcv_transaction_id = RTXN.transaction_id (+)
8366     AND  RTXN.shipment_line_id = RSL.shipment_line_id (+)
8367     AND  D.posted_flag in ('N', 'P')
8368     AND  nvl(D.encumbered_flag, 'N') in ('N', 'H', 'P')
8369     --Modified below condition for bug#14360581
8370     AND    (D.line_type_lookup_code IN ('ITEM', 'ACCRUAL',
8371                                        'RETROEXPENSE', 'RETROACCRUAL') --Retropricing
8372             OR (D.line_type_lookup_code ='IPV'
8373                 AND D.corrected_invoice_dist_id IS NOT NULL))
8374     --Bug#10416960
8375     AND NVL(D.dist_match_type,'NOT_MATCHED') <> 'ADJUSTMENT_CORRECTION'
8376     AND (  (NVL(D.dist_match_type,'NOT_MATCHED') = 'PO_PRICE_ADJUSTMENT'
8377 	    AND ail.line_source = 'PO PRICE ADJUSTMENT')
8378 	 OR NVL(D.dist_match_type,'NOT_MATCHED') <> 'PO_PRICE_ADJUSTMENT');
8379     --End 10416960
8380 
8381 --Bug 9242891 added new cursor for ERV creation on retainage release inv
8382     --added line_type_lookup_code RETAINAGE condition and relevant column
8383     --changes. Basic assumptions for this fix: NO IPV,ITEM,ACCRUAL line type can
8384     --be added in retainage release invoice. Retropricing/corrections are not allowed
8385     --once a retainage release has been issued.
8386   cursor Retainage_inv_dist_cursor is
8387   SELECT AI.invoice_currency_code,              -- l_inv_currency_code
8388          ASP.base_currency_code,                -- l_base_currency_code
8389          D.line_type_lookup_code,               -- l_dist_line_type
8390          D.unit_price,                          -- l_inv_price
8391          nvl(D.quantity_invoiced, 0),           -- l_quantity_invoiced
8392          nvl(PD.quantity_ordered,0) -
8393               nvl(PD.quantity_cancelled,0),     -- l_po_qty
8394          nvl(PLL.price_override, 0),            -- l_po_price
8395          decode(AI.invoice_currency_code,
8396                 ASP.base_currency_code, 1,
8397                 nvl(retain_ai.exchange_rate,1)), --l_po_rate bug 9242891 retained_inv_rate
8398          decode (AI.invoice_currency_code,
8399                  ASP.base_currency_code, 1 ,
8400                  nvl(retain_ai.exchange_rate,1)),  -- l_rtxn_rate --bug 9242891 retained_inv_rate
8401          nvl(AI.exchange_rate,1),  -- l_inv_rate
8402          nvl(PLL.match_option, 'P'),            -- l_match_option
8403          D.matched_uom_lookup_code,             -- l_rtxn_uom
8404          RSL.item_id,                           -- l_rtxn_item_id
8405          PL.unit_meas_lookup_code,              -- l_po_uom
8406          D.amount,                              -- l_distribution_amt
8407          decode(AI.invoice_currency_code,
8408                 ASP.base_currency_code, nvl(D.amount,0),
8409                                     nvl(D.base_amount,0)),  -- l_dist_base_amt
8410          D.dist_match_type,                     -- l_dist_match_type
8411          D.corrected_invoice_dist_id,           -- l_corrected_invoice_dist_id
8412          D.corrected_quantity,                  -- l_corrected_quantity
8413          PLL.matching_basis,                     -- l_match_basis /* Amount Based Matching */
8414          NULL                                    --line_source
8415   FROM   ap_invoices_all AI,
8416          ap_invoices retain_ai,  --bug 9242891 retained invoice
8417          ap_system_parameters_all ASP,
8418          ap_invoice_distributions D,
8419          ap_invoice_distributions retain_d, --bug 9242891 retainage inv dists
8420          po_distributions PD,
8421          po_lines PL,
8422          po_line_types PLT,                     -- Amount Based Matching
8423          po_line_locations PLL,
8424          rcv_transactions RTXN,
8425          rcv_shipment_lines RSL
8426   WHERE  AI.invoice_id = D.invoice_id
8427     AND  AI.invoice_type_lookup_code = 'RETAINAGE RELEASE' --bug 9242891
8428     AND  D.retained_invoice_dist_id = retain_d.Invoice_Distribution_Id --bug 9242891
8429     AND  retain_ai.invoice_id = retain_D.invoice_id --bug 9242891
8430     AND  D.invoice_distribution_id = X_distribution_id
8431     AND  nvl(ASP.org_id, -999) = nvl(AI.org_id,-999)
8432     AND  nvl(AI.org_id,-999) = nvl(D.org_id,-999)
8433     AND  D.po_distribution_id = PD.po_distribution_id
8434     AND  PL.po_header_id = PD.po_header_id
8435     AND  PL.po_line_id = PD.po_line_id
8436     AND  PL.line_type_id = PLT.line_type_id     -- Amount Based Matching
8437     AND  PD.line_location_id = PLL.line_location_id
8438     AND  D.rcv_transaction_id = RTXN.transaction_id (+)
8439     AND  RTXN.shipment_line_id = RSL.shipment_line_id (+)
8440     AND  D.posted_flag in ('N', 'P')
8441     AND  nvl(D.encumbered_flag, 'N') in ('N', 'H', 'P')
8442     AND  D.line_type_lookup_code = 'RETAINAGE' --bug 9242891
8443     AND  D.retained_invoice_dist_id is not NULL; --bug 9242891
8444 
8445   l_cnt  PLS_INTEGER DEFAULT 0; --bug 9242891
8446   l_api_name VARCHAR2(100); --bug 9242891
8447 
8448 
8449   BEGIN
8450 
8451     l_api_name := 'CALCULATE_VARIANCE'; --bug 9242891
8452 
8453     current_calling_sequence := 'AP_INVOICES_UTILITY_PKG.' ||
8454                                 'CALCULATE_VARIANCE<-'|| X_calling_sequence;
8455 
8456 
8457    --bug 9242891
8458     IF (G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
8459        FND_LOG.STRING(G_LEVEL_STATEMENT,G_MODULE_NAME||l_api_name,'AP_INVOICES_UTILITY_PKG.calculate_variance(+)');
8460     END IF; --bug 9242891
8461 
8462 
8463     --bug 9242891 select added to determine which cursor to open.
8464   SELECT COUNT(*)
8465     INTO l_cnt
8466    FROM AP_INVOICES_ALL ai,
8467         AP_INVOICE_DISTRIBUTIONS aid
8468   WHERE aid.Invoice_Distribution_Id = X_DISTRIBUTION_ID
8469    AND ai.invoice_id = aid.invoice_id
8470    AND ai.invoice_type_lookup_code = 'RETAINAGE RELEASE';
8471    --bug 9242891
8472 
8473    /*-----------------------------------------------------------------+
8474     |  Step 0 - Open Cursor to Initialize the all the information     |
8475     +-----------------------------------------------------------------*/
8476 
8477   IF l_cnt = 0 then --bug 9242891
8478 
8479      l_debug_info := 'CALCULATE_VARIANCE - Fetch cursor invoice_dist_cursor';
8480 
8481     --bug 9242891
8482     IF (G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
8483        FND_LOG.STRING(G_LEVEL_STATEMENT,G_MODULE_NAME||l_api_name,l_debug_info);
8484     END IF; --bug 9242891
8485 
8486     OPEN invoice_dist_cursor;
8487     FETCH invoice_dist_cursor INTO
8488                  l_inv_currency_code,
8489                  l_base_currency_code,
8490                  l_dist_line_type,
8491                  l_inv_price,
8492                  l_qty_invoiced,
8493                  l_po_qty,
8494                  l_po_price,
8495                  l_po_rate,
8496                  l_rtxn_rate,
8497                  l_inv_rate,
8498                  l_match_option,
8499                  l_rtxn_uom,
8500                  l_rtxn_item_id,
8501                  l_po_uom,
8502                  l_distribution_amt,
8503                  l_dist_base_amt,
8504                  l_dist_match_type,
8505                  l_corrected_inv_dist_id,
8506                  l_corrected_qty,
8507                  l_match_basis,
8508 		 l_line_source; --Bug#10416960
8509 
8510     IF (invoice_dist_cursor%NOTFOUND) THEN
8511       l_debug_info := 'CALCULATE_VARIANCE - ROW NOTFOUND';
8512       CLOSE invoice_dist_cursor;
8513       x_debug_info := l_debug_info;
8514       x_debug_context := current_calling_sequence;
8515       return (FALSE);
8516     END IF;
8517 
8518     CLOSE invoice_dist_cursor;
8519     l_debug_info := ' CALCULATE_VARIANCE - Close cursor invoice_dist_cursor';
8520 
8521   ELSE --bug 9242891
8522 
8523      l_debug_info := 'CALCULATE_VARIANCE - Fetch cursor Retainage_inv_dist_cursor';
8524 
8525     --bug 9242891
8526     IF (G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
8527        FND_LOG.STRING(G_LEVEL_STATEMENT,G_MODULE_NAME||l_api_name,l_debug_info);
8528     END IF; --bug 9242891
8529 
8530    OPEN Retainage_inv_dist_cursor;
8531     FETCH Retainage_inv_dist_cursor INTO
8532                  l_inv_currency_code,
8533                  l_base_currency_code,
8534                  l_dist_line_type,
8535                  l_inv_price,
8536                  l_qty_invoiced,
8537                  l_po_qty,
8538                  l_po_price,
8539                  l_po_rate,
8540                  l_rtxn_rate,
8541                  l_inv_rate,
8542                  l_match_option,
8543                  l_rtxn_uom,
8544                  l_rtxn_item_id,
8545                  l_po_uom,
8546                  l_distribution_amt,
8547                  l_dist_base_amt,
8548                  l_dist_match_type,
8549                  l_corrected_inv_dist_id,
8550                  l_corrected_qty,
8551                  l_match_basis,
8552                  l_line_source;       --line source passed as null bug 9242891
8553 
8554     IF (Retainage_inv_dist_cursor%NOTFOUND) THEN
8555       l_debug_info := 'CALCULATE_VARIANCE - ROW NOTFOUND IN RETAINAGE';
8556       CLOSE Retainage_inv_dist_cursor;
8557       x_debug_info := l_debug_info;
8558       x_debug_context := current_calling_sequence;
8559       return (FALSE);
8560     END IF;
8561 
8562     CLOSE Retainage_inv_dist_cursor;
8563     l_debug_info := ' CALCULATE_VARIANCE - Close cursor Retainage_inv_dist_cursor';
8564 
8565     --bug 9242891
8566     IF (G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
8567        FND_LOG.STRING(G_LEVEL_STATEMENT,G_MODULE_NAME||l_api_name,l_debug_info);
8568     END IF; --bug 9242891
8569 
8570   END IF; --bug 9242891 end
8571 
8572 
8573    /*-----------------------------------------------------------------+
8574     | Amount Based Matching. IPV for l_match_basis = 'QUANTITY' only  |
8575     +-----------------------------------------------------------------*/
8576 
8577     IF l_match_basis = 'QUANTITY' THEN
8578 
8579        /*-----------------------------------------------------------------+
8580        | Step 2 - try to assemble the original dist amt and base amt     |
8581        +-----------------------------------------------------------------*/
8582 
8583         --Commented below and introduced new l_original_dist_base_amt
8584 	--for bug#9252266
8585 
8586          /* l_original_dist_base_amt := l_dist_base_amt + NVL(x_bipv, 0)
8587                                 + NVL(x_erv, 0); */
8588 
8589          l_original_dist_base_amt := AP_UTILITIES_PKG.ap_round_currency(
8590                                        ((l_distribution_amt+NVL(x_ipv, 0))*l_inv_rate)
8591                                           ,l_base_currency_code);
8592          l_original_dist_amt := l_distribution_amt + NVL(x_ipv, 0);
8593 
8594 
8595       /*-----------------------------------------------------------------+
8596        | Step 3 - converte po/rcv uom                                    |
8597        +-----------------------------------------------------------------*/
8598 
8599        IF (l_match_option = 'R' and l_po_uom <> l_rtxn_uom ) THEN
8600           l_uom_conv_rate := po_uom_s.po_uom_convert (
8601                              l_rtxn_uom,
8602                              l_po_uom,
8603                              l_rtxn_item_id);
8604 
8605           l_qty_invoiced := l_qty_invoiced * l_uom_conv_rate;
8606           l_inv_price := l_inv_price / l_uom_conv_rate;
8607        END IF;
8608 
8609     ELSIF (l_match_basis = 'AMOUNT') THEN
8610 
8611         --Commented below and introduced new l_original_dist_base_amt
8612 	--for Bug 16029169
8613 
8614       /* l_original_dist_base_amt := l_dist_base_amt; */
8615 
8616       l_original_dist_base_amt := AP_UTILITIES_PKG.ap_round_currency(
8617                                        (l_distribution_amt*l_inv_rate)
8618                                           ,l_base_currency_code);
8619       l_original_dist_amt := l_distribution_amt;
8620 
8621     END IF;  -- End l_match_basis. /* Amount Based Matching  */
8622 
8623    /*-----------------------------------------------------------------+
8624     | Step 4 - get rate difference  and price diff                    |
8625     +-----------------------------------------------------------------*/
8626 
8627     If (l_rtxn_rate is null) Then
8628       l_rate_diff := l_inv_rate - l_po_rate;
8629     Else
8630       l_rate_diff := l_inv_rate - l_rtxn_rate;
8631     end if;
8632 
8633     l_price_diff := l_inv_price - l_po_price;
8634 
8635    /*-----------------------------------------------------------------+
8636     | Amount Based Matching. For AMOUNT Based mathing calculation of  |
8637     | ERV is different                                                |
8638     +-----------------------------------------------------------------*/
8639 
8640     IF l_match_basis = 'QUANTITY' THEN
8641         /*-----------------------------------------------------------------+
8642         | Step 5 - calculate erv/ipv                                      |
8643         +-----------------------------------------------------------------*/
8644         --Retropricing
8645 	/*Bug#10416960. Removed PO price adjustment here and introduced
8646           new ELSIF */
8647        IF  l_dist_match_type  IN ('QTY_CORRECTION') THEN
8648 
8649           /*-----------------------------------------------------------------+
8650            | calculate erv/ipv - quantity correction                         |
8651            +-----------------------------------------------------------------*/
8652 
8653           l_debug_info := ' CALCULATE_VARIANCE - for QTY_CORRECTION';
8654 
8655           IF (l_rate_diff = 0) THEN
8656             x_erv := 0;
8657           ELSE
8658             x_erv := AP_UTILITIES_PKG.ap_round_currency(
8659                      l_corrected_qty * l_po_price *
8660                      l_rate_diff
8661                      ,l_base_currency_code);
8662           END IF;
8663 
8664           x_ipv := AP_UTILITIES_PKG.ap_round_currency(
8665                    l_corrected_qty * l_price_diff
8666                    ,l_inv_currency_code);
8667 
8668           IF (x_ipv = 0) THEN
8669               x_bipv := 0;
8670           ELSE
8671                -- Bug 5484167  base invoice price variance should be calculated directly from the invoice price variance
8672                --to avoid incorrect rounding logic
8673                /* x_bipv := AP_UTILITIES_PKG.ap_round_currency(
8674                             l_corrected_qty * l_inv_rate * l_price_diff
8675                             , l_base_currency_code);*/
8676                x_bipv := AP_UTILITIES_PKG.ap_round_currency(x_ipv * l_inv_rate, l_base_currency_code);
8677 
8678           END IF;
8679        --Bug#10416960
8680       --Line_source condition is need when running cadip 2nd time for same PO
8681       ELSIF ( l_dist_match_type = 'PO_PRICE_ADJUSTMENT' and l_line_source='PO PRICE ADJUSTMENT') THEN
8682         x_ipv := 0;
8683         x_bipv := 0;
8684 
8685 	  IF (l_rate_diff = 0) THEN
8686             x_erv := 0;
8687           ELSE
8688             x_erv := AP_UTILITIES_PKG.ap_round_currency(
8689                      l_corrected_qty * l_inv_price *
8690                      l_rate_diff
8691                      ,l_base_currency_code);
8692           END IF;
8693         --End 10416960
8694        ELSIF ( l_dist_match_type = 'PRICE_CORRECTION' ) THEN
8695 
8696           /*-----------------------------------------------------------------+
8697           | calculate erv/ipv - price correction                            |
8698           +-----------------------------------------------------------------*/
8699 
8700           l_debug_info := ' CALCULATE_VARIANCE - for PRICE CORRECTION';
8701 
8702           select nvl(AI.exchange_rate, 1)
8703           into l_corrected_inv_rate
8704           from AP_INVOICES AI,
8705               AP_INVOICE_DISTRIBUTIONS  D
8706           where D.invoice_distribution_id = l_corrected_inv_dist_id
8707           and D.invoice_id = AI.invoice_id;
8708 
8709           /* Modified below statement for bug#14360581
8710           x_erv := AP_UTILITIES_PKG.ap_round_Currency( l_original_dist_amt *
8711                   (l_corrected_inv_rate - l_inv_rate)
8712                   , l_base_currency_code); */
8713 
8714           x_erv := AP_UTILITIES_PKG.ap_round_Currency( l_original_dist_amt *
8715                   ( l_inv_rate - l_corrected_inv_rate)
8716                   , l_base_currency_code);
8717           x_ipv  := 0;
8718           x_bipv := 0;
8719 
8720        ELSE
8721 
8722           /*-----------------------------------------------------------------+
8723            | calculate erv/ipv - regular quantity base match                 |
8724            +-----------------------------------------------------------------*/
8725 
8726           l_debug_info := ' CALCULATE_VARIANCE - for regular base match
8727                           For Quantity Based Matching';
8728 
8729          IF (l_rate_diff = 0) THEN
8730              x_erv := 0;
8731          ELSE
8732             IF l_cnt = 0 then --bug 9242891
8733              x_erv := AP_UTILITIES_PKG.ap_round_currency(
8734                          l_qty_invoiced * l_po_price * l_rate_diff
8735                          ,l_base_currency_code);
8736            ELSE
8737              x_erv := AP_UTILITIES_PKG.ap_round_currency(
8738                      l_original_dist_amt * l_rate_diff
8739                     ,l_base_currency_code);
8740           END IF;
8741           END IF;
8742 
8743 
8744           IF (l_price_diff = 0) THEN
8745              x_ipv := 0;
8746              x_bipv := 0;
8747           ELSE
8748              x_ipv := AP_UTILITIES_PKG.ap_round_currency(
8749                          l_qty_invoiced * l_price_diff
8750                          , l_inv_currency_code );
8751 
8752              IF (x_ipv = 0) THEN
8753                 x_bipv := 0;
8754              ELSE
8755                -- Bug 5484167  base invoice price variance should be calculated directly from the invoice price variance
8756                --to avoid incorrect rounding logic
8757                /* x_bipv := AP_UTILITIES_PKG.ap_round_currency(
8758                             l_qty_invoiced * l_inv_rate * l_price_diff
8759                             , l_base_currency_code);*/
8760                x_bipv := AP_UTILITIES_PKG.ap_round_currency(x_ipv * l_inv_rate, l_base_currency_code);
8761 
8762              END IF;
8763 
8764           END IF; -- end of check l_price_diff
8765 
8766        END IF; -- end of check the l_dist_match_type
8767 
8768     ELSE     -- l_match_basis = 'AMOUNT'. /*Amount Based Matching */
8769 
8770       IF ( l_dist_match_type = 'AMOUNT_CORRECTION' ) THEN
8771 
8772         /*-----------------------------------------------------------------+
8773         | calculate erv - amount correction                               |
8774         +-----------------------------------------------------------------*/
8775 
8776         l_debug_info := ' CALCULATE_VARIANCE - for AMOUNT CORRECTION';
8777 
8778         select nvl(AI.exchange_rate, 1)
8779         into l_corrected_inv_rate
8780         from AP_INVOICES AI,
8781              AP_INVOICE_DISTRIBUTIONS  D
8782         where D.invoice_distribution_id = l_corrected_inv_dist_id
8783         and D.invoice_id = AI.invoice_id;
8784 
8785         /* Modified below statement for bug#14360581
8786         x_erv := AP_UTILITIES_PKG.ap_round_Currency( l_original_dist_amt *
8787                   (l_corrected_inv_rate - l_inv_rate)
8788                   , l_base_currency_code); */
8789 
8790         x_erv := AP_UTILITIES_PKG.ap_round_Currency( l_original_dist_amt *
8791                   (l_inv_rate - l_corrected_inv_rate)
8792                   , l_base_currency_code);
8793 
8794         x_ipv  := 0;
8795         x_bipv := 0;
8796 
8797       ELSE
8798 
8799         /*-----------------------------------------------------------------+
8800         | calculate erv - regular amount base match                       |
8801         +-----------------------------------------------------------------*/
8802 
8803         l_debug_info := ' CALCULATE_VARIANCE - for regular base match for
8804                           AMOUNT Based Matching';
8805 
8806         IF (l_rate_diff = 0) THEN
8807           x_erv := 0;
8808         ELSE
8809           x_erv := AP_UTILITIES_PKG.ap_round_currency(
8810                      l_original_dist_amt * l_rate_diff
8811                     ,l_base_currency_code);
8812         END IF;
8813 
8814         x_ipv := 0;
8815         x_bipv := 0;
8816 
8817       END IF;
8818 
8819     END IF;  -- END l_match_basis. /* Amount Based Matching */
8820 
8821    /*-----------------------------------------------------------------+
8822     | Step 6 - Prepare the out parameter                              |
8823     +-----------------------------------------------------------------*/
8824     IF ( x_erv <> 0 or x_ipv <> 0 or x_bipv <> 0 ) THEN
8825        l_debug_info := 'CALCULATE_VARIANCE - variance exists -erv:'||x_erv||' ipv:'||x_ipv; --bug 9242891
8826 
8827     --bug 9242891
8828     IF (G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
8829        FND_LOG.STRING(G_LEVEL_STATEMENT,G_MODULE_NAME||l_api_name,l_debug_info);
8830     END IF; --bug 9242891
8831 
8832       X_DISTRIBUTION_AMT := l_original_dist_amt - X_IPV;
8833       X_DIST_BASE_AMT := l_original_dist_base_amt - X_ERV - X_BIPV;
8834       x_debug_info := l_debug_info;
8835       x_debug_context := current_calling_sequence;
8836     ELSE
8837       X_DISTRIBUTION_AMT := l_original_dist_amt;
8838       X_DIST_BASE_AMT := l_original_dist_base_amt;
8839     END IF;
8840 
8841 
8842     RETURN ( TRUE );
8843 
8844 EXCEPTION
8845     WHEN OTHERS THEN
8846       IF (SQLCODE <> -20001) then
8847         FND_MESSAGE.SET_NAME('SQLAP', 'AP_DEBUG');
8848         FND_MESSAGE.SET_TOKEN('ERROR', SQLERRM);
8849         FND_MESSAGE.SET_TOKEN('CALLING_SEQUENCE', current_calling_sequence);
8850         FND_MESSAGE.SET_TOKEN('PARAMETERS', 'distribution Id = '
8851                || X_distribution_Id);
8852         FND_MESSAGE.SET_TOKEN('DEBUG_INFO', l_debug_info);
8853       END IF;
8854 
8855       l_debug_info := 'CALCULATE_VARIANCE - OTHERS exception exists';
8856       x_debug_info := l_debug_info;
8857       x_debug_context := current_calling_sequence;
8858       RETURN ( FALSE);
8859 
8860 END CALCULATE_VARIANCE;
8861 
8862 
8863 /*============================================================================= |  Public FUNCTION Dist_Refer_Active_Corr
8864 |
8865 |      Check if the invoice distribution is been referred by a
8866 |      active correction
8867 |
8868 |  PROGRAM FLOW
8869 |
8870 |       return TRUE  - if distribution is been referred by any correction
8871 |       return FALSE - otherwise.
8872 |
8873 |  MODIFICATION HISTORY
8874 |  Date         Author               Description of Change
8875 |  01/28/04     Surekha Myadam       Created
8876  *============================================================================*/
8877 
8878 FUNCTION Dist_Refer_Active_Corr(
8879 		P_Invoice_Dist_ID  IN NUMBER,
8880 	        P_Calling_Sequence IN VARCHAR2) RETURN BOOLEAN IS
8881  dummy number := 0;
8882  current_calling_sequence   Varchar2(2000);
8883  debug_info                 Varchar2(100);
8884 BEGIN
8885 
8886     -- Update the calling sequence
8887     --
8888     current_calling_sequence :=
8889         'AP_INVOICE_DISTRIBUTIONS_PKG.DIST_REFER_ACTIVE_CORR<-'
8890                       ||p_Calling_Sequence;
8891 
8892     debug_info := 'Select from ap_invoice_distributions_all';
8893 
8894     Select count(*)
8895     Into   dummy
8896     From   ap_invoice_distributions_all AID
8897     Where  NVL(AID.cancellation_flag, 'N' ) <> 'Y'
8898     And NVL( AID.reversal_flag, 'N' ) <> 'Y'
8899     And AID.corrected_invoice_dist_id = p_invoice_dist_id
8900     And rownum < 2;   --bug 5034678
8901 
8902     If (dummy >= 1) Then
8903       return  TRUE;
8904     End if;
8905 
8906     return FALSE;
8907 
8908   Exception
8909     WHEN OTHERS THEN
8910       If (SQLCODE <> -20001) Then
8911         FND_MESSAGE.SET_NAME('SQLAP', 'AP_DEBUG');
8912         FND_MESSAGE.SET_TOKEN('ERROR', SQLERRM);
8913         FND_MESSAGE.SET_TOKEN('CALLING_SEQUENCE', current_calling_sequence);
8914         FND_MESSAGE.SET_TOKEN('PARAMETERS', 'Distribution Id = '||P_Invoice_Dist_Id);
8915         FND_MESSAGE.SET_TOKEN('DEBUG_INFO', debug_info);
8916       End If;
8917       APP_EXCEPTION.RAISE_EXCEPTION;
8918 
8919 
8920 END Dist_Refer_Active_Corr;
8921 
8922 /*=============================================================================
8923 |  Public FUNCTION Chrg_Refer_Active_Dist
8924 |
8925 |      Check if this charge distribution is been allocated to  a
8926 |      active invoice distribution
8927 |
8928 |  PROGRAM FLOW
8929 |
8930 |       return TRUE  - if distribution is been referred by any correction
8931 |       return FALSE - otherwise.
8932 |
8933 |  MODIFICATION HISTORY
8934 |  Date         Author               Description of Change
8935 |  01/28/04     Surekha Myadam       Created
8936 *============================================================================*/
8937 
8938 FUNCTION Chrg_Refer_Active_Dist(
8939 		P_Invoice_Dist_Id  IN NUMBER,
8940 		P_Calling_Sequence IN VARCHAR2) RETURN BOOLEAN IS
8941 
8942  dummy number := 0;
8943  dummy_self number := 0; --bug9542963
8944  current_calling_sequence   Varchar2(2000);
8945  debug_info                 Varchar2(100);
8946 
8947 BEGIN
8948 
8949     -- Update the calling sequence
8950     --
8951     current_calling_sequence :=
8952         'AP_INVOICE_DISTRIBUTIONS_PKG.CHRG_REFER_ACTIVE_DIST<-'
8953                       ||p_Calling_Sequence;
8954 
8955     debug_info := 'Select from ap_invoice_distributions_all';
8956 
8957     Select count(*)
8958     Into   dummy
8959     From   ap_invoice_distributions_all AID
8960     Where  AID.charge_applicable_to_dist_id =  p_invoice_dist_id
8961     And    NVL(AID.cancellation_flag, 'N')  <> 'Y'
8962     And    NVL(AID.reversal_flag, 'N')      <> 'Y';
8963 
8964     --bug9542963
8965     Select count(*)
8966     Into   dummy_self
8967     From   ap_self_assessed_tax_dist_all AID
8968     Where  AID.charge_applicable_to_dist_id =  p_invoice_dist_id
8969     And    NVL(AID.cancellation_flag, 'N')  <> 'Y'
8970     And    NVL(AID.reversal_flag, 'N')      <> 'Y';
8971 
8972     If (dummy >= 1 or dummy_self >= 1 ) Then
8973       return  TRUE;
8974     End if;
8975 
8976     return FALSE;
8977 
8978 
8979 
8980 Exception
8981  WHEN OTHERS THEN
8982   If (SQLCODE <> -20001) Then
8983    FND_MESSAGE.SET_NAME('SQLAP', 'AP_DEBUG');
8984    FND_MESSAGE.SET_TOKEN('ERROR', SQLERRM);
8985    FND_MESSAGE.SET_TOKEN('CALLING_SEQUENCE', current_calling_sequence);
8986    FND_MESSAGE.SET_TOKEN('PARAMETERS', 'Distribution Id = '||P_Invoice_Dist_Id);
8987    FND_MESSAGE.SET_TOKEN('DEBUG_INFO', debug_info);
8988   End If;
8989   APP_EXCEPTION.RAISE_EXCEPTION;
8990 END Chrg_Refer_Active_Dist;
8991 
8992 /*=============================================================================
8993 |
8994 |      Check if the invoice distribution is been referred by a
8995 |      active correction. Wrapper API to be used from Java layer.
8996 |      Introduced as part of bug 9374412.
8997 |
8998 |  PROGRAM FLOW
8999 |
9000 |       return 1  - if distribution is been referred by any correction
9001 |       return 0  - otherwise.
9002 |
9003 |  MODIFICATION HISTORY
9004 |  Date         Author               Description of Change
9005 |  06/03/10     Pramod Podhiyath     Created
9006  *============================================================================*/
9007 
9008 FUNCTION Dist_Refer_Active_Corr_Wrap(
9009 		P_Invoice_Dist_ID  IN NUMBER,
9010 	        P_Calling_Sequence IN VARCHAR2) RETURN NUMBER IS
9011  result_bool boolean := false ;
9012  result_num number := 0;
9013  current_calling_sequence   Varchar2(2000);
9014  debug_info                 Varchar2(1000);
9015 BEGIN
9016 
9017     -- Update the calling sequence
9018     --
9019     current_calling_sequence :=
9020         'AP_INVOICE_DISTRIBUTIONS_PKG.DIST_REFER_ACTIVE_CORR<-'
9021                       ||p_Calling_Sequence;
9022 
9023     debug_info := 'Inside wapper API Dist_Refer_Active_Corr_Wrap, ' ||
9024                   'invoked from NegotiationAMImpl.handleDistributionDeleteAction';
9025 
9026     result_bool := Dist_Refer_Active_Corr(P_Invoice_Dist_ID,
9027                                          P_Calling_Sequence) ;
9028 
9029     debug_info := 'Inside wapper API Dist_Refer_Active_Corr_Wrap, ' ||
9030                   'invoked from NegotiationAMImpl.handleDistributionDeleteAction';
9031 
9032     IF (result_bool) THEN
9033        result_num := 1 ;
9034     ELSE
9035        result_num := 0 ;
9036     END IF ;
9037 
9038     return result_num;
9039 
9040   Exception
9041     WHEN OTHERS THEN
9042       If (SQLCODE <> -20001) Then
9043         FND_MESSAGE.SET_NAME('SQLAP', 'AP_DEBUG');
9044         FND_MESSAGE.SET_TOKEN('ERROR', SQLERRM);
9045         FND_MESSAGE.SET_TOKEN('CALLING_SEQUENCE', current_calling_sequence);
9046         FND_MESSAGE.SET_TOKEN('PARAMETERS', 'Distribution Id = '||P_Invoice_Dist_Id);
9047         FND_MESSAGE.SET_TOKEN('DEBUG_INFO', debug_info);
9048       End If;
9049       APP_EXCEPTION.RAISE_EXCEPTION;
9050 
9051 END Dist_Refer_Active_Corr_Wrap;
9052 
9053 /*=============================================================================
9054 |  Public FUNCTION Chrg_Refer_Active_Dist_Wrap
9055 |
9056 |      Check if this charge distribution is been allocated to  a
9057 |      active invoice distribution. Wrapper API to be used from Java layer.
9058 |      Introduced as part of bug 9374412.
9059 |
9060 |  PROGRAM FLOW
9061 |
9062 |       return 1  - if distribution is been referred by any correction
9063 |       return 0  - otherwise.
9064 |
9065 |  MODIFICATION HISTORY
9066 |  Date         Author               Description of Change
9067 |  06/03/10     Pramod Podhiyath     Created
9068 *============================================================================*/
9069 
9070 FUNCTION Chrg_Refer_Active_Dist_Wrap(
9071 		P_Invoice_Dist_Id  IN NUMBER,
9072 		P_Calling_Sequence IN VARCHAR2) RETURN NUMBER IS
9073 
9074  result_bool boolean := false ;
9075  result_num number := 0;
9076  current_calling_sequence   Varchar2(2000);
9077  debug_info                 Varchar2(1000);
9078 
9079 BEGIN
9080 
9081     -- Update the calling sequence
9082     --
9083     current_calling_sequence :=
9084         'AP_INVOICE_DISTRIBUTIONS_PKG.CHRG_REFER_ACTIVE_DIST<-'
9085                       ||p_Calling_Sequence;
9086 
9087     debug_info := 'Inside wapper API Chrg_Refer_Active_Dist_Wrap, ' ||
9088                   'invoked from NegotiationAMImpl.handleDistributionDeleteAction';
9089 
9090     result_bool := Chrg_Refer_Active_Dist(P_Invoice_Dist_Id,
9091                                           P_Calling_Sequence) ;
9092 
9093     IF (result_bool) THEN
9094        result_num := 1 ;
9095     ELSE
9096        result_num := 0 ;
9097     END IF ;
9098 
9099     return result_num;
9100 
9101 Exception
9102  WHEN OTHERS THEN
9103   If (SQLCODE <> -20001) Then
9104    FND_MESSAGE.SET_NAME('SQLAP', 'AP_DEBUG');
9105    FND_MESSAGE.SET_TOKEN('ERROR', SQLERRM);
9106    FND_MESSAGE.SET_TOKEN('CALLING_SEQUENCE', current_calling_sequence);
9107    FND_MESSAGE.SET_TOKEN('PARAMETERS', 'Distribution Id = '||P_Invoice_Dist_Id);
9108    FND_MESSAGE.SET_TOKEN('DEBUG_INFO', debug_info);
9109   End If;
9110   APP_EXCEPTION.RAISE_EXCEPTION;
9111 END Chrg_Refer_Active_Dist_Wrap;
9112 
9113 PROCEDURE Make_Distributions_Permanent
9114                  (P_Invoice_Id IN NUMBER,
9115                   P_Invoice_Line_Number IN NUMBER DEFAULT NULL,
9116                   P_Calling_Sequence IN VARCHAR2) IS
9117 
9118 TYPE INVOICE_LINE_NUMBER_LIST IS TABLE OF ap_invoice_lines.line_number%TYPE;
9119 l_line_number_tab 	 INVOICE_LINE_NUMBER_LIST;
9120 l_debug_info 		 VARCHAR2(2000);
9121 current_calling_sequence VARCHAR2(2000);
9122 l_line_number		NUMBER;
9123 global_exception        EXCEPTION;
9124 
9125 BEGIN
9126 
9127  current_calling_sequence := 'Ap_Invoice_Distributions_Pkg.Make_Distributions_Permanent<-  '
9128 				||p_calling_sequence;
9129 
9130  l_debug_info := 'Updating ap_invoice_distributions';
9131 
9132  UPDATE ap_invoice_distributions_all
9133  SET distribution_class = 'PERMANENT'
9134  WHERE invoice_id = p_invoice_id
9135  AND   invoice_line_number = NVL(p_invoice_line_number, invoice_line_number)
9136  AND distribution_class = 'CANDIDATE'
9137  RETURNING invoice_line_number BULK COLLECT INTO l_line_number_tab;
9138 
9139  l_debug_info := 'Updating ap_self_assessed_tax_dist';
9140 
9141  UPDATE ap_self_assessed_tax_dist_all
9142  SET distribution_class = 'PERMANENT'
9143  WHERE invoice_id = p_invoice_id
9144  AND   invoice_line_number = NVL(p_invoice_line_number, invoice_line_number)
9145  AND distribution_class = 'CANDIDATE';
9146 
9147  l_debug_info := 'Updating ap_invoice_lines';
9148 
9149  FOR uniq_values IN 1 .. l_line_number_tab.count LOOP
9150 
9151    l_line_number := l_line_number_tab(uniq_values);
9152 
9153    UPDATE ap_invoice_lines_all ail
9154    SET generate_dists = 'D'
9155    WHERE nvl(ail.generate_dists,'N') = 'Y'
9156    AND invoice_id = p_invoice_id
9157    AND ail.line_number = l_line_number_tab(uniq_values);
9158 
9159    --Commented below condition for the bug 7483192
9160    /*AND ail.amount = (SELECT SUM(NVL(aid.amount,0))
9161   	             FROM ap_invoice_distributions_all aid
9162 		     WHERE aid.invoice_id = ail.invoice_id
9163 		     AND aid.invoice_line_number = ail.line_number
9164 		     AND aid.distribution_class = 'PERMANENT'); */
9165 
9166    UPDATE AP_ALLOCATION_RULES ALR
9167    SET STATUS  = 'EXECUTED'
9168    WHERE alr.invoice_id = p_invoice_id
9169    AND alr.chrg_invoice_line_number = l_line_number_tab(uniq_values)
9170    AND EXISTS (SELECT 'Valid charge line'
9171                FROM ap_invoice_lines ail
9172                WHERE ail.invoice_id = p_invoice_id  --bug 5052657
9173                AND ail.line_number = alr.chrg_invoice_line_number
9174                AND nvl(ail.generate_dists,'N') = 'D'
9175                AND ail.line_type_lookup_code IN ('FREIGHT','MISCELLANEOUS'));
9176 
9177    --Bug:4674229
9178    DECLARE
9179       l_awt_success   Varchar2(1000);
9180    BEGIN
9181       Ap_Extended_Withholding_Pkg.Ap_Ext_Withholding_Default
9182                (p_invoice_id => p_invoice_id,
9183                 p_inv_line_num => l_line_number_tab(uniq_values),
9184 		p_inv_dist_id  => NULL,
9185                 p_calling_module => current_calling_sequence,
9186 		p_parent_dist_id => NULL,
9187                 p_awt_success => l_awt_success);
9188       IF (l_awt_success <> 'SUCCESS') THEN
9189         RAISE Global_Exception;
9190       END IF;
9191    END;
9192 
9193  END LOOP;
9194 
9195 EXCEPTION
9196  WHEN OTHERS THEN
9197   IF (SQLCODE <> -20001) THEN
9198    FND_MESSAGE.SET_NAME('SQLAP', 'AP_DEBUG');
9199    FND_MESSAGE.SET_TOKEN('ERROR', SQLERRM);
9200    FND_MESSAGE.SET_TOKEN('CALLING_SEQUENCE', current_calling_sequence);
9201    FND_MESSAGE.SET_TOKEN('PARAMETERS', 'Invoice Id = '||P_Invoice_Id);
9202    FND_MESSAGE.SET_TOKEN('DEBUG_INFO', l_debug_info);
9203   END IF;
9204   APP_EXCEPTION.RAISE_EXCEPTION;
9205 
9206 END Make_Distributions_Permanent;
9207 
9208 /*=============================================================================
9209 |  Public FUNCTION Chrg_Refer_Active_Dist
9210 |
9211 |  This procedure will get the sum of total charge amount allocated
9212 |  to a particular invoice distribution.
9213 |
9214 |  PROGRAM FLOW
9215 |
9216 |       return   - 0 if no charges are allocated to this distribution.
9217 |		 - returns the sum of charge distributions that are
9218 |		   allocated to this distribution.
9219 |
9220 |  MODIFICATION HISTORY
9221 |  Date         Author               Description of Change
9222 |  02/23/04     Surekha Myadam       Created
9223 *============================================================================*/
9224 
9225 Function Associated_Charges(P_Invoice_Id	      IN NUMBER,
9226 			    P_Invoice_Distribution_Id IN NUMBER)
9227 							RETURN NUMBER IS
9228 
9229 l_total_charge_amount	  NUMBER := 0;
9230 l_debug_info		  VARCHAR2(200);
9231 
9232 BEGIN
9233 
9234   l_debug_info := 'Get total charge amount allocated to this distribution';
9235 
9236   SELECT sum(aid.amount)
9237   INTO l_total_charge_amount
9238   FROM ap_invoice_distributions aid
9239   WHERE aid.invoice_id = p_invoice_id
9240   AND aid.charge_applicable_to_dist_id = p_invoice_distribution_id;
9241 
9242   RETURN(l_total_charge_amount);
9243 
9244 EXCEPTION
9245  WHEN OTHERS THEN
9246   IF (SQLCODE <> -20001) THEN
9247    FND_MESSAGE.SET_NAME('SQLAP', 'AP_DEBUG');
9248    FND_MESSAGE.SET_TOKEN('ERROR', SQLERRM);
9249    FND_MESSAGE.SET_TOKEN('PARAMETERS', 'Invoice Distribution Id = '
9250 					||P_Invoice_Distribution_Id);
9251    FND_MESSAGE.SET_TOKEN('DEBUG_INFO', l_debug_info);
9252   END IF;
9253   APP_EXCEPTION.RAISE_EXCEPTION;
9254 
9255 END Associated_Charges;
9256 
9257 /*=============================================================================
9258 |  Public FUNCTION IS_AWT_COMPUTED_dist
9259 |
9260 |  This procedure will check whether the passed distribution id is parent of any awt distribution
9261 |  returns Y if there exists any awt distribution for this item distribution
9262 |
9263 |  PROGRAM FLOW
9264 |
9265 |       return   - Y if there exists any awt distribution for the passed input awt distribution
9266 |		 - N if there  doesn't exists any awt distribution for the passed input awt distribution
9267 |
9268 |  MODIFICATION HISTORY
9269 |  Date         Author               Description of Change
9270 |  09/20/2011   Nagoor Shaik          Created
9271 *============================================================================*/
9272 FUNCTION IS_AWT_COMPUTED_dist(P_DISTRIBUTION_ID IN  varchar2,P_INVOICE_ID IN VARCHAR2)
9273 RETURN  VARCHAR2 IS
9274 L_AWT_COMPUTED VARCHAR2(2):='N';
9275 BEGIN
9276  BEGIN
9277  SELECT 'Y' INTO L_AWT_COMPUTED
9278  FROM DUAL WHERE EXISTS
9279  (
9280  SELECT INVOICE_DISTRIBUTION_ID
9281  FROM AP_INVOICE_DISTRIBUTIONS
9282  WHERE LINE_TYPE_LOOKUP_CODE='AWT'
9283  AND INVOICE_ID=P_INVOICE_ID
9284  AND AWT_RELATED_ID=P_DISTRIBUTION_ID
9285  AND NVL(REVERSAL_FLAG,'N')='N'
9286   );
9287  EXCEPTION
9288  WHEN NO_DATA_FOUND THEN
9289  NULL;
9290  END;
9291 RETURN L_AWT_COMPUTED;
9292 END;
9293 
9294 
9295 END AP_INVOICE_DISTRIBUTIONS_PKG;