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.68.12010000.4 2009/01/13 02:19:05 bgoyal 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 
275             --commented below condition for the bug 7312805/7244811
276            /*AND ((aid.line_type_lookup_code NOT IN ('PREPAY', 'AWT', 'RETAINAGE')
277                  AND aid.prepay_distribution_id IS NULL)
278                  OR  (ail.line_type_lookup_code = 'RETAINAGE RELEASE'
279                       AND aid.line_type_lookup_code = 'RETAINAGE')
280                  OR  NVL(ail.invoice_includes_prepay_flag,'N') = 'Y');*/
281         end if;
282 
283         X_Total_Rtot_DB := X_Total;
284 
285      EXCEPTION
286        WHEN OTHERS THEN
287          if (SQLCODE <> -20001) then
288            FND_MESSAGE.SET_NAME('SQLAP', 'AP_DEBUG');
289            FND_MESSAGE.SET_TOKEN('ERROR', SQLERRM);
290            FND_MESSAGE.SET_TOKEN('CALLING_SEQUENCE', current_calling_sequence);
291            FND_MESSAGE.SET_TOKEN('PARAMETERS','Invoice Id = '||X_Invoice_Id
292                                           ||',Total = '||X_Total
293                                           ||',Total RTOT DB = '||
294                                               X_Total_Rtot_DB);
295            FND_MESSAGE.SET_TOKEN('DEBUG_INFO', debug_info);
296          end if;
297          APP_EXCEPTION.RAISE_EXCEPTION;
298      END Select_Summary;
299 
300  -----------------------------------------------------------------------
301 
302      -----------------------------------------------------------------------
303      -- Procedure Set_Packet_Id reads the packet id for an invoice.
304      --
305 
306      PROCEDURE Set_Inv_Packet_Id(X_Invoice_Id       IN NUMBER,
307                                  X_Packet_id        IN OUT NOCOPY NUMBER,
308                                  X_Calling_Sequence IN VARCHAR2)
309      IS
310        current_calling_sequence  VARCHAR2(2000);
311        debug_info                VARCHAR2(100);
312      BEGIN
313 
314         -- Update the calling sequence
315         --
316         current_calling_sequence :=
317          'AP_INVOICE_DISTRIBUTION_PKG.Set_Inv_Packet_Id<-'||X_Calling_Sequence;
318 
319         debug_info := 'Select from ap_invoice_distributions';
320 
321         select decode(count(distinct(packet_id)),1,max(packet_id),'')
322         into   X_Packet_Id
323         from   ap_invoice_distributions
324         where  invoice_id = X_Invoice_Id
325         and    packet_id is not null;
326 
327      EXCEPTION
328        WHEN OTHERS THEN
329          if (SQLCODE <> -20001) then
330            FND_MESSAGE.SET_NAME('SQLAP', 'AP_DEBUG');
331            FND_MESSAGE.SET_TOKEN('ERROR', SQLERRM);
332            FND_MESSAGE.SET_TOKEN('CALLING_SEQUENCE', current_calling_sequence);
333            FND_MESSAGE.SET_TOKEN('PARAMETERS', 'Invoice Id = '||X_Invoice_Id
334                                          ||', Packet Id = '||X_Packet_Id);
335            FND_MESSAGE.SET_TOKEN('DEBUG_INFO', debug_info);
336          end if;
337          APP_EXCEPTION.RAISE_EXCEPTION;
338 
339      END Set_Inv_Packet_Id;
340 
341      -----------------------------------------------------------------------
342 
343      -----------------------------------------------------------------------
344      -- Function Query_New_Packet_Id returns true if the packet id has changed
345      -- for a particular distribution.
346      --
347 
348      FUNCTION Query_New_Packet_Id(X_Rowid            VARCHAR2,
349                                   X_Packet_Id        NUMBER,
350                                   X_Calling_Sequence VARCHAR2)
351         RETURN BOOLEAN
352      IS
353         dummy  VARCHAR2(10);
354         current_calling_sequence  VARCHAR2(2000);
355         debug_info                VARCHAR2(100);
356      BEGIN
357 
358         -- Update the calling sequence
359         --
360         current_calling_sequence :=
361      'AP_INVOICE_DISTRIBUTIONS_PKG.Query_New_Packet_Id<-'||X_Calling_Sequence;
362 
363         debug_info := 'Select from ap_invoice_distributions';
364 
365         select 'TRUE'
366         into   dummy
367         from   ap_invoice_distributions
368         where  rowid = X_Rowid
369         and    NVL(packet_id, -1) <> NVL(X_Packet_Id, -1);
370 
371         return(TRUE);
372 
373      EXCEPTION
374        WHEN NO_DATA_FOUND THEN
375           RETURN(FALSE);
376        WHEN OTHERS THEN
377           if (SQLCODE <> -20001) then
378             FND_MESSAGE.SET_NAME('SQLAP', 'AP_DEBUG');
379             FND_MESSAGE.SET_TOKEN('ERROR', SQLERRM);
380             FND_MESSAGE.SET_TOKEN('CALLING_SEQUENCE',current_calling_sequence);
381             FND_MESSAGE.SET_TOKEN('PARAMETERS', 'Rowid = '||X_Rowid
382                                            ||', Packet Id = '||X_Packet_Id);
383           end if;
384           APP_EXCEPTION.RAISE_EXCEPTION;
385      END Query_New_Packet_Id;
386 
387      -----------------------------------------------------------------------
388 
389      -----------------------------------------------------------------------
390      -- Function All_Encumbered returns true if given a distribution line
391      -- all other distribution lines for the invoice have been encumbered.
392      --
393 
394      FUNCTION All_Encumbered(X_Invoice_Id       NUMBER,
395                              X_Rowid            VARCHAR2,
396                              X_Calling_Sequence VARCHAR2)
397         RETURN BOOLEAN
398      IS
399         dummy  VARCHAR2(80);
400         current_calling_sequence   VARCHAR2(2000);
401         debug_info                 VARCHAR2(100);
402      BEGIN
403 
404         -- Update the calling sequence
405         --
406         current_calling_sequence :=
407            'AP_INVOICE_DISTRIBUTIONS_PKG.All_Encumbered<-'||X_Calling_Sequence;
408 
409         debug_info := 'Select from sys.dual';
410 
411         select 'There are encumbered dists'
412         into   dummy
413         from   sys.dual
414         where  not exists (select 'There are other unencumbered dists'
415                              from ap_invoice_distributions
416                             where invoice_id = X_Invoice_Id
417                               and NVL(match_status_flag, 'N') <> 'A'
418                               and rowid <> X_Rowid);
419 
420         return(TRUE);
421 
422      EXCEPTION
423        WHEN NO_DATA_FOUND THEN
424           RETURN(FALSE);
425        WHEN OTHERS THEN
426           if (SQLCODE <> -20001) then
427             FND_MESSAGE.SET_NAME('SQLAP', 'AP_DEBUG');
428             FND_MESSAGE.SET_TOKEN('ERROR', SQLERRM);
429             FND_MESSAGE.SET_TOKEN('CALLING_SEQUENCE',current_calling_sequence);
430             FND_MESSAGE.SET_TOKEN('PARAMETERS', 'Invoice Id = '||X_Invoice_Id
431                                            ||', Rowid = '||X_Rowid);
432             FND_MESSAGE.SET_TOKEN('DEBUG_INFO', debug_info);
433           end if;
434           APP_EXCEPTION.RAISE_EXCEPTION;
435      END All_Encumbered;
436 
437          -----------------------------------------------------------------------
438 
439     -----------------------------------------------------------------------
440     -- Function Check_Cash_Basis_Paid returns true if given an invoice
441     -- we are running cash basis and the invoice has 1 of 2 conditions
442     -- set to TRUE; 1) There are posted payments and no voids.
443     --              2) There are unposted payments linked to a void.
444     --
445 
446      FUNCTION Check_Cash_Basis_Paid(X_Invoice_Id       NUMBER,
447                                     X_Calling_Sequence VARCHAR2)
448         RETURN BOOLEAN
449      IS
450         p_acct_meth    ap_system_parameters.accounting_method_option%TYPE;
451         s_acct_meth    ap_system_parameters.secondary_accounting_method%TYPE;
452         dummy          VARCHAR2(80);
453         current_calling_sequence  VARCHAR2(2000);
454         debug_info                VARCHAR2(100);
455         l_cash_basis   VARCHAR2(1);
456         CURSOR  posted_no_voids IS
457            SELECT 'Has posted payment with no corresponding void'
458            FROM   ap_invoice_payments p1
459            WHERE  p1.invoice_id = X_Invoice_Id
460            AND    nvl(p1.cash_posted_flag, 'N') = 'Y'
461            AND    NOT EXISTS (SELECT 'This is the void partner'
462                               FROM ap_invoice_payments p2
463                               WHERE p2.invoice_id = p1.invoice_id
464                               AND   p2.check_id = p1.check_id
465                               AND   p2.payment_num = p1.payment_num
466                               AND   p2.amount = ( -1 * p1.amount));
467        CURSOR  unposted_w_voids IS
468           SELECT 'Has unposted payment that is linked to a voided check'
469           FROM   ap_invoice_payments p, ap_checks c
470           WHERE  p.invoice_id = X_Invoice_Id
471           AND    nvl(p.cash_posted_flag,'N') <> 'Y'
472           AND    p.check_id = c.check_id
473           AND    c.void_date IS NOT NULL;
474      BEGIN
475 
476         -- Update the calling sequence
477         --
478         current_calling_sequence :=
479     'AP_INVOICE_DISTRIBUTIONS_PKG.Check_Cash_Basis_Paid<-'||X_Calling_Sequence;
480 
481         debug_info := 'Select accounting method from SOB';
482 
483         SELECT NVL(sla_ledger_cash_basis_flag, 'N')
484         INTO   l_cash_basis
485         FROM   ap_system_parameters ASP,
486                gl_sets_of_books  SOB,
487                ap_invoices   AI
488         WHERE  AI.invoice_id = x_invoice_id
489         AND    AI.org_id = ASP.org_id
490         AND    asp.set_of_books_id = sob.set_of_books_id;
491 
492         if (l_cash_basis <>'Y') then
493           return(FALSE);
494         end if;
495 
496         debug_info := 'Select from ap_invoice_payments';
497 
498         OPEN posted_no_voids;
499         debug_info := 'Fetch cursor posted_no_voids';
500         FETCH posted_no_voids INTO dummy;
501         if (posted_no_voids%ROWCOUNT <> 0) then
502           debug_info := 'Close cursor posted_no_voids - ROWCOUNT NOT ZERO';
503           CLOSE posted_no_voids;
504           return(TRUE);
505         end if;
506         debug_info := 'Close cursor posted_no_voids';
507         CLOSE posted_no_voids;
508 
509         debug_info := 'Select from ap_invoice_payments and ap_checks';
510 
511         OPEN unposted_w_voids;
512         debug_info := 'Fetch cursor unposted_w_voids';
513         FETCH unposted_w_voids INTO dummy;
514         if (unposted_w_voids%ROWCOUNT <> 0) then
515           debug_info := 'Close cursor unposted_w_voids';
516           CLOSE unposted_w_voids;
517           return(TRUE);
518         end if;
519 
520         return(FALSE);
521 
522      EXCEPTION
523        WHEN OTHERS THEN
524          if (SQLCODE <> -20001) then
525            FND_MESSAGE.SET_NAME('SQLAP', 'AP_DEBUG');
526            FND_MESSAGE.SET_TOKEN('ERROR', SQLERRM);
527            FND_MESSAGE.SET_TOKEN('CALLING_SEQUENCE', current_calling_sequence);
528            FND_MESSAGE.SET_TOKEN('PARAMETERS', 'Invoice Id = '||X_Invoice_Id);
529            FND_MESSAGE.SET_TOKEN('DEBUG_INFO', debug_info);
530          end if;
531          APP_EXCEPTION.RAISE_EXCEPTION;
532 
533      END Check_Cash_Basis_Paid;
534 
535 
536      -----------------------------------------------------------------------
537 
538 
539 
540      -----------------------------------------------------------------------
541      -- Procedure Adjust_PO is given a po_distribution_id, a line_location_id,
542      -- an amount billed and a quantity_billed it adjusts PO accordingly.
543      --
544 
545      PROCEDURE Adjust_PO(X_PO_Distribution_Id NUMBER,
546                          X_Line_Location_id   NUMBER,
547                          X_Quantity_Billed    NUMBER,
548                          X_Amount_Billed      NUMBER,
549                          X_Match_Basis        VARCHAR2,  /* Amount Based Matching */
550                          X_Matched_Uom        VARCHAR2,  /* Bug 4121303 */
551                          X_Calling_Sequence   VARCHAR2)
552      IS
553        l_po_ap_dist_rec          PO_AP_DIST_REC_TYPE;
554        l_po_ap_line_loc_rec      PO_AP_LINE_LOC_REC_TYPE;
555        l_return_status           VARCHAR2(100);
556        l_msg_data                VARCHAR2(4000);
557        current_calling_sequence  VARCHAR2(2000);
558        l_debug_info              VARCHAR2(100);
559        l_api_name		 VARCHAR2(50);
560 
561 
562     BEGIN
563 
564        l_api_name := 'Adjust_Po';
565        current_calling_sequence := 'AP_INVOICE_DISTRIBUTIONS_PKG.Adjust_PO<-'||X_Calling_Sequence;
566 
567        IF (G_LEVEL_PROCEDURE >= G_CURRENT_RUNTIME_LEVEL) THEN
568           FND_LOG.STRING(G_LEVEL_PROCEDURE,G_MODULE_NAME||l_api_name,'AP_INVOICE_DISTRIBUTIONS_PKG.Adjust_Po(-)');
569        END IF;
570 
571        l_debug_info := 'Create l_po_ap_dist_rec object';
572        IF (G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
573           FND_LOG.STRING(G_LEVEL_STATEMENT,G_MODULE_NAME||l_api_name,l_debug_info);
574        END IF;
575 
576        l_po_ap_dist_rec := PO_AP_DIST_REC_TYPE.create_object();
577 
578        l_po_ap_dist_rec.add_change(
579 				 p_po_distribution_id => x_po_distribution_id,
580                                  p_uom_code            => x_matched_uom,
581                                  p_quantity_billed     => x_quantity_billed,
582                                  p_amount_billed       => x_amount_billed,
583                                  p_quantity_financed   => NULL,
584                                  p_amount_financed     => NULL,
585                                  p_quantity_recouped   => NULL,
586                                  p_amount_recouped     => NULL,
587                                  p_retainage_withheld_amt => NULL,
588                                  p_retainage_released_amt => NULL
589                                 );
590 
591        l_debug_info := 'Create l_po_ap_line_loc_rec object and populate the data';
592        IF (G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
593           FND_LOG.STRING(G_LEVEL_STATEMENT,G_MODULE_NAME||l_api_name,l_debug_info);
594        END IF;
595 
596        l_po_ap_line_loc_rec := PO_AP_LINE_LOC_REC_TYPE.create_object(
597                                  p_po_line_location_id => x_line_location_id,
598                                  p_uom_code            => x_matched_uom,
599                                  p_quantity_billed     => x_quantity_billed,
600                                  p_amount_billed       => x_amount_billed,
601                                  p_quantity_financed   => NULL,
602                                  p_amount_financed     => NULL,
603                                  p_quantity_recouped   => NULL,
604                                  p_amount_recouped     => NULL,
605                                  p_retainage_withheld_amt => NULL,
606                                  p_retainage_released_amt => NULL
607                                 );
608 
609        l_debug_info := 'Call the PO_AP_INVOICE_MATCH_GRP to update the Po Distributions and Po Line Locations';
610        IF (G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
611           FND_LOG.STRING(G_LEVEL_STATEMENT,G_MODULE_NAME||l_api_name,l_debug_info);
612        END IF;
613 
614        PO_AP_INVOICE_MATCH_GRP.Update_Document_Ap_Values(
615                                         P_Api_Version 	       => 1.0,
616                                         P_Line_Loc_Changes_Rec => l_po_ap_line_loc_rec,
617                                         P_Dist_Changes_Rec     => l_po_ap_dist_rec,
618                                         X_Return_Status        => l_return_status,
619                                         X_Msg_Data             => l_msg_data);
620 
621 
622        IF (G_LEVEL_PROCEDURE >= G_CURRENT_RUNTIME_LEVEL) THEN
623           FND_LOG.STRING(G_LEVEL_PROCEDURE,G_MODULE_NAME||l_api_name,'AP_INVOICE_DISTRIBUTIONS_PKG.Adjust_Po(-)');
624        END IF;
625 
626      EXCEPTION
627        WHEN OTHERS THEN
628          if (SQLCODE <> -20001) then
629            FND_MESSAGE.SET_NAME('SQLAP', 'AP_DEBUG');
630            FND_MESSAGE.SET_TOKEN('ERROR', SQLERRM);
631            FND_MESSAGE.SET_TOKEN('CALLING_SEQUENCE', current_calling_sequence);
632            FND_MESSAGE.SET_TOKEN('PARAMETERS','PO Distribution Id = '||
633                         X_PO_Distribution_Id||', Line location Id = '||
634                           X_Line_Location_Id||', Quantity Billed = '||
635                            X_Quantity_Billed||', Amount Billed = '||
636                            X_Amount_Billed);
637            FND_MESSAGE.SET_TOKEN('DEBUG_INFO', l_debug_info);
638          end if;
639          APP_EXCEPTION.RAISE_EXCEPTION;
640 
641      END Adjust_PO;
642 
643 
644   -----------------------------------------------------------------------
645 
646      -----------------------------------------------------------------------
647      -- Function Substrbyte is used in substitution for the PL/SQL SUBSTRB.
648      -- Reason: Currently (as of 7/20/95) SUBSTRB in Forms does not work
649      -- properly.
650      --
651 
652      FUNCTION Substrbyte(X_String           VARCHAR2,
653                          X_Start            NUMBER,
654                          X_End              NUMBER,
655                          X_Calling_Sequence VARCHAR2)
656        RETURN VARCHAR2
657      IS
658        result_str  VARCHAR2(2000) := '';
659        current_calling_sequence   VARCHAR2(2000);
660        debug_info                 VARCHAR2(100);
661      BEGIN
662 
663        -- Update the calling sequence
664        --
665        current_calling_sequence :=
666        'AP_INVOICE_DISTRIBUTION_PKG.Substrbyte<-'||X_Calling_Sequence;
667 
668        debug_info := 'Select from sys.dual';
669 
670        select SUBSTRB(X_String, X_Start, X_End)
671        into   result_str
672        from   sys.dual;
673 
674        return(result_str);
675 
676      EXCEPTION
677        WHEN OTHERS THEN
678          if (SQLCODE <> -20001) then
679            FND_MESSAGE.SET_NAME('SQLAP', 'AP_DEBUG');
680            FND_MESSAGE.SET_TOKEN('ERROR', SQLERRM);
681            FND_MESSAGE.SET_TOKEN('CALLING_SEQUENCE', current_calling_sequence);
682            FND_MESSAGE.SET_TOKEN('PARAMETERS', 'String = '||X_String
683                                          ||', Start = '||X_Start
684                                          ||', End = '||X_End);
685            FND_MESSAGE.SET_TOKEN('DEBUG_INFO', debug_info);
686          END IF;
687          APP_EXCEPTION.RAISE_EXCEPTION;
688 
689      END Substrbyte;
690 
691      -----------------------------------------------------------------------
692      -- FUNCTION insert_from_dist_set inserts records into
693      -- ap_invoice_distributions given a line number, distribution set id and
694      -- table of distribution information.  It returns FALSE if an error
695      -- is encountered.
696      -- Called from ap_invoice_lines_pkg.insert_from_dist_set or from Import
697      -----------------------------------------------------------------------
698      FUNCTION Insert_From_Dist_Set(
699               X_batch_id            IN   NUMBER,
700               X_invoice_id          IN   NUMBER,
701               X_line_number         IN   NUMBER,
702               X_dist_tab            IN   AP_INVOICE_LINES_PKG.dist_tab_type,
703               X_Generate_Permanent  IN   VARCHAR2 DEFAULT 'N',
704               X_Debug_Info          OUT  NOCOPY VARCHAR2,
705               X_Debug_Context       OUT  NOCOPY VARCHAR2,
706               X_Calling_Sequence    IN   VARCHAR2) RETURN BOOLEAN
707      IS
708 
709      l_distribution_class     AP_INVOICE_DISTRIBUTIONS.DISTRIBUTION_CLASS%TYPE;
710      l_created_by             AP_INVOICE_DISTRIBUTIONS.CREATED_BY%TYPE;
711      l_inv_dist_id 	      AP_INVOICE_DISTRIBUTIONS.INVOICE_DISTRIBUTION_ID%TYPE;
712      l_last_update_login
713        AP_INVOICE_DISTRIBUTIONS.LAST_UPDATE_LOGIN%TYPE;
714      l_existing_distributions NUMBER := 0;
715      i                        BINARY_INTEGER := 0;
716      current_calling_sequence VARCHAR2(2000);
717      debug_info               VARCHAR2(100);
718      --Bug 4539462 DBI logging
719      l_dbi_key_value_list          ap_dbi_pkg.r_dbi_key_value_arr;
720      l_calling_module        varchar2(30);   --bug7014798
721 
722      BEGIN
723 
724      --------------------------------------------------------------------------
725      -- Step 1 - Update the calling sequence
726      --------------------------------------------------------------------------
727      current_calling_sequence :=
728             'AP_INVOICE_DISTRIBUTIONS_PKG.insert_from_dist_set<-'||
729             X_calling_sequence;
730 
731      -------------------------------------------------------------------------
732      -- Step 2 - Validate line does not contain other distributions
733      -------------------------------------------------------------------------
734      debug_info := 'Verify line does not contain distributions';
735      BEGIN
736        SELECT count(*)
737          INTO l_existing_distributions
738          FROM ap_invoice_distributions
739         WHERE invoice_id = X_invoice_id
740           AND invoice_line_number = X_line_number;
741 
742        IF (l_existing_distributions <> 0) then
743          X_debug_info := debug_info || ': line already has distributions';
744          X_debug_context := current_calling_sequence;
745          RETURN(FALSE);
746        END IF;
747 
748      EXCEPTION
749        WHEN OTHERS THEN
750        NULL;
751      END;
752 
753 
754      -------------------------------------------------------------------------
755      -- Step 3 - Set distribution class value (Permanent or Candidate)
756      -------------------------------------------------------------------------
757      if (X_Generate_Permanent = 'N') then
758        l_distribution_class := 'CANDIDATE';
759      else
760        l_distribution_class := 'PERMANENT';
761      end if;
762      -------------------------------------------------------------------------
763      -- Step 4 - Generate distributions
764      -------------------------------------------------------------------------
765      FOR i in nvl(X_dist_tab.FIRST, 0) .. nvl(X_dist_tab.LAST, -1) LOOP
766 
767 	SELECT ap_invoice_distributions_s.nextval INTO l_inv_dist_id FROM DUAL;
768 
769         INSERT INTO ap_invoice_distributions (
770                    batch_id,
771                    invoice_id,
772                    invoice_line_number,
773                    invoice_distribution_id,
774                    distribution_line_number,
775                    line_type_lookup_code,
776                    distribution_class,
777                    description,
778                    dist_match_type,
779                    org_id,
780                    dist_code_combination_id,
781                    accounting_date,
782                    period_name,
783  		   accrual_posted_flag,
784                    cash_posted_flag,
785                    amount_to_post,
786                    base_amount_to_post,
787                    posted_amount,
788                    posted_base_amount,
789                    posted_flag,
790                    accounting_event_id,
791                    upgrade_posted_amt,
792                    upgrade_base_posted_amt,
793                    set_of_books_id,
794                    amount,
795                    base_amount,
796                    rounding_amt,
797                    quantity_variance,
798                    base_quantity_variance,
799                    match_status_flag,
800                    encumbered_flag,
801                    packet_id,
802                    reversal_flag,
803                    parent_reversal_id,
804                    cancellation_flag,
805                    income_tax_region,
806                    type_1099,
807                    stat_amount,
808                    charge_applicable_to_dist_id,
809                    prepay_amount_remaining,
810                    prepay_distribution_id,
811                    parent_invoice_id,
812                    corrected_invoice_dist_id,
813                    corrected_quantity,
814                    other_invoice_id,
815                    po_distribution_id,
816                    rcv_transaction_id,
817                    unit_price,
818                    matched_uom_lookup_code,
819                    quantity_invoiced,
820                    final_match_flag,
821                    related_id,
822                    assets_addition_flag,
823                    assets_tracking_flag,
824                    asset_book_type_code,
825                    asset_category_id,
826                    project_id,
827                    task_id,
828                    expenditure_type,
829                    expenditure_item_date,
830                    expenditure_organization_id,
831 		   project_accounting_context,
832                    pa_quantity,
833                    pa_addition_flag,
834                    award_id,
835                    gms_burdenable_raw_cost,
836                    awt_flag,
837                    awt_group_id,
838                    awt_tax_rate_id,
839                    awt_gross_amount,
840                    awt_invoice_id,
841                    awt_origin_group_id,
842                    awt_invoice_payment_id,
843                    awt_withheld_amt,
844                    inventory_transfer_status,
845                    reference_1,
846                    reference_2,
847                    receipt_verified_flag,
848                    receipt_required_flag,
849                    receipt_missing_flag,
850                    justification,
851                    expense_group,
852                    start_expense_date,
853                    end_expense_date,
854                    receipt_currency_code,
855                    receipt_conversion_rate,
856                    receipt_currency_amount,
857                    daily_amount,
858                    web_parameter_id,
859                    adjustment_reason,
860                    merchant_document_number,
861                    merchant_name,
862                    merchant_reference,
863                    merchant_tax_reg_number,
864                    merchant_taxpayer_id,
865                    country_of_supply,
866                    credit_card_trx_id,
867                    company_prepaid_invoice_id,
868                    cc_reversal_flag,
869                    attribute_category,
870                    attribute1,
871                    attribute2,
872                    attribute3,
873                    attribute4,
874                    attribute5,
875                    attribute6,
876                    attribute7,
877                    attribute8,
878                    attribute9,
879                    attribute10,
880                    attribute11,
881                    attribute12,
882                    attribute13,
883                    attribute14,
884                    attribute15,
885                    global_attribute_category,
886                    global_attribute1,
887                    global_attribute2,
888                    global_attribute3,
889                    global_attribute4,
890                    global_attribute5,
891                    global_attribute6,
892                    global_attribute7,
893                    global_attribute8,
894                    global_attribute9,
895                    global_attribute10,
896                    global_attribute11,
897                    global_attribute12,
898                    global_attribute13,
899                    global_attribute14,
900                    global_attribute15,
901                    global_attribute16,
902                    global_attribute17,
903                    global_attribute18,
904                    global_attribute19,
905                    global_attribute20,
906                    created_by,
907                    creation_date,
908                    last_updated_by,
909                    last_update_date,
910                    last_update_login,
911                    program_application_id,
912                    program_id,
913                    program_update_date,
914                    request_id,
915 		   --ETAX: Invwkb
916 		   intended_use,
917 		   --Freight and Special Charges
918 		   rcv_charge_addition_flag,
919 		---added for 7022001
920 		pay_awt_group_id)
921        VALUES (
922                    X_batch_id,                    -- batch_id
923                    X_invoice_id,                  -- invoice_id
924                    X_line_number,                 -- invoice_line_number
925                    l_inv_dist_id,		  -- invoice_distribution_id
926                    X_dist_tab(i).dist_line_num,   -- distribution_line_number
927                    'ITEM',                        -- line_type_lookup_code
928                    l_distribution_class,          -- distribution_class
929                    X_dist_tab(i).description,     -- description
930                    'NOT_MATCHED',                 -- dist_match_type
931                    X_dist_tab(i).org_id,          -- l_org_id
932                    X_dist_tab(i).dist_ccid,       -- dist_code_combination_id
933                    X_dist_tab(i).accounting_date, -- accounting_date
934                    X_dist_tab(i).period_name,     -- period_name
935                    'N',                           -- accrual_posted_flag
936                    'N',                           -- cash_posted_flag
937                    NULL,                          -- amount_to_post
938                    NULL,                          -- base_amount_to_post
939                    NULL,                          -- posted_amount
940                    NULL,                          -- posted_base_amount
941                    'N',                           -- posted_flag
942                    NULL,                          -- accounting_event_id
943                    NULL,                          -- upgrade_posted_amt
944                    NULL,                          -- upgrade_base_posted_amt
945                    X_dist_tab(i).set_of_books_id, -- set_of_books_id
946                    X_dist_tab(i).amount,          -- amount
947                    X_dist_tab(i).base_amount,     -- base_amount
948                    X_dist_tab(i).rounding_amt,    -- rounding_amt
949                    NULL,                          -- quantity_variance
950                    NULL,                          -- base_quantity_variance
951 		   --Invoice Lines: Distributions, changed match_status_flag
952                    --to NULL from 'N'.
953                    NULL,                          -- match_status_flag
954                    'N',                           -- encumbered_flag
955                    NULL,                          -- packet_id
956                    'N',                           -- reversal_flag
957                    NULL,                          -- parent_reversal_id
958                    'N',                           -- cancellation_flag
959                    X_dist_tab(i).income_tax_region,  -- income_tax_region
960                    X_dist_tab(i).type_1099,       -- type_1099
961                    NULL,                          -- stat_amount
962                    NULL,                          -- charge_applicable_to_dist_id
963                    NULL,                          -- prepay_amount_remaining
964                    NULL,                          -- prepay_distribution_id
965                    NULL,                          -- parent_invoice_id
966                    NULL,                          -- corrected_inv_dist_id
967                    NULL,                          -- corrected_quantity
968                    NULL,                          -- other_invoice_id
969                    NULL,                          -- po_distribution_id
970                    NULL,                          -- rcv_transaction_id
971                    NULL,                          -- unit_price
972                    NULL,                          -- matched_uom_lookup_code
973                    NULL,                          -- quantity_invoiced
974                    NULL,                          -- final_match_flag
975                    NULL,                          -- related_id
976                    'U',                           -- assets_addition_flag
977                    X_dist_tab(i).assets_tracking_flag,-- assets_tracking_flag
978                    X_dist_tab(i).asset_book_type_code,-- asset_book_type_code
979                    X_dist_tab(i).asset_category_id,   -- asset_category_id
980                    X_dist_tab(i).project_id,      -- project_id
981                    X_dist_tab(i).task_id,         -- task_id
982                    X_dist_tab(i).expenditure_type,-- expenditure_type
983                    X_dist_tab(i).expenditure_item_date, -- expenditure_item_date
984                    X_dist_tab(i).expenditure_organization_id, -- expenditure_organization_id
985 		   X_dist_tab(i).project_accounting_context, --project_accounting_context
986                    X_dist_tab(i).pa_quantity,     -- pa_quantity
987                    X_dist_tab(i).pa_addition_flag,-- pa_addition_flag
988                    X_dist_tab(i).award_id,        -- award_id
989                    NULL,                          -- gms_burdenable_raw_cost
990                    NULL,                          -- awt_flag
991                    X_dist_tab(i).awt_group_id,    -- awt_group_id
992                    NULL,                          -- awt_tax_rate_id
993                    NULL,                          -- awt_gross_amount
994                    NULL,                          -- awt_invoice_id
995                    NULL,                          -- awt_origin_group_id
996                    NULL,                          -- awt_invoice_payment_id
997                    NULL,                          -- awt_withheld_amt
998                    'N',                           -- inventory_transfer_status
999                    NULL,                          -- reference_1
1000                    NULL,                          -- reference_2
1001                    NULL,                          -- receipt_verified_flag
1002                    NULL,                          -- receipt_required_flag
1003                    NULL,                          -- receipt_missing_flag
1004                    NULL,                          -- justification
1005                    NULL,                          -- expense_group
1006                    NULL,                          -- start_expense_date
1007                    NULL,                          -- end_expense_date
1008                    NULL,                          -- receipt_currency_code
1009                    NULL,                          -- receipt_conversion_rate
1010                    NULL,                          -- receipt_currency_amount
1011                    NULL,                          -- daily_amount
1012                    NULL,                          -- web_parameter_id
1013                    NULL,                          -- adjustment_reason
1014                    NULL,                          -- merchant_document_number
1015                    NULL,                          -- merchant_name
1016                    NULL,                          -- merchant_reference
1017                    NULL,                          -- merchant_tax_reg_number
1018                    NULL,                          -- merchant_taxpayer_id
1019                    NULL,                          -- country_of_supply
1020                    NULL,                          -- credit_card_trx_id
1021                    NULL,                          -- company_prepaid_invoice_id
1022                    NULL,                          -- cc_reversal_flag
1023                    X_dist_tab(i).attribute_category,  -- attribute_category
1024                    X_dist_tab(i).attribute1,      -- attribute1
1025                    X_dist_tab(i).attribute2,      -- attribute2
1026                    X_dist_tab(i).attribute3,      -- attribute3
1027                    X_dist_tab(i).attribute4,      -- attribute4
1028                    X_dist_tab(i).attribute5,      -- attribute5
1029                    X_dist_tab(i).attribute6,      -- attribute6
1030                    X_dist_tab(i).attribute7,      -- attribute7
1031                    X_dist_tab(i).attribute8,      -- attribute8
1032                    X_dist_tab(i).attribute9,      -- attribute9
1033                    X_dist_tab(i).attribute10,     -- attribute10
1034                    X_dist_tab(i).attribute11,     -- attribute11
1035                    X_dist_tab(i).attribute12,     -- attribute12
1036                    X_dist_tab(i).attribute13,     -- attribute13
1037                    X_dist_tab(i).attribute14,     -- attribute14
1038                    X_dist_tab(i).attribute15,     -- attribute15
1039                    NULL,                          -- global_attribute_category
1040                    NULL,                          -- global_attribute1
1041                    NULL,                          -- global_attribute2
1042 		   --bugfix:4674194
1043 		   Decode(AP_EXTENDED_WITHHOLDING_PKG.AP_EXTENDED_WITHHOLDING_OPTION,
1044 		   	  'Y',X_dist_tab(i).global_attribute3,''), --global_attribute3
1045                    NULL,                          -- global_attribute4
1046                    NULL,                          -- global_attribute5
1047                    NULL,                          -- global_attribute6
1048                    NULL,                          -- global_attribute7
1049                    NULL,                          -- global_attribute8
1050                    NULL,                          -- global_attribute9
1051                    NULL,                          -- global_attribute10
1052                    NULL,                          -- global_attribute11
1053                    NULL,                          -- global_attribute12
1054                    NULL,                          -- global_attribute13
1055                    NULL,                          -- global_attribute14
1056                    NULL,                          -- global_attribute15
1057                    NULL,                          -- global_attribute16
1058                    NULL,                          -- global_attribute17
1059                    NULL,                          -- global_attribute18
1060                    NULL,                          -- global_attribute19
1061                    NULL,                          -- global_attribute20
1062                    FND_GLOBAL.user_id,            -- created_by
1063                    SYSDATE,                       -- creation_date
1064                    FND_GLOBAL.user_id,            -- last_updated_by
1065                    SYSDATE,                       -- last_update_date
1066                    FND_GLOBAL.login_id,           -- last_update_login
1067                    NULL,                          -- program_application_id
1068                    NULL,                          -- program_id
1069                    NULL,                          -- program_update_date
1070                    NULL,                          -- request_id
1071 	  X_Dist_Tab(i).intended_use,    -- intended_use
1072 	 'N',				  -- rcv_charge_addition_flag
1073 	 X_dist_tab(i).pay_awt_group_id    -- added for pay_awt_group_id for 7022001
1074                    );
1075 
1076 		   IF x_dist_tab(i).award_id Is Not Null Then
1077 			GMS_AP_API.CREATE_AWARD_DISTRIBUTIONS
1078 				( p_invoice_id		     => x_invoice_id,
1079 				  p_distribution_line_number => x_dist_tab(i).dist_line_num,
1080 				  p_invoice_distribution_id  => l_inv_dist_id,
1081 				  p_award_id                 => x_dist_tab(i).award_id,
1082 				  p_mode		     => 'AP',
1083 				  p_dist_set_id		     => NULL,
1084 				  p_dist_set_line_number     => NULL);
1085 		   END IF ;
1086 
1087 
1088      END LOOP;
1089 
1090      --Bug 4539462 DBI logging
1091      SELECT invoice_distribution_id
1092      BULK COLLECT INTO  l_dbi_key_value_list
1093      FROM ap_invoice_distributions
1094      WHERE invoice_id = X_invoice_id;
1095 
1096      AP_DBI_PKG.Maintain_DBI_Summary
1097               (p_table_name => 'AP_INVOICE_DISTRIBUTIONS',
1098                p_operation => 'I',
1099                p_key_value1 => X_invoice_id,
1100                p_key_value_list => l_dbi_key_value_list,
1101                 p_calling_sequence => current_calling_sequence);
1102 
1103 
1104   ----------------------------------------------------------------------------
1105   -- Step 5 - Update generate distributions flag in invoice line but only if
1106   -- generating distributions in permanent mode.
1107   ----------------------------------------------------------------------------
1108   debug_info := 'Setting generate distributions flag to Done';
1109   if (l_distribution_class = 'PERMANENT') then
1110     BEGIN
1111       UPDATE AP_INVOICE_LINES
1112          SET GENERATE_DISTS = 'D'
1113          WHERE invoice_id = X_invoice_id
1114          AND line_number = X_line_number;
1115     EXCEPTION
1116       WHEN OTHERS THEN
1117         X_debug_info := debug_info || ': Error encountered';
1118         X_debug_context := current_calling_sequence;
1119         return (FALSE);
1120     END;
1121   end if;
1122 
1123   return(TRUE);
1124 
1125   EXCEPTION
1126     WHEN OTHERS THEN
1127       X_debug_info := 'Error encountered';
1128       X_debug_context := current_calling_sequence;
1129       return (FALSE);
1130 
1131   END insert_from_dist_set;
1132 
1133 
1134   -----------------------------------------------------------------------
1135     -- PROCEDURE update_distributions updates columns in
1136     --   AP_INVOICE_DISTRIBUTIONS such as match_status_flag, base_amount,
1137     --   type_1099, income_tax_region.
1138     -- PRECONDITION: Procedure is called during POST-FORMS-COMMIT
1139     -----------------------------------------------------------------------
1140 
1141     PROCEDURE update_distributions (
1142               X_invoice_id                   IN            number,
1143               X_line_number                  IN            number,
1144               X_type_1099                    IN            varchar2,
1145               X_income_tax_region            IN            varchar2,
1146               X_vendor_changed_flag          IN OUT NOCOPY varchar2,
1147               X_update_base                  IN OUT NOCOPY varchar2,
1148               X_reset_match_status           IN OUT NOCOPY varchar2,
1149               X_update_occurred              IN OUT NOCOPY varchar2,
1150               X_calling_sequence             IN            varchar2)
1151     IS
1152       l_purch_encumbrance_flag varchar2(10);
1153       l_multi_currency_flag    varchar2(10);
1154       l_base_dist_total        number;
1155       l_dist_total             number;
1156       l_base_currency_code
1157           ap_system_parameters.base_currency_code%TYPE;
1158       l_exchange_rate
1159           ap_invoices.exchange_rate%TYPE;
1160       l_exchange_rate_type
1161           ap_invoices.exchange_rate_type%TYPE;
1162       l_exchange_date
1163           ap_invoices.exchange_date%TYPE;
1164       l_base_amount
1165           ap_invoices.base_amount%TYPE;
1166       l_invoice_amount
1167           ap_invoices.invoice_amount%TYPE;
1168       l_invoice_currency_code
1169            ap_invoices.invoice_currency_code%TYPE;
1170       l_last_update_login
1171           ap_invoices.last_update_login%TYPE;
1172       l_last_updated_by
1173           ap_invoices.last_updated_by%TYPE;
1174       l_last_update_date
1175           ap_invoices.last_update_date%TYPE;
1176       l_invoice_distribution_id
1177            ap_invoice_distributions.invoice_distribution_id%TYPE;
1178       l_project_id
1179           ap_invoice_distributions.project_id%TYPE;
1180       l_task_id
1181           ap_invoice_distributions.task_id%TYPE;
1182       l_award_id
1183           ap_invoice_distributions.award_id%TYPE;  -- OGM_0.0 changes
1184       l_expenditure_item_date  DATE;
1185       l_expenditure_type
1186           ap_invoice_distributions.expenditure_type%TYPE;
1187       l_employee_id
1188           po_vendors.employee_id%TYPE;
1189       l_pa_quantity
1190           ap_invoice_distributions.pa_quantity%TYPE;
1191       l_dist_amount
1192           ap_invoice_distributions.amount%TYPE;
1193       l_dist_base_amount
1194           ap_invoice_distributions.base_amount%TYPE;
1195       l_expenditure_organization_id
1196           ap_invoice_distributions.expenditure_organization_id%TYPE;
1197 
1198       l_vendor_id              NUMBER;
1199       l_vendor_site_id         NUMBER;
1200       l_invoice_date           DATE;
1201       l_gl_allow_tax_override
1202           GL_TAX_OPTION_ACCOUNTS.ALLOW_TAX_CODE_OVERRIDE_FLAG%TYPE;
1203       l_tax_recoverable_flag
1204           ap_invoice_distributions.tax_recoverable_flag%TYPE;
1205       l_po_distribution_id
1206           ap_invoice_distributions.po_distribution_id%TYPE;
1207       l_line_location_id
1208           po_distributions.line_location_id%TYPE;
1209       l_accrue_on_receipt
1210            po_distributions.accrue_on_receipt_flag%TYPE;
1211       l_dist_count                   NUMBER;
1212       l_user_id                      NUMBER;
1213       l_dist_attribute_category
1214           ap_invoice_distributions.attribute_category%TYPE;
1215       l_dist_attribute1        ap_invoice_distributions.attribute1%TYPE;
1216       l_dist_attribute2        ap_invoice_distributions.attribute1%TYPE;
1217       l_dist_attribute3        ap_invoice_distributions.attribute1%TYPE;
1218       l_dist_attribute4        ap_invoice_distributions.attribute1%TYPE;
1219       l_dist_attribute5        ap_invoice_distributions.attribute1%TYPE;
1220       l_dist_attribute6        ap_invoice_distributions.attribute1%TYPE;
1221       l_dist_attribute7        ap_invoice_distributions.attribute1%TYPE;
1222       l_dist_attribute8        ap_invoice_distributions.attribute1%TYPE;
1223       l_dist_attribute9        ap_invoice_distributions.attribute1%TYPE;
1224       l_dist_attribute10       ap_invoice_distributions.attribute1%TYPE;
1225       l_dist_attribute11       ap_invoice_distributions.attribute1%TYPE;
1226       l_dist_attribute12       ap_invoice_distributions.attribute1%TYPE;
1227       l_dist_attribute13       ap_invoice_distributions.attribute1%TYPE;
1228       l_dist_attribute14       ap_invoice_distributions.attribute1%TYPE;
1229       l_dist_attribute15       ap_invoice_distributions.attribute1%TYPE;
1230       l_dist_posted_flag       ap_invoice_distributions.posted_flag%TYPE;
1231       l_dist_reversal_flag     ap_invoice_distributions.reversal_flag%TYPE;
1232       l_inv_attribute_category ap_invoices.attribute_category%TYPE;
1233       l_inv_attribute1         ap_invoices.attribute1%TYPE;
1234       l_inv_attribute2         ap_invoices.attribute1%TYPE;
1235       l_inv_attribute3         ap_invoices.attribute1%TYPE;
1236       l_inv_attribute4         ap_invoices.attribute1%TYPE;
1237       l_inv_attribute5         ap_invoices.attribute1%TYPE;
1238       l_inv_attribute6         ap_invoices.attribute1%TYPE;
1239       l_inv_attribute7         ap_invoices.attribute1%TYPE;
1240       l_inv_attribute8         ap_invoices.attribute1%TYPE;
1241       l_inv_attribute9         ap_invoices.attribute1%TYPE;
1242       l_inv_attribute10        ap_invoices.attribute1%TYPE;
1243       l_inv_attribute11        ap_invoices.attribute1%TYPE;
1244       l_inv_attribute12        ap_invoices.attribute1%TYPE;
1245       l_inv_attribute13        ap_invoices.attribute1%TYPE;
1246       l_inv_attribute14        ap_invoices.attribute1%TYPE;
1247       l_inv_attribute15        ap_invoices.attribute1%TYPE;
1248       l_msg_application        VARCHAR2(25);
1249       l_msg_type               VARCHAR2(25);
1250       l_msg_token1             VARCHAR2(30);
1251       l_msg_token2             VARCHAR2(30);
1252       l_msg_token3             VARCHAR2(30);
1253       l_msg_count              NUMBER;
1254       l_msg_data               VARCHAR2(30);
1255       l_billable_flag          VARCHAR2(25);
1256       l_invoice_type_lookup_code
1257           ap_invoices.invoice_type_lookup_code%TYPE;
1258       l_chart_of_accounts_id           NUMBER;
1259       l_DIST_CODE_COMBINATION_ID       NUMBER;
1260       l_concat_ids                     Varchar2(2000);
1261       l_concat_segs                    Varchar2(2000);
1262       l_concat_descrs                  Varchar2(300);
1263       l_errmsg                         Varchar2(1300);
1264       current_calling_sequence         VARCHAR2(2000);
1265       debug_info                       VARCHAR2(100);
1266       debug_context                    VARCHAR2(2000);
1267       l_key_value_list                 gl_ca_utility_pkg.r_key_value_arr;
1268       l_line_number
1269           ap_invoice_lines.line_number%TYPE;
1270       l_rounded_dist_id
1271           ap_invoice_distributions.invoice_distribution_id%type;
1272       l_round_amt_exists               BOOLEAN := FALSE;
1273       l_rounded_amt                    NUMBER;
1274        --Bug 4539462 DBI logging
1275        l_dbi_key_value_list        ap_dbi_pkg.r_dbi_key_value_arr;
1276        l_org_id			   ap_invoices_all.org_id%type;
1277 
1278       l_base_amt                   NUMBER; --6892789
1279       l_modified_dist_rounding_amt NUMBER; --6892789
1280       l_round_dist_id_list         AP_INVOICE_LINES_PKG.distribution_id_tab_type; --6892789
1281 
1282       cursor invoice_line_cursor is
1283       SELECT exchange_rate,
1284              exchange_rate_type,
1285              exchange_date,
1286              AI.invoice_currency_code,
1287              invoice_type_lookup_code,
1288              invoice_date,
1289              DECODE(x_line_number, null,
1290                     AI.last_update_login,
1291                     AIL.last_update_login ),
1292              DECODE(x_line_number, null,
1293                     AI.last_updated_by,
1294                     AIL.last_updated_by ),
1295              DECODE(x_line_number, null,
1296                     AI.last_update_date,
1297                     AIL.last_update_date ),
1298              AIL.line_number,
1299 	     AI.org_id
1300       FROM   ap_invoices AI,
1301              ap_invoice_lines AIL
1302       WHERE  AI.invoice_id = X_invoice_id
1303         AND  AIL.invoice_id = AI.invoice_id
1304         AND  AIL.line_number = NVL(X_line_number, AIL.line_number);
1305 
1306       cursor pa_related_dist_cur is
1307       SELECT AID.invoice_distribution_id,
1308              AID.project_id,
1309              AID.task_id,
1310              AID.award_id,  -- OGM_0.0 changes
1311              AID.expenditure_item_date,
1312              AID.expenditure_type,
1313              PV.employee_id,
1314              AID.pa_quantity,
1315              AID.amount,
1316              AID.base_amount,
1317              AID.expenditure_organization_id,
1318              AI.vendor_id,
1319              AI.vendor_site_id,
1320              AID.tax_recoverable_flag,
1321              PD.line_location_id,
1322              PD.accrue_on_receipt_flag,
1323              AID.po_distribution_id,
1324              AID.attribute_category,
1325              AID.attribute1,
1326              AID.attribute2,
1327              AID.attribute3,
1328              AID.attribute4,
1329              AID.attribute5,
1330              AID.attribute6,
1331              AID.attribute7,
1332              AID.attribute8,
1333              AID.attribute9,
1334              AID.attribute10,
1335              AID.attribute11,
1336              AID.attribute12,
1337              AID.attribute13,
1338              AID.attribute14,
1339              AID.attribute15,
1340              NVL(AID.posted_flag,'N'),
1341              NVL(AID.reversal_flag,'N'),
1342              AI.attribute_category,
1343              AI.attribute1,
1344              AI.attribute2,
1345              AI.attribute3,
1346              AI.attribute4,
1347              AI.attribute5,
1348              AI.attribute6,
1349              AI.attribute7,
1350              AI.attribute8,
1351              AI.attribute9,
1352              AI.attribute10,
1353              AI.attribute11,
1354              AI.attribute12,
1355              AI.attribute13,
1356              AI.attribute14,
1357              AI.attribute15,
1358              gsob.chart_of_accounts_id
1359       FROM ap_invoice_distributions AID,
1360            ap_invoices AI,
1361            ap_suppliers PV,
1362            po_distributions PD,
1363            ap_system_parameters ap,
1364            gl_sets_of_books gsob
1365       WHERE  AI.invoice_id = X_invoice_id
1366         AND  AID.invoice_id = AI.invoice_id
1367         AND  AID.invoice_line_number =
1368              NVL(X_line_number, invoice_line_number)
1369         AND  AID.project_id IS NOT NULL
1370         AND  AI.vendor_id = PV.vendor_id
1371         AND  AID.po_distribution_id = PD.po_distribution_id (+)
1372         AND  AID.last_update_login = -3
1373         AND  ap.set_of_books_id = gsob.set_of_books_id
1374         AND  ap.set_of_books_id = AID.set_of_books_id
1375 	AND  ap.org_id = ai.org_id;
1376 
1377         --Bug 1902980 last_update_login is set to -3 if the
1378         --record changes before reaching the PA code.
1379   BEGIN
1380     -- Update the calling sequence
1381     current_calling_sequence :=
1382         'AP_INVOICE_DISTRIBUTIONS_PKG.update_distributions<-'||
1383          X_calling_sequence;
1384 
1385     /*-----------------------------------------------------------------+
1386      |  First, assume that an update to AP_INVOICE_DISTRIBUTIONS       |
1387      |  will not occur.  We will override the this default value       |
1388      |  if an update does occur.                                       |
1389      +-----------------------------------------------------------------*/
1390 
1391     X_update_occurred := 'N';
1392 
1393 
1394     -- Bug 5052593 -- removed redundant code
1395     ----------------------------------------------------------
1396     --debug_info := 'Select from ap_system_parameters and
1397     --		   financials_system_parameters';
1398     ----------------------------------------------------------
1399      --SELECT FSP.purch_encumbrance_flag,
1400      --       SP.multi_currency_flag,
1401      --	    SP.base_currency_code
1402      --INTO l_purch_encumbrance_flag,
1403      --     l_multi_currency_flag,
1404      --	  l_base_currency_code
1405      --FROM financials_system_parameters FSP,
1406      --     ap_system_parameters SP;
1407 
1408     debug_info := 'select AP_INVOICES info';
1409 
1410     /*-----------------------------------------------------------------+
1411      |  Fetch the invoice information that we need in order to update  |
1412      |  the distribution base amounts                                  |
1413      +-----------------------------------------------------------------*/
1414 
1415     OPEN invoice_line_cursor;
1416     debug_info := 'Fetch cursor invoice_cursor';
1417     LOOP
1418     FETCH invoice_line_cursor
1419      INTO l_exchange_rate,
1420           l_exchange_rate_type,
1421           l_exchange_date,
1422           l_invoice_currency_code,
1423           l_invoice_type_lookup_code,
1424           l_invoice_date,
1425           l_last_update_login,
1426           l_last_updated_by,
1427           l_last_update_date,
1428           l_line_number,
1429 	  l_org_id;
1430     EXIT WHEN invoice_line_cursor%NOTFOUND;
1431 
1432     ----------------------------------------------------------
1433     debug_info := 'Select from ap_system_parameters and
1434                   financials_system_parameters';
1435     ----------------------------------------------------------
1436        SELECT FSP.purch_encumbrance_flag,
1437               SP.multi_currency_flag,
1438               SP.base_currency_code
1439          INTO l_purch_encumbrance_flag,
1440               l_multi_currency_flag,
1441               l_base_currency_code
1442          FROM financials_system_parameters FSP,
1443               ap_system_parameters SP
1444 	 WHERE sp.org_id = l_org_id
1445 	  AND  sp.org_id = fsp.org_id;
1446 
1447       ---------------------------------------------------------
1448       debug_info := 'Update AP_INVOICE_DISTRIBUTIONS tax info';
1449       ---------------------------------------------------------
1450 
1451     /*-----------------------------------------------------------------+
1452      |  Update 1099 type and income tax region for each distribution   |
1453      |  line if the vendor changed (test performed in PRE-UPDATE)      |
1454      +-----------------------------------------------------------------*/
1455 
1456       IF (nvl(X_vendor_changed_flag,'N') = 'Y') THEN
1457         UPDATE ap_invoice_distributions
1458            SET type_1099 = X_type_1099,
1459                income_tax_region = X_income_tax_region
1460          WHERE invoice_id = X_invoice_id
1461            AND invoice_line_number = NVL(X_line_number, invoice_line_number);
1462 
1463         IF (SQL%ROWCOUNT > 0) THEN
1464           X_update_occurred := 'Y';
1465         END IF;
1466 
1467         -- Reset the vendor changed flag
1468         X_vendor_changed_flag := 'N';
1469 
1470       END IF; -- end of x_vendor_changed_flag
1471 
1472       --------------------------------------------------------------
1473       debug_info := 'Update AP_INVOICE_DISTRIBUTIONS match status';
1474       --------------------------------------------------------------
1475 
1476        -- Reset the match status flags if X_reset_match_status
1477        -- is Y and encumbrance is not on.
1478        -- Don't change NULLS to N as these have never been through
1479        -- AutoApproval
1480        --
1481       UPDATE ap_invoice_distributions
1482          SET match_status_flag = 'N'
1483        WHERE invoice_id = X_invoice_id
1484          AND invoice_line_number = NVL( x_line_number, invoice_line_number)
1485          --Bug 5003892  AND l_purch_encumbrance_flag <> 'Y'
1486          AND nvl(X_reset_match_status,'N') = 'Y'
1487          AND NVL(match_status_flag,'N') <> 'N'
1488 	RETURNING invoice_distribution_id
1489         BULK COLLECT INTO l_dbi_key_value_list;
1490 
1491 	--Bug 4539462 DBI logging
1492         AP_DBI_PKG.Maintain_DBI_Summary
1493               (p_table_name => 'AP_INVOICE_DISTRIBUTIONS',
1494                p_operation => 'U',
1495                p_key_value1 => X_invoice_id,
1496                p_key_value_list => l_dbi_key_value_list,
1497                 p_calling_sequence => current_calling_sequence);
1498 
1499       if (SQL%ROWCOUNT > 0) then
1500         X_update_occurred := 'Y';
1501       end if;
1502 
1503       -- Reset the reset match status flag
1504       X_reset_match_status := 'N';
1505 
1506       IF (nvl(l_multi_currency_flag,'N') = 'Y' AND
1507           nvl(X_update_base,'N') = 'Y') THEN
1508 
1509         -- Update the distributions if this is a foreign currency invoice
1510         -- and there is an invoice exchange rate as something has been changed
1511         -- Check that the base amounts sum to the invoice base amount
1512         -- Fire for functional currency invoices if multi-curr is enabled
1513         -- as it may have just been changed to functional so we want to clear
1514         -- all the base columns
1515         -- Set the exchange rate info, base amount and WHO columns
1516         -- for the distributions
1517 
1518   	   --Bugfix:4644053 changed ap_invoice_distributions
1519 	   --to ap_invoice_distributions_all
1520            debug_info := 'Update AP_INVOICE_DISTRIBUTIONS base amounts';
1521 
1522            UPDATE AP_INVOICE_DISTRIBUTIONS_ALL
1523            SET base_amount        =
1524                    DECODE(l_base_currency_code,
1525                          l_invoice_currency_code, NULL,
1526                          ap_utilities_pkg.ap_round_currency(
1527                          amount * l_exchange_rate,
1528                                   l_base_currency_code)),
1529                last_update_login  =  l_last_update_login,
1530                last_updated_by    = l_last_updated_by,
1531                last_update_date   = SYSDATE
1532            WHERE invoice_id = X_invoice_id
1533            AND invoice_line_number = nvl( x_line_number, invoice_line_number)
1534            AND NVL(posted_flag,'N') = 'N'
1535            AND ( ( base_amount is null AND
1536                        DECODE(l_base_currency_code,
1537                               l_invoice_currency_code, NULL,
1538                               ap_utilities_pkg.ap_round_currency(
1539                                    amount * l_exchange_rate,
1540                                    l_base_currency_code)) is not null)
1541                  OR
1542                  (NVL(base_amount,0) <>
1543                        DECODE(l_base_currency_code,
1544                               l_invoice_currency_code, NULL,
1545                               ap_utilities_pkg.ap_round_currency(
1546                                   amount * l_exchange_rate,
1547                                   l_base_currency_code))))
1548                RETURNING invoice_distribution_id
1549                BULK COLLECT INTO l_key_value_list;
1550 
1551            if (SQL%ROWCOUNT > 0) then
1552               X_update_occurred := 'Y';
1553            end if;
1554 
1555            -- Reset the update base flag
1556            X_update_base := 'N';
1557 
1558         --END IF;
1559 
1560 	-- Check to see if the base amounts add up to the invoice base amount
1561 	-- If not update the biggest distribution
1562 	-- Only do this if the distributions add up in the entered currency
1563 
1564         -----------------------------------------------------------------
1565         debug_info := 'Call API to check if rounding amount is existing';
1566         -----------------------------------------------------------------
1567 
1568 
1569  /* modifying following code as per the bug 6892789 as there is a chance that
1570      distribution base amt goes to -ve value (amount being +ve) so in such case,
1571      adjust dist base amount upto zero and adjust the remaing amount in another
1572      distribution having next max amount */
1573     -- get the distributions which can be adjusted
1574     l_round_amt_exists := AP_INVOICE_LINES_PKG.round_base_amts(
1575                               x_invoice_id          => X_invoice_id,
1576                               x_line_number         => l_line_number,
1577                               x_reporting_ledger_id => NULL,
1578                               x_round_dist_id_list  => l_round_dist_id_list,
1579                               x_rounded_amt         => l_rounded_amt,
1580                               x_debug_info          => debug_info,
1581                               x_debug_context       => debug_context,
1582                               x_calling_sequence    => current_calling_sequence);
1583 
1584     -- adjustment required and there are existing distributions that can be adjusted
1585     IF ( l_round_amt_exists  AND l_round_dist_id_list.count > 0 ) THEN
1586       for i in 1 .. l_round_dist_id_list.count -- iterate through dists till there is no need to adjust
1587       loop
1588           IF l_rounded_amt <> 0 THEN
1589 
1590             -- get the existing base amount for the selected distribution
1591             select base_amount
1592             INTO   l_base_amt
1593             FROM   AP_INVOICE_DISTRIBUTIONS
1594             WHERE  invoice_id = X_invoice_id
1595             AND    invoice_line_number = l_line_number
1596             AND    invoice_distribution_id = l_round_dist_id_list(i);
1597 
1598             -- get the calculated adjusted base amount and rounding amount
1599             -- get rounding amount for the next dist, if required
1600             l_base_amt := AP_APPROVAL_PKG.get_adjusted_base_amount(p_base_amount => l_base_amt,
1601                                                                    p_rounding_amt => l_modified_dist_rounding_amt,
1602                                                                    p_next_line_rounding_amt => l_rounded_amt);
1603 
1604             -- update the calculatd base amount, rounding amount
1605             UPDATE AP_INVOICE_DISTRIBUTIONS
1606             SET    base_amount = l_base_amt,
1607             rounding_amt = ABS( l_modified_dist_rounding_amt ),
1608             last_update_date = SYSDATE,
1609             last_updated_by = FND_GLOBAL.user_id,
1610             last_update_login = FND_GLOBAL.login_id
1611             WHERE  invoice_distribution_id = l_round_dist_id_list(i);
1612 
1613             if (SQL%ROWCOUNT > 0) then
1614               X_update_occurred := 'Y';
1615             end if;
1616           ELSE -- adjustment not required or there are no dists that can be adjusted
1617               EXIT;
1618           END IF;
1619      end loop;
1620     END IF;
1621 
1622 /* CHANGES FOR BUG - 3025688 ** STARTS **
1623       /*  Commenting out PA calls as this is no more needed.
1624           If we are doing matching, we expect the details provided in PO
1625           are already validated and no more validation of PA should happen
1626           again. After matching if there is any change in the information
1627           provided in the distribution will be handled in Form validation. */
1628      /*-----------------------------------------------------------------+
1629      | For Projects, the call to flex build the account has changed,   |
1630      | The new design calls for calling the PA routine if the exchange |
1631      | rate information has changed. The exchange rate information     |
1632      | change in the invoice workbench leads to the variable           |
1633      | X_update_base being set to 'Y' so we use this same variable to  |
1634      | determine whether to call the PA flexbuilder routine again or   |
1635      | not                                                             |
1636      +-----------------------------------------------------------------*/
1637 
1638 /*        ------------------------------------------------
1639         debug_info := 'Call PA flex builder procedures';
1640         ------------------------------------------------
1641 
1642         OPEN pa_related_dist_cur;
1643         l_dist_count := 0;
1644 
1645         LOOP
1646           FETCH pa_related_dist_cur INTO
1647                         l_invoice_distribution_id,
1648                         l_project_id,
1649                         l_task_id,
1650                         l_award_id,   -- OGM_0.0 changes...
1651                         l_expenditure_item_date,
1652                         l_expenditure_type,
1653                         l_employee_id,
1654                         l_pa_quantity,
1655                         l_dist_amount,
1656                         l_dist_base_amount,
1657                         l_expenditure_organization_id,
1658                         l_vendor_id,
1659                         l_vendor_site_id,
1660                         l_tax_recoverable_flag,
1661                         l_line_location_id,
1662                         l_accrue_on_receipt,   -- Bug:1609628
1663                         l_po_distribution_id,
1664                         l_dist_attribute_category,
1665                         l_dist_attribute1,
1666                         l_dist_attribute2,
1667                         l_dist_attribute3,
1668                         l_dist_attribute4,
1669                         l_dist_attribute5,
1670                         l_dist_attribute6,
1671                         l_dist_attribute7,
1672                         l_dist_attribute8,
1673                         l_dist_attribute9,
1674                         l_dist_attribute10,
1675                         l_dist_attribute11,
1676                         l_dist_attribute12,
1677                         l_dist_attribute13,
1678                         l_dist_attribute14,
1679                         l_dist_attribute15,
1680                         l_dist_posted_flag, --Bug:1754223
1681                         l_dist_reversal_flag, --Bug:1754223
1682                         l_inv_attribute_category,
1683                         l_inv_attribute1,
1684                         l_inv_attribute2,
1685                         l_inv_attribute3,
1686                         l_inv_attribute4,
1687                         l_inv_attribute5,
1688                         l_inv_attribute6,
1689                         l_inv_attribute7,
1690                         l_inv_attribute8,
1691                         l_inv_attribute9,
1692                         l_inv_attribute10,
1693                         l_inv_attribute11,
1694                         l_inv_attribute12,
1695                         l_inv_attribute13,
1696                         l_inv_attribute14,
1697                         l_inv_attribute15,
1698                         l_chart_of_accounts_id;
1699 
1700           EXIT WHEN pa_related_dist_cur%NOTFOUND;
1701 
1702           -- get the user id
1703           FND_PROFILE.GET('USER_ID',l_user_id);
1704 
1705 	  --Added the below if for bug7014798
1706 
1707           if instr(current_calling_sequence, 'RECURR') <> 0 then
1708              l_calling_module := 'APXRICAD';
1709           else
1710              l_calling_module := 'apiindib.pls';
1711           end if;
1712 
1713 
1714           -- call the new function (replacment of patc.get_status)
1715 
1716           PA_TRANSACTIONS_PUB.VALIDATE_TRANSACTION(
1717                X_PROJECT_ID          => l_project_id,
1718                X_TASK_ID             => l_task_id,
1719                X_EI_DATE             => l_expenditure_item_date,
1720                X_EXPENDITURE_TYPE    => l_expenditure_type,
1721                X_NON_LABOR_RESOURCE  => null,
1722                X_PERSON_ID           => l_employee_id,
1723                X_QUANTITY            => l_pa_quantity,
1724                X_denom_currency_code => l_invoice_currency_code,
1725                X_acct_currency_code  => l_base_currency_code,
1726                X_denom_raw_cost      => l_dist_amount,
1727                X_acct_raw_cost       => l_dist_base_amount,
1728                X_acct_rate_type      => l_exchange_rate_type,
1729                X_acct_rate_date      => l_exchange_date,
1730                X_acct_exchange_rate  => l_exchange_rate,
1731                X_TRANSFER_EI         => null,
1732                X_INCURRED_BY_ORG_ID  => l_expenditure_organization_id,
1733                X_NL_RESOURCE_ORG_ID  => null,
1734                X_TRANSACTION_SOURCE  => null,
1735                X_CALLING_MODULE      => l_calling_module,  --bug7014798
1736                X_VENDOR_ID           => l_vendor_id,
1737                X_ENTERED_BY_USER_ID  => l_user_id,
1738                X_ATTRIBUTE_CATEGORY  => l_dist_attribute_category,
1739                X_ATTRIBUTE1          => l_dist_attribute1,
1740                X_ATTRIBUTE2          => l_dist_attribute2,
1741                X_ATTRIBUTE3          => l_dist_attribute3,
1742                X_ATTRIBUTE4          => l_dist_attribute4,
1743                X_ATTRIBUTE5          => l_dist_attribute5,
1744                X_ATTRIBUTE6          => l_dist_attribute6,
1745                X_ATTRIBUTE7          => l_dist_attribute7,
1746                X_ATTRIBUTE8          => l_dist_attribute8,
1747                X_ATTRIBUTE9          => l_dist_attribute9,
1748                X_ATTRIBUTE10         => l_dist_attribute10,
1749                X_ATTRIBUTE11         => l_dist_attribute11,
1750                X_ATTRIBUTE12         => l_dist_attribute12,
1751                X_ATTRIBUTE13         => l_dist_attribute13,
1752                X_ATTRIBUTE14         => l_dist_attribute14,
1753                X_ATTRIBUTE15         => l_dist_attribute15,
1754                X_msg_application     => l_msg_application,
1755                X_msg_type            => l_msg_type,
1756                X_msg_token1          => l_msg_token1,
1757                X_msg_token2          => l_msg_token2,
1758                X_msg_token3          => l_msg_token3,
1759                X_msg_count           => l_msg_count,
1760                X_msg_data            => l_msg_data,
1761                X_BILLABLE_FLAG       => l_billable_flag);
1762 
1763           IF (l_msg_data is not null) THEN
1764             FND_MESSAGE.SET_NAME(l_msg_application, l_msg_data);
1765             -- For bug3469917. Need to add token values for non-PA applications.
1766 
1767               if (l_msg_application <> 'PA') Then
1768 
1769 
1770                 IF (l_msg_token1 IS NOT NULL) THEN
1771                     fnd_message.set_token('PATC_MSG_TOKEN1',l_msg_token1);
1772                 ELSE
1773                     fnd_message.set_token('PATC_MSG_TOKEN1',app_api.G_NULL_CHAR);
1774                 END IF;
1775                 IF (l_msg_token2 IS NOT NULL) THEN
1776                     fnd_message.set_token('PATC_MSG_TOKEN2',l_msg_token2);
1777                 ELSE
1778                     fnd_message.set_token('PATC_MSG_TOKEN2',app_api.G_NULL_CHAR);
1779                 END IF;
1780                 IF (l_msg_token3 IS NOT NULL) THEN
1781                     fnd_message.set_token('PATC_MSG_TOKEN3',l_msg_token3);
1782                 ELSE
1783                     fnd_message.set_token('PATC_MSG_TOKEN3',app_api.G_NULL_CHAR);
1784                 END IF;
1785 
1786               end if;
1787 
1788              -- End for bug3469917
1789             app_exception.raise_exception;
1790           END IF;
1791 
1792           IF ( ( (l_po_distribution_id is NOT NULL) AND
1793                  (nvl(l_accrue_on_receipt,'N') <> 'Y') )
1794                OR
1795                  (l_po_distribution_id is NULL) ) THEN
1796 
1797             IF (l_invoice_type_lookup_code = 'EXPENSE REPORT') THEN
1798 
1799 	      /*
1800               IF ( NOT pa_acc_gen_wf_pkg.ap_er_generate_account (
1801                            p_project_id        =>l_project_id,
1802                            p_task_id           => l_task_id,
1803                            p_expenditure_type  => l_expenditure_type,
1804                            p_vendor_id         => l_VENDOR_ID,
1805                            p_expenditure_organization_id =>l_EXPENDITURE_ORGANIZATION_ID,
1806                            p_expenditure_item_date =>l_EXPENDITURE_ITEM_DATE,
1807                            p_billable_flag         =>l_billable_flag,
1808                            p_chart_of_accounts_id =>l_CHART_OF_ACCOUNTS_ID,
1809                            p_calling_module       => 'apiindib.pls',
1810                            p_employee_id          => l_employee_id,
1811                            p_employee_ccid        => null,
1812                            p_expense_type         => null,
1813                            p_expense_cc           => null,
1814                            P_ATTRIBUTE_CATEGORY => l_inv_ATTRIBUTE_CATEGORY,
1815                            P_ATTRIBUTE1  => l_inv_ATTRIBUTE1,
1816                            P_ATTRIBUTE2  => l_inv_ATTRIBUTE2,
1817                            P_ATTRIBUTE3  => l_inv_ATTRIBUTE3,
1818                            P_ATTRIBUTE4  => l_inv_ATTRIBUTE4,
1819                            P_ATTRIBUTE5  => l_inv_ATTRIBUTE5,
1820                            P_ATTRIBUTE6  => l_inv_ATTRIBUTE6,
1821                            P_ATTRIBUTE7  => l_inv_ATTRIBUTE7,
1822                            P_ATTRIBUTE8  => l_inv_ATTRIBUTE8,
1823                            P_ATTRIBUTE9  => l_inv_ATTRIBUTE9,
1824                            P_ATTRIBUTE10 => l_inv_ATTRIBUTE10,
1825                            P_ATTRIBUTE11 => l_inv_ATTRIBUTE11,
1826                            P_ATTRIBUTE12 => l_inv_ATTRIBUTE12,
1827                            P_ATTRIBUTE13 => l_inv_ATTRIBUTE13,
1828                            P_ATTRIBUTE14 => l_inv_ATTRIBUTE14,
1829                            P_ATTRIBUTE15 => l_inv_ATTRIBUTE15,
1830                            P_LINE_ATTRIBUTE_CATEGORY => l_dist_ATTRIBUTE_CATEGORY,
1831                            P_LINE_ATTRIBUTE1  => l_dist_ATTRIBUTE1,
1832                            P_LINE_ATTRIBUTE2  => l_dist_ATTRIBUTE2,
1833                            P_LINE_ATTRIBUTE3  => l_dist_ATTRIBUTE3,
1834                            P_LINE_ATTRIBUTE4  => l_dist_ATTRIBUTE4,
1835                            P_LINE_ATTRIBUTE5  => l_dist_ATTRIBUTE5,
1836                            P_LINE_ATTRIBUTE6  => l_dist_ATTRIBUTE6,
1837                            P_LINE_ATTRIBUTE7  => l_dist_ATTRIBUTE7,
1838                            P_LINE_ATTRIBUTE8  => l_dist_ATTRIBUTE8,
1839                            P_LINE_ATTRIBUTE9  => l_dist_ATTRIBUTE9,
1840                            P_LINE_ATTRIBUTE10 => l_dist_ATTRIBUTE10,
1841                            P_LINE_ATTRIBUTE11 => l_dist_ATTRIBUTE11,
1842                            P_LINE_ATTRIBUTE12 => l_dist_ATTRIBUTE12,
1843                            P_LINE_ATTRIBUTE13 => l_dist_ATTRIBUTE13,
1844                            P_LINE_ATTRIBUTE14 => l_dist_ATTRIBUTE14,
1845                            P_LINE_ATTRIBUTE15 => l_dist_ATTRIBUTE15,
1846                            x_return_ccid      => l_DIST_CODE_COMBINATION_ID,
1847                            x_concat_segs      => l_concat_segs,
1848                            x_concat_ids       => l_concat_ids,
1849                            x_concat_descrs    => l_concat_descrs,
1850                            x_error_message    => l_errmsg,
1851                            x_award_set_id     => l_award_id )) THEN
1852 
1853                 fnd_message.set_encoded(l_errmsg);
1854                 app_exception.raise_exception;
1855               END IF;
1856 	      */
1857 /*	      null;
1858             ELSE  -- non expense report
1859 
1860 	      /*
1861               IF ( NOT pa_acc_gen_wf_pkg.ap_inv_generate_account (
1862                            p_project_id  => l_project_id,
1863                            p_task_id     => l_task_id,
1864                            p_expenditure_type  => l_expenditure_type,
1865                            p_vendor_id         => l_VENDOR_ID,
1866                            p_expenditure_organization_id  => l_EXPENDITURE_ORGANIZATION_ID,
1867                            p_expenditure_item_date  => l_EXPENDITURE_ITEM_DATE,
1868                            p_billable_flag        => l_billable_flag,
1869                            p_chart_of_accounts_id =>l_CHART_OF_ACCOUNTS_ID,
1870                            P_ATTRIBUTE_CATEGORY => l_inv_ATTRIBUTE_CATEGORY,
1871                            P_ATTRIBUTE1  => l_inv_ATTRIBUTE1,
1872                            P_ATTRIBUTE2  => l_inv_ATTRIBUTE2,
1873                            P_ATTRIBUTE3  => l_inv_ATTRIBUTE3,
1874                            P_ATTRIBUTE4  => l_inv_ATTRIBUTE4,
1875                            P_ATTRIBUTE5  => l_inv_ATTRIBUTE5,
1876                            P_ATTRIBUTE6  => l_inv_ATTRIBUTE6,
1877                            P_ATTRIBUTE7  => l_inv_ATTRIBUTE7,
1878                            P_ATTRIBUTE8  => l_inv_ATTRIBUTE8,
1879                            P_ATTRIBUTE9  => l_inv_ATTRIBUTE9,
1880                            P_ATTRIBUTE10 => l_inv_ATTRIBUTE10,
1881                            P_ATTRIBUTE11 => l_inv_ATTRIBUTE11,
1882                            P_ATTRIBUTE12 => l_inv_ATTRIBUTE12,
1883                            P_ATTRIBUTE13 => l_inv_ATTRIBUTE13,
1884                            P_ATTRIBUTE14 => l_inv_ATTRIBUTE14,
1885                            P_ATTRIBUTE15 => l_inv_ATTRIBUTE15,
1886                            P_DIST_ATTRIBUTE_CATEGORY => l_dist_ATTRIBUTE_CATEGORY,
1887                            P_DIST_ATTRIBUTE1 => l_dist_ATTRIBUTE1,
1888                            P_DIST_ATTRIBUTE2 => l_dist_ATTRIBUTE2,
1889                            P_DIST_ATTRIBUTE3 => l_dist_ATTRIBUTE3,
1890                            P_DIST_ATTRIBUTE4 => l_dist_ATTRIBUTE4,
1891                            P_DIST_ATTRIBUTE5 => l_dist_ATTRIBUTE5,
1892                            P_DIST_ATTRIBUTE6 => l_dist_ATTRIBUTE6,
1893                            P_DIST_ATTRIBUTE7 => l_dist_ATTRIBUTE7,
1894                            P_DIST_ATTRIBUTE8 => l_dist_ATTRIBUTE8,
1895                            P_DIST_ATTRIBUTE9 => l_dist_ATTRIBUTE9,
1896                            P_DIST_ATTRIBUTE10 => l_dist_ATTRIBUTE10,
1897                            P_DIST_ATTRIBUTE11 => l_dist_ATTRIBUTE11,
1898                            P_DIST_ATTRIBUTE12 => l_dist_ATTRIBUTE12,
1899                            P_DIST_ATTRIBUTE13 => l_dist_ATTRIBUTE13,
1900                            P_DIST_ATTRIBUTE14 => l_dist_ATTRIBUTE14,
1901                            P_DIST_ATTRIBUTE15 => l_dist_ATTRIBUTE15,
1902                            x_return_ccid => l_DIST_CODE_COMBINATION_ID,
1903                            x_concat_segs => l_concat_segs,
1904                            x_concat_ids  => l_concat_ids,
1905                            x_concat_descrs => l_concat_descrs,
1906                            x_error_message    => l_errmsg,
1907                            x_award_set_id  => l_award_id )) THEN
1908 
1909                 FND_MESSAGE.SET_ENCODED(l_errmsg);
1910                 app_exception.raise_exception;
1911 
1912               END IF;
1913 	      */
1914 /*	      null;
1915             END IF; -- end of check l_invoice_type_lookup_code
1916 
1917 
1918 /*-----------------------------------------------------------------+
1919      | update invoice_distributions with l_dist_code_combination_id    |
1920      +-----------------------------------------------------------------*/
1921 
1922  /*           IF (l_dist_posted_flag = 'N') THEN
1923               IF (l_dist_reversal_flag <> 'Y') THEN
1924 
1925                 UPDATE ap_invoice_distributions
1926                     SET dist_code_combination_id   = l_dist_code_combination_id
1927                   WHERE invoice_distribution_id    = l_invoice_distribution_id;
1928 
1929                END IF; -- end of l_dist_reversal_flag
1930              END IF; -- end of l_dist_posted_flag
1931 
1932              l_dist_count := l_dist_count +1;
1933 
1934           END IF; -- end of check l_po_distribution_id/l_accrue_on_receipt_flag
1935         END LOOP; -- end loop of pa_related_dist_cursor
1936         CLOSE pa_related_dist_cur;
1937 
1938         IF (l_dist_count >0) THEN
1939           X_update_occurred := 'Y';
1940         END IF;
1941 
1942         UPDATE AP_INVOICE_DISTRIBUTIONS
1943            SET last_update_login = l_last_update_login
1944          WHERE invoice_id = X_invoice_id
1945            AND last_update_login = -3;
1946 -- CHANGES FOR BUG - 3025688 ** ENDS   **
1947 */
1948       END IF;  -- check l_multi_currency_flag = y and x_update_base=y
1949     END LOOP; -- end of invoice_line_cursor
1950 
1951     debug_info := 'Close cursor invoice_line_cursor';
1952     CLOSE invoice_line_cursor;
1953 
1954     EXCEPTION
1955     WHEN OTHERS THEN
1956       IF (SQLCODE <> -20001) THEN
1957         FND_MESSAGE.SET_NAME('SQLAP','AP_DEBUG');
1958         FND_MESSAGE.SET_TOKEN('ERROR',SQLERRM);
1959         FND_MESSAGE.SET_TOKEN('CALLING_SEQUENCE', current_calling_sequence);
1960         FND_MESSAGE.SET_TOKEN('PARAMETERS',
1961            'X_invoice_id = '             ||X_invoice_id
1962            ||', X_line_number = '        ||X_line_number
1963            ||', X_type_1099 = '          ||X_type_1099
1964            ||', X_income_tax_region = '  ||X_income_tax_region
1965            ||', X_vendor_changed_flag = '||X_vendor_changed_flag
1966            ||', X_update_base = '        ||X_update_base
1967            ||', X_reset_match_status = ' ||X_reset_match_status
1968            ||', X_update_occurred = '    ||X_update_occurred
1969                                        );
1970         FND_MESSAGE.SET_TOKEN('DEBUG_INFO',debug_info);
1971       END IF;
1972       APP_EXCEPTION.RAISE_EXCEPTION;
1973     END Update_Distributions;
1974 
1975 
1976    PROCEDURE Insert_Row(X_Rowid                   IN OUT NOCOPY VARCHAR2,
1977                        X_Invoice_Id                     NUMBER,
1978                        -- Invoice Lines Project Stage 1
1979                        X_Invoice_Line_Number            NUMBER,
1980                        X_Distribution_Class             VARCHAR2,
1981                        X_Invoice_Distribution_Id IN OUT NOCOPY NUMBER,
1982                        X_Dist_Code_Combination_Id       NUMBER,
1983                        X_Last_Update_Date               DATE,
1984                        X_Last_Updated_By                NUMBER,
1985                        X_Accounting_Date                DATE,
1986                        X_Period_Name                    VARCHAR2,
1987                        X_Set_Of_Books_Id                NUMBER,
1988                        X_Amount                         NUMBER,
1989                        X_Description                    VARCHAR2,
1990                        X_Type_1099                      VARCHAR2,
1991                        X_Posted_Flag                    VARCHAR2,
1992                        X_Batch_Id                       NUMBER,
1993                        X_Quantity_Invoiced              NUMBER,
1994                        X_Unit_Price                     NUMBER,
1995                        X_Match_Status_Flag              VARCHAR2,
1996                        X_Attribute_Category             VARCHAR2,
1997                        X_Attribute1                     VARCHAR2,
1998                        X_Attribute2                     VARCHAR2,
1999                        X_Attribute3                     VARCHAR2,
2000                        X_Attribute4                     VARCHAR2,
2001                        X_Attribute5                     VARCHAR2,
2002                        X_Prepay_Amount_Remaining        NUMBER,
2003                        X_Assets_Addition_Flag           VARCHAR2,
2004                        X_Assets_Tracking_Flag           VARCHAR2,
2005                        X_Distribution_Line_Number       NUMBER,
2006                        X_Line_Type_Lookup_Code          VARCHAR2,
2007                        X_Po_Distribution_Id             NUMBER,
2008                        X_Base_Amount                    NUMBER,
2009                        X_Pa_Addition_Flag               VARCHAR2,
2010                        X_Posted_Amount                  NUMBER,
2011                        X_Posted_Base_Amount             NUMBER,
2012                        X_Encumbered_Flag                VARCHAR2,
2013                        X_Accrual_Posted_Flag            VARCHAR2,
2014                        X_Cash_Posted_Flag               VARCHAR2,
2015                        X_Last_Update_Login              NUMBER,
2016                        X_Creation_Date                  DATE,
2017                        X_Created_By                     NUMBER,
2018                        X_Stat_Amount                    NUMBER,
2019                        X_Attribute11                    VARCHAR2,
2020                        X_Attribute12                    VARCHAR2,
2021                        X_Attribute13                    VARCHAR2,
2022                        X_Attribute14                    VARCHAR2,
2023                        X_Attribute6                     VARCHAR2,
2024                        X_Attribute7                     VARCHAR2,
2025                        X_Attribute8                     VARCHAR2,
2026                        X_Attribute9                     VARCHAR2,
2027                        X_Attribute10                    VARCHAR2,
2028                        X_Attribute15                    VARCHAR2,
2029                        X_Accts_Pay_Code_Comb_Id         NUMBER,
2030                        X_Reversal_Flag                  VARCHAR2,
2031                        X_Parent_Invoice_Id              NUMBER,
2032                        X_Income_Tax_Region              VARCHAR2,
2033                        X_Final_Match_Flag               VARCHAR2,
2034                        X_Expenditure_Item_Date          DATE,
2035                        X_Expenditure_Organization_Id    NUMBER,
2036                        X_Expenditure_Type               VARCHAR2,
2037                        X_Pa_Quantity                    NUMBER,
2038                        X_Project_Id                     NUMBER,
2039                        X_Task_Id                        NUMBER,
2040                        X_Quantity_Variance              NUMBER,
2041                        X_Base_Quantity_Variance         NUMBER,
2042                        X_Packet_Id                      NUMBER,
2043                        X_Awt_Flag                       VARCHAR2,
2044                        X_Awt_Group_Id                   NUMBER,
2045 		       X_Pay_Awt_Group_Id               NUMBER,--bug6639866
2046                        X_Awt_Tax_Rate_Id                NUMBER,
2047                        X_Awt_Gross_Amount               NUMBER,
2048                        X_Reference_1                    VARCHAR2,
2049                        X_Reference_2                    VARCHAR2,
2050                        X_Org_Id                         NUMBER,
2051                        X_Other_Invoice_Id               NUMBER,
2052                        X_Awt_Invoice_Id                 NUMBER,
2053                        X_Awt_Origin_Group_Id            NUMBER,
2054                        X_Program_Application_Id         NUMBER,
2055                        X_Program_Id                     NUMBER,
2056                        X_Program_Update_Date            DATE,
2057                        X_Request_Id                     NUMBER,
2058                        X_Tax_Recoverable_Flag           VARCHAR2,
2059                        X_Award_Id                       NUMBER,
2060                        X_Start_Expense_Date             DATE,
2061                        X_Merchant_Document_Number       VARCHAR2,
2062                        X_Merchant_Name                  VARCHAR2,
2063 		       X_Merchant_Reference		VARCHAR2,
2064                        X_Merchant_Tax_Reg_Number        VARCHAR2,
2065                        X_Merchant_Taxpayer_Id           VARCHAR2,
2066                        X_Country_Of_Supply              VARCHAR2,
2067                        X_Parent_Reversal_id    NUMBER,
2068                        X_rcv_transaction_id    NUMBER,
2069                        X_matched_uom_lookup_code  VARCHAR2,
2070                        X_global_attribute_category      VARCHAR2 DEFAULT NULL,
2071                        X_global_attribute1              VARCHAR2 DEFAULT NULL,
2072                        X_global_attribute2              VARCHAR2 DEFAULT NULL,
2073                        X_global_attribute3              VARCHAR2 DEFAULT NULL,
2074                        X_global_attribute4              VARCHAR2 DEFAULT NULL,
2075                        X_global_attribute5              VARCHAR2 DEFAULT NULL,
2076                        X_global_attribute6              VARCHAR2 DEFAULT NULL,
2077                        X_global_attribute7              VARCHAR2 DEFAULT NULL,
2078                        X_global_attribute8              VARCHAR2 DEFAULT NULL,
2079                        X_global_attribute9              VARCHAR2 DEFAULT NULL,
2080                        X_global_attribute10             VARCHAR2 DEFAULT NULL,
2081                        X_global_attribute11             VARCHAR2 DEFAULT NULL,
2082                        X_global_attribute12             VARCHAR2 DEFAULT NULL,
2083                        X_global_attribute13             VARCHAR2 DEFAULT NULL,
2084                        X_global_attribute14             VARCHAR2 DEFAULT NULL,
2085                        X_global_attribute15             VARCHAR2 DEFAULT NULL,
2086                        X_global_attribute16             VARCHAR2 DEFAULT NULL,
2087                        X_global_attribute17             VARCHAR2 DEFAULT NULL,
2088                        X_global_attribute18             VARCHAR2 DEFAULT NULL,
2089                        X_global_attribute19             VARCHAR2 DEFAULT NULL,
2090                        X_global_attribute20             VARCHAR2 DEFAULT NULL,
2091                        -- Invoice Lines Project Stage 1
2092                        X_rounding_amt                   NUMBER DEFAULT NULL,
2093                        X_charge_applicable_to_dist_id   NUMBER DEFAULT NULL,
2094                        X_corrected_invoice_dist_id      NUMBER DEFAULT NULL,
2095                        X_related_id                     NUMBER DEFAULT NULL,
2096                        X_asset_book_type_code           VARCHAR2 DEFAULT NULL,
2097                        X_asset_category_id              NUMBER DEFAULT NULL ,
2098 		       X_Intended_Use			VARCHAR2 DEFAULT NULL,
2099 		       x_calling_sequence               VARCHAR2
2100    ) IS
2101     current_calling_sequence VARCHAR2(2000);
2102     debug_info               VARCHAR2(100);
2103 
2104    BEGIN
2105       -- Update the calling sequence
2106        --
2107        current_calling_sequence :=
2108        'AP_INVOICE_DISTRIBUTIONS_PKG.Insert_Row<-'||X_Calling_Sequence;
2109 
2110        debug_info := 'Calling invoice distribution handler';
2111 
2112        AP_AID_TABLE_HANDLER_PKG.Insert_Row
2113              (X_Rowid,
2114               X_Invoice_Id,
2115               -- Invoice Lines Project Stage 1
2116               X_Invoice_Line_Number,
2117               X_Distribution_Class,
2118               X_Invoice_Distribution_Id,
2119               X_Dist_Code_Combination_Id,
2120               X_Last_Update_Date,
2121               X_Last_Updated_By,
2122               X_Accounting_Date,
2123               X_Period_Name,
2124               X_Set_Of_Books_Id,
2125               X_Amount,
2126               X_Description,
2127               X_Type_1099,
2128               X_Posted_Flag,
2129               X_Batch_Id,
2130               X_Quantity_Invoiced,
2131               X_Unit_Price,
2132               X_Match_Status_Flag,
2133               X_Attribute_Category,
2134               X_Attribute1,
2135               X_Attribute2,
2136               X_Attribute3,
2137               X_Attribute4,
2138               X_Attribute5,
2139               X_Prepay_Amount_Remaining,
2140               X_Assets_Addition_Flag,
2141               X_Assets_Tracking_Flag,
2142               X_Distribution_Line_Number,
2143               X_Line_Type_Lookup_Code,
2144               X_Po_Distribution_Id,
2145               X_Base_Amount,
2146               X_Pa_Addition_Flag,
2147               X_Posted_Amount,
2148               X_Posted_Base_Amount,
2149               X_Encumbered_Flag,
2150               X_Accrual_Posted_Flag,
2151               X_Cash_Posted_Flag,
2152               X_Last_Update_Login,
2153               X_Creation_Date,
2154               X_Created_By,
2155               X_Stat_Amount,
2156               X_Attribute11,
2157               X_Attribute12,
2158               X_Attribute13,
2159               X_Attribute14,
2160               X_Attribute6,
2161               X_Attribute7,
2162               X_Attribute8,
2163               X_Attribute9,
2164               X_Attribute10,
2165               X_Attribute15,
2166               X_Accts_Pay_Code_Comb_Id,
2167               X_Reversal_Flag,
2168               X_Parent_Invoice_Id,
2169               X_Income_Tax_Region,
2170               X_Final_Match_Flag,
2171               X_Expenditure_Item_Date,
2172               X_Expenditure_Organization_Id,
2173               X_Expenditure_Type,
2174               X_Pa_Quantity,
2175               X_Project_Id,
2176               X_Task_Id,
2177               X_Quantity_Variance,
2178               X_Base_Quantity_Variance,
2179               X_Packet_Id,
2180               X_Awt_Flag,
2181               X_Awt_Group_Id,
2182 	      X_Pay_Awt_Group_Id,--bug6639866
2183               X_Awt_Tax_Rate_Id,
2184               X_Awt_Gross_Amount,
2185               X_Reference_1,
2186               X_Reference_2,
2187               X_Org_Id,
2188               X_Other_Invoice_Id,
2189               X_Awt_Invoice_Id,
2190               X_Awt_Origin_Group_Id,
2191               X_Program_Application_Id,
2192               X_Program_Id,
2193               X_Program_Update_Date,
2194               X_Request_Id,
2195               X_Tax_Recoverable_Flag,
2196               X_Award_Id,
2197               X_Start_Expense_Date,
2198               X_Merchant_Document_Number,
2199               X_Merchant_Name,
2200               X_Merchant_Tax_Reg_Number,
2201               X_Merchant_Taxpayer_Id,
2202               X_Country_Of_Supply,
2203               X_Merchant_Reference,
2204               X_Parent_Reversal_Id,
2205               X_rcv_transaction_id,
2206               X_matched_uom_lookup_code,
2207               X_global_attribute_category,
2208               X_global_attribute1,
2209               X_global_attribute2,
2210               X_global_attribute3,
2211               X_global_attribute4,
2212               X_global_attribute5,
2213               X_global_attribute6,
2214               X_global_attribute7,
2215               X_global_attribute8,
2216               X_global_attribute9,
2217               X_global_attribute10,
2218               X_global_attribute11,
2219               X_global_attribute12,
2220               X_global_attribute13,
2221               X_global_attribute14,
2222               X_global_attribute15,
2223               X_global_attribute16,
2224               X_global_attribute17,
2225               X_global_attribute18,
2226               X_global_attribute19,
2227               X_global_attribute20,
2228               current_calling_sequence,
2229            -- Added by iyas cuz params don't exist in ap_aid_table_handlers_pkg
2230               NULL,
2231               NULL,
2232               NULL,
2233               NULL,
2234               NULL,
2235               NULL,
2236               NULL,
2237               NULL,
2238               NULL,
2239               NULL,
2240               NULL,
2241               NULL,
2242               NULL,
2243               NULL,
2244            -- Invoice Lines Project Stage 1
2245               X_rounding_amt,
2246               X_charge_applicable_to_dist_id,
2247               X_corrected_invoice_dist_id,
2248               X_related_id,
2249               X_asset_book_type_code,
2250               X_asset_category_id,
2251 	      X_Intended_Use
2252              );
2253 
2254 
2255   EXCEPTION
2256     WHEN OTHERS THEN
2257       if (SQLCODE <> -20001) then
2258         FND_MESSAGE.SET_NAME('SQLAP', 'AP_DEBUG');
2259         FND_MESSAGE.SET_TOKEN('ERROR', SQLERRM);
2260         FND_MESSAGE.SET_TOKEN('CALLING_SEQUENCE', current_calling_sequence);
2261         FND_MESSAGE.SET_TOKEN('DEBUG_INFO', debug_info);
2262       end if;
2263       APP_EXCEPTION.RAISE_EXCEPTION;
2264 
2265   END Insert_Row;
2266 
2267 
2268   PROCEDURE Lock_Row(X_Rowid                            VARCHAR2,
2269                      X_Invoice_Id                       NUMBER,
2270                      -- Invoice Lines Project Stage 1
2271                      X_Invoice_Line_Number              NUMBER,
2272                      X_Distribution_Class               VARCHAR2,
2273                      X_Invoice_Distribution_Id          NUMBER,
2274                      X_Dist_Code_Combination_Id         NUMBER,
2275                      X_Accounting_Date                  DATE,
2276                      X_Period_Name                      VARCHAR2,
2277                      X_Set_Of_Books_Id                  NUMBER,
2278                      X_Amount                           NUMBER,
2279                      X_Description                      VARCHAR2,
2280                      X_Type_1099                        VARCHAR2,
2281                      X_Posted_Flag                      VARCHAR2,
2282                      X_Batch_Id                         NUMBER,
2283                      X_Quantity_Invoiced                NUMBER,
2284                      X_Unit_Price                       NUMBER,
2285                      X_Match_Status_Flag                VARCHAR2,
2286                      X_Attribute_Category               VARCHAR2,
2287                      X_Attribute1                       VARCHAR2,
2288                      X_Attribute2                       VARCHAR2,
2289                      X_Attribute3                       VARCHAR2,
2290                      X_Attribute4                       VARCHAR2,
2291                      X_Attribute5                       VARCHAR2,
2292                      X_Prepay_Amount_Remaining          NUMBER,
2293                      X_Assets_Addition_Flag             VARCHAR2,
2294                      X_Assets_Tracking_Flag             VARCHAR2,
2295                      X_Distribution_Line_Number         NUMBER,
2296                      X_Line_Type_Lookup_Code            VARCHAR2,
2297                      X_Po_Distribution_Id               NUMBER,
2298                      X_Base_Amount                      NUMBER,
2299                      X_Pa_Addition_Flag                 VARCHAR2,
2300                      X_Posted_Amount                    NUMBER,
2301                      X_Posted_Base_Amount               NUMBER,
2302                      X_Encumbered_Flag                  VARCHAR2,
2303                      X_Accrual_Posted_Flag              VARCHAR2,
2304                      X_Cash_Posted_Flag                 VARCHAR2,
2305                      X_Stat_Amount                      NUMBER,
2306                      X_Attribute11                      VARCHAR2,
2307                      X_Attribute12                      VARCHAR2,
2308                      X_Attribute13                      VARCHAR2,
2309                      X_Attribute14                      VARCHAR2,
2310                      X_Attribute6                       VARCHAR2,
2311                      X_Attribute7                       VARCHAR2,
2312                      X_Attribute8                       VARCHAR2,
2313                      X_Attribute9                       VARCHAR2,
2314                      X_Attribute10                      VARCHAR2,
2315                      X_Attribute15                      VARCHAR2,
2316                      X_Accts_Pay_Code_Comb_Id    NUMBER,
2317                      X_Reversal_Flag                    VARCHAR2,
2318                      X_Parent_Invoice_Id                NUMBER,
2319                      X_Income_Tax_Region                VARCHAR2,
2320                      X_Final_Match_Flag                 VARCHAR2,
2321                      X_Expenditure_Item_Date            DATE,
2322                      X_Expenditure_Organization_Id      NUMBER,
2323                      X_Expenditure_Type                 VARCHAR2,
2324                      X_Pa_Quantity                      NUMBER,
2325                      X_Project_Id                       NUMBER,
2326                      X_Task_Id                          NUMBER,
2327                      X_Quantity_Variance                NUMBER,
2328                      X_Base_Quantity_Variance           NUMBER,
2329                      X_Packet_Id                        NUMBER,
2330                      X_Awt_Flag                         VARCHAR2,
2331                      X_Awt_Group_Id                     NUMBER,
2332 		     X_Pay_Awt_Group_Id                 NUMBER,--bug6639866
2333                      X_Awt_Tax_Rate_Id                  NUMBER,
2334                      X_Awt_Gross_Amount                 NUMBER,
2335                      X_Reference_1                      VARCHAR2,
2336                      X_Reference_2                      VARCHAR2,
2337                      X_Org_Id                           NUMBER,
2338                      X_Other_Invoice_Id                 NUMBER,
2339                      X_Awt_Invoice_Id                   NUMBER,
2340                      X_Awt_Origin_Group_Id              NUMBER,
2341                      X_Program_Application_Id           NUMBER,
2342                      X_Program_Id                       NUMBER,
2343                      X_Program_Update_Date              DATE,
2344                      X_Request_Id                       NUMBER,
2345                      X_Tax_Recoverable_Flag             VARCHAR2,
2346                      X_Award_Id                         NUMBER,
2347                      X_Start_Expense_Date               DATE,
2348                      X_Merchant_Document_Number         VARCHAR2,
2349                      X_Merchant_Name                    VARCHAR2,
2350 		     X_Merchant_Reference               VARCHAR2,
2351                      X_Merchant_Tax_Reg_Number          VARCHAR2,
2352                      X_Merchant_Taxpayer_Id             VARCHAR2,
2353                      X_Country_Of_Supply                VARCHAR2,
2354                      X_global_attribute_category        VARCHAR2 DEFAULT NULL,
2355                      X_global_attribute1                VARCHAR2 DEFAULT NULL,
2356                      X_global_attribute2                VARCHAR2 DEFAULT NULL,
2357                      X_global_attribute3                VARCHAR2 DEFAULT NULL,
2358                      X_global_attribute4                VARCHAR2 DEFAULT NULL,
2359                      X_global_attribute5                VARCHAR2 DEFAULT NULL,
2360                      X_global_attribute6                VARCHAR2 DEFAULT NULL,
2361                      X_global_attribute7                VARCHAR2 DEFAULT NULL,
2362                      X_global_attribute8                VARCHAR2 DEFAULT NULL,
2363                      X_global_attribute9                VARCHAR2 DEFAULT NULL,
2364                      X_global_attribute10               VARCHAR2 DEFAULT NULL,
2365                      X_global_attribute11               VARCHAR2 DEFAULT NULL,
2366                      X_global_attribute12               VARCHAR2 DEFAULT NULL,
2367                      X_global_attribute13               VARCHAR2 DEFAULT NULL,
2368                      X_global_attribute14               VARCHAR2 DEFAULT NULL,
2369                      X_global_attribute15               VARCHAR2 DEFAULT NULL,
2370                      X_global_attribute16               VARCHAR2 DEFAULT NULL,
2371                      X_global_attribute17               VARCHAR2 DEFAULT NULL,
2372                      X_global_attribute18               VARCHAR2 DEFAULT NULL,
2373                      X_global_attribute19               VARCHAR2 DEFAULT NULL,
2374                      X_global_attribute20               VARCHAR2 DEFAULT NULL,
2375                      -- Invoice Lines Project Stage 1
2376                      X_rounding_amt                   NUMBER DEFAULT NULL,
2377                      X_charge_applicable_to_dist_id   NUMBER DEFAULT NULL,
2378                      X_corrected_invoice_dist_id      NUMBER DEFAULT NULL,
2379                      X_related_id                     NUMBER DEFAULT NULL,
2380                      X_asset_book_type_code           VARCHAR2 DEFAULT NULL,
2381                      X_asset_category_id              NUMBER DEFAULT NULL,
2382 		     --ETAX: Invoice Workbench
2383  		     X_Intended_Use		      VARCHAR2 DEFAULT NULL,
2384 		     X_Calling_Sequence		      VARCHAR2
2385   ) IS
2386     current_calling_sequence VARCHAR2(2000);
2387     debug_info               VARCHAR2(100);
2388     CURSOR C IS
2389         SELECT
2390           PREPAY_DISTRIBUTION_ID,
2391           --ACCOUNTING_EVENT_ID,
2392           ACCOUNTING_DATE,
2393           ACCRUAL_POSTED_FLAG,
2394           ASSETS_ADDITION_FLAG,
2395           ASSETS_TRACKING_FLAG,
2396           CASH_POSTED_FLAG,
2397           DISTRIBUTION_LINE_NUMBER,
2398           DIST_CODE_COMBINATION_ID,
2399           INVOICE_ID,
2400           LAST_UPDATED_BY,
2401           LAST_UPDATE_DATE,
2402           LINE_TYPE_LOOKUP_CODE,
2403           PERIOD_NAME,
2404           SET_OF_BOOKS_ID,
2405           ACCTS_PAY_CODE_COMBINATION_ID,
2406           AMOUNT,
2407           BASE_AMOUNT,
2408           BATCH_ID,
2409           CREATED_BY,
2410           CREATION_DATE,
2411           DESCRIPTION,
2412           FINAL_MATCH_FLAG,
2413           INCOME_TAX_REGION,
2414           LAST_UPDATE_LOGIN,
2415           MATCH_STATUS_FLAG,
2416           POSTED_FLAG,
2417           PO_DISTRIBUTION_ID,
2418           PROGRAM_APPLICATION_ID,
2419           PROGRAM_ID,
2420           PROGRAM_UPDATE_DATE,
2421           QUANTITY_INVOICED,
2422           REQUEST_ID,
2423           REVERSAL_FLAG,
2424           TYPE_1099,
2425           UNIT_PRICE,
2426           --AMOUNT_ENCUMBERED,
2427           --BASE_AMOUNT_ENCUMBERED,
2428           ENCUMBERED_FLAG,
2429           --PRICE_ADJUSTMENT_FLAG,
2430           --QUANTITY_UNENCUMBERED,
2431           STAT_AMOUNT,
2432           --AMOUNT_TO_POST,
2433           ATTRIBUTE1,
2434           ATTRIBUTE10,
2435           ATTRIBUTE11,
2436           ATTRIBUTE12,
2437           ATTRIBUTE13,
2438           ATTRIBUTE14,
2439           ATTRIBUTE15,
2440           ATTRIBUTE2,
2441           ATTRIBUTE3,
2442           ATTRIBUTE4,
2443           ATTRIBUTE5,
2444           ATTRIBUTE6,
2445           ATTRIBUTE7,
2446           ATTRIBUTE8,
2447           ATTRIBUTE9,
2448           ATTRIBUTE_CATEGORY,
2449           --BASE_AMOUNT_TO_POST,
2450           EXPENDITURE_ITEM_DATE,
2451           EXPENDITURE_ORGANIZATION_ID,
2452           EXPENDITURE_TYPE,
2453           PARENT_INVOICE_ID,
2454           PA_ADDITION_FLAG,
2455           PA_QUANTITY,
2456           POSTED_AMOUNT,
2457           POSTED_BASE_AMOUNT,
2458           PREPAY_AMOUNT_REMAINING,
2459           PROJECT_ID,
2460           TASK_ID,
2461           --EARLIEST_SETTLEMENT_DATE,
2462           --REQ_DISTRIBUTION_ID,
2463           QUANTITY_VARIANCE,
2464           BASE_QUANTITY_VARIANCE,
2465           PACKET_ID,
2466           AWT_FLAG,
2467           AWT_GROUP_ID,
2468 	  PAY_AWT_GROUP_ID,--bug6639866
2469           AWT_TAX_RATE_ID,
2470           AWT_GROSS_AMOUNT,
2471           AWT_INVOICE_ID,
2472           AWT_ORIGIN_GROUP_ID,
2473           REFERENCE_1,
2474           REFERENCE_2,
2475           ORG_ID,
2476           OTHER_INVOICE_ID,
2477           --AWT_INVOICE_PAYMENT_ID,
2478           GLOBAL_ATTRIBUTE_CATEGORY,
2479           GLOBAL_ATTRIBUTE1,
2480           GLOBAL_ATTRIBUTE2,
2481           GLOBAL_ATTRIBUTE3,
2482           GLOBAL_ATTRIBUTE4,
2483           GLOBAL_ATTRIBUTE5,
2484           GLOBAL_ATTRIBUTE6,
2485           GLOBAL_ATTRIBUTE7,
2486           GLOBAL_ATTRIBUTE8,
2487           GLOBAL_ATTRIBUTE9,
2488           GLOBAL_ATTRIBUTE10,
2489           GLOBAL_ATTRIBUTE11,
2490           GLOBAL_ATTRIBUTE12,
2491           GLOBAL_ATTRIBUTE13,
2492           GLOBAL_ATTRIBUTE14,
2493           GLOBAL_ATTRIBUTE15,
2494           GLOBAL_ATTRIBUTE16,
2495           GLOBAL_ATTRIBUTE17,
2496           GLOBAL_ATTRIBUTE18,
2497           GLOBAL_ATTRIBUTE19,
2498           GLOBAL_ATTRIBUTE20,
2499           --LINE_GROUP_NUMBER,
2500           --RECEIPT_VERIFIED_FLAG,
2501           --RECEIPT_REQUIRED_FLAG,
2502           --RECEIPT_MISSING_FLAG,
2503           --JUSTIFICATION,
2504           --EXPENSE_GROUP,
2505           START_EXPENSE_DATE,
2506           --END_EXPENSE_DATE,
2507           --RECEIPT_CURRENCY_CODE,
2508           --RECEIPT_CONVERSION_RATE,
2509           --RECEIPT_CURRENCY_AMOUNT,
2510           --DAILY_AMOUNT,
2511           --WEB_PARAMETER_ID,
2512           --ADJUSTMENT_REASON,
2513           AWARD_ID,
2514           --MRC_DIST_CODE_COMBINATION_ID,
2515           --MRC_BASE_AMOUNT,
2516           --MRC_BASE_INV_PRICE_VARIANCE,
2517           --MRC_EXCHANGE_RATE_VARIANCE,
2518           --MRC_RATE_VAR_CCID,
2519           --MRC_EXCHANGE_DATE,
2520           --MRC_EXCHANGE_RATE,
2521           --MRC_EXCHANGE_RATE_TYPE,
2522           --MRC_RECEIPT_CONVERSION_RATE,
2523           DIST_MATCH_TYPE,
2524           RCV_TRANSACTION_ID,
2525           -- Invoice Lines Project Stage 1
2526           INVOICE_LINE_NUMBER,
2527           DISTRIBUTION_CLASS,
2528           INVOICE_DISTRIBUTION_ID,
2529           PARENT_REVERSAL_ID,
2530           TAX_RECOVERABLE_FLAG,
2531           --PA_CC_AR_INVOICE_ID,
2532           --PA_CC_AR_INVOICE_LINE_NUM,
2533           --PA_CC_PROCESSED_CODE,
2534           MERCHANT_DOCUMENT_NUMBER,
2535           MERCHANT_NAME,
2536           MERCHANT_REFERENCE,
2537           MERCHANT_TAX_REG_NUMBER,
2538           MERCHANT_TAXPAYER_ID,
2539           COUNTRY_OF_SUPPLY,
2540           MATCHED_UOM_LOOKUP_CODE,
2541           GMS_BURDENABLE_RAW_COST,
2542           --CREDIT_CARD_TRX_ID,
2543           --UPGRADE_POSTED_AMT,
2544           --UPGRADE_BASE_POSTED_AMT,
2545           -- Invoice Lines Project Stage 1
2546           ROUNDING_AMT,
2547           CHARGE_APPLICABLE_TO_DIST_ID,
2548           CORRECTED_INVOICE_DIST_ID,
2549           RELATED_ID,
2550           ASSET_BOOK_TYPE_CODE,
2551           ASSET_CATEGORY_ID,
2552 	  INTENDED_USE
2553         FROM   AP_INVOICE_DISTRIBUTIONS
2554         WHERE  rowid = X_Rowid
2555         FOR UPDATE of Invoice_Id NOWAIT;
2556     Recinfo C%ROWTYPE;
2557 
2558 
2559 BEGIN
2560 
2561     -- Update the calling sequence
2562     --
2563     current_calling_sequence :=
2564     'AP_INVOICE_DISTRIBUTIONS_PKG.Lock_Row<-'||X_Calling_Sequence;
2565 
2566     debug_info := 'Select from ap_invoice_distributions';
2567 
2568     OPEN C;
2569 
2570     debug_info := 'Fetch cursor C';
2571     FETCH C INTO Recinfo;
2572     if (C%NOTFOUND) then
2573       debug_info := 'Close cursor C - ROW NOTFOUND';
2574       CLOSE C;
2575       FND_MESSAGE.Set_Name('FND', 'FORM_RECORD_DELETED');
2576       APP_EXCEPTION.Raise_Exception;
2577     end if;
2578     debug_info := 'Close cursor C';
2579     CLOSE C;
2580     if (
2581                (Recinfo.invoice_id =  X_Invoice_Id)
2582            AND (Recinfo.dist_code_combination_id =  X_Dist_Code_Combination_Id)
2583            -- Invoice Lines Project Stage 1
2584            AND (Recinfo.invoice_line_number = X_Invoice_Line_Number)
2585            AND (Recinfo.distribution_class  = X_Distribution_Class)
2586            AND (Recinfo.invoice_distribution_id = X_Invoice_Distribution_Id)
2587            AND (Recinfo.accounting_date =  X_Accounting_Date)
2588            AND (Recinfo.period_name =  X_Period_Name)
2589            AND (Recinfo.set_of_books_id =  X_Set_Of_Books_Id)
2590            AND (   (Recinfo.amount =  X_Amount)
2591                 OR (    (Recinfo.amount IS NULL)
2592                     AND (X_Amount IS NULL)))
2593            AND (   (Recinfo.description =  X_Description)
2594                 OR (    (Recinfo.description IS NULL)
2595                     AND (X_Description IS NULL)))
2596            AND (   (Recinfo.type_1099 =  X_Type_1099)
2597                 OR (    (Recinfo.type_1099 IS NULL)
2598                     AND (X_Type_1099 IS NULL)))
2599            AND (   (Recinfo.posted_flag =  X_Posted_Flag)
2600                 OR (    (Recinfo.posted_flag IS NULL)
2601                     AND (X_Posted_Flag IS NULL)))
2602            AND (   (Recinfo.batch_id =  X_Batch_Id)
2603                 OR (    (Recinfo.batch_id IS NULL)
2604                     AND (X_Batch_Id IS NULL)))
2605            AND (   (Recinfo.quantity_invoiced =  X_Quantity_Invoiced)
2606                 OR (    (Recinfo.quantity_invoiced IS NULL)
2607                     AND (X_Quantity_Invoiced IS NULL)))
2608            AND (   (Recinfo.unit_price =  X_Unit_Price)
2609                 OR (    (Recinfo.unit_price IS NULL)
2610                     AND (X_Unit_Price IS NULL)))
2611            AND (   (Recinfo.match_status_flag =  X_Match_Status_Flag)
2612                 OR (    (Recinfo.match_status_flag IS NULL)
2613                     AND (X_Match_Status_Flag IS NULL)))
2614            AND (   (Recinfo.attribute_category =  X_Attribute_Category)
2615                 OR (    (Recinfo.attribute_category IS NULL)
2616                     AND (X_Attribute_Category IS NULL)))
2617            AND (   (Recinfo.attribute1 =  X_Attribute1)
2618                 OR (    (Recinfo.attribute1 IS NULL)
2619                     AND (X_Attribute1 IS NULL)))
2620            AND (   (Recinfo.attribute2 =  X_Attribute2)
2621                 OR (    (Recinfo.attribute2 IS NULL)
2622                     AND (X_Attribute2 IS NULL)))
2623            AND (   (Recinfo.attribute3 =  X_Attribute3)
2624                 OR (    (Recinfo.attribute3 IS NULL)
2625                     AND (X_Attribute3 IS NULL)))
2626            AND (   (Recinfo.attribute4 =  X_Attribute4)
2627                 OR (    (Recinfo.attribute4 IS NULL)
2628                     AND (X_Attribute4 IS NULL)))
2629            AND (   (Recinfo.attribute5 =  X_Attribute5)
2630                 OR (    (Recinfo.attribute5 IS NULL)
2631                     AND (X_Attribute5 IS NULL)))
2632            AND (Recinfo.assets_addition_flag =  X_Assets_Addition_Flag)
2633            AND (Recinfo.assets_tracking_flag =  X_Assets_Tracking_Flag)
2634            AND (Recinfo.distribution_line_number =  X_Distribution_Line_Number)
2635            AND (Recinfo.line_type_lookup_code =  X_Line_Type_Lookup_Code)
2636            AND (   (Recinfo.po_distribution_id =  X_Po_Distribution_Id)
2637                 OR (    (Recinfo.po_distribution_id IS NULL)
2638                     AND (X_Po_Distribution_Id IS NULL)))
2639            AND (   (Recinfo.base_amount =  X_Base_Amount)
2640                 OR (    (Recinfo.base_amount IS NULL)
2641                     AND (X_Base_Amount IS NULL)))
2642            AND (   (Recinfo.pa_addition_flag =  X_Pa_Addition_Flag)
2643                 OR (    (Recinfo.pa_addition_flag IS NULL)
2644                     AND (X_Pa_Addition_Flag IS NULL)))
2645            AND (   (Recinfo.posted_amount =  X_Posted_Amount)
2646                 OR (    (Recinfo.posted_amount IS NULL)
2647                     AND (X_Posted_Amount IS NULL)))
2648            AND (   (Recinfo.posted_base_amount =  X_Posted_Base_Amount)
2649                 OR (    (Recinfo.posted_base_amount IS NULL)
2650                     AND (X_Posted_Base_Amount IS NULL)))
2651            AND (   (Recinfo.encumbered_flag =  X_Encumbered_Flag)
2652                 OR (    (Recinfo.encumbered_flag IS NULL)
2653                     AND (X_Encumbered_Flag IS NULL)))
2654            AND (Recinfo.accrual_posted_flag =  X_Accrual_Posted_Flag)
2655            AND (Recinfo.cash_posted_flag =  X_Cash_Posted_Flag)
2656            AND (   (Recinfo.stat_amount =  X_Stat_Amount)
2657                 OR (    (Recinfo.stat_amount IS NULL)
2658                     AND (X_Stat_Amount IS NULL)))
2659            AND (   (Recinfo.attribute11 =  X_Attribute11)
2660                 OR (    (Recinfo.attribute11 IS NULL)
2661                     AND (X_Attribute11 IS NULL)))
2662            AND (   (Recinfo.attribute12 =  X_Attribute12)
2663                 OR (    (Recinfo.attribute12 IS NULL)
2664                     AND (X_Attribute12 IS NULL)))
2665            AND (   (Recinfo.attribute13 =  X_Attribute13)
2666                 OR (    (Recinfo.attribute13 IS NULL)
2667                     AND (X_Attribute13 IS NULL)))) then
2668       null;
2669     else
2670       FND_MESSAGE.Set_Name('FND', 'FORM_RECORD_CHANGED');
2671       APP_EXCEPTION.Raise_Exception;
2672     end if;
2673 
2674     if (
2675                (   (Recinfo.attribute14 =  X_Attribute14)
2676                 OR (    (Recinfo.attribute14 IS NULL)
2677                     AND (X_Attribute14 IS NULL)))
2678            AND (   (Recinfo.attribute6 =  X_Attribute6)
2679                 OR (    (Recinfo.attribute6 IS NULL)
2680                     AND (X_Attribute6 IS NULL)))
2681            AND (   (Recinfo.attribute7 =  X_Attribute7)
2682                 OR (    (Recinfo.attribute7 IS NULL)
2683                     AND (X_Attribute7 IS NULL)))
2684            AND (   (Recinfo.attribute8 =  X_Attribute8)
2685                 OR (    (Recinfo.attribute8 IS NULL)
2686                     AND (X_Attribute8 IS NULL)))
2687            AND (   (Recinfo.attribute9 =  X_Attribute9)
2688                 OR (    (Recinfo.attribute9 IS NULL)
2689                     AND (X_Attribute9 IS NULL)))
2690            AND (   (Recinfo.attribute10 =  X_Attribute10)
2691                 OR (    (Recinfo.attribute10 IS NULL)
2692                     AND (X_Attribute10 IS NULL)))
2693            AND (   (Recinfo.attribute15 =  X_Attribute15)
2694                 OR (    (Recinfo.attribute15 IS NULL)
2695                     AND (X_Attribute15 IS NULL)))
2696            AND (   (Recinfo.accts_pay_code_combination_id =  X_Accts_Pay_Code_Comb_Id)
2697                 OR (    (Recinfo.accts_pay_code_combination_id IS NULL)
2698                     AND (X_Accts_Pay_Code_Comb_Id IS NULL)))
2699            AND (   (Recinfo.reversal_flag =  X_Reversal_Flag)
2700                 OR (    (Recinfo.reversal_flag IS NULL)
2701                     AND (X_Reversal_Flag IS NULL)))
2702            AND (   (Recinfo.parent_invoice_id =  X_Parent_Invoice_Id)
2703                 OR (    (Recinfo.parent_invoice_id IS NULL)
2704                     AND (X_Parent_Invoice_Id IS NULL)))
2705            AND (   (Recinfo.income_tax_region =  X_Income_Tax_Region)
2706                 OR (    (Recinfo.income_tax_region IS NULL)
2707                     AND (X_Income_Tax_Region IS NULL)))
2708            AND (   (Recinfo.final_match_flag =  X_Final_Match_Flag)
2709                 OR (    (Recinfo.final_match_flag IS NULL)
2710                     AND (X_Final_Match_Flag IS NULL)))
2711            AND (   (Recinfo.expenditure_item_date =  X_Expenditure_Item_Date)
2712                 OR (    (Recinfo.expenditure_item_date IS NULL)
2713                     AND (X_Expenditure_Item_Date IS NULL)))
2714            AND (   (Recinfo.expenditure_organization_id =  X_Expenditure_Organization_Id)
2715                 OR (    (Recinfo.expenditure_organization_id IS NULL)
2716                     AND (X_Expenditure_Organization_Id IS NULL)))
2717            AND (   (Recinfo.expenditure_type =  X_Expenditure_Type)
2718                 OR (    (Recinfo.expenditure_type IS NULL)
2719                     AND (X_Expenditure_Type IS NULL)))
2720            AND (   (Recinfo.pa_quantity =  X_Pa_Quantity)
2721                 OR (    (Recinfo.pa_quantity IS NULL)
2722                     AND (X_Pa_Quantity IS NULL)))
2723            AND (   (Recinfo.project_id =  X_Project_Id)
2724                 OR (    (Recinfo.project_id IS NULL)
2725                     AND (X_Project_Id IS NULL)))
2726            AND (   (Recinfo.task_id =  X_Task_Id)
2727                 OR (    (Recinfo.task_id IS NULL)
2728                     AND (X_Task_Id IS NULL)))
2729            AND (   (Recinfo.quantity_variance =  X_Quantity_Variance)
2730                 OR (    (Recinfo.quantity_variance IS NULL)
2731                     AND (X_Quantity_Variance IS NULL)))
2732            AND (   (Recinfo.base_quantity_variance =  X_Base_Quantity_Variance)
2733                 OR (    (Recinfo.base_quantity_variance IS NULL)
2734                     AND (X_Base_Quantity_Variance IS NULL)))
2735            AND (   (Recinfo.packet_id =  X_Packet_Id)
2736                 OR (    (Recinfo.packet_id IS NULL)
2737                     AND (X_Packet_Id IS NULL)))
2738            AND (   (Recinfo.awt_flag =  X_Awt_Flag)
2739                 OR (    (Recinfo.awt_flag IS NULL)
2740                     AND (X_Awt_Flag IS NULL)))
2741            AND (   (Recinfo.awt_group_id =  X_Awt_Group_Id)
2742                 OR (    (Recinfo.awt_group_id IS NULL)
2743                     AND (X_Awt_Group_Id IS NULL)))
2744            AND (   (Recinfo.pay_awt_group_id =  X_Pay_Awt_Group_Id)
2745                 OR (    (Recinfo.pay_awt_group_id IS NULL)
2746                     AND (X_Pay_Awt_Group_Id IS NULL)))       --bug6639866
2747            AND (   (Recinfo.awt_tax_rate_id =  X_Awt_Tax_Rate_Id)
2748                 OR (    (Recinfo.awt_tax_rate_id IS NULL)
2749                     AND (X_Awt_Tax_Rate_Id IS NULL)))
2750            AND (   (Recinfo.awt_gross_amount =  X_Awt_Gross_Amount)
2751                 OR (    (Recinfo.awt_gross_amount IS NULL)
2752                     AND (X_Awt_Gross_Amount IS NULL)))
2753            AND (   (Recinfo.reference_1 =  X_Reference_1)
2754                 OR (    (Recinfo.reference_1 IS NULL)
2755                     AND (X_Reference_1 IS NULL)))
2756            AND (   (Recinfo.reference_2 =  X_Reference_2)
2757                 OR (    (Recinfo.reference_2 IS NULL)
2758                     AND (X_Reference_2 IS NULL)))
2759            AND (   (Recinfo.other_invoice_id =  X_Other_Invoice_Id)
2760                 OR (    (Recinfo.other_invoice_id IS NULL)
2761                     AND (X_Other_Invoice_Id IS NULL)))
2762            AND (   (Recinfo.awt_invoice_id =  X_Awt_Invoice_Id)
2763                 OR (    (Recinfo.awt_invoice_id IS NULL)
2764                     AND (X_Awt_Invoice_Id IS NULL)))
2765            AND (   (Recinfo.awt_origin_group_id =  X_Awt_Origin_Group_Id)
2766                 OR (    (Recinfo.awt_origin_group_id IS NULL)
2767                     AND (X_Awt_Origin_Group_Id IS NULL)))
2768            AND (   (Recinfo.program_application_id = X_Program_Application_Id)
2769                 OR (    (Recinfo.program_application_id IS NULL)
2770                     AND (X_Program_Application_id IS NULL)))
2771            AND (   (Recinfo.program_id = X_Program_Id)
2772                 OR (    (Recinfo.program_id IS NULL)
2773                     AND (X_Program_Id IS NULL)))
2774            AND (   (Recinfo.program_update_date = X_Program_Update_Date)
2775                 OR (    (Recinfo.program_update_date IS NULL)
2776                     AND (X_Program_Update_Date IS NULL)))
2777            AND (   (Recinfo.request_id = X_Request_Id)
2778                 OR (    (Recinfo.request_id IS NULL)
2779                     AND (X_Request_Id IS NULL)))
2780            AND (    (Recinfo.tax_recoverable_flag = X_Tax_Recoverable_Flag)
2781                 OR (    (Recinfo.tax_recoverable_flag IS NULL)
2782                      AND (X_Tax_Recoverable_Flag IS NULL)))
2783            AND (    (Recinfo.award_id = X_Award_Id)
2784                 OR (    (Recinfo.award_id IS NULL)
2785                      AND (X_Award_Id IS NULL)))
2786            AND (    (Recinfo.start_expense_date = X_Start_Expense_Date)
2787                 OR (    (Recinfo.start_expense_date IS NULL)
2788                      AND (X_Start_Expense_Date IS NULL)))
2789            AND (    (Recinfo.merchant_document_number = X_Merchant_Document_Number)
2790                 OR (    (Recinfo.merchant_document_number IS NULL)
2791                      AND (X_Merchant_Document_Number IS NULL)))
2792            AND (    (Recinfo.merchant_name = X_Merchant_Name)
2793                 OR (    (Recinfo.merchant_name IS NULL)
2794                      AND (X_Merchant_Name IS NULL)))
2795            AND (    (Recinfo.merchant_tax_reg_number = X_Merchant_Tax_Reg_Number)
2796                 OR (    (Recinfo.merchant_tax_reg_number IS NULL)
2797                      AND (X_Merchant_Tax_Reg_Number IS NULL)))
2798            AND (    (Recinfo.merchant_taxpayer_id = X_Merchant_Taxpayer_Id)
2799                 OR (    (Recinfo.merchant_taxpayer_id IS NULL)
2800                      AND (X_Merchant_Taxpayer_Id IS NULL)))
2801            AND (    (Recinfo.merchant_reference = X_Merchant_Reference)
2802                 OR (    (Recinfo.merchant_reference IS NULL)
2803                      AND (X_Merchant_Reference IS NULL)))
2804            AND (    (Recinfo.country_of_supply = X_Country_Of_Supply)
2805                 OR (    (Recinfo.country_of_supply IS NULL)
2806                      AND (X_Country_Of_Supply IS NULL)))
2807 
2808       ) then
2809       null;
2810     else
2811       FND_MESSAGE.Set_Name('FND', 'FORM_RECORD_CHANGED');
2812       APP_EXCEPTION.Raise_Exception;
2813     end if;
2814 
2815    if (
2816                (   (Recinfo.global_attribute_category =  X_global_attribute_category)
2817                 OR (    (Recinfo.global_attribute_category IS NULL)
2818                     AND (X_global_attribute_category IS NULL)))
2819            AND (   (Recinfo.global_attribute1 =  X_global_attribute1)
2820                 OR (    (Recinfo.global_attribute1 IS NULL)
2821                     AND (X_global_attribute1 IS NULL)))
2822            AND (   (Recinfo.global_attribute2 =  X_global_attribute2)
2823                 OR (    (Recinfo.global_attribute2 IS NULL)
2824                     AND (X_global_attribute2 IS NULL)))
2825            AND (   (Recinfo.global_attribute3 =  X_global_attribute3)
2826                 OR (    (Recinfo.global_attribute3 IS NULL)
2827                     AND (X_global_attribute3 IS NULL)))
2828            AND (   (Recinfo.global_attribute4 =  X_global_attribute4)
2829                 OR (    (Recinfo.global_attribute4 IS NULL)
2830                     AND (X_global_attribute4 IS NULL)))
2831            AND (   (Recinfo.global_attribute5 =  X_global_attribute5)
2832                 OR (    (Recinfo.global_attribute5 IS NULL)
2833                     AND (X_global_attribute5 IS NULL)))
2834            AND (   (Recinfo.global_attribute6 =  X_global_attribute6)
2835                 OR (    (Recinfo.global_attribute6 IS NULL)
2836                     AND (X_global_attribute6 IS NULL)))
2837            AND (   (Recinfo.global_attribute7 =  X_global_attribute7)
2838                 OR (    (Recinfo.global_attribute7 IS NULL)
2839                     AND (X_global_attribute7 IS NULL)))
2840            AND (   (Recinfo.global_attribute8 =  X_global_attribute8)
2841                 OR (    (Recinfo.global_attribute8 IS NULL)
2842                     AND (X_global_attribute8 IS NULL)))
2843            AND (   (Recinfo.global_attribute9 =  X_global_attribute9)
2844                 OR (    (Recinfo.global_attribute9 IS NULL)
2845                     AND (X_global_attribute9 IS NULL)))
2846            AND (   (Recinfo.global_attribute10 =  X_global_attribute10)
2847                 OR (    (Recinfo.global_attribute10 IS NULL)
2848                     AND (X_global_attribute10 IS NULL)))
2849            AND (   (Recinfo.global_attribute11 =  X_global_attribute11)
2850                 OR (    (Recinfo.global_attribute11 IS NULL)
2851                     AND (X_global_attribute11 IS NULL)))
2852            AND (   (Recinfo.global_attribute12 =  X_global_attribute12)
2853                 OR (    (Recinfo.global_attribute12 IS NULL)
2854                     AND (X_global_attribute12 IS NULL)))
2855            AND (   (Recinfo.global_attribute13 =  X_global_attribute13)
2856                 OR (    (Recinfo.global_attribute13 IS NULL)
2857                     AND (X_global_attribute13 IS NULL)))
2858            AND (   (Recinfo.global_attribute14 =  X_global_attribute14)
2859                 OR (    (Recinfo.global_attribute14 IS NULL)
2860                     AND (X_global_attribute14 IS NULL)))
2861            AND (   (Recinfo.global_attribute15 =  X_global_attribute15)
2862                 OR (    (Recinfo.global_attribute15 IS NULL)
2863                     AND (X_global_attribute15 IS NULL)))
2864            AND (   (Recinfo.global_attribute16 =  X_global_attribute16)
2865                 OR (    (Recinfo.global_attribute16 IS NULL)
2866                     AND (X_global_attribute16 IS NULL)))
2867            AND (   (Recinfo.global_attribute17 =  X_global_attribute17)
2868                 OR (    (Recinfo.global_attribute17 IS NULL)
2869                     AND (X_global_attribute17 IS NULL)))
2870            AND (   (Recinfo.global_attribute18 =  X_global_attribute18)
2871                 OR (    (Recinfo.global_attribute18 IS NULL)
2872                     AND (X_global_attribute18 IS NULL)))
2873            AND (   (Recinfo.global_attribute19 =  X_global_attribute19)
2874                 OR (    (Recinfo.global_attribute19 IS NULL)
2875                     AND (X_global_attribute19 IS NULL)))
2876            AND (   (Recinfo.global_attribute20 =  X_global_attribute20)
2877                 OR (    (Recinfo.global_attribute20 IS NULL)
2878                     AND (X_global_attribute20 IS NULL)))
2879           ) then
2880       return;
2881     else
2882       FND_MESSAGE.Set_Name('FND', 'FORM_RECORD_CHANGED');
2883       APP_EXCEPTION.Raise_Exception;
2884     end if;
2885 
2886        -- Invoice Lines Project Stage 1
2887        IF (
2888            (   (Recinfo.rOUNDING_AMT =  X_ROUNDING_AMT)
2889                 OR (    (Recinfo.ROUNDING_AMT IS NULL)
2890                     AND (X_ROUNDING_AMT IS NULL)))
2891            AND (   (Recinfo.CHARGE_APPLICABLE_TO_DIST_ID =  X_CHARGE_APPLICABLE_TO_DIST_ID)
2892                 OR (    (Recinfo.CHARGE_APPLICABLE_TO_DIST_ID IS NULL)
2893                     AND (X_CHARGE_APPLICABLE_TO_DIST_ID IS NULL)))
2894            AND (   (Recinfo.CORRECTED_INVOICE_DIST_ID =  X_CORRECTED_INVOICE_DIST_ID)
2895                 OR (    (Recinfo.CORRECTED_INVOICE_DIST_ID IS NULL)
2896                     AND (X_CORRECTED_INVOICE_DIST_ID IS NULL)))
2897            AND (   (Recinfo.RELATED_ID =  X_RELATED_ID)
2898                 OR (    (Recinfo.RELATED_ID IS NULL)
2899                     AND (X_RELATED_ID IS NULL)))
2900            AND (   (Recinfo.ASSET_BOOK_TYPE_CODE =  X_ASSET_BOOK_TYPE_CODE)
2901                 OR (    (Recinfo.ASSET_BOOK_TYPE_CODE IS NULL)
2902                     AND (X_ASSET_BOOK_TYPE_CODE IS NULL)))
2903            AND (   (Recinfo.ASSET_CATEGORY_ID =  X_ASSET_CATEGORY_ID)
2904                 OR (    (Recinfo.ASSET_CATEGORY_ID IS NULL)
2905                     AND (X_ASSET_CATEGORY_ID IS NULL)))
2906            AND (   (Recinfo.INTENDED_USE =  X_INTENDED_USE)
2907 	        OR (    (Recinfo.INTENDED_USE IS NULL)
2908 	            AND (X_INTENDED_USE IS NULL)))
2909       ) then
2910       return;
2911     else
2912       FND_MESSAGE.Set_Name('FND', 'FORM_RECORD_CHANGED');
2913       APP_EXCEPTION.Raise_Exception;
2914     end if;
2915 
2916   EXCEPTION
2917     WHEN OTHERS THEN
2918       if (SQLCODE <> -20001) then
2919         IF (SQLCODE = -54) THEN
2920           FND_MESSAGE.SET_NAME('SQLAP','AP_RESOURCE_BUSY');
2921         ELSE
2922           FND_MESSAGE.SET_NAME('SQLAP', 'AP_DEBUG');
2923           FND_MESSAGE.SET_TOKEN('ERROR', SQLERRM);
2924           FND_MESSAGE.SET_TOKEN('CALLING_SEQUENCE', current_calling_sequence);
2925           FND_MESSAGE.SET_TOKEN('DEBUG_INFO', debug_info);
2926         END IF;
2927       end if;
2928       APP_EXCEPTION.RAISE_EXCEPTION;
2929 
2930   END Lock_Row;
2931 
2932   PROCEDURE Update_Row(X_Rowid                          VARCHAR2,
2933                        X_Invoice_Id                     NUMBER,
2934                        -- Invoice Lines Project Stage 1
2935                        X_Invoice_Line_Number            NUMBER,
2936                        X_Distribution_Class             VARCHAR2,
2937                        X_Dist_Code_Combination_Id       NUMBER,
2938                        X_Last_Update_Date               DATE,
2939                        X_Last_Updated_By                NUMBER,
2940                        X_Accounting_Date                DATE,
2941                        X_Period_Name                    VARCHAR2,
2942                        X_Set_Of_Books_Id                NUMBER,
2943                        X_Amount                         NUMBER,
2944                        X_Description                    VARCHAR2,
2945                        X_Type_1099                      VARCHAR2,
2946                        X_Posted_Flag                    VARCHAR2,
2947                        X_Batch_Id                       NUMBER,
2948                        X_Quantity_Invoiced              NUMBER,
2949                        X_Unit_Price                     NUMBER,
2950                        X_Match_Status_Flag              VARCHAR2,
2951                        X_Attribute_Category             VARCHAR2,
2952                        X_Attribute1                     VARCHAR2,
2953                        X_Attribute2                     VARCHAR2,
2954                        X_Attribute3                     VARCHAR2,
2955                        X_Attribute4                     VARCHAR2,
2956                        X_Attribute5                     VARCHAR2,
2957                        X_Prepay_Amount_Remaining        NUMBER,
2958                        X_Assets_Addition_Flag           VARCHAR2,
2959                        X_Assets_Tracking_Flag           VARCHAR2,
2960                        X_Distribution_Line_Number       NUMBER,
2961                        X_Line_Type_Lookup_Code          VARCHAR2,
2962                        X_Po_Distribution_Id             NUMBER,
2963                        X_Base_Amount                    NUMBER,
2964                        X_Pa_Addition_Flag               VARCHAR2,
2965                        X_Posted_Amount                  NUMBER,
2966                        X_Posted_Base_Amount             NUMBER,
2967                        X_Encumbered_Flag                VARCHAR2,
2968                        X_Accrual_Posted_Flag            VARCHAR2,
2969                        X_Cash_Posted_Flag               VARCHAR2,
2970                        X_Last_Update_Login              NUMBER,
2971                        X_Stat_Amount                    NUMBER,
2972                        X_Attribute11                    VARCHAR2,
2973                        X_Attribute12                    VARCHAR2,
2974                        X_Attribute13                    VARCHAR2,
2975                        X_Attribute14                    VARCHAR2,
2976                        X_Attribute6                     VARCHAR2,
2977                        X_Attribute7                     VARCHAR2,
2978                        X_Attribute8                     VARCHAR2,
2979                        X_Attribute9                     VARCHAR2,
2980                        X_Attribute10                    VARCHAR2,
2981                        X_Attribute15                    VARCHAR2,
2982                        X_Accts_Pay_Code_Comb_Id         NUMBER,
2983                        X_Reversal_Flag                  VARCHAR2,
2984                        X_Parent_Invoice_Id              NUMBER,
2985                        X_Income_Tax_Region              VARCHAR2,
2986                        X_Final_Match_Flag               VARCHAR2,
2987                        X_Expenditure_Item_Date          DATE,
2988                        X_Expenditure_Organization_Id    NUMBER,
2989                        X_Expenditure_Type               VARCHAR2,
2990                        X_Pa_Quantity                    NUMBER,
2991                        X_Project_Id                     NUMBER,
2992                        X_Task_Id                        NUMBER,
2993                        X_Quantity_Variance              NUMBER,
2994                        X_Base_Quantity_Variance         NUMBER,
2995                        X_Packet_Id                      NUMBER,
2996                        X_Awt_Flag                       VARCHAR2,
2997                        X_Awt_Group_Id                   NUMBER,
2998 		       X_Pay_Awt_Group_Id               NUMBER,--bug6639866
2999                        X_Awt_Tax_Rate_Id                NUMBER,
3000                        X_Awt_Gross_Amount               NUMBER,
3001                        X_Reference_1                    VARCHAR2,
3002                        X_Reference_2                    VARCHAR2,
3003                        X_Org_Id                         NUMBER,
3004                        X_Other_Invoice_Id               NUMBER,
3005                        X_Awt_Invoice_Id                 NUMBER,
3006                        X_Awt_Origin_Group_Id            NUMBER,
3007                        X_Program_Application_Id         NUMBER,
3008                        X_Program_Id                     NUMBER,
3009                        X_Program_Update_Date            DATE,
3010                        X_Request_Id                     NUMBER,
3011                        X_Tax_Recoverable_Flag           VARCHAR2,
3012                        X_Award_Id                       NUMBER,
3013                        X_Start_Expense_Date             DATE,
3014                        X_Merchant_Document_Number       VARCHAR2,
3015                        X_Merchant_Name                  VARCHAR2,
3016                        X_Merchant_Tax_Reg_Number        VARCHAR2,
3017                        X_Merchant_Taxpayer_Id           VARCHAR2,
3018                        X_Country_Of_Supply              VARCHAR2,
3019                        X_Merchant_Reference             VARCHAR2,
3020                        X_global_attribute_category      VARCHAR2 DEFAULT NULL,
3021                        X_global_attribute1              VARCHAR2 DEFAULT NULL,
3022                        X_global_attribute2              VARCHAR2 DEFAULT NULL,
3023                        X_global_attribute3              VARCHAR2 DEFAULT NULL,
3024                        X_global_attribute4              VARCHAR2 DEFAULT NULL,
3025                        X_global_attribute5              VARCHAR2 DEFAULT NULL,
3026                        X_global_attribute6              VARCHAR2 DEFAULT NULL,
3027                        X_global_attribute7              VARCHAR2 DEFAULT NULL,
3028                        X_global_attribute8              VARCHAR2 DEFAULT NULL,
3029                        X_global_attribute9              VARCHAR2 DEFAULT NULL,
3030                        X_global_attribute10             VARCHAR2 DEFAULT NULL,
3031                        X_global_attribute11             VARCHAR2 DEFAULT NULL,
3032                        X_global_attribute12             VARCHAR2 DEFAULT NULL,
3033                        X_global_attribute13             VARCHAR2 DEFAULT NULL,
3034                        X_global_attribute14             VARCHAR2 DEFAULT NULL,
3035                        X_global_attribute15             VARCHAR2 DEFAULT NULL,
3036                        X_global_attribute16             VARCHAR2 DEFAULT NULL,
3037                        X_global_attribute17             VARCHAR2 DEFAULT NULL,
3038                        X_global_attribute18             VARCHAR2 DEFAULT NULL,
3039                        X_global_attribute19             VARCHAR2 DEFAULT NULL,
3040                        X_global_attribute20             VARCHAR2 DEFAULT NULL,
3041                        X_Calling_Sequence               VARCHAR2,
3042                        -- Invoice Lines Project Stage 1
3043                        X_rounding_amt                   NUMBER DEFAULT NULL,
3044                        X_charge_applicable_to_dist_id    NUMBER DEFAULT NULL,
3045                        X_corrected_invoice_dist_id      NUMBER DEFAULT NULL,
3046                        X_related_id                     NUMBER DEFAULT NULL,
3047                        X_asset_book_type_code           VARCHAR2 DEFAULT NULL,
3048                        X_asset_category_id              NUMBER DEFAULT NULL,
3049 		       X_intended_use			VARCHAR2 DEFAULT NULL
3050   ) IS
3051     current_calling_sequence VARCHAR2(2000);
3052     debug_info               VARCHAR2(100);
3053 
3054   BEGIN
3055 
3056     -- Update the calling sequence
3057     --
3058     current_calling_sequence :=
3059     'AP_INVOICE_DISTRIBUTIONS_PKG.Update_Row<-'||X_Calling_Sequence;
3060 
3061      AP_AID_TABLE_HANDLER_PKG.Update_Row
3062              (X_Rowid,
3063               X_Invoice_Id,
3064               -- Invoice Lines Project Stage 1
3065               X_Invoice_Line_number,
3066               X_Distribution_Class,
3067               X_Dist_Code_Combination_Id,
3068               X_Last_Update_Date,
3069               X_Last_Updated_By,
3070               X_Accounting_Date,
3071               X_Period_Name,
3072               X_Set_Of_Books_Id,
3073               X_Amount,
3074               X_Description,
3075               X_Type_1099,
3076               X_Posted_Flag,
3077               X_Batch_Id,
3078               X_Quantity_Invoiced,
3079               X_Unit_Price,
3080               X_Match_Status_Flag,
3081               X_Attribute_Category,
3082               X_Attribute1,
3083               X_Attribute2,
3084               X_Attribute3,
3085               X_Attribute4,
3086               X_Attribute5,
3087               X_Prepay_Amount_Remaining,
3088               X_Assets_Addition_Flag,
3089               X_Assets_Tracking_Flag,
3090               X_Distribution_Line_Number,
3091               X_Line_Type_Lookup_Code,
3092               X_Po_Distribution_Id,
3093               X_Base_Amount,
3094               X_Pa_Addition_Flag,
3095               X_Posted_Amount,
3096               X_Posted_Base_Amount,
3097               X_Encumbered_Flag,
3098               X_Accrual_Posted_Flag,
3099               X_Cash_Posted_Flag,
3100               X_Last_Update_Login,
3101               X_Stat_Amount,
3102               X_Attribute11,
3103               X_Attribute12,
3104               X_Attribute13,
3105               X_Attribute14,
3106               X_Attribute6,
3107               X_Attribute7,
3108               X_Attribute8,
3109               X_Attribute9,
3110               X_Attribute10,
3111               X_Attribute15,
3112               X_Accts_Pay_Code_Comb_Id,
3113               X_Reversal_Flag,
3114               X_Parent_Invoice_Id,
3115               X_Income_Tax_Region,
3116               X_Final_Match_Flag,
3117               X_Expenditure_Item_Date,
3118               X_Expenditure_Organization_Id,
3119               X_Expenditure_Type,
3120               X_Pa_Quantity,
3121               X_Project_Id,
3122               X_Task_Id,
3123               X_Quantity_Variance,
3124               X_Base_Quantity_Variance,
3125               X_Packet_Id,
3126               X_Awt_Flag,
3127               X_Awt_Group_Id,
3128 	      X_Pay_Awt_Group_Id,--bug6639866
3129               X_Awt_Tax_Rate_Id,
3130               X_Awt_Gross_Amount,
3131               X_Reference_1,
3132               X_Reference_2,
3133               X_Org_Id,
3134               X_Other_Invoice_Id,
3135               X_Awt_Invoice_Id,
3136               X_Awt_Origin_Group_Id,
3137               X_Program_Application_Id,
3138               X_Program_Id,
3139               X_Program_Update_Date,
3140               X_Request_Id,
3141               X_Tax_Recoverable_Flag,
3142               X_Award_Id,
3143               X_Start_Expense_Date,
3144               X_Merchant_Document_Number,
3145               X_Merchant_Name,
3146               X_Merchant_Tax_Reg_Number,
3147               X_Merchant_Taxpayer_Id,
3148               X_Country_Of_Supply,
3149               X_Merchant_Reference,
3150               X_global_attribute_category,
3151               X_global_attribute1,
3152               X_global_attribute2,
3153               X_global_attribute3,
3154               X_global_attribute4,
3155               X_global_attribute5,
3156               X_global_attribute6,
3157               X_global_attribute7,
3158               X_global_attribute8,
3159               X_global_attribute9,
3160               X_global_attribute10,
3161               X_global_attribute11,
3162               X_global_attribute12,
3163               X_global_attribute13,
3164               X_global_attribute14,
3165               X_global_attribute15,
3166               X_global_attribute16,
3167               X_global_attribute17,
3168               X_global_attribute18,
3169               X_global_attribute19,
3170               X_global_attribute20,
3171               current_calling_sequence,
3172               -- Invoice Lines Project Stage 1
3173               X_rounding_amt,
3174               X_charge_applicable_to_dist_id,
3175               X_corrected_invoice_dist_id,
3176               X_related_id,
3177               X_asset_book_type_code,
3178               X_asset_category_id,
3179 	      X_intended_use
3180              );
3181 
3182 
3183   EXCEPTION
3184     WHEN OTHERS THEN
3185       if (SQLCODE <> -20001) then
3186         FND_MESSAGE.SET_NAME('SQLAP', 'AP_DEBUG');
3187         FND_MESSAGE.SET_TOKEN('ERROR', SQLERRM);
3188         FND_MESSAGE.SET_TOKEN('CALLING_SEQUENCE', current_calling_sequence);
3189         FND_MESSAGE.SET_TOKEN('DEBUG_INFO', debug_info);
3190       end if;
3191       APP_EXCEPTION.RAISE_EXCEPTION;
3192 
3193   END Update_Row;
3194 
3195 
3196  PROCEDURE Delete_Row(X_Rowid            VARCHAR2,
3197                        X_Calling_Sequence VARCHAR2) IS
3198     current_calling_sequence VARCHAR2(2000);
3199     debug_info               VARCHAR2(100);
3200     l_invoice_distribution_id       AP_INVOICE_DISTRIBUTIONS.INVOICE_DISTRIBUTION_ID%TYPE;
3201 
3202    BEGIN
3203 
3204     -- Update the calling sequence
3205     --
3206     current_calling_sequence :=
3207     'AP_INVOICE_DISTRIBUTIONS_PKG.Delete_Row<-'||X_Calling_Sequence;
3208 
3209      AP_AID_TABLE_HANDLER_PKG.Delete_Row(
3210        X_Rowid,
3211        current_calling_sequence);
3212 
3213   EXCEPTION
3214     WHEN OTHERS THEN
3215       if (SQLCODE <> -20001) then
3216         FND_MESSAGE.SET_NAME('SQLAP', 'AP_DEBUG');
3217         FND_MESSAGE.SET_TOKEN('ERROR', SQLERRM);
3218         FND_MESSAGE.SET_TOKEN('CALLING_SEQUENCE', current_calling_sequence);
3219         FND_MESSAGE.SET_TOKEN('DEBUG_INFO', debug_info);
3220       end if;
3221       APP_EXCEPTION.RAISE_EXCEPTION;
3222 
3223   END Delete_Row;
3224 
3225 
3226   FUNCTION Get_UOM_From_Segments(
3227           X_Concatenated_Segments         IN      VARCHAR2,
3228           X_Ch_Of_Accts_Id                IN      NUMBER)
3229   RETURN VARCHAR2 IS
3230 
3231        l_segments                      FND_FLEX_EXT.SEGMENTARRAY;
3232        l_num_segments                  NUMBER;
3233        l_account_segment_num           NUMBER;
3234        l_result                        BOOLEAN;
3235        l_segment_delimiter             VARCHAR2(1);
3236        l_uom                           gl_stat_account_uom.unit_of_measure%TYPE;
3237        l_status                        VARCHAR2(10) := '';
3238        l_industry                      VARCHAR2(10) := '';
3239 
3240   BEGIN
3241        -- Verify GL is installed
3242        --
3243        IF (FND_INSTALLATION.GET(101, 101, l_status, l_industry)) then
3244          IF (l_status <> 'I') then
3245            return('');
3246          END IF;
3247        ELSE
3248          return('');
3249        END IF;
3250 
3251        -- Get the delimiter used in the Accounting FF
3252        --
3253        l_segment_delimiter := FND_FLEX_EXT.GET_DELIMITER(
3254                                                 'SQLGL',
3255                                                 'GL#',
3256                                                 X_Ch_Of_Accts_Id);
3257 
3258        IF (l_segment_delimiter IS NULL) THEN
3259              RETURN('');
3260        END IF;
3261 
3262        -- Break the passed concatenated segment into an array of segments
3263        --
3264        IF (X_Concatenated_Segments IS NOT NULL) THEN
3265            l_num_segments := FND_FLEX_EXT.breakup_segments(X_concatenated_segments,
3266                                           l_segment_delimiter,
3267                                           l_segments); --OUT
3268        END IF;
3269 
3270        -- Get the index of the Account segment in the FF
3271        --
3272        l_result := FND_FLEX_APIS.GET_QUALIFIER_SEGNUM(
3273                                     101,
3274                                     'GL#',
3275                                     X_Ch_Of_Accts_Id,
3276                                     'GL_ACCOUNT',
3277                                     l_account_segment_num);
3278 
3279        IF (NOT l_result) THEN
3280            RETURN('');
3281        END IF;
3282 
3283        -- Using the segment array and the index: Get the UOM value
3284        --
3285        SELECT unit_of_measure
3286        INTO   l_uom
3287        FROM   gl_stat_account_uom
3288        WHERE  account_segment_value = l_segments(l_account_segment_num)
3289        AND chart_of_accounts_id = X_Ch_Of_Accts_Id;
3290 
3291        RETURN(l_uom);
3292 
3293   EXCEPTION
3294      WHEN OTHERS THEN
3295         RETURN('');
3296 
3297   END Get_UOM_From_Segments;
3298 
3299 
3300   -- Bug 1567235.
3301   /* Function to get the sum of distribution amount for a given invoice
3302      and the balancing segment  */
3303   FUNCTION Get_Segment_Dist_Amount(
3304            X_Invoice_Id                   IN      NUMBER,
3305            X_Prepay_Dist_CCID             IN      NUMBER,
3306            X_Sob_Id                       IN      NUMBER) RETURN NUMBER IS
3307 
3308   l_dist_amount    NUMBER;
3309 
3310   BEGIN
3311 
3312      -- Bug 1892826. Added the line_type_lookup_code predicate
3313      -- Bug 2404982.  Added package qualifier to procedure call.
3314      SELECT sum(amount)
3315        INTO l_dist_amount
3316        FROM ap_invoice_distributions
3317       WHERE invoice_id = X_Invoice_Id
3318         AND line_type_lookup_code IN ('ITEM','PREPAY')
3319         AND nvl(reversal_flag,'N') <> 'Y'
3320         AND AP_INVOICE_DISTRIBUTIONS_PKG.get_balancing_segment_value(
3321     dist_code_combination_id, X_Sob_Id) =
3322                 AP_INVOICE_DISTRIBUTIONS_PKG.get_balancing_segment_value(
3323     X_Prepay_Dist_CCID, X_Sob_Id);
3324 
3325      RETURN (l_dist_amount);
3326 
3327   END Get_Segment_Dist_Amount;
3328 
3329 
3330   -- Bug 1567235.
3331   /* Procedure to get the sum of distribution amount for a given invoice
3332      and the sum of the distribution amount for a given prepayment */
3333   PROCEDURE Get_Prepay_Amount_Available(
3334             X_Invoice_ID                   IN      NUMBER,
3335             X_Prepay_ID                    IN      NUMBER,
3336             X_Sob_Id                       IN      NUMBER,
3337             X_Balancing_Segment            OUT NOCOPY     VARCHAR2,
3338             X_Prepay_Amount                OUT NOCOPY     NUMBER,
3339             X_Invoice_Amount               OUT NOCOPY     NUMBER) IS
3340 
3341   l_prepay_amount         NUMBER;
3342   l_invoice_amount        NUMBER;
3343   l_bal_segment           VARCHAR2(30);
3344 
3345   -- Bug 2404982.  Added package qualifier to procedure call.
3346   CURSOR c_prepay_dist IS
3347   SELECT sum(nvl(prepay_amount_remaining,amount)),
3348          AP_INVOICE_DISTRIBUTIONS_PKG.get_balancing_segment_value(
3349     aip.dist_code_combination_id, X_Sob_Id)
3350     FROM ap_invoice_distributions aip
3351    WHERE aip.invoice_id = X_Prepay_Id
3352      --bugfix:3881673
3353      AND aip.line_type_lookup_code in ('ITEM','ACCRUAL')
3354      AND nvl(aip.reversal_flag,'N') <> 'Y'
3355      AND nvl(aip.prepay_amount_remaining,amount) > 0
3356      AND AP_INVOICE_DISTRIBUTIONS_PKG.get_balancing_segment_value(
3357     aip.dist_code_combination_id, X_Sob_Id) IN
3358              (SELECT AP_INVOICE_DISTRIBUTIONS_PKG.get_balancing_segment_value(
3359     aid.dist_code_combination_id, X_Sob_Id)
3360                 FROM ap_invoice_distributions aid
3361                WHERE aid.invoice_id = X_Invoice_ID)
3362    GROUP BY AP_INVOICE_DISTRIBUTIONS_PKG.get_balancing_segment_value(
3363     aip.dist_code_combination_id, X_Sob_Id)
3364    ORDER BY AP_INVOICE_DISTRIBUTIONS_PKG.get_balancing_segment_value(
3365     aip.dist_code_combination_id, X_Sob_Id);
3366 
3367   BEGIN
3368 
3369      OPEN c_prepay_dist;
3370      LOOP
3371        FETCH c_prepay_dist into l_prepay_amount, l_bal_segment;
3372        EXIT WHEN c_prepay_dist%NOTFOUND;
3373 
3374   -- Bug 2404982.  Added package qualifier to procedure call
3375        SELECT sum(amount)
3376          INTO l_invoice_amount
3377          FROM ap_invoice_distributions
3378         WHERE invoice_id = X_Invoice_ID
3379           AND line_type_lookup_code IN ('ITEM','PREPAY')
3380           AND nvl(reversal_flag,'N') <> 'Y'
3381           AND AP_INVOICE_DISTRIBUTIONS_PKG.get_balancing_segment_value(
3382     dist_code_combination_id, X_Sob_Id)
3383                    = l_bal_segment;
3384 
3385        IF l_invoice_amount <> 0 THEN
3386           EXIT;
3387        END IF;
3388 
3389      END LOOP;
3390      CLOSE c_prepay_dist;
3391 
3392      X_Balancing_Segment := l_bal_segment;
3393      X_Prepay_Amount := l_prepay_amount;
3394      X_Invoice_Amount := l_invoice_amount;
3395 
3396   END Get_Prepay_Amount_Available;
3397 
3398 
3399   -- Bug 1648309.
3400   /* Function to check if an invoice has item lines with different balancing
3401      segments. */
3402   FUNCTION Check_Diff_Dist_Segments(
3403            X_Invoice_Id                   IN      NUMBER,
3404            X_Sob_Id                       IN      NUMBER) RETURN BOOLEAN IS
3405 
3406   l_dist_count         NUMBER;
3407 
3408   BEGIN
3409 
3410   --Bug 2404982. Added package qualifier to procedure call.
3411      SELECT count(distinct(
3412                  AP_INVOICE_DISTRIBUTIONS_PKG.get_balancing_segment_value(
3413                  dist_code_combination_id, X_Sob_Id)) )
3414        INTO l_dist_count
3415        FROM ap_invoice_distributions
3416       WHERE invoice_id = X_Invoice_Id;
3417 
3418      IF l_dist_count > 1 THEN
3419         RETURN (TRUE);
3420      ELSE
3421         RETURN (FALSE);
3422      END IF;
3423 
3424   END Check_Diff_Dist_Segments;
3425 
3426 
3427   -- Bug 1567235
3428   /* Function to get the value of the balancing segment for a given
3429      CCID */
3430 FUNCTION get_balancing_segment_value(
3431          X_Dist_Code_Combination_Id      IN      NUMBER,
3432          X_Sob_Id                        IN      NUMBER) RETURN VARCHAR2 IS
3433 
3434   l_dist_segments            FND_FLEX_EXT.SEGMENTARRAY ;
3435   l_segments                 FND_FLEX_EXT.SEGMENTARRAY ;
3436   l_num_of_segments          NUMBER ;
3437   l_result                   BOOLEAN ;
3438   l_coa_id                   NUMBER ;
3439   l_flex_segment_num         NUMBER ;
3440 
3441 BEGIN
3442 
3443   SELECT chart_of_accounts_id
3444   INTO   l_coa_id
3445   FROM   gl_sets_of_books
3446   WHERE  set_of_books_id = X_Sob_Id;
3447 
3448   -- Get the segments of the two given accounts
3449   IF (NOT FND_FLEX_EXT.GET_SEGMENTS('SQLGL', 'GL#',
3450                                     l_coa_id,
3451                                     X_Dist_Code_Combination_Id,
3452                                     l_num_of_segments,
3453                                     l_dist_segments)
3454      ) THEN
3455 
3456     -- Return -1 if flex failed
3457     RETURN (-1);
3458 
3459   END IF;
3460 
3461   IF (NOT FND_FLEX_APIS.GET_QUALIFIER_SEGNUM(
3462                               101, 'GL#',
3463                               l_coa_id,
3464                               'GL_BALANCING',
3465                               l_flex_segment_num)
3466      ) THEN
3467 
3468     RETURN (-1);
3469 
3470   END IF;
3471 
3472   FOR i IN 1.. l_num_of_segments LOOP
3473 
3474     IF (i = l_flex_segment_num) THEN
3475         RETURN(l_dist_segments(i));
3476     END IF;
3477 
3478   END LOOP;
3479 
3480 END Get_Balancing_Segment_Value;
3481 
3482   -- Bug 2118673
3483   /* Function to get the value of the balancing segment for a given
3484      account */
3485 FUNCTION get_balancing_seg_from_acc(
3486          X_account      IN      VARCHAR2,
3487          X_Sob_Id       IN      NUMBER) RETURN VARCHAR2 IS
3488 
3489   l_delimiter                VARCHAR2(1);
3490   l_dist_segments            FND_FLEX_EXT.SEGMENTARRAY ;
3491   l_num_of_segments          NUMBER ;
3492   l_coa_id                   NUMBER ;
3493   l_flex_segment_num         NUMBER ;
3494 
3495 BEGIN
3496 
3497   SELECT chart_of_accounts_id
3498   INTO   l_coa_id
3499   FROM   gl_sets_of_books
3500   WHERE  set_of_books_id = X_Sob_Id;
3501 
3502   -- Get the delimiter
3503   l_delimiter := FND_FLEX_EXT.GET_DELIMITER('SQLGL', 'GL#', l_coa_id);
3504 
3505   -- Get the segments
3506   l_num_of_segments := FND_FLEX_EXT.BREAKUP_SEGMENTS(
3507                                       x_account, l_delimiter,
3508                                       l_dist_segments);
3509 
3510   -- Get the balancing segment number
3511   IF (NOT FND_FLEX_APIS.GET_QUALIFIER_SEGNUM(
3512                               101, 'GL#',
3513                               l_coa_id,
3514                               'GL_BALANCING',
3515                               l_flex_segment_num)) THEN
3516 
3517     RETURN (-1);
3518   END IF;
3519 
3520   IF l_flex_segment_num > 0 AND l_flex_segment_num <= l_num_of_segments THEN
3521         RETURN(l_dist_segments(l_flex_segment_num));
3522   ELSE
3523         RETURN(NULL);
3524   END IF;
3525 END Get_Balancing_Seg_from_acc;
3526 
3527 
3528 
3529 
3530   PROCEDURE Round_Biggest_Distribution(
3531           X_Base_Currency_Code IN VARCHAR2,
3532           X_Invoice_Id         IN NUMBER,
3533           X_Calling_Sequence   IN VARCHAR2) IS
3534 
3535     current_calling_sequence VARCHAR2(2000);
3536     debug_info               VARCHAR2(100);
3537 
3538   BEGIN
3539 
3540     -- Update current calling sequence
3541     --
3542     current_calling_sequence :=
3543     'AP_INVOICE_DISTRIBUTIONS_PKG.Round_Biggest_Distribution<-'
3544        ||X_Calling_Sequence;
3545 
3546     debug_info := 'Adjusting distribution amount in biggest distribution';
3547 
3548     -- bug 5052661 --  modified SELECT portion of SQL in where clause to go to base tables to avoid FTS
3549     UPDATE ap_invoice_distributions d1
3550        SET base_amount =
3551            (SELECT DECODE(SIGN(SUM(d2.base_amount) -
3552                             DECODE(max(f.minimum_accountable_unit), NULL,
3553                                    ROUND((SUM(d2.amount)
3554                                           * i.exchange_rate),MAX(f.precision)),
3555                                    ROUND((SUM(d2.amount) * i.exchange_rate)
3556                                          / MAX(f.minimum_accountable_unit)) *
3557                                    MAX(f.minimum_accountable_unit))),
3558                         1, d1.base_amount
3559                             - (SUM(d2.base_amount) -
3560                                DECODE(MAX(f.minimum_accountable_unit), NULL,
3561                                       ROUND((SUM(d2.amount)
3562                                              * i.exchange_rate),
3563                                             MAX(f.precision)),
3564                                       ROUND((SUM(d2.amount) * i.exchange_rate)
3565                                             / MAX(f.minimum_accountable_unit))*
3566                                       MAX(f.minimum_accountable_unit))),
3567                         -1, d1.base_amount
3568                              - (SUM(d2.base_amount) -
3569                                 DECODE(MAX(f.minimum_accountable_unit), NULL,
3570                                        ROUND((SUM(d2.amount) *
3571                                               i.exchange_rate),
3572                                              MAX(f.precision)),
3573                                        ROUND((SUM(d2.amount) * i.exchange_rate)
3574                                             /MAX(f.minimum_accountable_unit))*
3575                                        MAX(f.minimum_accountable_unit))),
3576                         d1.base_amount)
3577               FROM ap_invoices i, ap_invoice_distributions d2, fnd_currencies F
3578              WHERE d1.invoice_id = i.invoice_id
3579                AND d1.invoice_id = d2.invoice_id
3580                AND f.currency_code = X_Base_Currency_Code
3581              GROUP BY i.exchange_rate)
3582      WHERE d1.invoice_id = X_Invoice_Id
3583        AND d1.posted_flag = 'N'
3584        AND (d1.invoice_id, d1.distribution_line_number) IN
3585            (SELECT d5.invoice_id, MAX(d5.distribution_line_number)
3586               FROM ap_invoice_distributions_all d5
3587              WHERE (d5.invoice_id, abs(d5.amount)) IN
3588                 (SELECT i1.invoice_id , MAX(ABS(d3.amount))
3589                    FROM ap_invoices_all i1, ap_invoice_distributions_all d3
3590                   WHERE i1.invoice_id = X_Invoice_Id
3591                     AND i1.invoice_id = d3.invoice_id
3592                     AND d3.line_type_lookup_code <> 'TAX'
3593                     AND NOT EXISTS
3594                       (SELECT d4.invoice_id
3595                          FROM ap_invoice_distributions_all d4
3596                         WHERE d4.invoice_id = X_Invoice_Id
3597                           AND (1 = DECODE(X_Base_Currency_Code,
3598                                       i1.invoice_currency_code,1,
3599                                       DECODE(d4.exchange_rate,null,1,0))
3600                            OR    1 = DECODE(X_Base_Currency_Code,
3601                                      i1.invoice_currency_code,
3602                                      1,DECODE(d4.base_amount,null,1,0))))
3603                   GROUP BY i1.invoice_id, i1.invoice_amount
3604                  HAVING nvl(i1.invoice_amount,0) = nvl(sum(d3.amount),0))
3605              GROUP BY d5.invoice_id);
3606 
3607 
3608   EXCEPTION
3609     WHEN OTHERS THEN
3610       IF (SQLCODE <> -20001) THEN
3611         FND_MESSAGE.SET_NAME('SQLAP', 'AP_DEBUG');
3612         FND_MESSAGE.SET_TOKEN('ERROR', SQLERRM);
3613         FND_MESSAGE.SET_TOKEN('CALLING_SEQUENCE', current_calling_sequence);
3614         FND_MESSAGE.SET_TOKEN('DEBUG_INFO', debug_info);
3615       END IF;
3616       APP_EXCEPTION.RAISE_EXCEPTION;
3617 
3618   END Round_Biggest_Distribution;
3619 
3620 
3621   -----------------------------------------------------------------------
3622   -- FUNCTION insert_single_dist_from_line inserts a record into
3623   -- ap_invoice_distributions given a line number number and/or line record.
3624   -- It returns FALSE if an error is encountered.
3625   -----------------------------------------------------------------------
3626   FUNCTION Insert_Single_Dist_From_Line(
3627            X_batch_id            IN         AP_INVOICES.BATCH_ID%TYPE,
3628            X_invoice_id          IN         NUMBER,
3629            X_invoice_date        IN         AP_INVOICES.INVOICE_DATE%TYPE,
3630            X_vendor_id           IN         AP_INVOICES.VENDOR_ID%TYPE,
3631            X_invoice_currency    IN         AP_INVOICES.INVOICE_CURRENCY_CODE%TYPE,
3632            X_exchange_rate       IN         AP_INVOICES.EXCHANGE_RATE%TYPE,
3633            X_exchange_rate_type  IN         AP_INVOICES.EXCHANGE_RATE_TYPE%TYPE,
3634            X_exchange_date       IN         AP_INVOICES.EXCHANGE_DATE%TYPE,
3635            X_line_number         IN         NUMBER,
3636            X_invoice_lines_rec   IN         AP_INVOICES_PKG.r_invoice_line_rec,
3637            X_line_source         IN         VARCHAR2,
3638            X_Generate_Permanent  IN         VARCHAR2 DEFAULT 'N',
3639            X_Validate_Info       IN         BOOLEAN DEFAULT TRUE,
3640            X_Error_Code          OUT NOCOPY VARCHAR2,
3641            X_Debug_Info          OUT NOCOPY VARCHAR2,
3642            X_Debug_Context       OUT NOCOPY VARCHAR2,
3643            X_Msg_Application     OUT NOCOPY VARCHAR2,
3644            X_Msg_Data            OUT NOCOPY VARCHAR2,
3645            X_Calling_Sequence    IN         VARCHAR2) RETURN BOOLEAN
3646   IS
3647 
3648   CURSOR line_rec IS
3649   SELECT INVOICE_ID,
3650       LINE_NUMBER,
3651       LINE_TYPE_LOOKUP_CODE,
3652       REQUESTER_ID,
3653       DESCRIPTION,
3654       LINE_SOURCE,
3655       ORG_ID,
3656       LINE_GROUP_NUMBER,
3657       INVENTORY_ITEM_ID,
3658       ITEM_DESCRIPTION,
3659       SERIAL_NUMBER,
3660       MANUFACTURER,
3661       MODEL_NUMBER,
3662       WARRANTY_NUMBER,
3663       GENERATE_DISTS,
3664       MATCH_TYPE,
3665       DISTRIBUTION_SET_ID,
3666       ACCOUNT_SEGMENT,
3667       BALANCING_SEGMENT,
3668       COST_CENTER_SEGMENT,
3669       OVERLAY_DIST_CODE_CONCAT,
3670       DEFAULT_DIST_CCID,
3671       PRORATE_ACROSS_ALL_ITEMS,
3672       ACCOUNTING_DATE,
3673       PERIOD_NAME,
3674       DEFERRED_ACCTG_FLAG,
3675       DEF_ACCTG_START_DATE,
3676       DEF_ACCTG_END_DATE,
3677       DEF_ACCTG_NUMBER_OF_PERIODS,
3678       DEF_ACCTG_PERIOD_TYPE,
3679       SET_OF_BOOKS_ID,
3680       AMOUNT,
3681       BASE_AMOUNT,
3682       ROUNDING_AMT,
3683       QUANTITY_INVOICED,
3684       UNIT_MEAS_LOOKUP_CODE,
3685       UNIT_PRICE,
3686       WFAPPROVAL_STATUS,
3687       DISCARDED_FLAG,
3688       ORIGINAL_AMOUNT,
3689       ORIGINAL_BASE_AMOUNT,
3690       ORIGINAL_ROUNDING_AMT,
3691       CANCELLED_FLAG,
3692       INCOME_TAX_REGION,
3693       TYPE_1099,
3694       STAT_AMOUNT,
3695       PREPAY_INVOICE_ID,
3696       PREPAY_LINE_NUMBER,
3697       INVOICE_INCLUDES_PREPAY_FLAG,
3698       CORRECTED_INV_ID,
3699       CORRECTED_LINE_NUMBER,
3700       PO_HEADER_ID,
3701       PO_LINE_ID,
3702       PO_RELEASE_ID,
3703       PO_LINE_LOCATION_ID,
3704       PO_DISTRIBUTION_ID,
3705       RCV_TRANSACTION_ID,
3706       FINAL_MATCH_FLAG,
3707       ASSETS_TRACKING_FLAG,
3708       ASSET_BOOK_TYPE_CODE,
3709       ASSET_CATEGORY_ID,
3710       PROJECT_ID,
3711       TASK_ID,
3712       EXPENDITURE_TYPE,
3713       EXPENDITURE_ITEM_DATE,
3714       EXPENDITURE_ORGANIZATION_ID,
3715       PA_QUANTITY,
3716       PA_CC_AR_INVOICE_ID,
3717       PA_CC_AR_INVOICE_LINE_NUM ,
3718       PA_CC_PROCESSED_CODE,
3719       AWARD_ID,
3720       AWT_GROUP_ID,
3721       REFERENCE_1,
3722       REFERENCE_2,
3723       RECEIPT_VERIFIED_FLAG,
3724       RECEIPT_REQUIRED_FLAG,
3725       RECEIPT_MISSING_FLAG,
3726       JUSTIFICATION,
3727       EXPENSE_GROUP,
3728       START_EXPENSE_DATE,
3729       END_EXPENSE_DATE,
3730       RECEIPT_CURRENCY_CODE,
3731       RECEIPT_CONVERSION_RATE,
3732       RECEIPT_CURRENCY_AMOUNT,
3733       DAILY_AMOUNT,
3734       WEB_PARAMETER_ID,
3735       ADJUSTMENT_REASON,
3736       MERCHANT_DOCUMENT_NUMBER,
3737       MERCHANT_NAME,
3738       MERCHANT_REFERENCE,
3739       MERCHANT_TAX_REG_NUMBER,
3740       MERCHANT_TAXPAYER_ID,
3741       COUNTRY_OF_SUPPLY,
3742       CREDIT_CARD_TRX_ID,
3743       COMPANY_PREPAID_INVOICE_ID,
3744       CC_REVERSAL_FLAG,
3745       CREATION_DATE,
3746       CREATED_BY,
3747       LAST_UPDATED_BY,
3748       LAST_UPDATE_DATE,
3749       LAST_UPDATE_LOGIN,
3750       PROGRAM_APPLICATION_ID,
3751       PROGRAM_ID,
3752       PROGRAM_UPDATE_DATE,
3753       REQUEST_ID,
3754       ATTRIBUTE_CATEGORY,
3755       ATTRIBUTE1,
3756       ATTRIBUTE2,
3757       ATTRIBUTE3,
3758       ATTRIBUTE4,
3759       ATTRIBUTE5,
3760       ATTRIBUTE6,
3761       ATTRIBUTE7,
3762       ATTRIBUTE8,
3763       ATTRIBUTE9,
3764       ATTRIBUTE10,
3765       ATTRIBUTE11,
3766       ATTRIBUTE12,
3767       ATTRIBUTE13,
3768       ATTRIBUTE14,
3769       ATTRIBUTE15,
3770       GLOBAL_ATTRIBUTE_CATEGORY,
3771       GLOBAL_ATTRIBUTE1,
3772       GLOBAL_ATTRIBUTE2,
3773       GLOBAL_ATTRIBUTE3,
3774       GLOBAL_ATTRIBUTE4,
3775       GLOBAL_ATTRIBUTE5,
3776       GLOBAL_ATTRIBUTE6,
3777       GLOBAL_ATTRIBUTE7,
3778       GLOBAL_ATTRIBUTE8,
3779       GLOBAL_ATTRIBUTE9,
3780       GLOBAL_ATTRIBUTE10,
3781       GLOBAL_ATTRIBUTE11,
3782       GLOBAL_ATTRIBUTE12,
3783       GLOBAL_ATTRIBUTE13,
3784       GLOBAL_ATTRIBUTE14,
3785       GLOBAL_ATTRIBUTE15,
3786       GLOBAL_ATTRIBUTE16,
3787       GLOBAL_ATTRIBUTE17,
3788       GLOBAL_ATTRIBUTE18,
3789       GLOBAL_ATTRIBUTE19,
3790       GLOBAL_ATTRIBUTE20,
3791       --ETAX: Invwkb, added included_tax_amount as modified the def
3792       --of ap_invoices_pkg.r_invoice_line_rec
3793       INCLUDED_TAX_AMOUNT,
3794       PRIMARY_INTENDED_USE,
3795       APPLICATION_ID,
3796       PRODUCT_TABLE,
3797       REFERENCE_KEY1,
3798       REFERENCE_KEY2,
3799       REFERENCE_KEY3,
3800       REFERENCE_KEY4,
3801       REFERENCE_KEY5,
3802       --bugfix:4674194
3803       SHIP_TO_LOCATION_ID,
3804       --bug7022001
3805       PAY_AWT_GROUP_ID
3806      FROM ap_invoice_lines_all
3807     WHERE invoice_id = X_invoice_id
3808       AND line_number = X_line_number;
3809 
3810 
3811   l_invoice_line_rec            AP_INVOICES_PKG.r_invoice_line_rec;
3812 
3813   l_distribution_class
3814       AP_INVOICE_DISTRIBUTIONS.DISTRIBUTION_CLASS%TYPE;
3815   l_dist_ccid
3816       AP_INVOICE_DISTRIBUTIONS.DIST_CODE_COMBINATION_ID%TYPE;
3817   l_base_currency_code         AP_SYSTEM_PARAMETERS.BASE_CURRENCY_CODE%TYPE;
3818   l_chart_of_accounts_id       GL_SETS_OF_BOOKS.CHART_OF_ACCOUNTS_ID%TYPE;
3819   l_account_type               GL_CODE_COMBINATIONS.ACCOUNT_TYPE%TYPE;
3820   l_assets_tracking_flag
3821       AP_INVOICE_DISTRIBUTIONS.ASSETS_TRACKING_FLAG%TYPE;
3822   l_employee_id                AP_SUPPLIERS.EMPLOYEE_ID%TYPE;
3823   l_accounting_date            AP_INVOICE_LINES.ACCOUNTING_DATE%TYPE;
3824   l_open_gl_date               AP_INVOICE_LINES.ACCOUNTING_DATE%TYPE;
3825   l_open_period_name           AP_INVOICE_LINES.PERIOD_NAME%TYPE;
3826   user_id                      NUMBER;
3827   l_msg_application            VARCHAR2(25);
3828   l_msg_type                   VARCHAR2(25);
3829   l_msg_token1                 VARCHAR2(30);
3830   l_msg_token2                 VARCHAR2(30);
3831   l_msg_token3                 VARCHAR2(30);
3832   l_msg_count                  NUMBER;
3833   l_msg_data                   VARCHAR2(30);
3834   l_billable_flag              VARCHAR2(25);
3835   l_pa_allows_overrides        VARCHAR2(1) := 'N';
3836   l_error_found                VARCHAR2(1) := 'N';
3837   l_existing_distributions     NUMBER := 0;
3838   l_unbuilt_flex               VARCHAR2(240):='';
3839   l_reason_unbuilt_flex        VARCHAR2(2000):='';
3840   current_calling_sequence     VARCHAR2(2000);
3841   debug_info                   VARCHAR2(100);
3842   debug_context                VARCHAR2(2000);
3843   l_dist_code_concat           VARCHAR2(2000);
3844   l_invoice_distribution_id
3845       ap_invoice_distributions.invoice_distribution_id%TYPE;
3846   l_invoice_type_lookup_code   ap_invoices_all.invoice_type_lookup_code%TYPE;
3847   l_sys_link_function          VARCHAR2(2); /* Bug 5102724 */
3848   l_web_parameter_id           number; --Bug5003249
3849   l_employee_ccid              number;
3850   l_message_text	       fnd_new_messages.message_text%type;
3851 
3852   BEGIN
3853 
3854   --------------------------------------------------------------------------
3855   -- Step 1 - Update the calling sequence
3856   --------------------------------------------------------------------------
3857   current_calling_sequence :=
3858       'AP_INVOICE_DISTRIBUTIONS_PKG.insert_single_dist_from_line <-'||
3859       X_calling_sequence;
3860 
3861   --------------------------------------------------------------------------
3862   -- Step 2 - If calling module provided X_invoice_id / X_line_number, then
3863   -- we assume the calling module is not passing a line record.  Read the line
3864   -- record from the transaction tables.
3865   -------------------------------------------------------------------------
3866   debug_info := 'Verify line record';
3867   IF (X_invoice_id IS NOT NULL AND X_line_number IS NOT NULL) THEN
3868     BEGIN
3869       OPEN line_rec;
3870       FETCH line_rec INTO l_invoice_line_rec;
3871       IF (line_rec%NOTFOUND) THEN
3872         CLOSE line_rec;
3873         RAISE NO_DATA_FOUND;
3874       END IF;
3875       CLOSE line_Rec;
3876     EXCEPTION
3877       WHEN NO_DATA_FOUND THEN
3878         debug_info := debug_info ||': No valid line record was found.';
3879         X_debug_context := current_calling_sequence;
3880         X_debug_info := debug_info;
3881         return(FALSE);
3882     END;
3883   ELSE
3884     l_invoice_line_rec := X_invoice_lines_rec;
3885     IF (X_invoice_lines_rec.invoice_id IS NULL AND
3886         X_invoice_lines_rec.line_number is NULL ) THEN
3887       X_debug_info := debug_info || ': line not provided';
3888       X_debug_context := current_calling_sequence;
3889       RETURN (FALSE);
3890     END IF;
3891   END IF;
3892 
3893   ----------------------------------------------------------------------------
3894   -- Step 3 - Validate line does not contain other distributions
3895   ----------------------------------------------------------------------------
3896   IF (X_Validate_Info) then
3897     debug_info := 'Verify line does not contain distributions';
3898     BEGIN
3899       SELECT count(*)
3900       INTO l_existing_distributions
3901       FROM ap_invoice_distributions
3902      WHERE invoice_id = l_invoice_line_rec.invoice_id
3903        AND invoice_line_number = l_invoice_line_rec.line_number;
3904 
3905       IF (l_existing_distributions <> 0) then
3906         X_debug_info := debug_info || ': line already has distributions';
3907         X_debug_context := current_calling_sequence;
3908         RETURN(FALSE);
3909       END IF;
3910 
3911     EXCEPTION
3912       WHEN OTHERS THEN
3913       NULL;
3914     END;
3915   END IF; -- If calling module requested validation
3916 
3917   ----------------------------------------------------------------------------
3918   -- Step 4 - Get GL Date and Period name.  Only if not called from the
3919   -- Open interface since Validation of the Import already verifies gl date
3920   -- nd period.
3921   ----------------------------------------------------------------------------
3922   IF (nvl(X_line_source, 'OTHERS') <> 'IMPORT') then
3923     debug_info := 'Get gl date from open period if line gl date is in' ||
3924                   'a closed one';
3925     BEGIN
3926       l_open_period_name := NULL;
3927 
3928       l_open_period_name :=
3929         AP_UTILITIES_PKG.GET_CURRENT_GL_DATE(
3930                 l_invoice_line_rec.accounting_date,
3931 	        l_invoice_line_rec.org_id);
3932 
3933       IF (l_open_period_name is NULL) then
3934         AP_UTILITIES_PKG.GET_OPEN_GL_DATE(l_invoice_line_rec.accounting_date,
3935                                           l_open_period_name,
3936                                           l_open_gl_date);
3937       --Invoice Lines: Distributions
3938       --For the case when the accounting_date on the line fell in an open
3939       --period, we were trying to insert NULL into a NOT NULL column
3940       --accounting_date, since the variable l_open_gl_date was not being
3941       --populated properly.
3942       ELSE
3943         l_open_gl_date := l_invoice_line_rec.accounting_date;
3944       END IF;
3945       IF (l_open_period_name is NULL) then
3946         X_error_code := 'AP_NO_OPEN_PERIOD';
3947         RETURN(FALSE);
3948       END IF;
3949     END;
3950   ELSE
3951     l_open_period_name := l_invoice_line_rec.period_name;
3952     l_open_gl_date := l_invoice_line_rec.accounting_date;
3953   END IF;
3954 
3955   --------------------------------------------------------------
3956   -- Step 5 - Get system level information necessary for
3957   -- validation and generation of distributions
3958   --------------------------------------------------------------
3959   debug_info := 'Get system information';
3960   BEGIN
3961     SELECT gsob.chart_of_accounts_id, ap.base_currency_code
3962       INTO l_chart_of_accounts_id, l_base_currency_code
3963       FROM ap_system_parameters ap, gl_sets_of_books gsob
3964      WHERE ap.set_of_books_id = gsob.set_of_books_id
3965        AND ap.set_of_books_id = l_invoice_line_rec.set_of_books_id;
3966 
3967   EXCEPTION
3968     WHEN NO_DATA_FOUND THEN
3969       Debug_info := debug_info || ': No GL information was found';
3970       X_debug_context := current_calling_sequence;
3971       X_debug_info := debug_info;
3972     RETURN(FALSE);
3973   END;
3974 
3975 
3976   ----------------------------------------------------------------------------
3977   -- Step 6 - Get Expenditure Item Date if PA related and if validation
3978   -- requested validate PA information. Note that expenditure item date may
3979   -- already be populated when the process is called from the Interface Import
3980   -- in which case we bypass getting the expenditure item date.
3981 
3982   ----------------------------------------------------------------------------
3983   debug_info := 'Get expenditure item date and validate if PA related';
3984   IF (l_invoice_line_rec.project_id is not null) then
3985     IF (l_invoice_line_rec.expenditure_item_date is null) then
3986       l_invoice_line_rec.expenditure_item_date :=
3987            AP_INVOICES_PKG.get_expenditure_item_date(
3988                                          l_invoice_line_rec.invoice_id,
3989                                          X_invoice_date,
3990                                          l_open_GL_date,
3991                                          NULL,
3992                                          NULL,
3993                                          l_error_found);
3994       IF (l_error_found = 'Y') then
3995         Debug_info :=
3996           debug_info ||': cannot read expenditure item date information';
3997         X_debug_context := current_calling_sequence;
3998         X_debug_info := debug_info;
3999         RETURN(FALSE);
4000       END IF;
4001     END IF; -- Expenditure item date is null
4002     l_pa_allows_overrides :=
4003     FND_PROFILE.VALUE('PA_ALLOW_FLEXBUILDER_OVERRIDES');
4004 
4005     -- The Import process should make the call with X_Validate_Info  FALSE
4006     -- since The same validation should have been done in the Import Validation
4007 
4008     IF (X_validate_info) then
4009       user_id := to_number(FND_PROFILE.VALUE('USER_ID'));
4010 
4011       BEGIN
4012         SELECT employee_id
4013           INTO l_employee_id
4014           FROM ap_suppliers  /* bUg 4718054 */
4015          WHERE DECODE(SIGN(TO_DATE(TO_CHAR(START_DATE_ACTIVE,'DD-MM-YYYY'),
4016                'DD-MM-YYYY') - TO_DATE(TO_CHAR(SYSDATE,'DD-MM-YYYY'),'DD-MM-YYYY')),
4017                1, 'N', DECODE(SIGN(TO_DATE(TO_CHAR(END_DATE_ACTIVE ,'DD-MM-YYYY'),
4018                'DD-MM-YYYY') -  TO_DATE(TO_CHAR(SYSDATE,'DD-MM-YYYY'),'DD-MM-YYYY')),
4019                -1, 'N', 0, 'N', 'Y')) = 'Y'
4020            AND enabled_flag = 'Y'
4021            AND vendor_id = X_vendor_id;
4022       EXCEPTION
4023         WHEN no_data_found then
4024           l_employee_id := NULL;
4025         WHEN OTHERS then
4026           l_employee_id := NULL;
4027       END;
4028 
4029 --bug5003249
4030      Begin
4031         select default_code_comb_id
4032         into  l_employee_ccid
4033         from  PER_ASSIGNMENTS_F
4034         where person_id =  l_employee_id
4035         and   set_of_books_id =  l_invoice_line_rec.set_of_books_id
4036         and   trunc(sysdate) BETWEEN trunc(effective_start_date)
4037         and   nvl(trunc(effective_end_date), trunc(sysdate));
4038      EXCEPTION
4039          WHEN OTHERS then
4040           l_employee_ccid := NULL;
4041      End;
4042 
4043         select WEB_PARAMETER_ID
4044         into  l_web_parameter_id
4045         from  ap_invoice_lines
4046         where invoice_id = X_invoice_id
4047         AND line_number = X_line_number;
4048 
4049       /* Bug 5102724 */
4050       BEGIN
4051         SELECT invoice_type_lookup_code
4052         INTO   l_invoice_type_lookup_code
4053         FROM   ap_invoices_all
4054         WHERE  invoice_id = X_invoice_id;
4055       EXCEPTION
4056         WHEN no_data_found then
4057           NULL;
4058         WHEN OTHERS then
4059           NULL;
4060       END;
4061 
4062       If (l_invoice_type_lookup_code ='EXPENSE REPORT') Then
4063         l_sys_link_function :='ER' ;
4064       Else
4065         l_sys_link_function :='VI' ;
4066       End if;
4067 
4068 
4069     debug_info := 'Validate PA related information';
4070       PA_TRANSACTIONS_PUB.VALIDATE_TRANSACTION(
4071                     X_PROJECT_ID          => l_invoice_line_rec.project_id,
4072                     X_TASK_ID             => l_invoice_line_rec.task_id,
4073                     X_EI_DATE             => l_invoice_line_rec.expenditure_item_date,
4074                     X_EXPENDITURE_TYPE    => l_invoice_line_rec.expenditure_type,
4075                     X_NON_LABOR_RESOURCE  => null,
4076                     X_PERSON_ID           => l_employee_id,
4077                     X_QUANTITY            => nvl(l_invoice_line_rec.pa_quantity, '1'),
4078                     X_denom_currency_code => X_invoice_currency,
4079                     X_acct_currency_code  => l_base_currency_code,
4080                     X_denom_raw_cost      => l_invoice_line_rec.amount,
4081                     X_acct_raw_cost       => l_invoice_line_rec.base_amount,
4082                     X_acct_rate_type      => X_exchange_rate_type,
4083                     X_acct_rate_date      => X_exchange_date,
4084                     X_acct_exchange_rate  => X_exchange_rate,
4085                     X_TRANSFER_EI         => null,
4086                     X_INCURRED_BY_ORG_ID  => l_invoice_line_rec.expenditure_organization_id,
4087                     X_NL_RESOURCE_ORG_ID  => null,
4088                     X_TRANSACTION_SOURCE  => l_sys_link_function, /*bug 5102724 */
4089                     X_CALLING_MODULE      => 'apiindib.pls',
4090                     X_VENDOR_ID           => X_vendor_id,
4091                     X_ENTERED_BY_USER_ID  => user_id,
4092                     X_ATTRIBUTE_CATEGORY  => NULL,
4093                     X_ATTRIBUTE1          => NULL,
4094                     X_ATTRIBUTE2          => NULL,
4095                     X_ATTRIBUTE3          => NULL,
4096                     X_ATTRIBUTE4          => NULL,
4097                     X_ATTRIBUTE5          => NULL,
4098                     X_ATTRIBUTE6          => NULL,
4099                     X_ATTRIBUTE7          => NULL,
4100                     X_ATTRIBUTE8          => NULL,
4101                     X_ATTRIBUTE9          => NULL,
4102                     X_ATTRIBUTE10         => NULL,
4103                     X_ATTRIBUTE11         => NULL,
4104                     X_ATTRIBUTE12         => NULL,
4105                     X_ATTRIBUTE13         => NULL,
4106                     X_ATTRIBUTE14         => NULL,
4107                     X_ATTRIBUTE15         => NULL,
4108                     X_msg_application     => l_msg_application,
4109                     X_msg_type            => l_msg_type,
4110                     X_msg_token1          => l_msg_token1,
4111                     X_msg_token2          => l_msg_token2,
4112                     X_msg_token3          => l_msg_token3,
4113                     X_msg_count           => l_msg_count,
4114                     X_msg_data            => l_msg_data,
4115                     X_BILLABLE_FLAG       => l_billable_flag);
4116         IF (l_msg_data is not null) THEN
4117           X_msg_application := l_msg_application;
4118           X_msg_data := l_msg_data;
4119 	  --bugfix:5725904
4120 	  Fnd_Message.Set_Name(l_msg_application, l_msg_data);
4121 	  /*bug 6682104 setting the token values*/
4122             IF (l_msg_token1 IS NOT NULL) THEN
4123 	       fnd_message.set_token('PATC_MSG_TOKEN1',l_msg_token1);
4124             ELSE
4125 	       fnd_message.set_token('PATC_MSG_TOKEN1',FND_API.G_MISS_CHAR);
4126 	    END IF;
4127 
4128             IF (l_msg_token2 IS NOT NULL) THEN
4129 	        fnd_message.set_token('PATC_MSG_TOKEN2',l_msg_token2);
4130             ELSE
4131 	       fnd_message.set_token('PATC_MSG_TOKEN2',FND_API.G_MISS_CHAR);
4132             END IF;
4133 
4134             IF (l_msg_token3 IS NOT NULL) THEN
4135 	         fnd_message.set_token('PATC_MSG_TOKEN3',l_msg_token3);
4136             ELSE
4137 	          fnd_message.set_token('PATC_MSG_TOKEN3',FND_API.G_MISS_CHAR);
4138             END IF;
4139 	  l_message_text := Fnd_Message.get;
4140 	  X_Error_Code := l_message_text;
4141 
4142           return(FALSE);
4143         END IF;
4144       END IF; -- X_validate_info is TRUE
4145     END IF; --l_project_id is not null
4146 
4147   ----------------------------------------------------------------------------
4148   -- Step 7 - Obtain final account and account related information.
4149   -- But only if calling module is not the Import since through the import
4150   -- The account should already be built.
4151   ----------------------------------------------------------------------------
4152   debug_info := 'Obtain account to be used in distribution';
4153   IF (nvl(X_line_source, 'OTHERS') <> 'IMPORT') then
4154     --Bug5003249 added condition on invoice type lookup code
4155 
4156     IF (l_invoice_line_rec.project_id is not null
4157         and l_invoice_type_lookup_code<>'PREPAYMENT') then
4158       -- Need to create a utility to flexbuild.  Look at import code.  Utility
4159       -- there is PA_FLEXBUILD
4160       IF ( NOT (AP_UTILITIES_PKG.pa_flexbuild(
4161                     p_vendor_id                 => X_vendor_id,          --IN
4162                     p_employee_id               => l_employee_id,        --IN
4163                     p_set_of_books_id           =>
4164                       l_invoice_line_rec.set_of_books_id,                --IN
4165                     p_chart_of_accounts_id      =>
4166                       l_chart_of_accounts_id,                            --IN
4167                     p_base_currency_code        => l_base_currency_code, --IN
4168                     p_accounting_date           => l_open_GL_date,       --IN
4169                     p_award_id                  =>
4170                       l_invoice_line_rec.award_id,                       --IN
4171                     P_project_id                =>
4172                       l_invoice_line_rec.project_id,                     --IN
4173                     p_task_id                   =>
4174                       l_invoice_line_rec.task_id,                        --IN
4175                     p_expenditure_type          =>
4176                       l_invoice_line_rec.expenditure_type,
4177                     p_expenditure_org_id        =>
4178                       l_invoice_line_rec.expenditure_organization_id,
4179                     p_expenditure_item_date     =>
4180                       l_invoice_line_rec.expenditure_item_date,
4181                     p_employee_ccid             =>
4182                       l_employee_ccid,   --Bug5003249
4183                     p_web_parameter_id          =>
4184                       l_web_parameter_id,   --Bug5003249
4185                     p_invoice_type_lookup_code  =>
4186                       l_invoice_type_lookup_code, --Bug5003249
4187                     p_default_last_updated_by   => FND_GLOBAL.user_id,
4188                     p_default_last_update_login => FND_GLOBAL.login_id,
4189                     p_pa_default_dist_ccid      => l_dist_ccid,
4190                     p_pa_concatenated_segments  =>
4191                       l_dist_code_concat,                         --OUT NOCOPY
4192                     p_debug_Info                => debug_Info,    --OUT NOCOPY
4193                     p_debug_Context             => debug_Context, --OUT NOCOPY
4194                     p_calling_sequence          =>
4195                       'Get_Proj_And_Acc_For_Chrg_Dist' ,
4196                    p_default_dist_ccid         =>   l_invoice_line_rec.default_dist_ccid --IN bug 5386396
4197                   ))) THEN
4198         debug_info := debug_info || ': Error encountered';
4199         debug_context := current_calling_sequence;
4200         RETURN(FALSE);
4201       END IF;
4202 
4203       IF (l_pa_allows_overrides = 'N') then
4204         IF ( NOT (AP_UTILITIES_PKG.IS_CCID_VALID(
4205                     l_dist_ccid,
4206                     l_chart_of_accounts_id,
4207                     l_open_gl_date,
4208                     current_calling_sequence))) then
4209           X_error_code := 'AP_INVALID_ACCOUNT';
4210           RETURN(FALSE);
4211         END IF;
4212       ELSE -- pa allows overrides is Y
4213         -- If the user provided an account at the line level,
4214         --  use it instead of the Account produced by PA
4215         IF (l_invoice_line_rec.default_dist_ccid is not null) then
4216          l_dist_ccid := l_invoice_line_rec.default_dist_ccid;
4217         END IF;
4218         IF (l_invoice_line_rec.overlay_dist_code_concat is NULL AND
4219             l_invoice_line_rec.balancing_segment is NULL AND
4220             l_invoice_line_rec.account_segment is NULL AND
4221             l_invoice_line_rec.cost_center_segment is NULL) then
4222           IF ( NOT (AP_UTILITIES_PKG.IS_CCID_VALID(
4223                        l_dist_ccid,
4224                        l_chart_of_accounts_id,
4225                        l_open_gl_date,
4226                        current_calling_sequence))) then
4227             X_error_code := 'AP_INVALID_ACCOUNT';
4228             RETURN(FALSE);
4229           END IF;
4230         ELSE
4231           IF ( NOT (AP_UTILITIES_PKG.OVERLAY_SEGMENTS (
4232                     l_invoice_line_rec.balancing_segment,
4233                     l_invoice_line_rec.cost_center_segment,
4234                     l_invoice_line_rec.account_segment,
4235                     l_invoice_line_rec.overlay_dist_code_concat,
4236                     l_dist_ccid,
4237                     l_invoice_line_rec.set_of_books_id,
4238                     'CREATE_COMB_NO_AT',
4239                     l_unbuilt_flex,
4240                     l_reason_unbuilt_flex,
4241                     FND_GLOBAL.RESP_APPL_ID,
4242                     FND_GLOBAL.RESP_ID,
4243                     FND_GLOBAL.USER_ID,
4244                     current_calling_sequence))) THEN
4245             X_error_code := 'AP_CANNOT_OVERLAY';
4246             RETURN(FALSE);
4247           END IF;
4248         END IF; -- overlay information is null
4249       END IF; -- pa allows overrides
4250     ELSE -- project id is null
4251 
4252       l_dist_ccid := l_invoice_line_rec.default_dist_ccid;
4253       IF (l_invoice_line_rec.overlay_dist_code_concat is NULL AND
4254           l_invoice_line_rec.balancing_segment is NULL AND
4255           l_invoice_line_rec.account_segment is NULL AND
4256           l_invoice_line_rec.cost_center_segment is NULL) then
4257         IF ( NOT (AP_UTILITIES_PKG.IS_CCID_VALID(
4258                      l_dist_ccid,
4259                      l_chart_of_accounts_id,
4260                      l_open_gl_date,
4261                      current_calling_sequence))) THEN
4262           X_error_code := 'AP_INVALID_ACCOUNT';
4263           RETURN(FALSE);
4264         END IF;
4265       ELSE
4266         IF ( NOT (AP_UTILITIES_PKG.OVERLAY_SEGMENTS (
4267                     l_invoice_line_rec.balancing_segment,
4268                     l_invoice_line_rec.cost_center_segment,
4269                     l_invoice_line_rec.account_segment,
4270                     l_invoice_line_rec.overlay_dist_code_concat,
4271                     l_dist_ccid,
4272                     l_invoice_line_rec.set_of_books_id,
4273                     'CREATE_COMB_NO_AT',
4274                     l_unbuilt_flex,
4275                     l_reason_unbuilt_flex,
4276                     FND_GLOBAL.RESP_APPL_ID,
4277                     FND_GLOBAL.RESP_ID,
4278                     FND_GLOBAL.USER_ID,
4279                     current_calling_sequence))) then
4280           X_error_code := 'AP_CANNOT_OVERLAY';
4281           RETURN(FALSE);
4282         END IF;
4283       END IF; -- overlay information is null
4284     END IF; -- project id is null
4285 
4286     IF (l_invoice_line_rec.project_id is not null) THEN
4287 
4288 	GMS_AP_API.validate_transaction
4289 			( x_project_id		  => l_invoice_line_rec.project_id,
4290 			  x_task_id		  => l_invoice_line_rec.task_id,
4291 			  x_award_id		  => l_invoice_line_rec.award_id,
4292 			  x_expenditure_type	  => l_invoice_line_rec.expenditure_type,
4293 			  x_expenditure_item_date => l_invoice_line_rec.expenditure_item_date,
4294 			  x_calling_sequence	  => 'AWARD_ID',
4295 			  x_msg_application       => l_msg_application,
4296 			  x_msg_type              => l_msg_type,
4297 			  x_msg_count             => l_msg_count,
4298 			  x_msg_data              => l_msg_data ) ;
4299 
4300 	IF (l_msg_data is not null) THEN
4301 	    x_msg_application := l_msg_application;
4302 	    x_msg_data := l_msg_data;
4303 	    return(FALSE);
4304 	END IF;
4305     END IF ;
4306 
4307   ELSE
4308 
4309     -- Need to assign the value from the pass in record
4310     l_dist_ccid := l_invoice_line_rec.default_dist_ccid;
4311 
4312   END IF; -- Calling module is other than the IMPORT
4313 
4314 
4315   ---------------------------------------------------------------------------
4316   -- Step 8 - Get account type.
4317   ---------------------------------------------------------------------------
4318   debug_info := 'Get account type for ccid' || l_dist_ccid;
4319     BEGIN
4320     SELECT account_type
4321       INTO l_account_type
4322       FROM gl_code_combinations
4323      WHERE code_combination_id = l_dist_ccid;
4324 
4325   EXCEPTION
4326     When no_data_found THEN
4327        Debug_info := debug_info || ': cannot read account type information';
4328        X_debug_context := current_calling_sequence;
4329        X_debug_info := debug_info;
4330        RETURN(FALSE);
4331   END;
4332   -- Obtain the assets tracking flag given the account type
4333   IF (l_account_type = 'A' OR
4334       (l_account_type = 'E' AND
4335        l_invoice_line_rec.assets_tracking_flag = 'Y')) then
4336     l_assets_tracking_flag := 'Y';
4337   ELSE
4338     l_assets_tracking_flag := 'N';
4339   END IF;
4340 
4341   ----------------------------------------------------------------------------
4342   -- Step 9 - Set distribution class value (Permanent or Candidate)
4343   ----------------------------------------------------------------------------
4344   if (X_Generate_Permanent = 'N') then
4345     l_distribution_class := 'CANDIDATE';
4346   else
4347     l_distribution_class := 'PERMANENT';
4348   end if;
4349 
4350 
4351   ---------------------------------------------------------------------------
4352   -- ETAX: Invwkb
4353   -- Step 10 - Exclude the included_tax_amount from the line_amount before
4354   --	       creating a item distribution.
4355   ---------------------------------------------------------------------------
4356   --bug6653070
4357 
4358   /*l_invoice_line_rec.amount := l_invoice_line_rec.amount -
4359   				   NVL(l_invoice_line_rec.included_tax_amount,0);*/
4360   l_invoice_line_rec.base_amount := ap_utilities_pkg.ap_round_currency(
4361   					l_invoice_line_rec.amount * x_exchange_rate,
4362 					l_base_currency_code);
4363 
4364   ----------------------------------------------------------------------------
4365   -- Step 11 - Generate distributions
4366   ----------------------------------------------------------------------------
4367   BEGIN
4368 
4369     INSERT INTO ap_invoice_distributions(
4370               batch_id,
4371               invoice_id,
4372               invoice_line_number,
4373               invoice_distribution_id,
4374               distribution_line_number,
4375               line_type_lookup_code,
4376               distribution_class,
4377               description,
4378               dist_match_type,
4379               org_id,
4380               dist_code_combination_id,
4381               accounting_date,
4382               period_name,
4383               accrual_posted_flag,
4384               cash_posted_flag,
4385               amount_to_post,
4386               base_amount_to_post,
4387               posted_amount,
4388               posted_base_amount,
4389               posted_flag,
4390               accounting_event_id,
4391               upgrade_posted_amt,
4392               upgrade_base_posted_amt,
4393               set_of_books_id,
4394               amount,
4395               base_amount,
4396               rounding_amt,
4397               quantity_variance,
4398               base_quantity_variance,
4399               match_status_flag,
4400               encumbered_flag,
4401               packet_id,
4402               reversal_flag,
4403               parent_reversal_id,
4404               cancellation_flag,
4405               income_tax_region,
4406               type_1099,
4407               stat_amount,
4408               charge_applicable_to_dist_id,
4409               prepay_amount_remaining,
4410               prepay_distribution_id,
4411               parent_invoice_id,
4412               corrected_invoice_dist_id,
4413               corrected_quantity,
4414               other_invoice_id,
4415               po_distribution_id,
4416               rcv_transaction_id,
4417               unit_price,
4418               matched_uom_lookup_code,
4419               quantity_invoiced,
4420               final_match_flag,
4421               related_id,
4422               assets_addition_flag,
4423               assets_tracking_flag,
4424               asset_book_type_code,
4425               asset_category_id,
4426               project_id,
4427               task_id,
4428               expenditure_type,
4429               expenditure_item_date,
4430               expenditure_organization_id,
4431               pa_quantity,
4432               pa_addition_flag,
4433               award_id,
4434               gms_burdenable_raw_cost,
4435               awt_flag,
4436               awt_group_id,
4437               awt_tax_rate_id,
4438               awt_gross_amount,
4439               awt_invoice_id,
4440               awt_origin_group_id,
4441               awt_invoice_payment_id,
4442               awt_withheld_amt,
4443               inventory_transfer_status,
4444               reference_1,
4445               reference_2,
4446               receipt_verified_flag,
4447               receipt_required_flag,
4448               receipt_missing_flag,
4449               justification,
4450               expense_group,
4451               start_expense_date,
4452               end_expense_date,
4453               receipt_currency_code,
4454               receipt_conversion_rate,
4455               receipt_currency_amount,
4456               daily_amount,
4457               web_parameter_id,
4458               adjustment_reason,
4459               merchant_document_number,
4460               merchant_name,
4461               merchant_reference,
4462               merchant_tax_reg_number,
4463               merchant_taxpayer_id,
4464               country_of_supply,
4465               credit_card_trx_id,
4466               company_prepaid_invoice_id,
4467               cc_reversal_flag,
4468               attribute_category,
4469               attribute1,
4470               attribute2,
4471               attribute3,
4472               attribute4,
4473               attribute5,
4474               attribute6,
4475               attribute7,
4476               attribute8,
4477               attribute9,
4478               attribute10,
4479               attribute11,
4480               attribute12,
4481               attribute13,
4482               attribute14,
4483               attribute15,
4484               global_attribute_category,
4485               global_attribute1,
4486               global_attribute2,
4487               global_attribute3,
4488               global_attribute4,
4489               global_attribute5,
4490               global_attribute6,
4491               global_attribute7,
4492               global_attribute8,
4493               global_attribute9,
4494               global_attribute10,
4495               global_attribute11,
4496               global_attribute12,
4497               global_attribute13,
4498               global_attribute14,
4499               global_attribute15,
4500               global_attribute16,
4501               global_attribute17,
4502               global_attribute18,
4503               global_attribute19,
4504               global_attribute20,
4505               created_by,
4506               creation_date,
4507               last_updated_by,
4508               last_update_date,
4509               last_update_login,
4510               program_application_id,
4511               program_id,
4512               program_update_date,
4513               request_id,
4514 	      --ETAX: Invwkb
4515 	      intended_use,
4516 	      --Freight and Special Charges
4517 	      rcv_charge_addition_flag,
4518 	      --bug7022001
4519 	      pay_awt_group_id)
4520     VALUES  (X_batch_id,                          -- batch_id
4521             l_invoice_line_rec.invoice_id,        -- invoice_id
4522             l_invoice_line_rec.line_number,       -- invoice_line_number
4523             ap_invoice_distributions_s.nextval,   -- invoice_distribution_id
4524             1,                                    -- distribution_line_number
4525             l_invoice_line_rec.line_type_lookup_code,  -- line_type_lookup_code
4526             l_distribution_class,                 -- distribution_class
4527             l_invoice_line_rec.description,       -- description
4528             'NOT_MATCHED',                        -- dist_match_type
4529             l_invoice_line_rec.org_id,            -- l_org_id
4530             l_dist_ccid,                          -- dist_code_combination_id
4531             l_open_gl_date,                       -- accounting_date
4532             l_open_period_name,                   -- period_name
4533             'N',                                  -- accrual_posted_flag
4534             'N',                                  -- cash_posted_flag
4535             NULL,                                 -- amount_to_post
4536             NULL,                                 -- base_amount_to_post
4537             NULL,                                 -- posted_amount
4538             NULL,                                 -- posted_base_amount
4539             'N',                                  -- posted_flag
4540             NULL,                                 -- accounting_event_id
4541             NULL,                                 -- upgrade_posted_amt
4542             NULL,                                 -- upgrade_base_posted_amt
4543             l_invoice_line_rec.set_of_books_id,   -- set_of_books_id
4544             l_invoice_line_rec.amount,            -- amount
4545             l_invoice_line_rec.base_amount,       -- base_amount
4546             l_invoice_line_rec.rounding_amt,      -- rounding_amt
4547             NULL,                                 -- quantity_variance
4548             NULL,                                 -- base_quantity_variance
4549 	    --Invoice Lines: Distributions, changed match_status_flag
4550             --to NULL from 'N'.
4551             NULl,                                 -- match_status_flag
4552             'N',                                  -- encumbered_flag
4553             NULL,                                 -- packet_id
4554          -- decode(l_invoice_line_rec.line_type_lookup_code,
4555             'N',                                  -- reversal_flag
4556             NULL,                                 -- parent_reversal_id
4557             'N',                                  -- cancellation_flag
4558             decode(l_invoice_line_rec.type_1099,null,null,
4559                   l_invoice_line_rec.income_tax_region),  -- income_tax_region
4560             l_invoice_line_rec.type_1099,         -- type_1099
4561             NULL,                                 -- stat_amount
4562             NULL,                                 -- charge_applicable_to_dist_id
4563             NULL,                                 -- prepay_amount_remaining
4564             NULL,                                 -- prepay_distribution_id
4565             NULL,                                 -- parent_invoice_id
4566             NULL,                                 -- corrected_inv_dist_id
4567             NULL,                                 -- corrected_quantity
4568             NULL,                                 -- other_invoice_id
4569             NULL,                                 -- po_distribution_id
4570             NULL,                                 -- rcv_transaction_id
4571             NULL,                                 -- unit_price
4572             NULL,                                 -- matched_uom_lookup_code
4573             NULL,                                 -- quantity_invoiced
4574             NULL,                                 -- final_match_flag
4575             NULL,                                 -- related_id
4576             'U',                                  -- assets_addition_flag
4577             l_assets_tracking_flag,               -- assets_tracking_flag
4578             decode(l_assets_tracking_flag,'Y',
4579                  l_invoice_line_rec.asset_book_type_code, NULL),-- asset_book_type_code
4580             decode(l_assets_tracking_flag,'Y',
4581                     l_invoice_line_rec.asset_category_id, NULL),-- asset_category_id
4582             l_invoice_line_rec.project_id,                           -- project_id
4583             l_invoice_line_rec.task_id,                              -- task_id
4584             l_invoice_line_rec.expenditure_type,                     -- expenditure_type
4585             l_invoice_line_rec.expenditure_item_date,              -- expenditure_item_date
4586             l_invoice_line_rec.expenditure_organization_id,          -- expenditure_organization_id
4587             l_invoice_line_rec.pa_quantity,       -- pa_quantity
4588             decode(l_invoice_line_rec.project_id,NULL,'E', 'N'),     -- pa_addition_flag
4589             l_invoice_line_rec.award_id,                             -- award_id
4590             NULL,                                 -- gms_burdenable_raw_cost
4591             /*Added the following decode for bug#7695497 Start */
4592             decode(l_invoice_line_rec.line_type_lookup_code,
4593 	           'AWT', decode(l_invoice_line_rec.line_source ,'MANUAL LINE ENTRY','M', NULL),
4594 	           NULL),                                            -- awt_flag
4595             /*Added the above decode for bug#7695497 End */
4596             l_invoice_line_rec.awt_group_id,                         -- awt_group_id
4597             NULL,                                 -- awt_tax_rate_id
4598             NULL,                                 -- awt_gross_amount
4599             NULL,                                 -- awt_invoice_id
4600             NULL,                                 -- awt_origin_group_id
4601             NULL,                                 -- awt_invoice_payment_id
4602             NULL,                                 -- awt_withheld_amt
4603             'N',                                  -- inventory_transfer_status
4604             NULL,                                 -- reference_1
4605             NULL,                                 -- reference_2
4606             NULL,                                 -- receipt_verified_flag
4607             NULL,                                 -- receipt_required_flag
4608             NULL,                                 -- receipt_missing_flag
4609             NULL,                                 -- justification
4610             NULL,                                 -- expense_group
4611             NULL,                                 -- start_expense_date
4612             NULL,                                 -- end_expense_date
4613             NULL,                                 -- receipt_currency_code
4614             NULL,                                 -- receipt_conversion_rate
4615             NULL,                                 -- receipt_currency_amount
4616             NULL,                                 -- daily_amount
4617             NULL,                                 -- web_parameter_id
4618             NULL,                                 -- adjustment_reason
4619             NULL,                                 -- merchant_document_number
4620             NULL,                                 -- merchant_name
4621             NULL,                                 -- merchant_reference
4622             NULL,                                 -- merchant_tax_reg_number
4623             NULL,                                 -- merchant_taxpayer_id
4624             NULL,                                 -- country_of_supply
4625             NULL,                                 -- credit_card_trx_id
4626             NULL,                                 -- company_prepaid_invoice_id
4627             NULL,                                 -- cc_reversal_flag
4628             NULL,                                 -- attribute_category
4629             NULL,                                 -- attribute1
4630             NULL,                                 -- attribute2
4631             NULL,                                 -- attribute3
4632             NULL,                                 -- attribute4
4633             NULL,                                 -- attribute5
4634             NULL,                                 -- attribute6
4635             NULL,                                 -- attribute7
4636             NULL,                                 -- attribute8
4637             NULL,                                 -- attribute9
4638             NULL,                                 -- attribute10
4639             NULL,                                 -- attribute11
4640             NULL,                                 -- attribute12
4641             NULL,                                 -- attribute13
4642             NULL,                                 -- attribute14
4643             NULL,                                 -- attribute15
4644             NULL,                                 -- global_attribute_category
4645             NULL,                                 -- global_attribute1
4646             NULL,                                 -- global_attribute2
4647 	    --bugfix:4674194
4648 	    Decode(AP_EXTENDED_WITHHOLDING_PKG.AP_EXTENDED_WITHHOLDING_OPTION,
4649 	           'Y',l_invoice_line_rec.ship_to_location_id,''), --global_attribute3
4650             NULL,                                 -- global_attribute4
4651             NULL,                                 -- global_attribute5
4652             NULL,                                 -- global_attribute6
4653             NULL,                                 -- global_attribute7
4654             NULL,                                 -- global_attribute8
4655             NULL,                                 -- global_attribute9
4656             NULL,                                 -- global_attribute10
4657             NULL,                                 -- global_attribute11
4658             NULL,                                 -- global_attribute12
4659             NULL,                                 -- global_attribute13
4660             NULL,                                 -- global_attribute14
4661             NULL,                                 -- global_attribute15
4662             NULL,                                 -- global_attribute16
4663             NULL,                                 -- global_attribute17
4664             NULL,                                 -- global_attribute18
4665             NULL,                                 -- global_attribute19
4666             NULL,                                 -- global_attribute20
4667             FND_GLOBAL.user_id,                   -- created_by
4668             SYSDATE,                              -- creation_date
4669             0,                                    -- last_updated_by
4670             SYSDATE,                              -- last_update_date
4671             FND_GLOBAL.login_id,                  -- last_update_login
4672             NULL,                                 -- program_application_id
4673             NULL,                                 -- program_id
4674             NULL,                                 -- program_update_date
4675             NULL,                                 -- request_id
4676 	    l_invoice_line_rec.primary_intended_use, -- intended_use
4677 	    'N',				  -- rcv_charge_addition_flag
4678             l_invoice_line_rec.pay_awt_group_id   --pay_awt_group_id  --bug7022001
4679 	    ) returning invoice_distribution_id into l_invoice_distribution_id;
4680 
4681 	    GMS_AP_API.CREATE_AWARD_DISTRIBUTIONS
4682 			( p_invoice_id		     => l_invoice_line_rec.invoice_id,
4683 			  p_distribution_line_number => 1,
4684 			  p_invoice_distribution_id  => l_invoice_distribution_id,
4685 			  p_award_id		     => l_invoice_line_rec.award_id,
4686 			  p_mode		     => 'AP',
4687 			  p_dist_set_id		     => NULL,
4688 			  p_dist_set_line_number     => NULL );
4689 
4690 
4691      EXCEPTION
4692       WHEN OTHERS THEN
4693         X_debug_info := debug_info || ': Error encountered during dist insert';
4694         X_debug_context := current_calling_sequence;
4695 	--Bugfix: 3859755, added the below stmt.
4696 	X_Error_Code := sqlerrm;
4697         return (FALSE);
4698     END;
4699 
4700     ----------------------------------------------------------------------------
4701   -- Step 10 - Update generate distributions flag in invoice line if generating
4702   -- permanent distributions.
4703   ----------------------------------------------------------------------------
4704   debug_info := 'Setting generate distributions flag to Done';
4705   IF (l_distribution_class = 'PERMANENT') then
4706     BEGIN
4707       UPDATE AP_INVOICE_LINES
4708          SET GENERATE_DISTS = 'D'
4709        WHERE invoice_id = X_invoice_id
4710          AND line_number = l_invoice_line_rec.line_number;
4711     EXCEPTION
4712       WHEN OTHERS THEN
4713         X_debug_info := debug_info || ': Error encountered';
4714         X_debug_context := current_calling_sequence;
4715         return (FALSE);
4716     END;
4717   END IF;
4718 
4719   RETURN(TRUE);
4720 
4721   EXCEPTION
4722     WHEN OTHERS THEN
4723     X_debug_info := 'Error encountered';
4724     X_debug_context := current_calling_sequence;
4725     RETURN (FALSE);
4726   END insert_single_dist_from_line;
4727 
4728 
4729   ----------------------------------------------------------------------
4730   -- PRIVATE FUNCTION get_project_and_account_for_chrg_dist encapsulates the
4731   -- logic for obtaining the project and account information for a
4732   -- distribution created for a charge line that is allocated to one
4733   -- or more lines in an invoice.
4734   -- Returns FALSE if an error is encountered and an specific error
4735   -- code for invalid PA, invalid account or if it is unable to overlay.
4736   --------------------------------------------------------------------------
4737 
4738   FUNCTION Get_Proj_And_Acc_For_Chrg_Dist(
4739   X_invoice_id             IN         NUMBER,
4740   X_invoice_date           IN         AP_INVOICES.INVOICE_DATE%TYPE,
4741   X_vendor_id              IN         NUMBER,
4742   X_invoice_currency_code  IN         AP_INVOICES.INVOICE_CURRENCY_CODE%TYPE,
4743   X_sob_id                 IN         AP_INVOICE_LINES.SET_OF_BOOKS_ID%TYPE,
4744   X_chart_of_accounts_id   IN         GL_SETS_OF_BOOKS.CHART_OF_ACCOUNTS_ID%TYPE,
4745   X_base_currency_code     IN         AP_SYSTEM_PARAMETERS.BASE_CURRENCY_CODE%TYPE,
4746   X_amount                 IN         AP_INVOICE_DISTRIBUTIONS.AMOUNT%TYPE,
4747   X_base_amount            IN         AP_INVOICE_DISTRIBUTIONS.BASE_AMOUNT%TYPE,
4748   X_exchange_rate_type     IN         AP_INVOICES.EXCHANGE_RATE_TYPE%TYPE,
4749   X_exchange_date          IN         AP_INVOICES.EXCHANGE_DATE%TYPE,
4750   X_exchange_rate          IN         AP_INVOICES.EXCHANGE_RATE%TYPE,
4751   X_line_number            IN         NUMBER,
4752   X_GL_Date                IN         AP_INVOICE_LINES.ACCOUNTING_DATE%TYPE,
4753   X_Period_Name            IN         AP_INVOICE_LINES.PERIOD_NAME%TYPE,
4754   X_chrg_line_project_id   IN         AP_INVOICE_LINES.PROJECT_ID%TYPE,
4755   X_chrg_line_task_id      IN         AP_INVOICE_LINES.TASK_ID%TYPE,
4756   X_chrg_line_award_id	   IN	      AP_INVOICE_LINES.award_ID%TYPE,
4757   X_chrg_line_expenditure_type IN         AP_INVOICE_LINES.EXPENDITURE_TYPE%TYPE,
4758   X_chrg_line_exp_org_id   IN         AP_INVOICE_LINES.EXPENDITURE_ORGANIZATION_ID%TYPE,
4759   X_chrg_assets_track_flag IN         AP_INVOICE_LINES.ASSETS_TRACKING_FLAG%TYPE,
4760   X_chrg_asset_book_type_code  IN         AP_INVOICE_LINES.ASSET_BOOK_TYPE_CODE%TYPE,
4761   X_chrg_asset_category_id IN         AP_INVOICE_LINES.ASSET_CATEGORY_ID%TYPE,
4762   X_item_dist_project_id   IN         AP_INVOICE_DISTRIBUTIONS.PROJECT_ID%TYPE,
4763   X_item_dist_task_id      IN         AP_INVOICE_DISTRIBUTIONS.TASK_ID%TYPE,
4764   X_item_dist_award_id	   IN	      AP_INVOICE_DISTRIBUTIONS.award_ID%TYPE,
4765   X_item_dist_expenditure_type IN         AP_INVOICE_DISTRIBUTIONS.EXPENDITURE_TYPE%TYPE,
4766   X_item_dist_exp_org_id   IN         AP_INVOICE_DISTRIBUTIONS.EXPENDITURE_ORGANIZATION_ID%TYPE,
4767   X_item_assets_track_flag IN         AP_INVOICE_DISTRIBUTIONS.ASSETS_TRACKING_FLAG%TYPE,
4768   X_item_asset_book_type_code  IN         AP_INVOICE_DISTRIBUTIONS.ASSET_BOOK_TYPE_CODE%TYPE,
4769   X_item_asset_category_id IN         AP_INVOICE_DISTRIBUTIONS.ASSET_CATEGORY_ID%TYPE,
4770   X_chrg_line_default_ccid IN         NUMBER,
4771   X_overlay_dist_code_concat   IN         AP_INVOICE_LINES.OVERLAY_DIST_CODE_CONCAT%TYPE,
4772   X_balancing_segment      IN         AP_INVOICE_LINES.BALANCING_SEGMENT%TYPE,
4773   X_account_segment        IN         AP_INVOICE_LINES.ACCOUNT_SEGMENT%TYPE,
4774   X_cost_center_segment    IN         AP_INVOICE_LINES.COST_CENTER_SEGMENT%TYPE,
4775   X_item_dist_ccid         IN         AP_INVOICE_DISTRIBUTIONS.DIST_CODE_COMBINATION_ID%TYPE,
4776   X_item_po_dist_id        IN         AP_INVOICE_DISTRIBUTIONS.PO_DISTRIBUTION_ID%TYPE,
4777   X_item_rcv_trx_id        IN         AP_INVOICE_DISTRIBUTIONS.RCV_TRANSACTION_ID%TYPE,
4778   X_pa_allows_overrides    IN         VARCHAR2,
4779   X_allow_po_override      IN         VARCHAR2,
4780   X_project_id             OUT NOCOPY AP_INVOICE_DISTRIBUTIONS.PROJECT_ID%TYPE,
4781   X_task_id                OUT NOCOPY AP_INVOICE_DISTRIBUTIONS.TASK_ID%TYPE,
4782   X_award_id		   OUT NOCOPY AP_INVOICE_LINES.award_ID%TYPE,
4783   X_expenditure_type       OUT NOCOPY AP_INVOICE_DISTRIBUTIONS.EXPENDITURE_TYPE%TYPE,
4784   X_expenditure_org_id     OUT NOCOPY AP_INVOICE_DISTRIBUTIONS.EXPENDITURE_ORGANIZATION_ID%TYPE,
4785   X_expenditure_item_date  OUT NOCOPY AP_INVOICE_DISTRIBUTIONS.EXPENDITURE_ITEM_DATE%TYPE,
4786   X_pa_addition_flag       OUT NOCOPY AP_INVOICE_DISTRIBUTIONS.PA_ADDITION_FLAG%TYPE,
4787   X_account_for_dist       OUT NOCOPY NUMBER,
4788   X_assets_tracking_flag   OUT NOCOPY AP_INVOICE_DISTRIBUTIONS.ASSETS_TRACKING_FLAG%TYPE,
4789   X_asset_book_typ_code    OUT NOCOPY AP_INVOICE_DISTRIBUTIONS.ASSET_BOOK_TYPE_CODE%TYPE,
4790   X_asset_category_id      OUT NOCOPY AP_INVOICE_DISTRIBUTIONS.ASSET_CATEGORY_ID%TYPE,
4791   X_error_code             OUT NOCOPY VARCHAR2,
4792   X_msg_application        OUT NOCOPY VARCHAR2,
4793   X_msg_data               OUT NOCOPY VARCHAR2,
4794   X_default_dist_ccid      IN   AP_INVOICE_LINES.DEFAULT_DIST_CCID%TYPE) --bug 5386396
4795   RETURN BOOLEAN
4796 IS
4797 
4798   l_po_accrue_on_receipt_flag PO_DISTRIBUTIONS.ACCRUE_ON_RECEIPT_FLAG%TYPE;
4799   l_po_ccid                   PO_DISTRIBUTIONS.CODE_COMBINATION_ID%TYPE;
4800   l_dist_ccid                 AP_INVOICE_DISTRIBUTIONS.DIST_CODE_COMBINATION_ID%TYPE;
4801   l_dist_code_concat          VARCHAR2(2000);
4802   l_employee_id               AP_SUPPLIERS.EMPLOYEE_ID%TYPE;
4803   l_account_type              GL_CODE_COMBINATIONS.ACCOUNT_TYPE%TYPE;
4804   user_id                     NUMBER;
4805   l_msg_application         VARCHAR2(25);
4806   l_msg_type              VARCHAR2(25);
4807   l_msg_token1               VARCHAR2(30);
4808   l_msg_token2               VARCHAR2(30);
4809   l_msg_token3               VARCHAR2(30);
4810   l_msg_count              NUMBER;
4811   l_msg_data              VARCHAR2(30);
4812   l_billable_flag             VARCHAR2(25);
4813   l_unbuilt_flex              VARCHAR2(240):='';
4814   l_reason_unbuilt_flex       VARCHAR2(2000):='';
4815   l_error_found               VARCHAR2(1) := 'N';
4816   l_vendor_id                 AP_INVOICES.VENDOR_ID%TYPE;
4817   current_calling_sequence            VARCHAR2(200);
4818   debug_context               VARCHAR2(2000);
4819   debug_info                  VARCHAR2(100);
4820   l_invoice_type_lookup_code   ap_invoices_all.invoice_type_lookup_code%TYPE;
4821   l_sys_link_function          VARCHAR2(2); /* Bug 5102724 */
4822   l_web_parameter_id           number; --Bug5003249
4823   l_employee_ccid              number;
4824   l_message_text	       fnd_new_messages.message_text%TYPE;
4825 
4826 BEGIN
4827 
4828   -------------------------------------------------------------------
4829   -- Step 1 - Gather whether distribution is project related and at
4830   -- which level.
4831   -------------------------------------------------------------------
4832   IF (X_item_dist_project_id IS NOT NULL) THEN
4833     X_project_id := X_item_dist_project_id;
4834     X_task_id := X_item_dist_task_id;
4835     X_expenditure_type := X_item_dist_expenditure_type;
4836     X_expenditure_org_id := X_item_dist_exp_org_id;
4837     X_pa_addition_flag := 'N';
4838   ELSIF (X_chrg_line_project_id is not null) then
4839     X_project_id := X_chrg_line_project_id;
4840     X_task_id := X_chrg_line_task_id;
4841     X_expenditure_type := X_chrg_line_expenditure_type;
4842     X_expenditure_org_id := X_chrg_line_exp_org_id;
4843     X_pa_addition_flag := 'N';
4844   ELSE
4845     X_project_id := NULL;
4846     X_task_id := NULL;
4847     X_expenditure_type := NULL;
4848     X_expenditure_org_id := NULL;
4849     X_pa_addition_flag := 'E';
4850   END IF;
4851 
4852   -------------------------------------------------------------------
4853   -- Step 2 - Validate PA information
4854   -------------------------------------------------------------------
4855   IF (X_project_id IS NOT NULL AND X_item_dist_project_id IS NOT NULL) then
4856     user_id := TO_NUMBER(FND_PROFILE.VALUE('USER_ID'));
4857 
4858     X_expenditure_item_date := AP_INVOICES_PKG.get_expenditure_item_date(
4859                                                    X_invoice_id,
4860                                                    X_invoice_date,
4861                                                    X_GL_date,
4862                                                    X_item_po_dist_id,
4863                                                    X_item_rcv_trx_id,
4864                                                    l_error_found);
4865     if (l_error_found = 'Y') then
4866       X_error_code := 'AP_CANNOT_READ_EXP_DATE';
4867       RETURN(FALSE);
4868     END IF;
4869 
4870     BEGIN
4871     SELECT employee_id
4872     INTO l_employee_id
4873         FROM ap_suppliers /* bUg 4718054 */
4874        WHERE DECODE(SIGN(TO_DATE(TO_CHAR(START_DATE_ACTIVE,'DD-MM-YYYY'),
4875                'DD-MM-YYYY') - TO_DATE(TO_CHAR(SYSDATE,'DD-MM-YYYY'),'DD-MM-YYYY')),
4876                1, 'N', DECODE(SIGN(TO_DATE(TO_CHAR(END_DATE_ACTIVE ,'DD-MM-YYYY'),
4877                'DD-MM-YYYY') -  TO_DATE(TO_CHAR(SYSDATE,'DD-MM-YYYY'),'DD-MM-YYYY')),
4878                -1, 'N', 0, 'N', 'Y')) = 'Y'
4879          AND enabled_flag = 'Y'
4880          AND vendor_id = l_vendor_id;
4881     EXCEPTION
4882       WHEN no_data_found then
4883         l_employee_id := NULL;
4884       WHEN OTHERS then
4885         l_employee_id := NULL;
4886     END;
4887 
4888 --bug5003249
4889      Begin
4890         select default_code_comb_id
4891         into  l_employee_ccid
4892         from  PER_ASSIGNMENTS_F
4893         where person_id =  l_employee_id
4894         and   set_of_books_id =  x_sob_id
4895         and   trunc(sysdate) BETWEEN trunc(effective_start_date)
4896         and   nvl(trunc(effective_end_date), trunc(sysdate));
4897      EXCEPTION
4898          WHEN OTHERS then
4899           l_employee_ccid := NULL;
4900      End;
4901 
4902         select WEB_PARAMETER_ID
4903         into  l_web_parameter_id
4904         from  ap_invoice_lines
4905         where invoice_id = X_invoice_id
4906         AND line_number = X_line_number;
4907 
4908      /* Bug 5102724 */
4909       BEGIN
4910         SELECT invoice_type_lookup_code
4911         INTO   l_invoice_type_lookup_code
4912         FROM   ap_invoices_all
4913         WHERE  invoice_id = X_invoice_id;
4914       EXCEPTION
4915         WHEN no_data_found then
4916           NULL;
4917         WHEN OTHERS then
4918           NULL;
4919       END;
4920 
4921       If (l_invoice_type_lookup_code ='EXPENSE REPORT') Then
4922         l_sys_link_function :='ER' ;
4923       Else
4924         l_sys_link_function :='VI' ;
4925       End if;
4926 
4927     PA_TRANSACTIONS_PUB.VALIDATE_TRANSACTION(
4928                 X_PROJECT_ID          => X_project_id,
4929                 X_TASK_ID             => X_task_id,
4930                 X_EI_DATE             => X_expenditure_item_date,
4931                 X_EXPENDITURE_TYPE    => X_expenditure_type,
4932                 X_NON_LABOR_RESOURCE  => null,
4933                 X_PERSON_ID           => l_employee_id,
4934                 X_QUANTITY            => '1',
4935                 X_denom_currency_code => X_invoice_currency_code,
4936                 X_acct_currency_code  => X_base_currency_code,
4937                 X_denom_raw_cost      => X_amount,
4938                 X_acct_raw_cost       => X_base_amount,
4939                 X_acct_rate_type      => X_exchange_rate_type,
4940                 X_acct_rate_date      => X_exchange_date,
4941                 X_acct_exchange_rate  => X_exchange_rate,
4942                 X_TRANSFER_EI         => null,
4943                 X_INCURRED_BY_ORG_ID  => X_expenditure_org_id,
4944                 X_NL_RESOURCE_ORG_ID  => null,
4945                 X_TRANSACTION_SOURCE  => l_sys_link_function,  /* bug 5102724 */
4946                 X_CALLING_MODULE      => 'apiindib.pls',
4947                 X_VENDOR_ID           => X_vendor_id,
4948                 X_ENTERED_BY_USER_ID  => user_id,
4949                 X_ATTRIBUTE_CATEGORY  => NULL,
4950                 X_ATTRIBUTE1          => NULL,
4951                 X_ATTRIBUTE2          => NULL,
4952                 X_ATTRIBUTE3          => NULL,
4953                 X_ATTRIBUTE4          => NULL,
4954                 X_ATTRIBUTE5          => NULL,
4955                 X_ATTRIBUTE6          => NULL,
4956                 X_ATTRIBUTE7          => NULL,
4957                 X_ATTRIBUTE8          => NULL,
4958                 X_ATTRIBUTE9          => NULL,
4959                 X_ATTRIBUTE10         => NULL,
4960                 X_ATTRIBUTE11         => NULL,
4961                 X_ATTRIBUTE12         => NULL,
4962                 X_ATTRIBUTE13         => NULL,
4963                 X_ATTRIBUTE14         => NULL,
4964                 X_ATTRIBUTE15         => NULL,
4965                 X_msg_application     => l_msg_application,
4966                 X_msg_type            => l_msg_type,
4967                 X_msg_token1          => l_msg_token1,
4968                 X_msg_token2          => l_msg_token2,
4969                 X_msg_token3          => l_msg_token3,
4970                 X_msg_count           => l_msg_count,
4971                 X_msg_data            => l_msg_data,
4972                 X_BILLABLE_FLAG       => l_billable_flag);
4973 
4974     if (l_msg_data is not null) then
4975       X_msg_application := l_msg_application;
4976       X_msg_data := l_msg_data;
4977       --bugfix:5725904
4978       Fnd_Message.Set_Name(l_msg_application, l_msg_data);
4979       /*bug 6682104 setting the token values*/
4980             IF (l_msg_token1 IS NOT NULL) THEN
4981 	       fnd_message.set_token('PATC_MSG_TOKEN1',l_msg_token1);
4982             ELSE
4983 	       fnd_message.set_token('PATC_MSG_TOKEN1',FND_API.G_MISS_CHAR);
4984 	    END IF;
4985 
4986             IF (l_msg_token2 IS NOT NULL) THEN
4987 	        fnd_message.set_token('PATC_MSG_TOKEN2',l_msg_token2);
4988             ELSE
4989 	       fnd_message.set_token('PATC_MSG_TOKEN2',FND_API.G_MISS_CHAR);
4990             END IF;
4991 
4992             IF (l_msg_token3 IS NOT NULL) THEN
4993 	         fnd_message.set_token('PATC_MSG_TOKEN3',l_msg_token3);
4994             ELSE
4995 	          fnd_message.set_token('PATC_MSG_TOKEN3',FND_API.G_MISS_CHAR);
4996             END IF;
4997       l_message_text := Fnd_Message.get;
4998       x_error_code := l_message_text;
4999 
5000       return(FALSE);
5001 
5002     end if;
5003 
5004   end if;
5005 
5006 
5007   --------------------------------------------------------------------------
5008   -- Step 3 - Gather the source of the account. Possible values are
5009   -- a) Account from item distribution (if no PA information)
5010   -- b) Account from item distribution (if PA information from dist)
5011   -- c) Account from PO if accrue on receipt and dist PO matched
5012   -- d) Account from PA if PA information from line
5013   -- Also, the accounts above may be overlayed with overlay information if:
5014   -- 1) Overlay information available
5015   -- 2) If PO matched and account not from line PA info and PO allows overrides
5016   -- 3) If account from line PA info and PA allows overrides
5017   -- 4) If account from item dist, (not PO matched but PA related) and
5018   --    PA allows overrides
5019   -- 5) If account from item dist (not PO matched and not PA related)
5020   ----------------------------------------------------------------------------
5021     --Bug5003249 added condition on invoice type lookup code
5022   IF (X_project_id IS NOT NULL AND X_item_dist_project_id IS NULL
5023       AND l_invoice_type_lookup_code<>'PREPAYMENT') THEN
5024     -- l_dist_ccid := AP_UTILITIES_PKG.PA_FLEXBUILD
5025 
5026     IF ( NOT (AP_UTILITIES_PKG.pa_flexbuild(
5027                p_vendor_id          =>  X_vendor_id,          --IN
5028                p_employee_id        =>  l_employee_id,        --IN
5029                p_set_of_books_id    =>  X_sob_id,             --IN
5030                p_chart_of_accounts_id => X_chart_of_accounts_id, -- IN
5031                p_base_currency_code    =>  X_base_currency_code, --IN
5032                p_accounting_date       =>  X_GL_Date,            --IN
5033                p_award_id              =>  X_award_id,           --IN
5034                P_project_id             => X_project_id,
5035                p_task_id                => X_task_id,
5036                p_expenditure_type       => X_expenditure_type,
5037                p_expenditure_org_id     => X_expenditure_org_id,
5038                p_expenditure_item_date  => X_expenditure_item_date,
5039                p_employee_ccid             =>
5040                       l_employee_ccid,   --Bug5003249
5041                p_web_parameter_id          =>
5042                       l_web_parameter_id,   --Bug5003249
5043                p_invoice_type_lookup_code  =>
5044                       l_invoice_type_lookup_code, --Bug5003249
5045                p_default_last_updated_by => FND_GLOBAL.user_id,
5046                p_default_last_update_login  => FND_GLOBAL.login_id,
5047                p_pa_default_dist_ccid       => l_dist_ccid,
5048                p_pa_concatenated_segments   => l_dist_code_concat, --OUT NOCOPY
5049                p_debug_Info                 => debug_Info, -- OUT  NOCOPY
5050                p_debug_Context             =>  debug_Context, --OUT  NOCOPY
5051                p_calling_sequence          => 'Get_Proj_And_Acc_For_Chrg_Dist' ,
5052                p_default_dist_ccid         =>  X_default_dist_ccid  --IN  bug 5386396
5053                ))) THEN
5054        debug_info := debug_info || ': Error encountered';
5055        debug_context := current_calling_sequence;
5056        RETURN(FALSE);
5057     END IF;
5058     IF (X_pa_allows_overrides = 'Y' AND
5059         (X_overlay_dist_code_concat   IS NOT NULL OR
5060          X_balancing_segment   IS NOT NULL OR
5061          X_account_segment     IS NOT NULL OR
5062          X_cost_center_segment IS NOT NULL)) THEN
5063 
5064       IF ( NOT (AP_UTILITIES_PKG.OVERLAY_SEGMENTS (
5065                    X_balancing_segment,
5066                    X_cost_center_segment,
5067                    X_account_segment,
5068                    X_overlay_dist_code_concat,
5069                    l_dist_ccid,
5070                    X_sob_id,
5071                    'CREATE_COMB_NO_AT',
5072                    l_unbuilt_flex,
5073                    l_reason_unbuilt_flex,
5074                    FND_GLOBAL.RESP_APPL_ID,
5075                    FND_GLOBAL.RESP_ID,
5076                    FND_GLOBAL.USER_ID,
5077                    'Create Charge Account'))) then
5078         X_error_code := 'AP_CANNOT_OVERLAY';
5079         RETURN(FALSE);
5080       END IF;
5081     END IF;
5082 
5083   ELSIF (X_item_po_dist_id IS NOT NULL) THEN
5084     BEGIN
5085       SELECT code_combination_id,
5086              accrue_on_receipt_flag
5087         INTO l_po_ccid,
5088              l_po_accrue_on_receipt_flag
5089         FROM po_distributions
5090        WHERE po_distribution_id = X_item_po_dist_id;
5091 
5092     EXCEPTION
5093       When no_data_found then
5094         return(FALSE);
5095     END;
5096 
5097     IF (l_po_accrue_on_receipt_flag = 'Y') THEN
5098       l_dist_ccid := l_po_ccid;
5099     ELSE
5100       l_dist_ccid := X_item_dist_ccid;
5101     END IF;
5102 
5103 
5104     IF (((X_item_dist_project_id is null and
5105           X_allow_po_override = 'Y' ) OR
5106          (X_item_dist_project_id IS NOT NULL AND
5107           X_pa_allows_overrides = 'Y' AND
5108           X_allow_po_override = 'Y')) AND
5109         (X_overlay_dist_code_concat   IS NOT NULL OR
5110          X_balancing_segment          IS NOT NULL OR
5111          X_account_segment            IS NOT NULL OR
5112          X_cost_center_segment        IS NOT NULL)
5113 
5114          ) THEN
5115 
5116       IF ( NOT (AP_UTILITIES_PKG.OVERLAY_SEGMENTS (
5117                    X_balancing_segment,
5118                    X_cost_center_segment,
5119                    X_account_segment,
5120                    X_overlay_dist_code_concat,
5121                    l_dist_ccid,
5122                    X_sob_id,
5123                    'CREATE_COMB_NO_AT',
5124                    l_unbuilt_flex,
5125                    l_reason_unbuilt_flex,
5126                    FND_GLOBAL.RESP_APPL_ID,
5127                    FND_GLOBAL.RESP_ID,
5128                    FND_GLOBAL.USER_ID,
5129                    'Create Charge Account'))) THEN
5130         X_error_code := 'AP_CANNOT_OVERLAY';
5131         RETURN(FALSE);
5132       END IF;
5133 
5134     ELSE
5135       IF ( NOT (AP_UTILITIES_PKG.IS_CCID_VALID(
5136                   l_dist_ccid,
5137                   X_chart_of_accounts_id,
5138                   X_GL_date,
5139                   'Create Charge Account'))) THEN
5140         X_error_code := 'AP_INVALID_ACCOUNT';
5141         RETURN(FALSE);
5142       END IF;
5143 
5144     END IF;
5145 
5146   ELSE
5147     l_dist_ccid := X_item_dist_ccid;
5148     if (X_overlay_dist_code_concat IS NOT NULL OR
5149         X_balancing_segment   IS NOT NULL OR
5150         X_account_segment     IS NOT NULL OR
5151         X_cost_center_segment IS NOT NULL) THEN
5152 
5153       IF ( NOT (AP_UTILITIES_PKG.OVERLAY_SEGMENTS (
5154                   X_balancing_segment,
5155                   X_cost_center_segment,
5156                   X_account_segment,
5157                   X_overlay_dist_code_concat,
5158                   l_dist_ccid,
5159                   X_sob_id,
5160                   'CREATE_COMB_NO_AT',
5161                   l_unbuilt_flex,
5162                   l_reason_unbuilt_flex,
5163                   FND_GLOBAL.RESP_APPL_ID,
5164                   FND_GLOBAL.RESP_ID,
5165                   FND_GLOBAL.USER_ID,
5166                   'Create Charge Account'))) then
5167         X_error_code := 'AP_CANNOT_OVERLAY';
5168         RETURN(FALSE);
5169       END IF;
5170     ELSE
5171       IF ( NOT (AP_UTILITIES_PKG.IS_CCID_VALID(l_dist_ccid,
5172                                                X_chart_of_accounts_id,
5173                                                X_GL_date,
5174                                                'Create Charge Account'))) then
5175         X_error_code := 'AP_INVALID_ACCOUNT';
5176         RETURN(FALSE);
5177       END IF;
5178     END IF;
5179   END IF;
5180 
5181   X_account_for_dist := l_dist_ccid;
5182 
5183   -------------------------------------------------------------------
5184   -- Step 4 - Get account type and asset information
5185   -------------------------------------------------------------------
5186   BEGIN
5187     SELECT account_type
5188       INTO l_account_type
5189       FROM gl_code_combinations
5190      WHERE code_combination_id = l_dist_ccid;
5191 
5192   EXCEPTION
5193     WHEN no_data_found THEN
5194        RETURN(FALSE);
5195   END;
5196 
5197   IF (l_account_type = 'A') THEN
5198     X_assets_tracking_flag := 'Y';
5199     X_asset_book_typ_code := nvl(X_item_asset_book_type_code,
5200                                   X_chrg_asset_book_type_code);
5201     X_asset_category_id := nvl(X_item_asset_category_id,
5202                                       X_chrg_asset_category_id);
5203   ELSIF (l_account_type = 'E' AND
5204          X_chrg_assets_track_flag = 'Y') THEN
5205     X_assets_tracking_flag := 'Y';
5206     X_asset_book_typ_code := X_chrg_asset_book_type_code;
5207     X_asset_category_id := X_chrg_asset_category_id;
5208   ELSE
5209     X_assets_tracking_flag := 'N';
5210     X_asset_book_typ_code := NULL;
5211     X_asset_category_id := NULL;
5212   END IF;
5213 
5214   IF (X_item_dist_award_id IS NOT NULL) THEN
5215       gms_ap_api.get_distribution_award
5216 			(p_invoice_id		    => NULL,
5217 			 p_distribution_line_number => NULL,
5218 			 p_invoice_distribution_id  => NULL,
5219 			 p_award_set_id             => x_item_dist_award_id,
5220 			 p_award_id		    => x_award_id);
5221 
5222   ELSIF (X_chrg_line_award_id is not null) then
5223     x_award_id := X_chrg_line_award_id;
5224   ELSE
5225     x_award_id := NULL;
5226   END IF;
5227 
5228   IF (X_award_id IS NOT NULL AND X_item_dist_award_id IS NOT NULL) then
5229 	GMS_AP_API.validate_transaction
5230 			( x_project_id		  => X_project_id,
5231 			  x_task_id		  => X_task_id,
5232 			  x_award_id		  => X_award_id,
5233 			  x_expenditure_type	  => X_expenditure_type,
5234  			  x_expenditure_item_date => X_expenditure_item_date,
5235 			  x_calling_sequence	  => current_calling_sequence,
5236 			  x_msg_application       => l_msg_application,
5237 			  x_msg_type              => l_msg_type,
5238 			  x_msg_count             => l_msg_count,
5239 			  x_msg_data              => l_msg_data );
5240 
5241 	IF (l_msg_data is not null) THEN
5242 	    X_msg_application := l_msg_application;
5243 	    X_msg_data := l_msg_data;
5244 	    Return(FALSE);
5245 	END IF;
5246   END IF;
5247 
5248   RETURN(TRUE);
5249 
5250 END get_proj_and_acc_for_chrg_dist;
5251 
5252 
5253   -----------------------------------------------------------------------
5254   -- FUNCTION insert_charge_from_alloc inserts charge distributions based
5255   -- on the defined allocations for the parent line.
5256   -- It returns FALSE if an error is encountered.
5257   -----------------------------------------------------------------------
5258   FUNCTION Insert_Charge_From_Alloc(
5259            X_invoice_id          IN         NUMBER,
5260            X_line_number         IN         NUMBER,
5261            X_Generate_Permanent  IN         VARCHAR2 DEFAULT 'N',
5262            X_Validate_Info       IN         BOOLEAN DEFAULT TRUE,
5263            X_Error_Code          OUT NOCOPY VARCHAR2,
5264            X_Debug_Info          OUT NOCOPY VARCHAR2,
5265            X_Debug_Context       OUT NOCOPY VARCHAR2,
5266            X_Msg_Application     OUT NOCOPY VARCHAR2,
5267            X_Msg_Data            OUT NOCOPY VARCHAR2,
5268            X_Calling_Sequence    IN         VARCHAR2) RETURN BOOLEAN
5269   IS
5270 
5271   CURSOR alloc_rule_lines_cur IS
5272   SELECT ARL.to_invoice_line_number,
5273          ARL.percentage,
5274          ARL.amount,
5275          Sum(AID.amount)
5276     FROM AP_Allocation_Rule_Lines ARL,
5277          AP_invoice_distributions_all AID
5278     WHERE ARL.invoice_id = X_invoice_id
5279       AND AID.invoice_id = X_invoice_id
5280       AND ARL.chrg_invoice_line_number = X_line_number
5281       AND AID.invoice_line_number = ARL.to_invoice_line_number
5282       AND AID.line_type_lookup_code in ('ITEM', 'ACCRUAL', 'IPV', 'ERV')
5283   --Invoice Lines: Distributions,  Added the ARL.amount, ARL.percentage
5284   --to the GROUP BY , without those cursor is INVALID
5285   GROUP BY ARL.to_invoice_line_number, ARL.amount,ARL.percentage
5286   ORDER BY ARL.to_invoice_line_number;
5287 
5288 
5289   CURSOR applicable_lines_cur IS
5290     SELECT AIL.line_number,
5291            AIL.amount,
5292            sum(AID.amount)
5293       FROM AP_invoice_lines AIL,
5294            AP_invoice_distributions_all AID
5295      WHERE AIL.invoice_id = X_invoice_id
5296        AND nvl(AIL.discarded_flag, 'N') = 'N'
5297        AND nvl(AIL.cancelled_flag, 'N') = 'N'
5298        AND AIL.amount <> 0
5299        AND AIL.line_type_lookup_code = 'ITEM'
5300        AND nvl(AIL.match_type,'NOT_MATCHED') NOT IN
5301  	      ('PRICE_CORRECTION', 'QTY_CORRECTION','LINE_CORRECTION','AMOUNT_CORRECTION')
5302        AND AID.invoice_line_number = AIL.line_number
5303        AND AID.invoice_id = X_invoice_id
5304        AND AID.line_type_lookup_code IN ('ITEM', 'ACCRUAL', 'IPV', 'ERV')
5305   --Invoice Lines: Distributions, added AIL.amount to the GROUPBY clause
5306   GROUP BY AIL.line_number,AIL.amount
5307   ORDER BY AIL.line_number;
5308 
5309   CURSOR applicable_dists_cur (P_line_number IN NUMBER) IS
5310     SELECT AID.invoice_distribution_id,
5311            AID.po_distribution_id,
5312            AID.rcv_transaction_id,
5313            AID.project_id,
5314            AID.task_id,
5315 	   AID.pa_quantity,   -- bug6699834
5316            AID.expenditure_type,
5317            AID.expenditure_organization_id,
5318            AID.award_id,
5319 	   AP_INVOICE_DISTRIBUTIONS_PKG.GET_TOTAL_DIST_AMOUNT(
5320 			aid.invoice_distribution_id),
5321            AID.dist_code_combination_id,
5322            AID.assets_tracking_flag,
5323            AID.asset_book_type_code,
5324            AID.asset_category_id,
5325            AID.description
5326       FROM ap_invoice_distributions_all AID
5327      WHERE AID.invoice_id = X_invoice_id
5328        AND AID.invoice_line_number = P_line_number
5329        AND AID.line_type_lookup_code in ('ITEM', 'ACCRUAL')
5330   ORDER BY AID.distribution_line_number;
5331 
5332 
5333   l_batch_id               AP_INVOICE_DISTRIBUTIONS.BATCH_ID%TYPE;
5334   l_distribution_class     AP_INVOICE_DISTRIBUTIONS.DISTRIBUTION_CLASS%TYPE;
5335   l_org_id                 AP_INVOICE_LINES.ORG_ID%TYPE;
5336   l_sob_id                 AP_INVOICE_LINES.SET_OF_BOOKS_ID%TYPE;
5337   l_base_currency_code     AP_SYSTEM_PARAMETERS.BASE_CURRENCY_CODE%TYPE;
5338   l_chart_of_accounts_id   GL_SETS_OF_BOOKS.CHART_OF_ACCOUNTS_ID%TYPE;
5339   l_account_type           GL_CODE_COMBINATIONS.ACCOUNT_TYPE%TYPE;
5340   l_invoice_date           AP_INVOICES.INVOICE_DATE%TYPE;
5341   l_vendor_id              AP_INVOICES.VENDOR_ID%TYPE;
5342   l_invoice_amount         AP_INVOICES.INVOICE_AMOUNT%TYPE;
5343   l_exchange_rate          AP_INVOICES.EXCHANGE_RATE%TYPE;
5344   l_exchange_rate_type     AP_INVOICES.EXCHANGE_RATE_TYPE%TYPE;
5345   l_exchange_date          AP_INVOICES.EXCHANGE_DATE%TYPE;
5346   l_invoice_currency_code  AP_INVOICES.INVOICE_CURRENCY_CODE%TYPE;
5347   l_assets_tracking_flag   AP_INVOICE_LINES.ASSETS_TRACKING_FLAG%TYPE;
5348   l_asset_book_type_code   AP_INVOICE_LINES.ASSET_BOOK_TYPE_CODE%TYPE;
5349   l_asset_category_id      AP_INVOICE_LINES.ASSET_CATEGORY_ID%TYPE;
5350   l_line_amount            AP_INVOICE_LINES.AMOUNT%TYPE;
5351   l_line_base_amount       AP_INVOICE_LINES.BASE_AMOUNT%TYPE;
5352   l_line_type_lookup_code  AP_INVOICE_LINES.LINE_TYPE_LOOKUP_CODE%TYPE;
5353   l_line_description       AP_INVOICE_LINES.DESCRIPTION%TYPE;
5354   l_sum_lines_amount       AP_INVOICE_LINES.AMOUNT%TYPE;
5355   l_default_dist_ccid      AP_INVOICE_LINES.DEFAULT_DIST_CCID%TYPE;
5356   l_overlay_dist_concat    AP_INVOICE_LINES.OVERLAY_DIST_CODE_CONCAT%TYPE;
5357   l_balancing_segment      AP_INVOICE_LINES.BALANCING_SEGMENT%TYPE;
5358   l_account_segment        AP_INVOICE_LINES.ACCOUNT_SEGMENT%TYPE;
5359   l_cost_center_segment    AP_INVOICE_LINES.COST_CENTER_SEGMENT%TYPE;
5360   l_project_id             AP_INVOICE_LINES.PROJECT_ID%TYPE;
5361   l_task_id                AP_INVOICE_LINES.TASK_ID%TYPE;
5362   l_award_id		   AP_INVOICE_LINES.AWARD_ID%TYPE;
5363   l_expenditure_type       AP_INVOICE_LINES.EXPENDITURE_TYPE%TYPE;
5364   l_expenditure_organization_id
5365     AP_INVOICE_LINES.EXPENDITURE_ORGANIZATION_ID%TYPE;
5366   l_accounting_date        AP_INVOICE_LINES.ACCOUNTING_DATE%TYPE;
5367   l_created_by             AP_INVOICE_LINES.CREATED_BY%TYPE;
5368   l_last_update_login      AP_INVOICE_LINES.LAST_UPDATE_LOGIN%TYPE;
5369   l_awt_group_id           AP_INVOICE_LINES.AWT_GROUP_ID%TYPE;
5370 
5371 l_pay_awt_group_id           AP_INVOICE_LINES.PAY_AWT_GROUP_ID%TYPE;	---7022001
5372 
5373   l_type_1099              AP_INVOICE_LINES.TYPE_1099%TYPE;
5374   l_income_tax_region      AP_INVOICE_LINES.INCOME_TAX_REGION%TYPE;
5375   l_open_gl_date           AP_INVOICE_LINES.ACCOUNTING_DATE%TYPE;
5376   l_open_period_name       AP_INVOICE_LINES.PERIOD_NAME%TYPE;
5377   l_invoice_distribution_id
5378     AP_INVOICE_DISTRIBUTIONS.INVOICE_DISTRIBUTION_ID%TYPE;
5379   l_po_distribution_id     AP_INVOICE_DISTRIBUTIONS.PO_DISTRIBUTION_ID%TYPE;
5380   l_rcv_transaction_id     AP_INVOICE_DISTRIBUTIONS.RCV_TRANSACTION_ID%TYPE;
5381   l_dist_project_id        AP_INVOICE_DISTRIBUTIONS.PROJECT_ID%TYPE;
5382   l_dist_task_id           AP_INVOICE_DISTRIBUTIONS.TASK_ID%TYPE;
5383   l_dist_pa_quantity       AP_INVOICE_DISTRIBUTIONS.PA_QUANTITY%TYPE; --6699834
5384   l_dist_award_id          AP_INVOICE_DISTRIBUTIONS.AWARD_ID%TYPE;
5385   l_dist_expenditure_type  AP_INVOICE_DISTRIBUTIONS.EXPENDITURE_TYPE%TYPE;
5386   l_dist_expenditure_org_id
5387     AP_INVOICE_DISTRIBUTIONS.EXPENDITURE_ORGANIZATION_ID%TYPE;
5388   l_dist_amount            AP_INVOICE_DISTRIBUTIONS.AMOUNT%TYPE;
5389   l_dist_base_amount       AP_INVOICE_DISTRIBUTIONS.BASE_AMOUNT%TYPE;
5390   l_dist_code_combination_id
5391     AP_INVOICE_DISTRIBUTIONS.DIST_CODE_COMBINATION_ID%TYPE;
5392   l_dist_assets_tracking_flag
5393     AP_INVOICE_DISTRIBUTIONS.ASSETS_TRACKING_FLAG%TYPE;
5394   l_dist_asset_book_type_code
5395     AP_INVOICE_DISTRIBUTIONS.ASSET_BOOK_TYPE_CODE%TYPE;
5396   l_dist_asset_category_id
5397     AP_INVOICE_DISTRIBUTIONS.ASSET_CATEGORY_ID%TYPE;
5398   l_dist_description       AP_INVOICE_DISTRIBUTIONS.DESCRIPTION%TYPE;
5399   l_dist_tab               AP_INVOICE_LINES_PKG.dist_tab_type;
5400   l_alloc_line_tab         AP_INVOICE_LINES_PKG.alloc_line_tab_type;
5401   l_rule_type              AP_ALLOCATION_RULES.RULE_TYPE%TYPE;
5402   l_rule_status            AP_ALLOCATION_RULES.STATUS%TYPE;
5403   l_alloc_rule_line_percent AP_ALLOCATION_RULE_LINES.PERCENTAGE%TYPE := 0;
5404   l_alloc_rule_line_amount AP_ALLOCATION_RULE_LINES.AMOUNT%TYPE := 0;
5405   l_alloc_rule_line_number
5406     AP_ALLOCATION_RULE_LINES.TO_INVOICE_LINE_NUMBER%TYPE;
5407   l_applicable_line_number AP_INVOICE_LINES.LINE_NUMBER%TYPE;
5408   l_applicable_line_amount AP_INVOICE_LINES.AMOUNT%TYPE := 0;
5409   l_sum_applic_lines       AP_INVOICE_LINES.AMOUNT%TYPE := 0;
5410   l_sum_dists_applic_line  AP_INVOICE_DISTRIBUTIONS.AMOUNT%TYPE := 0;
5411   l_running_total_alloc    AP_INVOICE_LINES.AMOUNT%TYPE := 0;
5412   l_running_total_base_amt AP_INVOICE_LINES.BASE_AMOUNT%TYPE := 0;
5413   l_max_alloc              AP_INVOICE_LINES.AMOUNT%TYPE := 0;
5414   l_max_base_alloc         AP_INVOICE_LINES.BASE_AMOUNT%TYPE := 0;
5415   l_msg_application      VARCHAR2(25);
5416   l_msg_data           VARCHAR2(30);
5417   i                        BINARY_INTEGER := 0;
5418   t                        BINARY_INTEGER := 0;
5419   l_max_i                  BINARY_INTEGER := 0;
5420   l_max_base_i             BINARY_INTEGER := 0;
5421   l_max_t                  BINARY_INTEGER := 0;
5422   l_pa_allows_overrides    VARCHAR2(1) := 'N';
5423   l_allow_po_override      AP_SYSTEM_PARAMETERS.ALLOW_FLEX_OVERRIDE_FLAG%TYPE;
5424   l_error_found            VARCHAR2(1) := 'N';
5425   l_error_code             VARCHAR2(80);
5426   l_existing_distributions NUMBER := 0;
5427   l_count_undistributed_lines NUMBER := 1;
5428   l_count_applicable_dists NUMBER := 0;
5429   current_calling_sequence VARCHAR2(2000);
5430   debug_info               VARCHAR2(1000);
5431 
5432   l_inv_dist_id		   AP_INVOICE_DISTRIBUTIONS.INVOICE_DISTRIBUTION_ID%TYPE;
5433 
5434   -- Bug 5114543
5435   l_max_dist_line_num	   NUMBER :=0;
5436   l_chrg_line_rec	   ap_invoice_lines_all%rowtype;
5437   l_dummy		   VARCHAR2(30);
5438 
5439 BEGIN
5440 
5441 
5442   ---------------------------------------------------------------------------
5443   -- Step 1 - Update the calling sequence
5444   ---------------------------------------------------------------------------
5445   current_calling_sequence :=
5446     'AP_INVOICE_DISTRIBUTIONS_PKG.insert_charge_from_alloc <-'
5447     ||X_calling_sequence;
5448 
5449   --------------------------------------------------------------------------
5450   -- Step 2 - Validate the line exists and get line level information
5451   --------------------------------------------------------------------------
5452   debug_info := 'Verify valid invoice line provided';
5453   BEGIN
5454     SELECT org_id,
5455            set_of_books_id,
5456            default_dist_ccid,
5457            overlay_dist_code_concat,
5458            balancing_segment,
5459            account_segment,
5460            cost_center_segment,
5461            project_id,
5462            task_id,
5463 	   award_id,
5464            expenditure_type,
5465            expenditure_organization_id,
5466            assets_tracking_flag,
5467            asset_book_type_code,
5468            asset_category_id,
5469            accounting_date,
5470            amount,
5471            base_amount,
5472            line_type_lookup_code,
5473            description,
5474            awt_group_id,
5475            type_1099,
5476            income_tax_region,
5477            created_by,
5478            last_update_login,
5479           pay_awt_group_id
5480       INTO l_org_id,
5481            l_sob_id,
5482            l_default_dist_ccid,
5483            l_overlay_dist_concat,
5484            l_balancing_segment,
5485            l_account_segment,
5486            l_cost_center_segment,
5487            l_project_id,
5488            l_task_id,
5489 	   l_award_id,
5490            l_expenditure_type,
5491            l_expenditure_organization_id,
5492            l_assets_tracking_flag,
5493            l_asset_book_type_code,
5494            l_asset_category_id,
5495            l_accounting_date,
5496            l_line_amount,
5497            l_line_base_amount,
5498            l_line_type_lookup_code,
5499            l_line_description,
5500            l_awt_group_id,
5501            l_type_1099,
5502            l_income_tax_region,
5503            l_created_by,
5504            l_last_update_login,
5505            l_pay_awt_group_id
5506       FROM ap_invoice_lines
5507      WHERE invoice_id = X_invoice_id
5508        AND line_number = X_line_number;
5509 
5510   EXCEPTION
5511     WHEN NO_DATA_FOUND THEN
5512       X_debug_info := debug_info || ': line not found';
5513       X_debug_context := current_calling_sequence;
5514       RETURN (FALSE);
5515 
5516   END;
5517   --------------------------------------------------------------------------
5518   -- Step 3 - Validate line does not contain other distributions
5519   --------------------------------------------------------------------------
5520   IF (X_Validate_Info) then
5521     debug_info := 'Verify line does not contain distributions';
5522     BEGIN
5523       SELECT count(*)
5524         INTO l_existing_distributions
5525         FROM ap_invoice_distributions
5526        WHERE invoice_id = X_invoice_id
5527          AND invoice_line_number = X_line_number;
5528 
5529       IF (l_existing_distributions <> 0) then
5530           -- X_debug_info := debug_info || ': line already has distributions';
5531           -- X_debug_context := current_calling_sequence;
5532           -- RETURN(FALSE);
5533 
5534           -- Bug 5114543
5535 	  -- Instead of returning a failure, reverse any open inv distributions and
5536 	  -- continue with creation of charge distributions based on the allocation.
5537 
5538 	  select ail.*
5539             into l_chrg_line_rec
5540 	    from ap_invoice_lines_all ail
5541 	   where invoice_id  = X_invoice_id
5542 	     and line_number = X_line_number;
5543 
5544           if not ap_invoice_lines_pkg.reverse_charge_distributions
5545 		                        (p_inv_line_rec         => l_chrg_line_rec
5546 		                        ,p_calling_mode         => l_dummy
5547 		                        ,x_error_code           => x_error_code
5548 		                        ,x_debug_info           => debug_info
5549 		                        ,p_calling_sequence     => current_calling_sequence) then
5550 
5551 	     x_debug_info := debug_info || ': unable to reverse charge distributions';
5552 	     x_debug_context := current_calling_sequence;
5553 	     return (false);
5554 
5555           end if;
5556       END IF;
5557 
5558     EXCEPTION
5559       WHEN OTHERS THEN
5560         NULL;
5561     END;
5562   END IF;
5563 
5564   --------------------------------------------------------------------------
5565   -- Step 4 - Get invoice information
5566   --------------------------------------------------------------------------
5567   debug_info := 'Get invoice information';
5568   BEGIN
5569     SELECT batch_id,
5570            invoice_date,
5571            vendor_id,
5572            exchange_rate,
5573            exchange_rate_type,
5574            exchange_date,
5575            invoice_currency_code,
5576            invoice_amount
5577       INTO l_batch_id,
5578            l_invoice_date,
5579            l_vendor_id,
5580            l_exchange_rate,
5581            l_exchange_rate_type,
5582            l_exchange_date,
5583            l_invoice_currency_code,
5584            l_invoice_amount
5585       FROM ap_invoices
5586      WHERE invoice_id = X_invoice_id;
5587 
5588   EXCEPTION
5589     When no_data_found then
5590       X_debug_info := debug_info || ': cannot read invoice';
5591       X_debug_context := current_calling_sequence;
5592       RETURN (FALSE);
5593   END;
5594 
5595   ---------------------------------------------------------------------------
5596   -- Step 5 - Validate all lines charge is allocated to have been distributed
5597   ---------------------------------------------------------------------------
5598   debug_info := 'Verify all lines to allocate against are distributed';
5599 
5600   BEGIN
5601     SELECT rule_type, status
5602       INTO l_rule_type, l_rule_status
5603       FROM ap_allocation_rules
5604      WHERE invoice_id = X_invoice_id
5605        AND chrg_invoice_line_number = X_line_number;
5606 
5607   EXCEPTION
5608     WHEN no_data_found THEN
5609       X_error_code := 'AP_NO_ALLOCATION_RULE_FOUND';
5610       RETURN(FALSE);
5611   END;
5612 
5613   IF (l_rule_status = 'EXECUTED') then
5614     X_error_code := 'AP_ALLOCATION_ALREADY_EXECUTED';
5615     RETURN(FALSE);
5616   END IF;
5617 
5618   IF (l_rule_type = 'PRORATION') then
5619     BEGIN
5620       --Bug 5558693
5621       SELECT DECODE(NVL(ai.net_of_retainage_flag, 'N'),
5622                    'Y', (SUM(NVL(ail.amount, 0)) + SUM(NVL(retained_amount,0))),
5623                     SUM(ail.amount) )
5624         INTO l_sum_lines_amount
5625         FROM ap_invoice_lines_all ail,
5626              ap_invoices_all ai
5627        WHERE ai.invoice_id = ail.invoice_id
5628          AND ail.invoice_id = X_invoice_id
5629          AND ail.line_type_lookup_code NOT IN ('AWT')
5630 	 /*bugfix:5685469*/
5631 	 AND    ((AIL.line_type_lookup_code <> 'TAX'
5632 	          and (AIL.line_type_lookup_code NOT IN ('PREPAY')
5633 		       or NVL(AIL.invoice_includes_prepay_flag,'N') = 'Y'
5634 		      )
5635 		 OR
5636 		 (AIL.line_type_lookup_code = 'TAX'
5637                   and (AIL.prepay_invoice_id IS NULL
5638                       or (AIL.prepay_invoice_id is not null
5639                           and NVL(AIL.invoice_includes_prepay_flag, 'N') = 'Y'
5640 			 )
5641 	       	      )
5642 		 )
5643 		)
5644 	       )
5645           group by ai.net_of_retainage_flag;
5646 
5647     EXCEPTION
5648       When no_data_found then
5649         X_debug_info := debug_info || ': cannot read lines for invoice';
5650         X_debug_context := current_calling_sequence;
5651         RETURN(FALSE);
5652     END;
5653 
5654     IF (l_invoice_amount <> l_sum_lines_amount) then
5655       X_error_code := 'AP_NON_FULL_INVOICE';
5656       RETURN(FALSE);
5657     END IF;
5658 
5659     BEGIN
5660       SELECT count(*)
5661         INTO l_count_undistributed_lines
5662         FROM ap_invoice_lines_all AIL
5663        WHERE AIL.invoice_id = X_invoice_id
5664          AND AIL.line_type_lookup_code = 'ITEM'
5665          AND NVL(AIL.match_type,'NOT_MATCHED') NOT IN
5666 		('PRICE_CORRECTION', 'QTY_CORRECTION','LINE_CORRECTION','AMOUNT_CORRECTION')
5667          --Bug 5558693
5668          AND amount  <>
5669                (SELECT NVL(SUM(NVL(aid.amount,0)),0)
5670                           FROM ap_invoice_distributions_all AID
5671                          WHERE AID.invoice_id = ail.invoice_id
5672                            AND AID.invoice_line_number = AIL.line_number
5673                            AND (AID.line_type_lookup_code NOT IN ('RETAINAGE','PREPAY')
5674                                 OR (AID.prepay_distribution_id IS NOT NULL
5675                                      AND AID.line_type_lookup_code IN ('REC_TAX', 'NONREC_TAX', 'TIPV', 'TRV', 'TERV')))
5676                 );
5677 
5678       IF (l_count_undistributed_lines <> 0) then
5679         X_error_code := 'AP_UNDISTRIBUTED_LINE_EXISTS';
5680         RETURN(FALSE);
5681       END IF;
5682     EXCEPTION
5683       WHEN no_data_found THEN
5684         X_debug_info := debug_info || ': cannot read lines for invoice';
5685         X_debug_context := current_calling_sequence;
5686     END;
5687 
5688   ELSE
5689     BEGIN
5690 
5691       SELECT count(*)
5692         INTO l_count_undistributed_lines
5693         FROM ap_invoice_lines AIL, ap_allocation_rule_lines ARL
5694        WHERE AIL.invoice_id = X_invoice_id
5695          AND ARL.invoice_id = X_invoice_id
5696          AND ARL.chrg_invoice_line_number = X_line_number
5697          AND ARL.to_invoice_line_number = AIL.line_number
5698          --Bug 5558693
5699          AND AIL.amount <> (SELECT NVL(SUM(nvl(amount,0)),0)
5700                               FROM ap_invoice_distributions AID
5701                              WHERE AID.invoice_id = AIL.invoice_id
5702                                AND AID.invoice_line_number = AIL.line_number
5703                                AND (AID.line_type_lookup_code NOT IN ('RETAINAGE','PREPAY')
5704                                 OR (AID.prepay_distribution_id IS NOT NULL
5705                                      AND AID.line_type_lookup_code IN ('REC_TAX', 'NONREC_TAX', 'TIPV', 'TRV', 'TERV')))
5706                            );
5707 
5708       IF (l_count_undistributed_lines <> 0) then
5709         X_error_code := 'AP_UNDISTRIBUTED_LINE_EXISTS';
5710         RETURN(FALSE);
5711       END IF;
5712     EXCEPTION
5713       WHEN NO_DATA_FOUND THEN
5714         X_debug_info := debug_info || ': cannot read lines for invoice';
5715         X_debug_context := current_calling_sequence;
5716     END;
5717   END IF;
5718 
5719   ---------------------------------------------------------------------------
5720   -- Step 6 - Get GL Date and Period name.
5721   ---------------------------------------------------------------------------
5722   debug_info :=
5723     'Get gl date from open period if line gl date is in a closed one';
5724   BEGIN
5725     l_open_period_name := NULL;
5726     l_open_period_name := AP_UTILITIES_PKG.GET_CURRENT_GL_DATE(
5727                                     l_accounting_date,
5728 				    l_org_id);
5729 
5730     IF (l_open_period_name is NULL) then
5731       AP_UTILITIES_PKG.GET_OPEN_GL_DATE(l_accounting_date, l_open_period_name,
5732                                         l_open_gl_date,l_org_id);
5733     --Invoice Lines: Distributions, added the ELSE part of the IF condition
5734     ELSE
5735       l_open_gl_date := l_accounting_date;
5736     END IF;
5737 
5738     IF (l_open_period_name is NULL) THEN
5739       X_error_code := 'AP_NO_OPEN_PERIOD';
5740       RETURN(FALSE);
5741     END IF;
5742   END;
5743 
5744 
5745   --------------------------------------------------------------
5746   -- Step 7 - Get system level information necessary for
5747   -- validation and generation of distributions
5748   --------------------------------------------------------------
5749   debug_info := 'Get system information';
5750   BEGIN
5751     SELECT gsob.chart_of_accounts_id, ap.base_currency_code,
5752            ap.allow_flex_override_flag
5753       INTO l_chart_of_accounts_id, l_base_currency_code,
5754            l_allow_po_override
5755       FROM ap_system_parameters ap, gl_sets_of_books gsob
5756      WHERE ap.set_of_books_id = gsob.set_of_books_id;
5757 
5758   l_pa_allows_overrides :=
5759     FND_PROFILE.VALUE('PA_ALLOW_FLEXBUILDER_OVERRIDES');
5760 
5761   EXCEPTION
5762   WHEN no_data_found THEN
5763     Debug_info := debug_info || ': No GL information was found';
5764     X_debug_context := current_calling_sequence;
5765     X_debug_info := debug_info;
5766     RETURN(FALSE);
5767   END;
5768 
5769 
5770   --------------------------------------------------------------------------
5771   -- Step 8 - Commence proration to all applicable lines.
5772   -- Verify per line that we may not divide by 0 (which could happen
5773   -- if all distributions for a line are of type other than ITEM or
5774   -- ACCRUAL (IPV and ERV included).  Will divide sql into the 3 rule types.
5775   --------------------------------------------------------------------------
5776   debug_info := 'Commence proration';
5777   BEGIN
5778     IF (l_rule_type = 'PRORATION') THEN
5779       t := 0;
5780       BEGIN
5781         OPEN applicable_lines_cur;
5782         LOOP
5783           FETCH applicable_lines_cur
5784            INTO l_applicable_line_number,
5785                 l_applicable_line_amount,
5786                 l_sum_dists_applic_line;
5787 
5788           EXIT WHEN applicable_lines_cur%NOTFOUND;
5789 
5790           IF (l_sum_dists_applic_line <> 0) THEN
5791             l_sum_applic_lines :=
5792               l_sum_applic_lines + l_applicable_line_amount;
5793             l_alloc_line_tab(t).invoice_line_number :=
5794               l_applicable_line_number;
5795             l_alloc_line_tab(t).amount := l_applicable_line_amount;
5796             l_alloc_line_tab(t).sum_amount_dists := l_sum_dists_applic_line;
5797             t := t+1;
5798           END IF;
5799         END LOOP;
5800         CLOSE applicable_lines_cur;
5801 
5802         FOR t IN 0..l_alloc_line_tab.COUNT-1
5803         LOOP
5804           l_alloc_line_tab(t).amount :=
5805              AP_UTILITIES_PKG.Ap_Round_Currency(
5806                (l_alloc_line_tab(t).amount * l_line_amount) /
5807                 l_sum_applic_lines,
5808                 l_invoice_currency_code);
5809           IF (ABS(l_alloc_line_tab(t).amount) >= ABS(nvl(l_max_alloc,0)) OR
5810               t = 0) then
5811             l_max_alloc := l_alloc_line_tab(t).amount;
5812             l_max_t := t;
5813           END IF;
5814           l_running_total_alloc :=
5815             nvl(l_running_total_alloc, 0) + l_alloc_line_tab(t).amount;
5816         END LOOP;
5817 
5818 	--Invoice Lines: Distributions
5819 	--Basically for the case when user allocates the charge line
5820 	--to items lines which have no item distributions, this can
5821 	--result in l_alloca_line_tab having no records in the table.
5822 
5823         l_count_applicable_dists := l_alloc_line_tab.COUNT;
5824         IF (l_count_applicable_dists = 0) THEN
5825            x_error_code := 'NO_APPLICABLE_DISTS';
5826            RETURN(FALSE);
5827         END IF;
5828 
5829       EXCEPTION
5830         WHEN OTHERS THEN
5831           CLOSE applicable_lines_cur;
5832           X_debug_info := debug_info || ': Error encountered';
5833           X_debug_context := current_calling_sequence;
5834           RETURN(FALSE);
5835       END;
5836 
5837       IF (l_line_amount <> l_running_total_alloc) then
5838         l_alloc_line_tab(l_max_t).amount :=
5839             l_alloc_line_tab(l_max_t).amount +
5840            (l_line_amount - l_running_total_alloc);
5841       END IF;
5842 
5843     ELSIF (l_rule_type = 'PERCENTAGE') then
5844       t := 0;
5845       BEGIN
5846         OPEN alloc_rule_lines_cur;
5847         LOOP
5848           FETCH alloc_rule_lines_cur
5849            INTO l_alloc_rule_line_number,
5850                 l_alloc_rule_line_percent,
5851                 l_alloc_rule_line_amount,
5852                 l_sum_dists_applic_line;
5853 
5854           EXIT WHEN alloc_rule_lines_cur%NOTFOUND;
5855 
5856           IF (l_sum_dists_applic_line = 0) then
5857             X_error_code := 'AP_IMPROPER_LINE_IN_ALLOC_RULE';
5858             CLOSE alloc_rule_lines_cur;
5859             RETURN(FALSE);
5860           ELSE
5861             l_alloc_line_tab(t).invoice_line_number :=
5862                                        l_alloc_rule_line_number;
5863             l_alloc_line_tab(t).percentage := l_alloc_rule_line_percent;
5864             l_alloc_line_tab(t).amount :=
5865               AP_UTILITIES_PKG.Ap_Round_Currency(
5866                  (l_line_amount * l_alloc_rule_line_percent) / 100,
5867                   l_invoice_currency_code);
5868             l_alloc_line_tab(t).sum_amount_dists := l_sum_dists_applic_line;
5869 
5870             IF (ABS(l_alloc_line_tab(t).amount) >= ABS(nvl(l_max_alloc,0)) OR
5871                 t = 0) THEN
5872               l_max_alloc := l_alloc_line_tab(t).amount;
5873               l_max_t := t;
5874             END IF;
5875             l_running_total_alloc :=
5876                  nvl(l_running_total_alloc, 0) + l_alloc_line_tab(t).amount;
5877             t := t+1;
5878           END IF;
5879         END LOOP;
5880         CLOSE alloc_rule_lines_Cur;
5881 
5882 	--Invoice Lines: Distributions
5883 	l_count_applicable_dists := l_alloc_line_tab.COUNT;
5884         IF (l_count_applicable_dists = 0) THEN
5885            x_error_code := 'NO_APPLICABLE_DISTS';
5886            RETURN(FALSE);
5887         END IF;
5888 
5889         IF (l_line_amount <> l_running_total_alloc) THEN
5890           l_alloc_line_tab(l_max_t).amount :=
5891             l_alloc_line_tab(l_max_t).amount +
5892                (l_line_amount - l_running_total_alloc);
5893         END IF;
5894 
5895       EXCEPTION
5896         WHEN OTHERS THEN
5897           CLOSE alloc_rule_lines_cur;
5898           X_debug_info := debug_info || ': Error encountered';
5899           X_debug_context := current_calling_sequence;
5900           RETURN(FALSE);
5901       END;
5902 
5903 
5904     ELSE /* rule type is AMOUNT */
5905       t := 0;
5906       BEGIN
5907         OPEN alloc_rule_lines_cur;
5908         LOOP
5909           FETCH alloc_rule_lines_cur
5910            INTO l_alloc_rule_line_number,
5911                 l_alloc_rule_line_percent,
5912                 l_alloc_rule_line_amount,
5913                 l_sum_dists_applic_line;
5914 
5915           EXIT WHEN alloc_rule_lines_cur%NOTFOUND;
5916 
5917           IF (l_sum_dists_applic_line = 0) then
5918             X_error_code := 'AP_IMPROPER_LINE_IN_ALLOC_RULE';
5919             CLOSE alloc_rule_lines_cur;
5920             RETURN(FALSE);
5921           ELSE
5922             l_alloc_line_tab(t).invoice_line_number :=
5923               l_alloc_rule_line_number;
5924             l_alloc_line_tab(t).amount := l_alloc_rule_line_amount;
5925             l_alloc_line_tab(t).sum_amount_dists := l_sum_dists_applic_line;
5926             t := t + 1;
5927           END IF;
5928         END LOOP;
5929         CLOSE alloc_rule_lines_Cur;
5930 
5931 	--Invoice Lines: Distributions
5932 	l_count_applicable_dists := l_alloc_line_tab.COUNT;
5933         IF (l_count_applicable_dists = 0) THEN
5934            x_error_code := 'NO_APPLICABLE_DISTS';
5935            RETURN(FALSE);
5936         END IF;
5937 
5938       EXCEPTION
5939         WHEN OTHERS THEN
5940           CLOSE alloc_rule_lines_cur;
5941           X_debug_info := debug_info || ': Error encountered';
5942           X_debug_context := current_calling_sequence;
5943           RETURN(FALSE);
5944       END;
5945 
5946     END IF;
5947 
5948   EXCEPTION
5949     WHEN OTHERS THEN
5950       X_debug_info := debug_info || ': Error encountered';
5951       X_debug_context := current_calling_sequence;
5952       RETURN(FALSE);
5953   END;
5954 
5955 
5956   --------------------------------------------------------------
5957   -- Step 9 - Commence proration to all applicable distributions.
5958   --------------------------------------------------------------
5959   debug_info := 'Commence proration to distributions';
5960   BEGIN
5961     i := 0;
5962     l_max_base_i := 0;
5963     l_max_base_alloc := 0;
5964     l_running_total_base_amt := 0;
5965 
5966     -- Bug 5114543
5967     l_max_dist_line_num := AP_INVOICE_LINES_PKG.get_max_dist_line_num
5968 					(x_invoice_id, x_line_number) + 1;
5969 
5970     FOR t IN 0..l_alloc_line_tab.COUNT-1 LOOP
5971       l_running_total_alloc := 0;
5972       l_max_alloc := 0;
5973       l_max_i := -1;
5974 
5975       OPEN applicable_dists_cur(l_alloc_line_tab(t).invoice_line_number);
5976       LOOP
5977         FETCH applicable_dists_cur
5978          INTO l_invoice_distribution_id,
5979               l_po_distribution_id,
5980               l_rcv_transaction_id,
5981               l_dist_project_id,
5982               l_dist_task_id,
5983 	      l_dist_pa_quantity,   -- bug6699834
5984               l_dist_expenditure_type,
5985               l_dist_expenditure_org_id,
5986               l_dist_award_id,
5987               l_dist_amount,
5988               l_dist_code_combination_id,
5989               l_dist_assets_tracking_flag,
5990               l_dist_asset_book_type_code,
5991               l_dist_asset_category_id,
5992               l_dist_description;
5993 
5994         EXIT WHEN applicable_dists_cur%NOTFOUND;
5995 
5996 	-- Bug 5114543
5997         l_dist_tab(i).dist_line_num := l_max_dist_line_num;
5998 
5999         l_dist_tab(i).description := l_line_description;
6000         l_dist_tab(i).charge_applicable_to_dist := l_invoice_distribution_id;
6001         l_dist_tab(i).award_id := l_dist_award_id;
6002 	l_dist_tab(i).pa_quantity := l_dist_pa_quantity; -- bug6699834
6003         l_dist_tab(i).attribute_category := NULL;
6004         l_dist_tab(i).attribute1 := NULL;
6005         l_dist_tab(i).attribute2 := NULL;
6006         l_dist_tab(i).attribute3 := NULL;
6007         l_dist_tab(i).attribute4 := NULL;
6008         l_dist_tab(i).attribute5 := NULL;
6009         l_dist_tab(i).attribute6 := NULL;
6010         l_dist_tab(i).attribute7 := NULL;
6011         l_dist_tab(i).attribute8 := NULL;
6012         l_dist_tab(i).attribute9 := NULL;
6013         l_dist_tab(i).attribute10 := NULL;
6014         l_dist_tab(i).attribute11 := NULL;
6015         l_dist_tab(i).attribute12 := NULL;
6016         l_dist_tab(i).attribute13 := NULL;
6017         l_dist_tab(i).attribute14 := NULL;
6018         l_dist_tab(i).attribute15 := NULL;
6019         l_dist_tab(i).type_1099   := l_type_1099;
6020         l_dist_tab(i).income_tax_region := l_income_tax_region;
6021         l_dist_tab(i).amount:=
6022           AP_UTILITIES_PKG.Ap_Round_Currency(
6023             (l_alloc_line_tab(t).amount * l_dist_amount) /
6024              l_alloc_line_tab(t).sum_amount_dists,
6025              l_invoice_currency_code);
6026         l_dist_tab(i).base_amount :=
6027           AP_UTILITIES_PKG.Ap_Round_Currency(
6028           NVL(l_dist_tab(i).amount, 0) * l_exchange_rate ,
6029           l_base_currency_code);
6030         l_dist_tab(i).rounding_amt := 0;
6031 
6032         -- Get project and account information
6033         --
6034         IF (NOT (
6035                 Get_Proj_And_Acc_For_Chrg_Dist(
6036                  X_invoice_id,
6037                  l_invoice_date,
6038                  l_vendor_id,
6039                  l_invoice_currency_code,
6040                  l_sob_id,
6041                  l_chart_of_accounts_id,
6042                  l_base_currency_code,
6043                  l_dist_tab(i).amount,
6044                  l_dist_tab(i).base_amount,
6045                  l_exchange_rate_type,
6046                  l_exchange_date,
6047                  l_exchange_rate,
6048                  X_line_number,
6049                  l_open_gl_date,
6050                  l_open_period_name,
6051                  l_project_id,
6052                  l_task_id,
6053 		 l_award_id,
6054                  l_expenditure_type,
6055                  l_expenditure_organization_id,
6056                  l_assets_tracking_flag,
6057                  l_asset_book_type_code,
6058                  l_asset_category_id,
6059                  l_dist_project_id,
6060                  l_dist_task_id,
6061 		 l_dist_award_id,
6062                  l_dist_expenditure_type,
6063                  l_dist_expenditure_org_id,
6064                  l_dist_assets_tracking_flag,
6065                  l_dist_asset_book_type_code,
6066                  l_dist_asset_category_id,
6067                  l_default_dist_ccid,
6068                  l_overlay_dist_concat,
6069                  l_balancing_segment,
6070                  l_account_segment,
6071                  l_cost_center_segment,
6072                  l_dist_code_combination_id,
6073                  l_po_distribution_id,
6074                  l_rcv_transaction_id,
6075                  l_pa_allows_overrides,
6076                  l_allow_po_override,
6077                  l_dist_tab(i).project_id,
6078                  l_dist_tab(i).task_id,
6079                  l_dist_tab(i).award_id,
6080                  l_dist_tab(i).expenditure_type,
6081                  l_dist_tab(i).expenditure_organization_id,
6082                  l_dist_tab(i).expenditure_item_date,
6083                  l_dist_tab(i).pa_addition_flag,
6084                  l_dist_tab(i).dist_ccid,
6085                  l_dist_tab(i).assets_tracking_flag,
6086                  l_dist_tab(i).asset_book_type_code,
6087                  l_dist_tab(i).asset_category_id,
6088                  l_error_code,
6089                  l_msg_application,
6090                  l_msg_data,
6091                  l_default_dist_ccid --bug 5386396
6092             ))) THEN
6093 
6094           CLOSE applicable_dists_cur;
6095 
6096           IF (l_error_code is not null) then
6097             X_error_code := l_error_code;
6098             RETURN(FALSE);
6099           ELSIF (l_msg_data is not null) then
6100             X_msg_application := l_msg_application;
6101             X_msg_data := l_msg_data;
6102             RETURN(FALSE);
6103           ELSE
6104             X_debug_info := debug_info
6105                             ||': Error encountered while reading account info';
6106             X_debug_context := current_calling_sequence;
6107             RETURN(FALSE);
6108           END IF;
6109         END IF;
6110 
6111        -- l_dist_tab(i).assets_tracking_flag :=
6112         IF (l_dist_tab(i).assets_tracking_flag = 'Y') THEN
6113           l_dist_tab(i).asset_book_type_code := l_asset_book_type_code;
6114           l_dist_tab(i).asset_category_id := l_asset_category_id;
6115         END IF;
6116 
6117         IF (l_max_i = -1 OR ABS(nvl(l_max_alloc, 0)) <=
6118              ABS(l_dist_tab(i).amount)) then
6119           l_max_i := i;
6120           l_max_alloc := l_dist_tab(i).amount;
6121         END IF;
6122         IF (i = 0 OR ABS(nvl(l_max_base_alloc, 0)) <=
6123              ABS(l_dist_tab(i).base_amount)) THEN
6124           l_max_base_i := i;
6125           l_max_base_alloc := l_dist_tab(i).base_amount;
6126         END IF;
6127         l_running_total_alloc := nvl(l_running_total_alloc, 0) +
6128                                  l_dist_tab(i).amount;
6129         l_running_total_base_amt := nvl(l_running_total_base_amt, 0) +
6130                                     l_dist_tab(i).base_amount;
6131 
6132         i := i+1;
6133 
6134 	-- Bug 5114543
6135 	l_max_dist_line_num := l_max_dist_line_num +1;
6136 
6137       END LOOP; -- Loop through distributions within line
6138 
6139       CLOSE applicable_dists_cur;
6140 
6141       if (l_alloc_line_tab(t).amount <> l_running_total_alloc) then
6142         l_dist_tab(l_max_i).amount :=
6143             l_dist_tab(l_max_i).amount + (l_alloc_line_tab(t).amount -
6144                                              l_running_total_alloc);
6145         l_running_total_base_amt := l_running_total_base_amt -
6146                                       l_dist_tab(l_max_I).base_amount;
6147         l_dist_tab(l_max_i).base_amount :=
6148           AP_UTILITIES_PKG.Ap_Round_Currency(
6149             NVL(l_dist_tab(l_max_i).amount, 0) * l_exchange_rate ,
6150             l_base_currency_code);
6151         l_running_total_base_amt := l_running_total_base_amt +
6152                                     l_dist_tab(l_max_i).base_amount;
6153       end if;
6154       if (ABS(nvl(l_max_base_alloc, 0)) <=
6155           ABS(l_dist_tab(l_max_i).base_amount)) then
6156         l_max_base_i := l_max_i;
6157         l_max_base_alloc := l_dist_tab(l_max_i).base_amount;
6158       end if;
6159 
6160     END LOOP;  -- Loop through lines
6161 
6162     if (l_running_total_base_amt <> l_line_base_amount) then
6163       l_dist_tab(l_max_base_i).rounding_amt := l_line_base_amount -
6164                                                 l_running_total_base_amt;
6165       l_dist_tab(l_max_base_i).base_amount :=
6166         l_dist_tab(l_max_base_i).base_amount + l_line_base_amount -
6167             l_running_total_base_amt;
6168     end if;
6169 
6170   END;
6171 
6172   ----------------------------------------------------------------------------
6173   -- Step 10 - Set distribution class value (Permanent or Candidate)
6174   ----------------------------------------------------------------------------
6175   if (X_Generate_Permanent = 'N') then
6176     l_distribution_class := 'CANDIDATE';
6177   else
6178     l_distribution_class := 'PERMANENT';
6179   end if;
6180 
6181   ----------------------------------------------------------------------------
6182   -- Step 11 - Generate distributions
6183   ----------------------------------------------------------------------------
6184 
6185   FOR i in nvl(l_dist_tab.FIRST, 0) .. nvl(l_dist_tab.LAST, -1)  LOOP
6186 
6187      SELECT ap_invoice_distributions_s.nextval INTO l_inv_dist_id FROM DUAL;
6188 
6189      INSERT INTO ap_invoice_distributions(
6190               batch_id,
6191               invoice_id,
6192               invoice_line_number,
6193               invoice_distribution_id,
6194               distribution_line_number,
6195               line_type_lookup_code,
6196               distribution_class,
6197               description,
6198               dist_match_type,
6199               org_id,
6200               dist_code_combination_id,
6201               accounting_date,
6202               period_name,
6203               accrual_posted_flag,
6204               cash_posted_flag,
6205               amount_to_post,
6206               base_amount_to_post,
6207               posted_amount,
6208               posted_base_amount,
6209               posted_flag,
6210               accounting_event_id,
6211               upgrade_posted_amt,
6212               upgrade_base_posted_amt,
6213               set_of_books_id,
6214               amount,
6215               base_amount,
6216               rounding_amt,
6217               quantity_variance,
6218               base_quantity_variance,
6219               match_status_flag,
6220               encumbered_flag,
6221               packet_id,
6222               reversal_flag,
6223               parent_reversal_id,
6224               cancellation_flag,
6225               income_tax_region,
6226               type_1099,
6227               stat_amount,
6228               charge_applicable_to_dist_id,
6229               prepay_amount_remaining,
6230               prepay_distribution_id,
6231               parent_invoice_id,
6232               corrected_invoice_dist_id,
6233               corrected_quantity,
6234               other_invoice_id,
6235               po_distribution_id,
6236               rcv_transaction_id,
6237               unit_price,
6238               matched_uom_lookup_code,
6239               quantity_invoiced,
6240               final_match_flag,
6241               related_id,
6242               assets_addition_flag,
6243               assets_tracking_flag,
6244               asset_book_type_code,
6245               asset_category_id,
6246               project_id,
6247               task_id,
6248               expenditure_type,
6249               expenditure_item_date,
6250               expenditure_organization_id,
6251               pa_quantity,
6252               pa_addition_flag,
6253               award_id,
6254               gms_burdenable_raw_cost,
6255               awt_flag,
6256               awt_group_id,
6257               awt_tax_rate_id,
6258               awt_gross_amount,
6259               awt_invoice_id,
6260               awt_origin_group_id,
6261               awt_invoice_payment_id,
6262               awt_withheld_amt,
6263               inventory_transfer_status,
6264               reference_1,
6265               reference_2,
6266               receipt_verified_flag,
6267               receipt_required_flag,
6268               receipt_missing_flag,
6269               justification,
6270               expense_group,
6271               start_expense_date,
6272               end_expense_date,
6273               receipt_currency_code,
6274               receipt_conversion_rate,
6275               receipt_currency_amount,
6276               daily_amount,
6277               web_parameter_id,
6278               adjustment_reason,
6279               merchant_document_number,
6280               merchant_name,
6281               merchant_reference,
6282               merchant_tax_reg_number,
6283               merchant_taxpayer_id,
6284               country_of_supply,
6285               credit_card_trx_id,
6286               company_prepaid_invoice_id,
6287               cc_reversal_flag,
6288               attribute_category,
6289               attribute1,
6290               attribute2,
6291               attribute3,
6292               attribute4,
6293               attribute5,
6294               attribute6,
6295               attribute7,
6296               attribute8,
6297               attribute9,
6298               attribute10,
6299               attribute11,
6300               attribute12,
6301               attribute13,
6302               attribute14,
6303               attribute15,
6304               global_attribute_category,
6305               global_attribute1,
6306               global_attribute2,
6307               global_attribute3,
6308               global_attribute4,
6309               global_attribute5,
6310               global_attribute6,
6311               global_attribute7,
6312               global_attribute8,
6313               global_attribute9,
6314               global_attribute10,
6315               global_attribute11,
6316               global_attribute12,
6317               global_attribute13,
6318               global_attribute14,
6319               global_attribute15,
6320               global_attribute16,
6321               global_attribute17,
6322               global_attribute18,
6323               global_attribute19,
6324               global_attribute20,
6325               created_by,
6326               creation_date,
6327               last_updated_by,
6328               last_update_date,
6329               last_update_login,
6330               program_application_id,
6331               program_id,
6332               program_update_date,
6333               request_id,
6334 	      --ETAX: Invwkb
6335 	      intended_use,
6336 	      --Freight and Special Charges
6337 	      rcv_charge_addition_flag,
6338 	---7022001
6339 	pay_awt_group_id)
6340     SELECT    l_batch_id,                       -- batch_id
6341               X_invoice_id,                     -- invoice_id
6342               X_line_number,                    -- invoice_line_number
6343               l_inv_dist_id,           		-- invoice_distribution_id
6344               l_dist_tab(i).dist_line_num,      -- distribution_line_number
6345               l_line_type_lookup_code,          -- line_type_lookup_code
6346               l_distribution_class,             -- distribution_class
6347               l_dist_tab(i).description,        -- description
6348               'NOT_MATCHED',                    -- dist_match_type
6349               l_org_id,                         -- l_org_id
6350               l_dist_tab(i).dist_ccid,          -- dist_code_combination_id
6351               l_open_gl_date,                   -- accounting_date
6352               l_open_period_name,               -- period_name
6353               'N',                              -- accrual_posted_flag
6354               'N',                              -- cash_posted_flag
6355               NULL,                             -- amount_to_post
6356               NULL,                             -- base_amount_to_post
6357               NULL,                             -- posted_amount
6358               NULL,                             -- posted_base_amount
6359               'N',                              -- posted_flag
6360               NULL,                             -- accounting_event_id
6361               NULL,                             -- upgrade_posted_amt
6362               NULL,                             -- upgrade_base_posted_amt
6363               l_sob_id,                         -- set_of_books_id
6364               l_dist_tab(i).amount,             -- amount
6365               l_dist_tab(i).base_amount,        -- base_amount
6366               l_dist_tab(i).rounding_amt,       -- rounding_amt
6367               NULL,                             -- quantity_variance
6368               NULL,                             -- base_quantity_variance
6369 	      --Invoice Lines: Distributions, changed match_status_flag
6370 	      --to NULL from 'N'.
6371               NULL,                             -- match_status_flag
6372               'N',                              -- encumbered_flag
6373               NULL,                             -- packet_id
6374               'N',                              -- reversal_flag
6375               NULL,                             -- parent_reversal_id
6376               'N',                              -- cancellation_flag
6377               decode(l_type_1099,null,null,l_income_tax_region),
6378                                                 -- income_tax_region
6379               l_type_1099,                      -- type_1099
6380               NULL,                             -- stat_amount
6381               l_dist_tab(i).charge_applicable_to_dist, -- charge_applicable_to_dist_id
6382               NULL,                             -- prepay_amount_remaining
6383               NULL,                             -- prepay_distribution_id
6384               NULL,                             -- parent_invoice_id
6385               NULL,                             -- corrected_inv_dist_id
6386               NULL,                             -- corrected_quantity
6387               NULL,                             -- other_invoice_id
6388               NULL,                             -- po_distribution_id
6389               NULL,                             -- rcv_transaction_id
6390               NULL,                             -- unit_price
6391               NULL,                             -- matched_uom_lookup_code
6392               NULL,                             -- quantity_invoiced
6393               NULL,                             -- final_match_flag
6394               NULL,                             -- related_id
6395               'U',                              -- assets_addition_flag
6396               l_dist_tab(i).assets_tracking_flag,   -- assets_tracking_flag
6397               l_dist_tab(i).asset_book_type_code,   -- asset_book_type_code
6398               l_dist_tab(i).asset_category_id,  -- asset_category_id
6399               l_dist_tab(i).project_id,         -- project_id
6400               l_dist_tab(i).task_id,            -- task_id
6401               l_dist_tab(i).expenditure_type,   -- expenditure_type
6402               l_dist_tab(i).expenditure_item_date,  -- expenditure_item_date
6403               l_dist_tab(i).expenditure_organization_id,  -- expenditure_organization_id
6404 /* commented for Bug fix 6699834. added below line as replacement                             NULL,                             -- pa_quantity  */
6405               l_dist_tab(i).pa_quantity,        -- pa_quantity  -- bug6699834
6406               l_dist_tab(i).pa_addition_flag,   -- pa_addition_flag
6407               NULL,                             -- award_id
6408               NULL,                             -- gms_burdenable_raw_cost
6409               NULL,                             -- awt_flag
6410               l_awt_group_id,                   -- awt_group_id
6411               NULL,                             -- awt_tax_rate_id
6412               NULL,                             -- awt_gross_amount
6413               NULL,                             -- awt_invoice_id
6414               NULL,                             -- awt_origin_group_id
6415               NULL,                             -- awt_invoice_payment_id
6416               NULL,                             -- awt_withheld_amt
6417               'N',                              -- inventory_transfer_status
6418               NULL,                             -- reference_1
6419               NULL,                             -- reference_2
6420               NULL,                             -- receipt_verified_flag
6421               NULL,                             -- receipt_required_flag
6422               NULL,                             -- receipt_missing_flag
6423               NULL,                             -- justification
6424               NULL,                             -- expense_group
6425               NULL,                             -- start_expense_date
6426               NULL,                             -- end_expense_date
6427               NULL,                             -- receipt_currency_code
6428               NULL,                             -- receipt_conversion_rate
6429               NULL,                             -- receipt_currency_amount
6430               NULL,                             -- daily_amount
6431               NULL,                             -- web_parameter_id
6432               NULL,                             -- adjustment_reason
6433               NULL,                             -- merchant_document_number
6434               NULL,                             -- merchant_name
6435               NULL,                             -- merchant_reference
6436               NULL,                             -- merchant_tax_reg_number
6437               NULL,                             -- merchant_taxpayer_id
6438               NULL,                             -- country_of_supply
6439               NULL,                             -- credit_card_trx_id
6440               NULL,                             -- company_prepaid_invoice_id
6441               NULL,                             -- cc_reversal_flag
6442               NULL,                             -- attribute_category
6443               NULL,                             -- attribute1
6444               NULL,                             -- attribute2
6445               NULL,                             -- attribute3
6446               NULL,                             -- attribute4
6447               NULL,                             -- attribute5
6448               NULL,                             -- attribute6
6449               NULL,                             -- attribute7
6450               NULL,                             -- attribute8
6451               NULL,                             -- attribute9
6452               NULL,                             -- attribute10
6453               NULL,                             -- attribute11
6454               NULL,                             -- attribute12
6455               NULL,                             -- attribute13
6456               NULL,                             -- attribute14
6457               NULL,                             -- attribute15
6458               NULL,                             -- global_attribute_category
6459               NULL,                             -- global_attribute1
6460               NULL,                             -- global_attribute2
6461 	      --bugfix:4674194
6462 	      decode(AP_EXTENDED_WITHHOLDING_PKG.AP_EXTENDED_WITHHOLDING_OPTION,
6463 	             'Y',ail1.ship_to_location_id,''), --global_attribute3
6464               NULL,                             -- global_attribute4
6465               NULL,                             -- global_attribute5
6466               NULL,                             -- global_attribute6
6467               NULL,                             -- global_attribute7
6468               NULL,                             -- global_attribute8
6469               NULL,                             -- global_attribute9
6470               NULL,                             -- global_attribute10
6471               NULL,                             -- global_attribute11
6472               NULL,                             -- global_attribute12
6473               NULL,                             -- global_attribute13
6474               NULL,                             -- global_attribute14
6475               NULL,                             -- global_attribute15
6476               NULL,                             -- global_attribute16
6477               NULL,                             -- global_attribute17
6478               NULL,                             -- global_attribute18
6479               NULL,                             -- global_attribute19
6480               NULL,                             -- global_attribute20
6481               l_created_by,                     -- created_by
6482               sysdate,                          -- creation_date
6483               0,                                -- last_updated_by
6484               sysdate,                          -- last_update_date
6485               l_last_update_login,              -- last_update_login
6486               NULL,                             -- program_application_id
6487               NULL,                             -- program_id
6488               NULL,                             -- program_update_date
6489               NULL,                             -- request_id
6490 	      --ETAX: Invwkb
6491 	      ail.primary_intended_use,		-- intended_use
6492 	      'N',				-- rcv_charge_addition_flag
6493 	 l_pay_awt_group_id                   -- pay_awt_group_id 7022001
6494          FROM ap_invoice_lines AIL, --Charge line
6495 	      ap_invoice_lines AIL1, --ITEM Line
6496 	      ap_invoice_distributions aid
6497          WHERE ail.invoice_id = X_invoice_id
6498          AND ail.line_number = X_line_number
6499 	 AND aid.invoice_id = ail.invoice_id
6500 	 AND aid.invoice_distribution_id = l_dist_tab(i).charge_applicable_to_dist
6501 	 AND ail1.invoice_id = ail.invoice_id
6502 	 AND ail1.line_number = aid.invoice_line_number;
6503 
6504 	 GMS_AP_API.CREATE_AWARD_DISTRIBUTIONS
6505 			( p_invoice_id		     => X_invoice_id,
6506 			  p_distribution_line_number => l_dist_tab(i).dist_line_num,
6507 			  p_invoice_distribution_id  => l_inv_dist_id,
6508 			  p_award_id		     => l_dist_tab(i).award_id,
6509 			  p_mode		     => 'AP',
6510 			  p_dist_set_id		     => NULL,
6511 			  p_dist_set_line_number     => NULL);
6512 
6513 
6514   END LOOP;
6515 
6516 ----------------------------------------------------------------------------
6517   -- Step 12 - Update generate distributions flag in invoice line if generating
6518   -- permanent distributions.
6519   ----------------------------------------------------------------------------
6520   debug_info := 'Setting generate distributions flag to Done';
6521   if (l_distribution_class = 'PERMANENT') then
6522 
6523     -- Bug 5114543
6524     -- generate_dists on the charge line should be set to 'Done'
6525     -- when the line amount equals the distributions total.
6526 
6527     BEGIN
6528       UPDATE AP_INVOICE_LINES
6529          SET GENERATE_DISTS = 'D'
6530        WHERE invoice_id = X_invoice_id
6531          AND line_number = X_line_number
6532 	 AND amount = (select sum(amount)
6533 			 from ap_invoice_distributions
6534 			where invoice_id = x_invoice_id
6535 			  and invoice_line_number = x_line_number);
6536     EXCEPTION
6537       WHEN OTHERS THEN
6538          X_debug_info := debug_info || ': Error encountered';
6539          X_debug_context := current_calling_sequence;
6540          return (FALSE);
6541     END;
6542   end if;
6543 
6544   ----------------------------------------------------------------------------
6545   -- Step 13 - Update status of allocation rule type if the distributions were
6546   -- generated in permanent mode.
6547   ----------------------------------------------------------------------------
6548   debug_info := 'Setting status of allocation rule to Executed';
6549   if (l_distribution_class = 'PERMANENT') then
6550 
6551     -- Bug 5114543
6552     -- allocation rule status should be set to 'Executed' when the associated
6553     -- charge line amount equals its distributions total.
6554 
6555     BEGIN
6556       UPDATE AP_ALLOCATION_RULES
6557          SET STATUS = 'EXECUTED'
6558        WHERE invoice_id = X_invoice_id
6559          AND chrg_invoice_line_number = X_line_number
6560 	 AND exists
6561 		(select 'Line Amount Equals Distribution Total'
6562 		 from   ap_invoice_lines_all ail,
6563 			ap_invoice_distributions_all aid
6564 		 where  ail.invoice_id  = aid.invoice_id
6565 		 and	ail.line_number = aid.invoice_line_number
6566 		 and	ail.invoice_id  = X_invoice_id
6567 		 and	ail.line_number = X_line_number
6568 		 group by ail.line_number, ail.amount
6569 		 having ail.amount = sum(aid.amount));
6570 
6571     EXCEPTION
6572       WHEN OTHERS THEN
6573          X_debug_info := debug_info || ': Error encountered';
6574          X_debug_context := current_calling_sequence;
6575          RETURN (FALSE);
6576     END;
6577   END IF;
6578 
6579   RETURN(TRUE);
6580 
6581   EXCEPTION
6582      WHEN OTHERS THEN
6583        X_debug_info := debug_info || 'Error encountered';
6584        X_debug_context := current_calling_sequence;
6585        X_error_code := sqlerrm;
6586        return (FALSE);
6587 
6588 END insert_charge_from_alloc;
6589 
6590   -----------------------------------------------------------------------
6591   -- FUNCTION get_total_dist_amount returns the total of the original
6592   -- ITEM or ACCRUAL distribution when the same has been split into
6593   -- ITEM/ACCRUAL, IPV and ERV.  It may also be called in Price
6594   -- Corrections where there was no original ITEM/ACCRUAL. It returns
6595   -- NULL if an error is found.
6596   -----------------------------------------------------------------------
6597   FUNCTION Get_Total_Dist_Amount(
6598          X_invoice_distribution_id IN       NUMBER) RETURN NUMBER
6599   IS
6600 
6601   l_original_amount    AP_INVOICE_DISTRIBUTIONS.AMOUNT%TYPE := 0;
6602 
6603   BEGIN
6604 
6605     SELECT sum(nvl(AID.amount,0))
6606       INTO l_original_amount
6607       FROM ap_invoice_distributions_all  AID
6608      WHERE AID.invoice_distribution_id = X_invoice_distribution_id
6609         OR AID.related_id = X_invoice_distribution_id;
6610 
6611 
6612     RETURN(l_original_amount);
6613 
6614 EXCEPTION
6615   WHEN no_data_found THEN
6616     RETURN(l_original_amount) ;
6617   WHEN OTHERS THEN
6618     RETURN(l_original_amount);
6619 
6620 END get_total_dist_amount;
6621 
6622 
6623  -----------------------------------------------------------------------
6624   -- Function get_dist_line_num returns the distribution line
6625   -- number of invoice distributions belonging to P_invoice_dist_id
6626   -----------------------------------------------------------------------
6627   FUNCTION GET_DIST_LINE_NUM(
6628           X_invoice_dist_id      IN NUMBER)
6629   RETURN NUMBER
6630   IS
6631       l_dist_line_num number := 0;
6632   BEGIN
6633 
6634     SELECT nvl(distribution_line_number,0)
6635       INTO l_dist_line_num
6636       FROM ap_invoice_distributions
6637      WHERE invoice_distribution_id = X_invoice_dist_id;
6638 
6639     RETURN(l_dist_line_num);
6640 
6641   END GET_DIST_LINE_NUM;
6642 
6643 
6644   -----------------------------------------------------------------------
6645   -- Function get_inv_line_num returns the invoice line
6646   -- number of invoice distribution belonging to P_invoice_dist_id
6647   -----------------------------------------------------------------------
6648   FUNCTION GET_INV_LINE_NUM(
6649           X_invoice_dist_id      IN NUMBER )
6650   RETURN NUMBER
6651   IS
6652       l_inv_line_num number := 0;
6653   BEGIN
6654 
6655     SELECT nvl(invoice_line_number,0)
6656       INTO l_inv_line_num
6657       FROM ap_invoice_distributions
6658      WHERE invoice_distribution_id = X_invoice_dist_id;
6659 
6660     RETURN(l_inv_line_num);
6661 
6662   END GET_INV_LINE_NUM;
6663 
6664   -----------------------------------------------------------------------
6665   -- Function get_invoice_num returns the parent invoice
6666   -- number of invoice distribution belonging to P_invoice_dist_id
6667   -----------------------------------------------------------------------
6668   FUNCTION GET_INVOICE_NUM(
6669           X_invoice_dist_id      IN NUMBER )
6670   RETURN VARCHAR2
6671   IS
6672       l_inv_num VARCHAR2(50);
6673   BEGIN
6674 
6675     SELECT nvl(ai.invoice_num,0)
6676       INTO l_inv_num
6677       FROM ap_invoice_distributions aid,
6678            ap_invoices ai
6679      WHERE aid.invoice_distribution_id = X_invoice_dist_id
6680        AND aid.invoice_id = ai.invoice_id;
6681 
6682     RETURN(l_inv_num);
6683 
6684   END GET_INVOICE_NUM;
6685 
6686 
6687   -----------------------------------------------------------------------
6688   -- Function GET_REVERSAL_RELATED_ID returns the ditribution id value
6689   -- that should populates the related_id column when distribution line
6690   -- is reversed and invoice line is discarded.
6691   -----------------------------------------------------------------------
6692   FUNCTION GET_REVERSAL_RELATED_ID(
6693           X_related_dist_id    IN  NUMBER )
6694   RETURN NUMBER
6695   IS
6696       l_distribution_id  ap_invoice_distributions.invoice_distribution_id%TYPE;
6697   BEGIN
6698 
6699     BEGIN
6700       SELECT invoice_distribution_id
6701         INTO l_distribution_id
6702         FROM ap_invoice_distributions
6703        WHERE parent_reversal_id = X_related_dist_id;
6704     EXCEPTION
6705       WHEN no_data_found THEN
6706         l_distribution_id := null;
6707     END;
6708 
6709     RETURN(l_distribution_id);
6710 
6711   END GET_REVERSAL_RELATED_ID;
6712 
6713 
6714  --Invoice Lines: Distributions
6715  -----------------------------------------------------------------------
6716   -- Function GET_REVERSING_DIST_NUM returns the ditribution num value
6717   -- of the invoice distribution that is reversing the invoice distribution
6718   --identified by x_invoice_dist_id.
6719   -----------------------------------------------------------------------
6720  FUNCTION GET_REVERSING_DIST_NUM(X_Invoice_Dist_Id NUMBER) RETURN NUMBER IS
6721     l_reversing_dist_num ap_invoice_distributions.distribution_line_number%TYPE;
6722  BEGIN
6723 
6724    BEGIN
6725       SELECT distribution_line_number
6726       INTO l_reversing_dist_num
6727       FROM ap_invoice_distributions
6728       WHERE parent_reversal_id = x_invoice_dist_id;
6729 
6730    EXCEPTION WHEN NO_DATA_FOUND THEN
6731      l_reversing_dist_num := NULL;
6732    END;
6733 
6734    RETURN(l_reversing_dist_num);
6735 
6736  END GET_REVERSING_DIST_NUM;
6737 
6738 
6739 /*=============================================================================
6740  |  PUBLIC PROCEDURE Calculate_Variance
6741  |
6742  |  DESCRIPTION
6743  |   Procedure that calculates the IPV/ERV for an distribution line which
6744  |   could be ITEM, ACCRUAL, RETROEXPENSE, RETROACCRUAL or IPV type. It
6745  |   returns TRUE if there is no error or exception. It returns True if no
6746  |   error.
6747  |
6748  |  PARAMETERS
6749  |    x_distribution_id - Distributions which could be ITEM, ACCRUAL and IPV
6750  |    x_reporting_ledger_id - reporting set of books id value for MRC
6751  |    x_distribution_amt - Out parameter as updated value for this dist line
6752  |    x_dist_base_amt - Out parameter as updated value for this dist line
6753  |    x_ipv - Out parameter as calculated ipv
6754  |    x_bipv - Out parameter as calculated base amount for ipv
6755  |    x_erv - Out parameter as calculated erv in base currency code
6756  |    x_calling_sequence - calling sequence for debug purpose
6757  |    x_debug_switch - a control to log debug information
6758  |
6759  |  PROGRAM FLOW
6760  |
6761  |  KNOWN ISSUES
6762  |
6763  |  NOTES
6764  |
6765  |  MODIFICATION HISTORY
6766  |  Date         Author             Description of Change
6767  |
6768  *============================================================================*/
6769 
6770 FUNCTION Calculate_Variance(
6771              X_DISTRIBUTION_ID      IN            NUMBER,
6772              X_REPORTING_LEDGER_ID  IN            NUMBER,
6773              X_DISTRIBUTION_AMT        OUT NOCOPY NUMBER,
6774              X_DIST_BASE_AMT           OUT NOCOPY NUMBER,
6775              X_IPV                  IN OUT NOCOPY NUMBER,
6776              X_BIPV                 IN OUT NOCOPY NUMBER,
6777              X_ERV                  IN OUT NOCOPY NUMBER,
6778              X_DEBUG_INFO           IN OUT NOCOPY VARCHAR2,
6779              X_DEBUG_CONTEXT        IN OUT NOCOPY VARCHAR2,
6780              X_CALLING_SEQUENCE     IN OUT NOCOPY VARCHAR2) Return Boolean
6781 
6782 IS
6783   l_inv_currency_code        ap_invoices.invoice_currency_code%TYPE;
6784   l_base_currency_code       ap_system_parameters.base_currency_code%TYPE;
6785   l_dist_line_type           VARCHAR2(25);
6786   l_inv_price                ap_invoice_distributions.unit_price%TYPE;
6787   l_qty_invoiced             NUMBER;
6788   l_po_qty                   NUMBER;
6789   l_po_price                 po_line_locations.price_override%TYPE;
6790   l_po_rate                  NUMBER;
6791   l_rtxn_rate                NUMBER;
6792   l_inv_rate                 ap_invoices.exchange_rate%TYPE;
6793   l_match_option             po_line_locations.match_option%TYPE;
6794   l_rtxn_uom                 VARCHAR2(25);
6795   l_rtxn_item_id             rcv_shipment_lines.item_id%TYPE;
6796   l_po_uom                   po_line_locations.unit_meas_lookup_code%TYPE;
6797   l_distribution_amt         ap_invoice_distributions.amount%TYPE;
6798   l_dist_base_amt            ap_invoice_distributions.base_amount%TYPE;
6799   l_dist_match_type          ap_invoice_distributions.dist_match_type%TYPE;
6800   l_corrected_inv_dist_id    NUMBER(15);
6801   l_corrected_qty            NUMBER;
6802   l_uom_conv_rate            NUMBER;
6803   l_rate_diff                NUMBER;
6804   l_price_diff               NUMBER;
6805 
6806   l_original_dist_base_amt   NUMBER;
6807   l_original_dist_amt        NUMBER;
6808 
6809   l_corrected_inv_rate       ap_invoices.exchange_rate%TYPE;
6810   current_calling_sequence   VARCHAR2(2000);
6811   l_debug_info               VARCHAR2(100);
6812 
6813   l_match_basis              po_line_types.matching_basis%TYPE;  -- Amount Based Matching
6814 
6815   cursor invoice_dist_cursor is
6816   SELECT AI.invoice_currency_code,              -- l_inv_currency_code
6817          ASP.base_currency_code,                -- l_base_currency_code
6818          D.line_type_lookup_code,               -- l_dist_line_type
6819          D.unit_price,                          -- l_inv_price
6820          nvl(D.quantity_invoiced, 0),           -- l_quantity_invoiced
6821          nvl(PD.quantity_ordered,0) -
6822               nvl(PD.quantity_cancelled,0),     -- l_po_qty
6823          nvl(PLL.price_override, 0),            -- l_po_price
6824          decode(AI.invoice_currency_code,
6825                 ASP.base_currency_code, 1,
6826                 PD.rate), -- l_po_rate
6827          decode (AI.invoice_currency_code,
6828                  ASP.base_currency_code, 1 ,
6829                  RTXN.currency_conversion_rate),  -- l_rtxn_rate
6830          nvl(AI.exchange_rate,1),  -- l_inv_rate
6831          nvl(PLL.match_option, 'P'),            -- l_match_option
6832          D.matched_uom_lookup_code,             -- l_rtxn_uom
6833          RSL.item_id,                           -- l_rtxn_item_id
6834          PL.unit_meas_lookup_code,              -- l_po_uom
6835          D.amount,                              -- l_distribution_amt
6836          decode(AI.invoice_currency_code,
6837                 ASP.base_currency_code, nvl(D.amount,0),
6838                                     nvl(D.base_amount,0)),  -- l_dist_base_amt
6839          D.dist_match_type,                     -- l_dist_match_type
6840          D.corrected_invoice_dist_id,           -- l_corrected_invoice_dist_id
6841          D.corrected_quantity,                  -- l_corrected_quantity
6842          PLL.matching_basis                     -- l_match_basis /* Amount Based Matching */
6843   FROM   ap_invoices_all AI,
6844          ap_system_parameters_all ASP,
6845          ap_invoice_distributions D,
6846          po_distributions PD,
6847          po_lines PL,
6848          po_line_types PLT,                     -- Amount Based Matching
6849          po_line_locations PLL,
6850          rcv_transactions RTXN,
6851          rcv_shipment_lines RSL
6852   WHERE  AI.invoice_id = D.invoice_id
6853     AND  D.invoice_distribution_id = X_distribution_id
6854     AND  nvl(ASP.org_id, -999) = nvl(AI.org_id,-999)
6855     AND  nvl(AI.org_id,-999) = nvl(D.org_id,-999)
6856     AND  D.po_distribution_id = PD.po_distribution_id
6857     AND  PL.po_header_id = PD.po_header_id
6858     AND  PL.po_line_id = PD.po_line_id
6859     AND  PL.line_type_id = PLT.line_type_id     -- Amount Based Matching
6860     AND  PD.line_location_id = PLL.line_location_id
6861     AND  D.rcv_transaction_id = RTXN.transaction_id (+)
6862     AND  RTXN.shipment_line_id = RSL.shipment_line_id (+)
6863     AND  D.posted_flag in ('N', 'P')
6864     AND  nvl(D.encumbered_flag, 'N') in ('N', 'H', 'P')
6865     AND  D.line_type_lookup_code in ( 'ITEM', 'ACCRUAL','IPV', 'RETROEXPENSE',
6866                                       'RETROACCRUAL');  --Retropricing
6867 
6868   BEGIN
6869 
6870     current_calling_sequence := 'AP_INVOICES_UTILITY_PKG.' ||
6871                                 'CALCULATE_VARIANCE<-'|| X_calling_sequence;
6872 
6873    /*-----------------------------------------------------------------+
6874     |  Step 0 - Open Cursor to Initialize the all the information     |
6875     +-----------------------------------------------------------------*/
6876     l_debug_info := 'CALCULATE_VARIANCE - Fetch cursor invoice_dist_cursor';
6877 
6878     OPEN invoice_dist_cursor;
6879     FETCH invoice_dist_cursor INTO
6880                  l_inv_currency_code,
6881                  l_base_currency_code,
6882                  l_dist_line_type,
6883                  l_inv_price,
6884                  l_qty_invoiced,
6885                  l_po_qty,
6886                  l_po_price,
6887                  l_po_rate,
6888                  l_rtxn_rate,
6889                  l_inv_rate,
6890                  l_match_option,
6891                  l_rtxn_uom,
6892                  l_rtxn_item_id,
6893                  l_po_uom,
6894                  l_distribution_amt,
6895                  l_dist_base_amt,
6896                  l_dist_match_type,
6897                  l_corrected_inv_dist_id,
6898                  l_corrected_qty,
6899                  l_match_basis;
6900 
6901     IF (invoice_dist_cursor%NOTFOUND) THEN
6902       l_debug_info := 'CALCULATE_VARIANCE - ROW NOTFOUND';
6903       CLOSE invoice_dist_cursor;
6904       x_debug_info := l_debug_info;
6905       x_debug_context := current_calling_sequence;
6906       return (FALSE);
6907     END IF;
6908 
6909     CLOSE invoice_dist_cursor;
6910     l_debug_info := ' CALCULATE_VARIANCE - Close cursor invoice_dist_cursor';
6911 
6912    /*-----------------------------------------------------------------+
6913     | Amount Based Matching. IPV for l_match_basis = 'QUANTITY' only  |
6914     +-----------------------------------------------------------------*/
6915 
6916     IF l_match_basis = 'QUANTITY' THEN
6917 
6918        /*-----------------------------------------------------------------+
6919        | Step 2 - try to assemble the original dist amt and base amt     |
6920        +-----------------------------------------------------------------*/
6921 
6922        l_original_dist_base_amt := l_dist_base_amt + NVL(x_bipv, 0)
6923                                 + NVL(x_erv, 0);
6924        l_original_dist_amt := l_distribution_amt + NVL(x_ipv, 0);
6925 
6926 
6927       /*-----------------------------------------------------------------+
6928        | Step 3 - converte po/rcv uom                                    |
6929        +-----------------------------------------------------------------*/
6930 
6931        IF (l_match_option = 'R' and l_po_uom <> l_rtxn_uom ) THEN
6932           l_uom_conv_rate := po_uom_s.po_uom_convert (
6933                              l_rtxn_uom,
6934                              l_po_uom,
6935                              l_rtxn_item_id);
6936 
6937           l_qty_invoiced := l_qty_invoiced * l_uom_conv_rate;
6938           l_inv_price := l_inv_price / l_uom_conv_rate;
6939        END IF;
6940 
6941     ELSIF (l_match_basis = 'AMOUNT') THEN
6942 
6943       l_original_dist_base_amt := l_dist_base_amt;
6944       l_original_dist_amt := l_distribution_amt;
6945 
6946     END IF;  -- End l_match_basis. /* Amount Based Matching  */
6947 
6948    /*-----------------------------------------------------------------+
6949     | Step 4 - get rate difference  and price diff                    |
6950     +-----------------------------------------------------------------*/
6951 
6952     If (l_rtxn_rate is null) Then
6953       l_rate_diff := l_inv_rate - l_po_rate;
6954     Else
6955       l_rate_diff := l_inv_rate - l_rtxn_rate;
6956     end if;
6957 
6958     l_price_diff := l_inv_price - l_po_price;
6959 
6960    /*-----------------------------------------------------------------+
6961     | Amount Based Matching. For AMOUNT Based mathing calculation of  |
6962     | ERV is different                                                |
6963     +-----------------------------------------------------------------*/
6964 
6965     IF l_match_basis = 'QUANTITY' THEN
6966         /*-----------------------------------------------------------------+
6967         | Step 5 - calculate erv/ipv                                      |
6968         +-----------------------------------------------------------------*/
6969         --Retropricing
6970        IF  l_dist_match_type  IN ('QTY_CORRECTION', 'PO_PRICE_ADJUSTMENT' ) THEN
6971 
6972           /*-----------------------------------------------------------------+
6973            | calculate erv/ipv - quantity correction                         |
6974            +-----------------------------------------------------------------*/
6975 
6976           l_debug_info := ' CALCULATE_VARIANCE - for QTY_CORRECTION';
6977 
6978           IF (l_rate_diff = 0) THEN
6979             x_erv := 0;
6980           ELSE
6981             x_erv := AP_UTILITIES_PKG.ap_round_currency(
6982                      l_corrected_qty * l_po_price *
6983                      l_rate_diff
6984                      ,l_base_currency_code);
6985           END IF;
6986 
6987           x_ipv := AP_UTILITIES_PKG.ap_round_currency(
6988                    l_corrected_qty * l_price_diff
6989                    ,l_inv_currency_code);
6990 
6991           IF (x_ipv = 0) THEN
6992               x_bipv := 0;
6993           ELSE
6994                -- Bug 5484167  base invoice price variance should be calculated directly from the invoice price variance
6995                --to avoid incorrect rounding logic
6996                /* x_bipv := AP_UTILITIES_PKG.ap_round_currency(
6997                             l_corrected_qty * l_inv_rate * l_price_diff
6998                             , l_base_currency_code);*/
6999                x_bipv := AP_UTILITIES_PKG.ap_round_currency(x_ipv * l_inv_rate, l_base_currency_code);
7000 
7001           END IF;
7002 
7003        ELSIF ( l_dist_match_type = 'PRICE_CORRECTION' ) THEN
7004 
7005           /*-----------------------------------------------------------------+
7006           | calculate erv/ipv - price correction                            |
7007           +-----------------------------------------------------------------*/
7008 
7009           l_debug_info := ' CALCULATE_VARIANCE - for PRICE CORRECTION';
7010 
7011           select nvl(AI.exchange_rate, 1)
7012           into l_corrected_inv_rate
7013           from AP_INVOICES AI,
7014               AP_INVOICE_DISTRIBUTIONS  D
7015           where D.invoice_distribution_id = l_corrected_inv_dist_id
7016           and D.invoice_id = AI.invoice_id;
7017 
7018           x_erv := AP_UTILITIES_PKG.ap_round_Currency( l_original_dist_amt *
7019                   (l_corrected_inv_rate - l_inv_rate)
7020                   , l_base_currency_code);
7021 
7022           x_ipv  := 0;
7023           x_bipv := 0;
7024 
7025        ELSE
7026 
7027           /*-----------------------------------------------------------------+
7028            | calculate erv/ipv - regular quantity base match                 |
7029            +-----------------------------------------------------------------*/
7030 
7031           l_debug_info := ' CALCULATE_VARIANCE - for regular base match
7032                           For Quantity Based Matching';
7033 
7034           IF (l_rate_diff = 0) THEN
7035              x_erv := 0;
7036           ELSE
7037              x_erv := AP_UTILITIES_PKG.ap_round_currency(
7038                          l_qty_invoiced * l_po_price * l_rate_diff
7039                          ,l_base_currency_code);
7040           END IF;
7041 
7042           IF (l_price_diff = 0) THEN
7043              x_ipv := 0;
7044              x_bipv := 0;
7045           ELSE
7046              x_ipv := AP_UTILITIES_PKG.ap_round_currency(
7047                          l_qty_invoiced * l_price_diff
7048                          , l_inv_currency_code );
7049 
7050              IF (x_ipv = 0) THEN
7051                 x_bipv := 0;
7052              ELSE
7053                -- Bug 5484167  base invoice price variance should be calculated directly from the invoice price variance
7054                --to avoid incorrect rounding logic
7055                /* x_bipv := AP_UTILITIES_PKG.ap_round_currency(
7056                             l_qty_invoiced * l_inv_rate * l_price_diff
7057                             , l_base_currency_code);*/
7058                x_bipv := AP_UTILITIES_PKG.ap_round_currency(x_ipv * l_inv_rate, l_base_currency_code);
7059 
7060              END IF;
7061 
7062           END IF; -- end of check l_price_diff
7063 
7064        END IF; -- end of check the l_dist_match_type
7065 
7066     ELSE     -- l_match_basis = 'AMOUNT'. /*Amount Based Matching */
7067 
7068       IF ( l_dist_match_type = 'AMOUNT_CORRECTION' ) THEN
7069 
7070         /*-----------------------------------------------------------------+
7071         | calculate erv - amount correction                               |
7072         +-----------------------------------------------------------------*/
7073 
7074         l_debug_info := ' CALCULATE_VARIANCE - for AMOUNT CORRECTION';
7075 
7076         select nvl(AI.exchange_rate, 1)
7077         into l_corrected_inv_rate
7078         from AP_INVOICES AI,
7079              AP_INVOICE_DISTRIBUTIONS  D
7080         where D.invoice_distribution_id = l_corrected_inv_dist_id
7081         and D.invoice_id = AI.invoice_id;
7082 
7083         x_erv := AP_UTILITIES_PKG.ap_round_Currency( l_original_dist_amt *
7084                   (l_corrected_inv_rate - l_inv_rate)
7085                   , l_base_currency_code);
7086 
7087         x_ipv  := 0;
7088         x_bipv := 0;
7089 
7090       ELSE
7091 
7092         /*-----------------------------------------------------------------+
7093         | calculate erv - regular amount base match                       |
7094         +-----------------------------------------------------------------*/
7095 
7096         l_debug_info := ' CALCULATE_VARIANCE - for regular base match for
7097                           AMOUNT Based Matching';
7098 
7099         IF (l_rate_diff = 0) THEN
7100           x_erv := 0;
7101         ELSE
7102           x_erv := AP_UTILITIES_PKG.ap_round_currency(
7103                      l_original_dist_amt * l_rate_diff
7104                     ,l_base_currency_code);
7105         END IF;
7106 
7107         x_ipv := 0;
7108         x_bipv := 0;
7109 
7110       END IF;
7111 
7112     END IF;  -- END l_match_basis. /* Amount Based Matching */
7113 
7114    /*-----------------------------------------------------------------+
7115     | Step 6 - Prepare the out parameter                              |
7116     +-----------------------------------------------------------------*/
7117     IF ( x_erv <> 0 or x_ipv <> 0 or x_bipv <> 0 ) THEN
7118       l_debug_info := 'CALCULATE_VARIANCE - variance exists';
7119       X_DISTRIBUTION_AMT := l_original_dist_amt - X_IPV;
7120       X_DIST_BASE_AMT := l_original_dist_base_amt - X_ERV - X_BIPV;
7121       x_debug_info := l_debug_info;
7122       x_debug_context := current_calling_sequence;
7123     ELSE
7124       X_DISTRIBUTION_AMT := l_original_dist_amt;
7125       X_DIST_BASE_AMT := l_original_dist_base_amt;
7126     END IF;
7127 
7128 
7129     RETURN ( TRUE );
7130 
7131 EXCEPTION
7132     WHEN OTHERS THEN
7133       IF (SQLCODE <> -20001) then
7134         FND_MESSAGE.SET_NAME('SQLAP', 'AP_DEBUG');
7135         FND_MESSAGE.SET_TOKEN('ERROR', SQLERRM);
7136         FND_MESSAGE.SET_TOKEN('CALLING_SEQUENCE', current_calling_sequence);
7137         FND_MESSAGE.SET_TOKEN('PARAMETERS', 'distribution Id = '
7138                || X_distribution_Id);
7139         FND_MESSAGE.SET_TOKEN('DEBUG_INFO', l_debug_info);
7140       END IF;
7141 
7142       l_debug_info := 'CALCULATE_VARIANCE - OTHERS exception exists';
7143       x_debug_info := l_debug_info;
7144       x_debug_context := current_calling_sequence;
7145       RETURN ( FALSE);
7146 
7147 END CALCULATE_VARIANCE;
7148 
7149 
7150 /*============================================================================= |  Public FUNCTION Dist_Refer_Active_Corr
7151 |
7152 |      Check if the invoice distribution is been referred by a
7153 |      active correction
7154 |
7155 |  PROGRAM FLOW
7156 |
7157 |       return TRUE  - if distribution is been referred by any correction
7158 |       return FALSE - otherwise.
7159 |
7160 |  MODIFICATION HISTORY
7161 |  Date         Author               Description of Change
7162 |  01/28/04     Surekha Myadam       Created
7163  *============================================================================*/
7164 
7165 FUNCTION Dist_Refer_Active_Corr(
7166 		P_Invoice_Dist_ID  IN NUMBER,
7167 	        P_Calling_Sequence IN VARCHAR2) RETURN BOOLEAN IS
7168  dummy number := 0;
7169  current_calling_sequence   Varchar2(2000);
7170  debug_info                 Varchar2(100);
7171 BEGIN
7172 
7173     -- Update the calling sequence
7174     --
7175     current_calling_sequence :=
7176         'AP_INVOICE_DISTRIBUTIONS_PKG.DIST_REFER_ACTIVE_CORR<-'
7177                       ||p_Calling_Sequence;
7178 
7179     debug_info := 'Select from ap_invoice_distributions_all';
7180 
7181     Select count(*)
7182     Into   dummy
7183     From   ap_invoice_distributions_all AID
7184     Where  NVL(AID.cancellation_flag, 'N' ) <> 'Y'
7185     And NVL( AID.reversal_flag, 'N' ) <> 'Y'
7186     And AID.corrected_invoice_dist_id = p_invoice_dist_id
7187     And rownum < 2;   --bug 5034678
7188 
7189     If (dummy >= 1) Then
7190       return  TRUE;
7191     End if;
7192 
7193     return FALSE;
7194 
7195   Exception
7196     WHEN OTHERS THEN
7197       If (SQLCODE <> -20001) Then
7198         FND_MESSAGE.SET_NAME('SQLAP', 'AP_DEBUG');
7199         FND_MESSAGE.SET_TOKEN('ERROR', SQLERRM);
7200         FND_MESSAGE.SET_TOKEN('CALLING_SEQUENCE', current_calling_sequence);
7201         FND_MESSAGE.SET_TOKEN('PARAMETERS', 'Distribution Id = '||P_Invoice_Dist_Id);
7202         FND_MESSAGE.SET_TOKEN('DEBUG_INFO', debug_info);
7203       End If;
7204       APP_EXCEPTION.RAISE_EXCEPTION;
7205 
7206 
7207 END Dist_Refer_Active_Corr;
7208 
7209 /*=============================================================================
7210 |  Public FUNCTION Chrg_Refer_Active_Dist
7211 |
7212 |      Check if this charge distribution is been allocated to  a
7213 |      active invoice distribution
7214 |
7215 |  PROGRAM FLOW
7216 |
7217 |       return TRUE  - if distribution is been referred by any correction
7218 |       return FALSE - otherwise.
7219 |
7220 |  MODIFICATION HISTORY
7221 |  Date         Author               Description of Change
7222 |  01/28/04     Surekha Myadam       Created
7223 *============================================================================*/
7224 
7225 FUNCTION Chrg_Refer_Active_Dist(
7226 		P_Invoice_Dist_Id  IN NUMBER,
7227 		P_Calling_Sequence IN VARCHAR2) RETURN BOOLEAN IS
7228 
7229  dummy number := 0;
7230  current_calling_sequence   Varchar2(2000);
7231  debug_info                 Varchar2(100);
7232 
7233 BEGIN
7234 
7235     -- Update the calling sequence
7236     --
7237     current_calling_sequence :=
7238         'AP_INVOICE_DISTRIBUTIONS_PKG.CHRG_REFER_ACTIVE_DIST<-'
7239                       ||p_Calling_Sequence;
7240 
7241     debug_info := 'Select from ap_invoice_distributions_all';
7242 
7243     Select count(*)
7244     Into   dummy
7245     From   ap_invoice_distributions_all AID
7246     Where  AID.charge_applicable_to_dist_id =  p_invoice_dist_id
7247     And    NVL(AID.cancellation_flag, 'N')  <> 'Y'
7248     And    NVL(AID.reversal_flag, 'N')      <> 'Y';
7249 
7250     If (dummy >= 1) Then
7251       return  TRUE;
7252     End if;
7253 
7254     return FALSE;
7255 
7256 
7257 
7258 Exception
7259  WHEN OTHERS THEN
7260   If (SQLCODE <> -20001) Then
7261    FND_MESSAGE.SET_NAME('SQLAP', 'AP_DEBUG');
7262    FND_MESSAGE.SET_TOKEN('ERROR', SQLERRM);
7263    FND_MESSAGE.SET_TOKEN('CALLING_SEQUENCE', current_calling_sequence);
7264    FND_MESSAGE.SET_TOKEN('PARAMETERS', 'Distribution Id = '||P_Invoice_Dist_Id);
7265    FND_MESSAGE.SET_TOKEN('DEBUG_INFO', debug_info);
7266   End If;
7267   APP_EXCEPTION.RAISE_EXCEPTION;
7268 END Chrg_Refer_Active_Dist;
7269 
7270 
7271 PROCEDURE Make_Distributions_Permanent
7272                  (P_Invoice_Id IN NUMBER,
7273                   P_Invoice_Line_Number IN NUMBER DEFAULT NULL,
7274                   P_Calling_Sequence IN VARCHAR2) IS
7275 
7276 TYPE INVOICE_LINE_NUMBER_LIST IS TABLE OF ap_invoice_lines.line_number%TYPE;
7277 l_line_number_tab 	 INVOICE_LINE_NUMBER_LIST;
7278 l_debug_info 		 VARCHAR2(2000);
7279 current_calling_sequence VARCHAR2(2000);
7280 l_line_number		NUMBER;
7281 global_exception        EXCEPTION;
7282 
7283 BEGIN
7284 
7285  current_calling_sequence := 'Ap_Invoice_Distributions_Pkg.Make_Distributions_Permanent<-  '
7286 				||p_calling_sequence;
7287 
7288  l_debug_info := 'Updating ap_invoice_distributions';
7289 
7290  UPDATE ap_invoice_distributions_all
7291  SET distribution_class = 'PERMANENT'
7292  WHERE invoice_id = p_invoice_id
7293  AND   invoice_line_number = NVL(p_invoice_line_number, invoice_line_number)
7294  AND distribution_class = 'CANDIDATE'
7295  RETURNING invoice_line_number BULK COLLECT INTO l_line_number_tab;
7296 
7297  l_debug_info := 'Updating ap_self_assessed_tax_dist';
7298 
7299  UPDATE ap_self_assessed_tax_dist_all
7300  SET distribution_class = 'PERMANENT'
7301  WHERE invoice_id = p_invoice_id
7302  AND   invoice_line_number = NVL(p_invoice_line_number, invoice_line_number)
7303  AND distribution_class = 'CANDIDATE';
7304 
7305  l_debug_info := 'Updating ap_invoice_lines';
7306 
7307  FOR uniq_values IN 1 .. l_line_number_tab.count LOOP
7308 
7309    l_line_number := l_line_number_tab(uniq_values);
7310 
7311    UPDATE ap_invoice_lines_all ail
7312    SET generate_dists = 'D'
7313    WHERE nvl(ail.generate_dists,'N') = 'Y'
7314    AND invoice_id = p_invoice_id
7315    AND ail.line_number = l_line_number_tab(uniq_values);
7316 
7317    --Commented below condition for the bug 7483192
7318    /*AND ail.amount = (SELECT SUM(NVL(aid.amount,0))
7319   	             FROM ap_invoice_distributions_all aid
7320 		     WHERE aid.invoice_id = ail.invoice_id
7321 		     AND aid.invoice_line_number = ail.line_number
7322 		     AND aid.distribution_class = 'PERMANENT'); */
7323 
7324    UPDATE AP_ALLOCATION_RULES ALR
7325    SET STATUS  = 'EXECUTED'
7326    WHERE alr.invoice_id = p_invoice_id
7327    AND alr.chrg_invoice_line_number = l_line_number_tab(uniq_values)
7328    AND EXISTS (SELECT 'Valid charge line'
7329                FROM ap_invoice_lines ail
7330                WHERE ail.invoice_id = p_invoice_id  --bug 5052657
7331                AND ail.line_number = alr.chrg_invoice_line_number
7332                AND nvl(ail.generate_dists,'N') = 'D'
7333                AND ail.line_type_lookup_code IN ('FREIGHT','MISCELLANEOUS'));
7334 
7335    --Bug:4674229
7336    DECLARE
7337       l_awt_success   Varchar2(1000);
7338    BEGIN
7339       Ap_Extended_Withholding_Pkg.Ap_Ext_Withholding_Default
7340                (p_invoice_id => p_invoice_id,
7341                 p_inv_line_num => l_line_number_tab(uniq_values),
7342 		p_inv_dist_id  => NULL,
7343                 p_calling_module => current_calling_sequence,
7344 		p_parent_dist_id => NULL,
7345                 p_awt_success => l_awt_success);
7346       IF (l_awt_success <> 'SUCCESS') THEN
7347         RAISE Global_Exception;
7348       END IF;
7349    END;
7350 
7351  END LOOP;
7352 
7353 EXCEPTION
7354  WHEN OTHERS THEN
7355   IF (SQLCODE <> -20001) THEN
7356    FND_MESSAGE.SET_NAME('SQLAP', 'AP_DEBUG');
7357    FND_MESSAGE.SET_TOKEN('ERROR', SQLERRM);
7358    FND_MESSAGE.SET_TOKEN('CALLING_SEQUENCE', current_calling_sequence);
7359    FND_MESSAGE.SET_TOKEN('PARAMETERS', 'Invoice Id = '||P_Invoice_Id);
7360    FND_MESSAGE.SET_TOKEN('DEBUG_INFO', l_debug_info);
7361   END IF;
7362   APP_EXCEPTION.RAISE_EXCEPTION;
7363 
7364 END Make_Distributions_Permanent;
7365 
7366 /*=============================================================================
7367 |  Public FUNCTION Chrg_Refer_Active_Dist
7368 |
7369 |  This procedure will get the sum of total charge amount allocated
7370 |  to a particular invoice distribution.
7371 |
7372 |  PROGRAM FLOW
7373 |
7374 |       return   - 0 if no charges are allocated to this distribution.
7375 |		 - returns the sum of charge distributions that are
7376 |		   allocated to this distribution.
7377 |
7378 |  MODIFICATION HISTORY
7379 |  Date         Author               Description of Change
7380 |  02/23/04     Surekha Myadam       Created
7381 *============================================================================*/
7382 
7383 Function Associated_Charges(P_Invoice_Id	      IN NUMBER,
7384 			    P_Invoice_Distribution_Id IN NUMBER)
7385 							RETURN NUMBER IS
7386 
7387 l_total_charge_amount	  NUMBER := 0;
7388 l_debug_info		  VARCHAR2(200);
7389 
7390 BEGIN
7391 
7392   l_debug_info := 'Get total charge amount allocated to this distribution';
7393 
7394   SELECT sum(aid.amount)
7395   INTO l_total_charge_amount
7396   FROM ap_invoice_distributions aid
7397   WHERE aid.invoice_id = p_invoice_id
7398   AND aid.charge_applicable_to_dist_id = p_invoice_distribution_id;
7399 
7400   RETURN(l_total_charge_amount);
7401 
7402 EXCEPTION
7403  WHEN OTHERS THEN
7404   IF (SQLCODE <> -20001) THEN
7405    FND_MESSAGE.SET_NAME('SQLAP', 'AP_DEBUG');
7406    FND_MESSAGE.SET_TOKEN('ERROR', SQLERRM);
7407    FND_MESSAGE.SET_TOKEN('PARAMETERS', 'Invoice Distribution Id = '
7408 					||P_Invoice_Distribution_Id);
7409    FND_MESSAGE.SET_TOKEN('DEBUG_INFO', l_debug_info);
7410   END IF;
7411   APP_EXCEPTION.RAISE_EXCEPTION;
7412 
7413 END Associated_Charges;
7414 
7415 
7416 END AP_INVOICE_DISTRIBUTIONS_PKG;