DBA Data[Home] [Help]

PACKAGE BODY: APPS.JAI_AP_DTC_GENERATION_PKG

Source


1 PACKAGE BODY jai_ap_dtc_generation_pkg
2 /* $Header: jai_ap_dtc_gen.plb 120.65.12020000.8 2013/06/03 06:47:58 cholei noship $ */
3 AS
4 /* ----------------------------------------------------------------------------
5  FILENAME      : jai_ap_dtc_gen.plb
6 
7  Created By    : Zhhou
8 
9  Created Date  : 19-dec-2011
10 
11  Bug           :
12 
13  Purpose       : Implementation of tax defaultation functionality on AP invoice.
14 
15  Called from   : Trigger ja_ap_aid_before_trg
16 
17 
18  CHANGE HISTORY:
19  -------------------------------------------------------------------------------
20  S.No      Date         Author and Details
21  -------------------------------------------------------------------------------
22  1.       19/12/2011
23                         Created this package to implement AP DTC functionality
24                          Copied from jai_ap_tds_gen.plb
25 
26  1.       17/09/2012    Updated For bug#13802244
27                         1).Added hook code for validation in threshold_rollback procedure.
28                         2).In validateion procedure added branches for call from rollback.
29                          a) Do not check or update process_status flag.
30                          b) Call defaultation procedure with 'Y,Y' to redefaultation all.
31                          c) Pass p_call_from parameter to defaultation procedure.
32                          d) Do not add invoice amount to cumulative amount in group information.
33 
34                         3) Update cursor c_jai_ap_tds_thhold_slabs_new to get slab for multi rate
35                            a. Added cp_legal_entity_id parameter
36                            b. Added alias for table jai_ap_tds_thhold_types. Added table alias prefix to
37                               threshold_hdr_id,threshold_type_id.
38                         4) When invoice is prepayment, do not get slab throuth nature accounting.
39 ---------------------------------------------------------------------------- */
40 G_PKG_NAME          CONSTANT VARCHAR2(30) := 'JAI_AP_DTC_GENERATION_PKG';
41 G_MSG_UERROR        CONSTANT NUMBER       := FND_MSG_PUB.G_MSG_LVL_UNEXP_ERROR;
42 G_MSG_ERROR         CONSTANT NUMBER       := FND_MSG_PUB.G_MSG_LVL_ERROR;
43 G_MSG_SUCCESS       CONSTANT NUMBER       := FND_MSG_PUB.G_MSG_LVL_SUCCESS;
44 G_MSG_HIGH          CONSTANT NUMBER       := FND_MSG_PUB.G_MSG_LVL_DEBUG_HIGH;
45 G_MSG_MEDIUM        CONSTANT NUMBER       := FND_MSG_PUB.G_MSG_LVL_DEBUG_MEDIUM;
46 G_MSG_LOW           CONSTANT NUMBER       := FND_MSG_PUB.G_MSG_LVL_DEBUG_LOW;
47 
48 G_CURRENT_RUNTIME_LEVEL CONSTANT NUMBER       := FND_LOG.G_CURRENT_RUNTIME_LEVEL;
49 G_LEVEL_UNEXPECTED      CONSTANT NUMBER       := FND_LOG.LEVEL_UNEXPECTED;
50 G_LEVEL_ERROR           CONSTANT NUMBER       := FND_LOG.LEVEL_ERROR;
51 G_LEVEL_EXCEPTION       CONSTANT NUMBER       := FND_LOG.LEVEL_EXCEPTION;
52 G_LEVEL_EVENT           CONSTANT NUMBER       := FND_LOG.LEVEL_EVENT;
53 G_LEVEL_PROCEDURE       CONSTANT NUMBER       := FND_LOG.LEVEL_PROCEDURE;
54 G_LEVEL_STATEMENT       CONSTANT NUMBER       := FND_LOG.LEVEL_STATEMENT;
55 G_MODULE_NAME           CONSTANT VARCHAR2(40) := 'JAI.PLSQL.JAI_AP_DTC_GENERATION_PKG.';
56 G_CALL_FROM_ROLLBACK    CONSTANT VARCHAR2(40) := 'PROCESS_THRESHOLD_ROLLBACK';  --Added by Chong for Bug#13802244 2012/09/17
57 G_VENDOR_SITE_DEF_SEC_CODE     CONSTANT VARCHAR2(40)     := 'Vendor Site Default Section Code';        --Added by Chong for Bug#13802244 2012/09/17
58 G_NTL_ACC_SEC_MAP              CONSTANT VARCHAR2(40)     := 'Natural Account - Section Code Mapping';  --Added by Chong for Bug#13802244 2012/09/17
59 G_SURCHARGE_ROLLBACK    CONSTANT VARCHAR2(20)     := 'SURCHARGE_ROLLBACK';   --Added by Chong for Bug#13359892 2012/09/27
60 G_SURCHARGE_CALCULATE   CONSTANT VARCHAR2(20)     := 'SURCHARGE_CALCULATE';   --Added by Chong for Bug#13359892 2012/09/27
61 G_INVOICE_VALIDATE      CONSTANT VARCHAR2(20) := 'INVOICE VALIDATE';
62 G_TDS_SECTION           CONSTANT VARCHAR2(20) := 'TDS_SECTION';
63 G_WCT_SECTION           CONSTANT VARCHAR2(20) := 'WCT_SECTION';
64 G_ESSI_SECTION          CONSTANT VARCHAR2(20) := 'ESSI_SECTION';
65 
66 /*Added Procedure below for Xiao for Bug#7154864*/
67 /*Added pn_section_type parameter to get_prepay_invoice_amt - Bug 11070443*/
68 Type ref_cur is ref cursor; -- Added by Zhiwei Hou on 20120114
69 procedure get_prepay_invoice_amt(pn_invoice_id NUMBER, pn_section_type VARCHAR2, pn_prepay_amt OUT NOCOPY NUMBER)
70 is
71 --PRAGMA AUTONOMOUS_TRANSACTION;  --commented by Cholei for ZX integration bug#14040855
72 cursor c_get_dist_prepay(p_invoice_id number) is
73 --select prepay_distribution_id, amount --Comments by Jia for FP Bug#7431371
74 select prepay_distribution_id, sum(amount) amount --Modified by Jia for FP Bug#7431371
75 from ap_invoice_distributions_all
76 where invoice_id = p_invoice_id
77 --Added the following clause to select the prepayment amounts with the same section type as the distribution - Bug 11070443
78 and
79 ((pn_section_type = 'TDS_SECTION' and global_attribute1 is not null)
80   or (pn_section_type = 'WCT_SECTION' and global_attribute2 is not null)
81   or (pn_section_type = 'ESSI_SECTION' and global_attribute3 is not null))
82 and prepay_distribution_id is not null
83 group by prepay_distribution_id; --Addec by Jia for FP Bug#7431371
84 
85 cursor c_get_prepay_inv(p_prepay_dist_id number) is
86 select invoice_id
87 from ap_invoice_distributions_all
88 where invoice_distribution_id = p_prepay_dist_id;
89 
90 cursor c_prepay_tds_cal(p_invoice_id number) is --Xiao for Bug#6767347
91 select 1 from
92 jai_ap_tds_thhold_trxs where
93 invoice_id = p_invoice_id;
94 
95 --Addec by Jia for FP Bug#7431371, Begin
96 -------------------------------------------------------------------------------
97 cursor c_get_tax_code(p_invoice_id number, p_invoice_distribution_id number) is
98 select nvl(actual_tax_id, default_tax_id) tax_id
99 from jai_ap_tds_inv_taxes
100 where invoice_id = p_invoice_id
101 and invoice_distribution_id = p_invoice_distribution_id;
102 
103 cursor c_get_tax_rate(p_tax_id number) is
104 select tax_rate
105 from jai_cmn_taxes_all
106 where tax_id = p_tax_id;
107 
108 ln_tax_id number;
109 ln_tax_rate number;
110 -------------------------------------------------------------------------------
111 --Addec by Jia for FP Bug#7431371, End
112 
113 ln_invoice_id number;
114 ln_prepay_tds_exists number := 0;
115 BEGIN
116     BEGIN
117 	  pn_prepay_amt := 0;
118 	  for r_get_dist_prepay in c_get_dist_prepay(pn_invoice_id)
119 	  loop
120 	   open c_get_prepay_inv(r_get_dist_prepay.prepay_distribution_id);
121        fetch c_get_prepay_inv into ln_invoice_id;
122        close c_get_prepay_inv;
123 
124 	   open c_prepay_tds_cal(ln_invoice_id);
125 	   fetch c_prepay_tds_cal into ln_prepay_tds_exists;
126 	   close c_prepay_tds_cal;
127 
128 	   if ln_prepay_tds_exists = 1 then
129 	   pn_prepay_amt := pn_prepay_amt + abs(r_get_dist_prepay.amount);
130 
131      --Addec by Jia for FP Bug#7431371, Begin
132      -------------------------------------------------------------------------------
133      ELSE
134         open c_get_tax_code(ln_invoice_id, r_get_dist_prepay.prepay_distribution_id);
135         fetch c_get_tax_code into ln_tax_id;
136         close c_get_tax_code;
137 
138         open c_get_tax_rate(ln_tax_id);
139         fetch c_get_tax_rate into ln_tax_rate;
140         close c_get_tax_rate;
141 
142         if ln_tax_rate = 0 then
143         pn_prepay_amt := pn_prepay_amt + abs(r_get_dist_prepay.amount);
144         end if;
145      -------------------------------------------------------------------------------
146      --Addec by Jia for FP Bug#7431371, End
147 	   end if;
148 	  end loop;
149 
150     EXCEPTION
151 	WHEN NO_DATA_FOUND THEN
152 		pn_prepay_amt:=0;
153 	END;
154 END get_prepay_invoice_amt;
155 
156 
157   --Added by Zhiwei Hou on 20120113 begin
158   -------------------------------------------------------------
159   procedure chk_tax_exists(
160             pn_invoice_id          number,
161             pn_count    OUT NOCOPY NUMBER
162   )
163   is
164       --PRAGMA AUTONOMOUS_TRANSACTION;  --commented by Cholei for ZX integration bug#14040855
165 
166 
167         ln_count number:= 0;
168 
169         cursor c_chk_tax_exists(cn_invoice_id number)
170         is
171         select count(1)
172         from AP_INVOICE_DISTRIBUTIONS_ALL
173         where invoice_id = cn_invoice_id
174         and   invoice_distribution_id not in
175         (
176               select invoice_distribution_id
177               from JAI_AP_TDS_INV_TAXES
178               where invoice_id = cn_invoice_id
179               and   threshold_transition is null
180         );
181 
182   begin
183 
184         open c_chk_tax_exists(pn_invoice_id);
185         fetch c_chk_tax_exists into ln_count;
186         close c_chk_tax_exists;
187 
188         pn_count := ln_count;
189 
190   end chk_tax_exists;
191 
192 
193 
194   --Added by Zhiwei Hou for Bug#13818183 on 20120308 begin
195   ---------------------------------------------------------
196   procedure  get_diff_section_code(
197             pn_invoice_id number,
198             pn_diff       out nocopy number
199   )
200   is
201 
202 
203   --PRAGMA AUTONOMOUS_TRANSACTION;  --commented by Cholei for ZX integration bug#14040855
204 
205       ln_diff number:= 0;
206 
207       cursor  c_chk_section_chg
208       is
209       select count(1)
210       from jai_ap_tds_inv_taxes tax
211       where tax.invoice_id = pn_invoice_id
212       and   tax.actual_section_code not in
213             (
214 
215             select section_code
216             from JAI_AP_TDS_VENDOR_HDRS
217             where vendor_id      = tax.vendor_id
218             and   vendor_site_id = tax.vendor_site_id
219             )
220       and  tax.threshold_transition is null
221       and  nvl(tax.tax_category_overriden,'N') = 'N';--Added by Zhiwei Hou for DTC enhancement bug#13833686 on 20120312
222 
223   begin
224       open c_chk_section_chg;
225       fetch c_chk_section_chg into ln_diff;
226       close c_chk_section_chg;
227 
228       pn_diff := ln_diff;
229 
230   end get_diff_section_code;
231   ---------------------------------------------------------
232   --Added by Zhiwei Hou for Bug#13818183 on 20120308 begin
233 
234   --Added by Zhiwei Hou for Bug#13740826 begin
235   -----------------------------------------------------
236   procedure get_amount_change(
237             pn_invoice_id          number,
238             pn_diff    OUT NOCOPY NUMBER
239   )
240   is
241       --PRAGMA AUTONOMOUS_TRANSACTION;  --commented by Cholei for ZX integration bug#14040855
242 
243 
244       ln_diff number:= 0;
245 
246 
247       cursor c_chk_amount_chg(cn_invoice_id number)
248       is
249       select dist.invoice_id, dist.INVOICE_DISTRIBUTION_ID,nvl(dist.amount-sum(tax.amount),0) diff
250       from AP_INVOICE_DISTRIBUTIONS_ALL dist,
251            JAI_AP_TDS_INV_TAXES          tax
252       where dist.invoice_id = tax.invoice_id
253       and   dist.INVOICE_DISTRIBUTION_ID = tax.INVOICE_DISTRIBUTION_ID
254       and   tax.threshold_transition is null
255       and   dist.invoice_id = cn_invoice_id
256       group by dist.invoice_id, dist.INVOICE_DISTRIBUTION_ID,dist.amount;
257 
258       rec_amount c_chk_amount_chg%rowtype;
259 
260   begin
261 
262         open c_chk_amount_chg(pn_invoice_id);
263         fetch c_chk_amount_chg into rec_amount;
264         close c_chk_amount_chg;
265 
266         ln_diff := rec_amount.diff;
267 
268         pn_diff := ln_diff;
269 
270   end get_amount_change;
271   -----------------------------------------------------
272   --Added by Zhiwei Hou for Bug#13740826 end
273 
274   --Added by Chong.lei for Bug#13782492 on 20120301 begin
275   --------------------------------------------------------------------
276   /*Given invoice_id, check all distriutions line in this invoice
277    count distribution line:
278     1).exists in jai_ap_tds_default but not in ap_invoice_distributions_all.
279     2).exists in ap_invoice_distributions_all but not in jai_ap_tds_default.
280     3).both exist in this two tables but with diff accounting date.
281 
282     return pn_diff > 0, then need redefaultation.
283   */
284   procedure chk_accounting_date(
285               pn_invoice_id          number,
286               pn_cnt                out nocopy number
287   )is
288       --PRAGMA AUTONOMOUS_TRANSACTION;  --commented by Cholei for ZX integration bug#14040855
289       /*Check distribution line:
290         1).exists in jai_ap_tds_default but not in ap_invoice_distributions_all.
291         2).exists in ap_invoice_distributions_all but not in jai_ap_tds_default.
292         3).both exist in this two tables but with diff accounting date.
293       */
294       cursor c_changed_acdate(cn_invoice_id number)
295       is
296       select sum(
297                 decode(to_char(trunc(aida.accounting_date),'YYYYMMDD'), to_char(trunc(jatd.accounting_date),'YYYYMMDD'), 0, 1)
298              )
299       from   jai_ap_tds_default jatd full outer join
300              ap_invoice_distributions_all aida on (
301                 jatd.invoice_distribution_id = aida.invoice_distribution_id
302                 and jatd.invoice_id = aida.invoice_id
303              )
304       where (aida.invoice_id = cn_invoice_id or jatd.invoice_id = cn_invoice_id)
305       and not exists
306             (select 1
307              from   ap_invoice_lines_all         aila
308              where  aida.invoice_id = aila.invoice_id
309                and  aida.invoice_line_number = aila.line_number
310                and  NVL(aila.DISCARDED_FLAG,'N') = 'Y'
311                and  aila.invoice_id = cn_invoice_id
312                );
313 
314       ln_count number := 0;
315   begin
316 
317       open c_changed_acdate(pn_invoice_id);
318       fetch c_changed_acdate into ln_count;
319       close c_changed_acdate;
320 
321       pn_cnt := ln_count;
322 
323   end chk_accounting_date;
324 
325   procedure get_CCID(
326               pn_invoice_distribution_id          number,
327               pn_CCID                  out nocopy number
328   )is
329       --PRAGMA AUTONOMOUS_TRANSACTION;  --commented by Cholei for ZX integration bug#14040855
330 	    CURSOR c_CCID(c_invoice_distribution_id NUMBER
331                  ) IS
332       SELECT dist_code_combination_id
333         FROM ap_invoice_distributions_all
334        WHERE invoice_distribution_id = c_invoice_distribution_id;
335   begin
336 
337       OPEN c_CCID(pn_invoice_distribution_id);
338       FETCH c_CCID INTO pn_CCID;
339       CLOSE c_CCID;
340 
341   end get_CCID;
342   --------------------------------------------------------------------
343   --Added by Chong.lei Bug#13782492 on 20120301 end
344 
345 
346   /*
347   */
348   procedure get_non_match_dist(
349             pn_invoice_id number,
350             pn_non_count OUT NOCOPY NUMBER
351             )
352   is
353       --PRAGMA AUTONOMOUS_TRANSACTION;  --commented by Cholei for ZX integration bug#14040855
354 
355       cursor c_get_non_match_dist(cn_invoice_id number)
356       is
357       SELECT count(1)
358       FROM AP_INVOICE_DISTRIBUTIONS_ALL AIDA, JAI_AP_TDS_INV_TAXES JATIT
359       WHERE AIDA.INVOICE_ID = JATIT.INVOICE_ID
360       and   aida.invoice_id = cn_invoice_id
361       AND AIDA.INVOICE_DISTRIBUTION_ID = JATIT.INVOICE_DISTRIBUTION_ID
362       AND AIDA.DIST_CODE_COMBINATION_ID <> JATIT.DIST_CODE_COMBINATION_ID
363       and JATIT.threshold_transition is null;
364 
365       ln_count number := 0;
366   begin
367 
368       open c_get_non_match_dist(pn_invoice_id);
369       fetch c_get_non_match_dist into ln_count;
370       close c_get_non_match_dist;
371 
372       pn_non_count := ln_count;
373 
374 
375   end get_non_match_dist;
376 
377   /*
378   */
379   Function get_natural_account_value(
380            pn_invoice_id number,
381            pn_invoice_distribution_id number,
382            pv_segment_name varchar2
383   )return varchar2
384   is
385   --PRAGMA AUTONOMOUS_TRANSACTION;  --commented by Cholei for ZX integration bug#14040855
386 
387   lv_natural_account_value varchar2(10);
388 
389   cursor get_result
390   is
391   --select get_natural_account(dist_code_combination_id)
392   select JAI_AP_UTILS_PKG.GET_NATURAL_ACCOUNT_VALUE(dist_code_combination_id,pv_segment_name)
393   from ap_invoice_distributions_all
394   where invoice_id = pn_invoice_id
395   and   invoice_distribution_id = pn_invoice_distribution_id;
396 
397 
398 
399   begin
400 
401         open get_result;
402         fetch get_result into lv_natural_account_value;
403         close get_result;
404 
405         return lv_natural_account_value;
406 
407   end get_natural_account_value;
408 
409     --Added by Zhiwei Hou on 20120114 begin
410     ------------------------------------------------------------
411     FUNCTION chk_prepay_inv(pn_invoice_id number)return number
412     is
413     --PRAGMA AUTONOMOUS_TRANSACTION;  --commented by Cholei for ZX integration bug#14040855
414 
415     ln_flag number;
416     cursor chk_exist(cn_invoice_id number)
417     is
418     select 1
419     from dual
420     where exists
421     (
422         SELECT INVOICE_ID
423         FROM AP_INVOICE_DISTRIBUTIONS_ALL
424         WHERE INVOICE_DISTRIBUTION_ID IN
425                                       (
426                                           SELECT PREPAY_DISTRIBUTION_ID
427                                           FROM AP_INVOICE_DISTRIBUTIONS_ALL
428                                           WHERE LINE_TYPE_LOOKUP_CODE = 'PREPAY'
429                                           AND INVOICE_ID = cn_invoice_id
430                                       )
431          AND NOT EXISTS (
432               SELECT '1'
433               FROM JAI_AP_TDS_THHOLD_TRXS JATTT
434               WHERE JATTT.INVOICE_ID = INVOICE_ID
435               )
436     );
437     begin
438 
439            open chk_exist(pn_invoice_id);
440            fetch chk_exist into ln_flag;
441            close chk_exist;
442 
443            return nvl(ln_flag,0);
444 
445     END chk_prepay_inv;
446 
447     /*
448     */
449     FUNCTION chk_no_prepay_inv(pn_invoice_id number)return number
450     is
451     --PRAGMA AUTONOMOUS_TRANSACTION;  --commented by Cholei for ZX integration bug#14040855
452 
453     ln_flag number;
454     cursor chk_exist(cn_invoice_id number)
455     is
456     select 1
457     from dual
458     where not exists
459     (
460             SELECT PREPAY_DISTRIBUTION_ID
461             FROM AP_INVOICE_DISTRIBUTIONS_ALL
462             WHERE LINE_TYPE_LOOKUP_CODE = 'PREPAY'
463             AND INVOICE_ID = cn_invoice_id
464     );
465 
466     begin
467 
468            open chk_exist(pn_invoice_id);
469            fetch chk_exist into ln_flag;
470            close chk_exist;
471 
472            return nvl(ln_flag,0);
473 
474     END chk_no_prepay_inv;
475 
476     /*
477     To avoid Mutating issue
478     Updated by Zhiwei hou for bug#13787158, add check for prepayment invoice may be rollbacked.
479     */
480     FUNCTION get_invoice_tax_not_deducted(
481              pn_invoice_id       number,
482              pv_section_code     varchar2,
483              pn_threshold_grp_id number
484     )RETURN ref_cur
485     IS
486     PRAGMA AUTONOMOUS_TRANSACTION;  --commented by Cholei for ZX integration bug#14040855 --released comment by Cholei for bug#14207353  in ZX ER
487 
488     lv_sql  VARCHAR2(4000);
489     l_tab   ref_cur;
490     l_api_name                   CONSTANT  VARCHAR2(50) := 'get_invoice_tax_not_deducted()';
491 
492     BEGIN
493 
494 	  jai_cmn_utils_pkg.WRITE_FND_LOG(G_LEVEL_PROCEDURE, G_MODULE_NAME||l_api_name||'.BEGIN', G_PKG_NAME || ': '||l_api_name||'()+');
495 
496           lv_sql :=
497     'SELECT INVOICE_ID, SUM (AMOUNT) ,ACTUAL_SECTION_CODE, TAX_CATEGORY_ID
498     FROM  JAI_AP_TDS_INV_TAXES JATIT
499     WHERE JATIT.INVOICE_ID <> $$P_INVOICE_ID$$
500     AND  (
501           ( JATIT.TAX_LINE_NO <> 0 and JATIT.TAX_CATEGORY_ID IS NOT NULL and JATIT.invoice_distribution_id <> 1 )
502           or
503           ( JATIT.TAX_LINE_NO = 0 and JATIT.TAX_CATEGORY_ID IS  NULL and JATIT.ACTUAL_TAX_ID IS NULL)
504          )
505     AND (JATIT.TAX_CATEGORY_ID IS NOT NULL or (JATIT.TAX_CATEGORY_ID IS  NULL and JATIT.ACTUAL_TAX_ID IS NULL))
506     AND   JATIT.ACTUAL_SECTION_CODE = ''$$cv_section_code$$''
507     AND   JATIT.THRESHOLD_GRP_ID = $$P_THRESHOLD_GRP_ID$$
508     AND   (
509                 NOT EXISTS (SELECT 1
510                             FROM JAI_AP_TDS_THHOLD_TRXS
511                             WHERE INVOICE_ID = JATIT.INVOICE_ID
512                             AND TDS_SECTION_CODE = JATIT.ACTUAL_SECTION_CODE
513                            )
514             OR
515                 EXISTS (
516                       SELECT 1
517                       FROM JAI_AP_TDS_THHOLD_TRXS    TRX1
518                       WHERE TRX1.INVOICE_ID = JATIT.INVOICE_ID
519                       AND   TRX1.TDS_SECTION_CODE = JATIT.ACTUAL_SECTION_CODE
520                       AND   TRX1.TDS_ROLLBACKED = ''Y''
521                       AND   TRX1.THRESHOLD_TRX_ID IN
522                       (
523                             SELECT MAX(THRESHOLD_TRX_ID)
524                             FROM JAI_AP_TDS_THHOLD_TRXS TRX2
525                             WHERE TRX2.INVOICE_ID = JATIT.INVOICE_ID
526                             AND   TRX2.TDS_SECTION_CODE = JATIT.ACTUAL_SECTION_CODE
527                       )
528                 )
529          )
530     AND  (
531           EXISTS
532           (
533                 SELECT DIST.INVOICE_ID
534                 FROM AP_INVOICE_DISTRIBUTIONS_ALL DIST
535                 WHERE DIST.INVOICE_DISTRIBUTION_ID IN
536                                               (
537                                                   SELECT PREPAY_DISTRIBUTION_ID
538                                                   FROM AP_INVOICE_DISTRIBUTIONS_ALL
539                                                   WHERE LINE_TYPE_LOOKUP_CODE = ''PREPAY''
540                                                   AND INVOICE_ID = JATIT.INVOICE_ID
541                                               )
542                 AND
543                 (
544                     NOT EXISTS (
545                         SELECT ''1''
546                         FROM JAI_AP_TDS_THHOLD_TRXS JAITTT
547                         WHERE JAITTT.INVOICE_ID = DIST.INVOICE_ID
548                     )
549                     or
550                     exists
551                     (
552                         SELECT 1
553                         FROM JAI_AP_TDS_THHOLD_TRXS    TRX3
554                         WHERE TRX3.INVOICE_ID = DIST.INVOICE_ID
555                         AND   TRX3.TDS_SECTION_CODE = JATIT.ACTUAL_SECTION_CODE
556                         AND   TRX3.TDS_ROLLBACKED = ''Y''
557                         AND   TRX3.THRESHOLD_TRX_ID IN
558                         (
559                               SELECT MAX(THRESHOLD_TRX_ID)
560                               FROM JAI_AP_TDS_THHOLD_TRXS TRX4
561                               WHERE TRX4.INVOICE_ID = DIST.INVOICE_ID
562                               AND   TRX4.TDS_SECTION_CODE = JATIT.ACTUAL_SECTION_CODE
563                         )
564                     )
565                 )
566         )
567         OR
568        NOT EXISTS
569        (
570             SELECT PREPAY_DISTRIBUTION_ID
571             FROM AP_INVOICE_DISTRIBUTIONS_ALL
572             WHERE LINE_TYPE_LOOKUP_CODE = ''PREPAY''
573             AND INVOICE_ID = JATIT.INVOICE_ID
574        )
575     )
576     AND EXISTS
577     (
578         SELECT 1
579         FROM AP_INVOICES_ALL
580         WHERE INVOICE_ID = JATIT.INVOICE_ID
581         and   cancelled_date is null
582         AND   INVOICE_TYPE_LOOKUP_CODE <> ''PREPAYMENT''
583     )
584     GROUP BY INVOICE_ID, ACTUAL_SECTION_CODE, TAX_CATEGORY_ID';
585 
586           lv_sql  :=   REPLACE
587              ( lv_sql
588              , '$$P_INVOICE_ID$$'
589              , NVL(pn_invoice_id,-999)  --Updated by Zhiwei Hou for Bug#13787158 on 20120305
590              );
591           lv_sql  :=   REPLACE
592              ( lv_sql
593              , '$$cv_section_code$$'
594              , ''||pv_section_code||''
595              );
596 
597           lv_sql  :=   REPLACE
598              ( lv_sql
599              , '$$P_THRESHOLD_GRP_ID$$'
600              ,  pn_threshold_grp_id
601              );
602 
603 
604           open l_tab for lv_sql;
605 
606 
607 	  jai_cmn_utils_pkg.WRITE_FND_LOG(G_LEVEL_PROCEDURE, G_MODULE_NAME||l_api_name||'.END', G_PKG_NAME || ': '||l_api_name||'()-');
608 
609           return l_tab;
610 
611     END get_invoice_tax_not_deducted;
612 
613 
614 
615     /*
616     To avoid Mutating issue
617     */
618     FUNCTION get_invoice_unpaid(
619              pn_invoice_id       number,
620              pv_section_code     varchar2,
621              pn_threshold_grp_id number
622     )RETURN ref_cur
623     IS
624     PRAGMA AUTONOMOUS_TRANSACTION;  --commented by Cholei for ZX integration bug#14040855  --released comment by Cholei for bug#14207353  in ZX ER
625 
626     lv_sql  VARCHAR2(4000);
627     l_tab   ref_cur;
628     l_api_name                   CONSTANT  VARCHAR2(50) := 'get_invoice_unpaid()';
629 
630     BEGIN
631 
632 	  jai_cmn_utils_pkg.WRITE_FND_LOG(G_LEVEL_PROCEDURE, G_MODULE_NAME||l_api_name||'.BEGIN', G_PKG_NAME || ': '||l_api_name||'()+');
633 
634           lv_sql :=
635                   'SELECT INVOICE_ID, SUM (AMOUNT), ACTUAL_SECTION_CODE, TAX_CATEGORY_ID
636                   FROM
637                   (
638                   SELECT JATIT.INVOICE_ID, (JATIT.AMOUNT-NVL(JATP.APPLICATION_AMOUNT, 0)) AMOUNT, JATIT.ACTUAL_SECTION_CODE, JATIT.TAX_CATEGORY_ID
639                   FROM JAI_AP_TDS_INV_TAXES JATIT, JAI_AP_TDS_PREPAYMENTS JATP
640                   WHERE JATIT.INVOICE_ID <> $$P_INVOICE_ID$$
641                   AND  (
642                         ( JATIT.TAX_LINE_NO <> 0 and JATIT.TAX_CATEGORY_ID IS NOT NULL and JATIT.invoice_distribution_id <> 1 )
643                         or
644                         ( JATIT.TAX_LINE_NO = 0 and JATIT.TAX_CATEGORY_ID IS  NULL and JATIT.ACTUAL_TAX_ID IS NULL)
645                        )
646                   AND (JATIT.TAX_CATEGORY_ID IS NOT NULL or (JATIT.TAX_CATEGORY_ID IS  NULL and JATIT.ACTUAL_TAX_ID IS NULL))
647                   AND JATIT.ACTUAL_SECTION_CODE = ''$$cv_section_code$$''
648                   AND JATIT.THRESHOLD_GRP_ID = $$P_THRESHOLD_GRP_ID$$
649                   AND JATIT.INVOICE_DISTRIBUTION_ID = JATP.INVOICE_DISTRIBUTION_ID (+)
650                   AND (NOT EXISTS (   SELECT 1
651                                       FROM JAI_AP_TDS_THHOLD_TRXS
652                                       WHERE INVOICE_ID = JATIT.INVOICE_ID
653                                       AND TDS_SECTION_CODE = JATIT.ACTUAL_SECTION_CODE
654                                      )
655                         OR
656                         EXISTS
657                                  (
658                                           SELECT 1
659                                           FROM JAI_AP_TDS_THHOLD_TRXS    TRX1
660                                           WHERE TRX1.INVOICE_ID = JATIT.INVOICE_ID
661                                           AND   TRX1.TDS_SECTION_CODE = JATIT.ACTUAL_SECTION_CODE
662                                           AND   TRX1.TDS_ROLLBACKED = ''Y''
663                                           AND   TRX1.THRESHOLD_TRX_ID IN
664                                           (
665                                                 SELECT MAX(THRESHOLD_TRX_ID)
666                                                 FROM JAI_AP_TDS_THHOLD_TRXS TRX2
667                                                 WHERE TRX2.INVOICE_ID = JATIT.INVOICE_ID
668                                                 AND   TRX2.TDS_SECTION_CODE = JATIT.ACTUAL_SECTION_CODE
669 
670                                           )
671                                  )
672                        )
673                  AND EXISTS (
674                               SELECT DIST.INVOICE_ID
675                               FROM AP_INVOICE_DISTRIBUTIONS_ALL DIST
676                               WHERE DIST.INVOICE_DISTRIBUTION_ID IN (
677                                     SELECT PREPAY_DISTRIBUTION_ID
678                                     FROM AP_INVOICE_DISTRIBUTIONS_ALL
679                                     WHERE LINE_TYPE_LOOKUP_CODE = ''PREPAY''
680                                     AND INVOICE_ID = JATIT.INVOICE_ID
681                                     )
682                               AND EXISTS (
683                                   SELECT ''1''
684                                   FROM JAI_AP_TDS_THHOLD_TRXS JAITTT
685                                   WHERE JAITTT.INVOICE_ID = DIST.INVOICE_ID)
686                       )
687                   AND NOT EXISTS(
688                       SELECT 1
689                       FROM   AP_INVOICES_ALL aia
690                       WHERE  aia.invoice_id = JATIT.invoice_id
691                       AND    aia.cancelled_date IS NOT NULL
692                       )
693                   )
694                   GROUP BY INVOICE_ID, ACTUAL_SECTION_CODE, TAX_CATEGORY_ID';
695 
696           lv_sql  :=   REPLACE
697              ( lv_sql
698              , '$$P_INVOICE_ID$$'
699              , NVL(pn_invoice_id,-999)  --Updated by Zhiwei Hou for Bug#13787158 on 20120305
700              );
701           lv_sql  :=   REPLACE
702              ( lv_sql
703              , '$$cv_section_code$$'
704              , ''||pv_section_code||''
705              );
706 
707           lv_sql  :=   REPLACE
708              ( lv_sql
709              , '$$P_THRESHOLD_GRP_ID$$'
710              ,  pn_threshold_grp_id
711              );
712 
713 
714           open l_tab for lv_sql;
715 
716 	  jai_cmn_utils_pkg.WRITE_FND_LOG(G_LEVEL_PROCEDURE, G_MODULE_NAME||l_api_name||'.END', G_PKG_NAME || ': '||l_api_name||'()-');
717 
718           return l_tab;
719 
720     END get_invoice_unpaid;
721 
722 
723 
724     /*
725     To avoid Mutating issue
726     */
727     /* Changed by Zhiwei Hou for bug#13797556 on 20120302.
728        change AIDA.PREPAY_AMOUNT_REMAINING
729        to     nvl(AIDA.PREPAY_AMOUNT_REMAINING,aida.amount)
730        As prepay_amount_remaining will be populated after pay,
731        if not pay, the column is null, so Gerneration will avoid unpay prepayment invoice.
732     */
733     FUNCTION get_prepay_unapplied(
734              pn_invoice_id       number,
735              pv_section_code     varchar2,
736              --Updated by Chong.Lei for bug#13787158 begin
737              pn_threshold_grp_id number,
738              pn_prepayment_inovice_id number,
739              pn_unapply_amount        number
740              --Updated by Chong.Lei for bug#13787158 end
741     )RETURN ref_cur
742     IS
743     PRAGMA AUTONOMOUS_TRANSACTION;  --commented by Cholei for ZX integration bug#14040855  --released comment by Cholei for bug#14207353  in ZX ER
744 
745     lv_sql  VARCHAR2(4000);
746 
747 
748     l_tab   ref_cur;
749     l_api_name                   CONSTANT  VARCHAR2(50) := 'get_prepay_unapplied()';
750 
751     BEGIN
752 
753 	  jai_cmn_utils_pkg.WRITE_FND_LOG(G_LEVEL_PROCEDURE, G_MODULE_NAME||l_api_name||'.BEGIN', G_PKG_NAME || ': '||l_api_name||'()+');
754 
755           --Updated by Chong.Lei for bug#13787158 begin
756           -----------------------------------------------------------------------------------------------------
757 /*         lv_sql := 'SELECT JATIT.INVOICE_ID, SUM (nvl(AIDA.PREPAY_AMOUNT_REMAINING,aida.amount)) AMOUNT, JATIT.ACTUAL_SECTION_CODE, JATIT.TAX_CATEGORY_ID
758               FROM JAI_AP_TDS_INV_TAXES JATIT, AP_INVOICE_DISTRIBUTIONS_ALL AIDA
759               WHERE JATIT.INVOICE_ID <> $$P_INVOICE_ID$$
760               AND (
761                         ( JATIT.TAX_LINE_NO <> 0 and JATIT.TAX_CATEGORY_ID IS NOT NULL and JATIT.invoice_distribution_id <> 1 )
762                         or
763                         ( JATIT.TAX_LINE_NO = 0 and JATIT.TAX_CATEGORY_ID IS  NULL and JATIT.ACTUAL_TAX_ID IS NULL)
764                   )
765               AND (JATIT.TAX_CATEGORY_ID IS NOT NULL or (JATIT.TAX_CATEGORY_ID IS  NULL and JATIT.ACTUAL_TAX_ID IS NULL))
766               AND JATIT.ACTUAL_SECTION_CODE = ''$$cv_section_code$$''
767               AND JATIT.INVOICE_DISTRIBUTION_ID = AIDA.INVOICE_DISTRIBUTION_ID
768               AND JATIT.THRESHOLD_GRP_ID = $$P_THRESHOLD_GRP_ID$$
769               AND (
770                   nvl(AIDA.PREPAY_AMOUNT_REMAINING,aida.amount) IS NOT NULL
771                   OR
772                   nvl(AIDA.PREPAY_AMOUNT_REMAINING,aida.amount) > 0
773                   )
774               AND EXISTS
775               (
776               SELECT 1
777               FROM AP_INVOICES_ALL
778               WHERE INVOICE_ID = AIDA.INVOICE_ID
779               AND INVOICE_TYPE_LOOKUP_CODE = ''PREPAYMENT'')
780               AND (NOT EXISTS (SELECT 1
781                                   FROM JAI_AP_TDS_THHOLD_TRXS
782                                   WHERE INVOICE_ID = JATIT.INVOICE_ID
783                                   AND TDS_SECTION_CODE = JATIT.ACTUAL_SECTION_CODE
784                                  )
785                     OR
786                     EXISTS
787                              (
788                                           SELECT 1
789                                           FROM JAI_AP_TDS_THHOLD_TRXS    TRX1
790                                           WHERE TRX1.INVOICE_ID = JATIT.INVOICE_ID
791                                           AND   TRX1.TDS_SECTION_CODE = JATIT.ACTUAL_SECTION_CODE
792                                           AND   TRX1.TDS_ROLLBACKED = ''Y''
793                                           AND   TRX1.THRESHOLD_TRX_ID IN
794                                           (
795                                                 SELECT MAX(THRESHOLD_TRX_ID)
796                                                 FROM JAI_AP_TDS_THHOLD_TRXS TRX2
797                                                 WHERE TRX2.INVOICE_ID = JATIT.INVOICE_ID
798                                                 AND   TRX2.TDS_SECTION_CODE = JATIT.ACTUAL_SECTION_CODE
799 
800                                           )
801                              )
802                    )
803               GROUP BY JATIT.INVOICE_ID, JATIT.ACTUAL_SECTION_CODE, JATIT.TAX_CATEGORY_ID';*/
804 		--Updated by Chong.Lei for bug#14218068,  Added left outer join for ap_invoice_distributions_all table to get prepayments invoice which never applied to any standard invoice.
805          lv_sql := 'SELECT JATIT.INVOICE_ID, DECODE(JATIT.INVOICE_ID ,$$pn_prepayment_inovice_id$$, SUM(JATIT.AMOUNT) - NVL(abs(SUM (AIDA.AMOUNT)),0) + $$pn_unapply_amount$$ ,SUM(JATIT.AMOUNT) - NVL(abs(SUM (AIDA.AMOUNT)),0)) AMOUNT
806                   ,JATIT.ACTUAL_SECTION_CODE, JATIT.TAX_CATEGORY_ID
807               FROM JAI_AP_TDS_INV_TAXES JATIT, AP_INVOICE_DISTRIBUTIONS_ALL AIDA
808               WHERE JATIT.INVOICE_ID <> $$P_INVOICE_ID$$
809               AND JATIT.TAX_LINE_NO = 0
810               AND (JATIT.TAX_CATEGORY_ID IS NOT NULL or (JATIT.TAX_CATEGORY_ID IS  NULL and JATIT.ACTUAL_TAX_ID IS NULL))
811               AND JATIT.ACTUAL_SECTION_CODE = ''$$cv_section_code$$''
812               AND JATIT.INVOICE_DISTRIBUTION_ID = AIDA.PREPAY_DISTRIBUTION_ID(+)
813               AND AIDA.LINE_TYPE_LOOKUP_CODE(+) = ''PREPAY''
814               AND AIDA.REVERSAL_FLAG(+) = ''N''
815               AND JATIT.THRESHOLD_GRP_ID = $$P_THRESHOLD_GRP_ID$$
816               AND EXISTS
817               (
818               SELECT 1
819               FROM AP_INVOICES_ALL
820               WHERE INVOICE_ID = JATIT.INVOICE_ID
821               AND INVOICE_TYPE_LOOKUP_CODE = ''PREPAYMENT'')
822               AND (NOT EXISTS (SELECT 1
823                                   FROM JAI_AP_TDS_THHOLD_TRXS
824                                   WHERE INVOICE_ID = JATIT.INVOICE_ID
825                                   AND TDS_SECTION_CODE = JATIT.ACTUAL_SECTION_CODE
826                                  )
827                     OR
828                     EXISTS
829                              (
830                                           SELECT 1
831                                           FROM JAI_AP_TDS_THHOLD_TRXS    TRX1
832                                           WHERE TRX1.INVOICE_ID = JATIT.INVOICE_ID
833                                           AND   TRX1.TDS_SECTION_CODE = JATIT.ACTUAL_SECTION_CODE
834                                           AND   TRX1.TDS_ROLLBACKED = ''Y''
835                                           AND   TRX1.THRESHOLD_TRX_ID IN
836                                           (
837                                                 SELECT MAX(THRESHOLD_TRX_ID)
838                                                 FROM JAI_AP_TDS_THHOLD_TRXS TRX2
839                                                 WHERE TRX2.INVOICE_ID = JATIT.INVOICE_ID
840                                                 AND   TRX2.TDS_SECTION_CODE = JATIT.ACTUAL_SECTION_CODE
841 
842                                           )
843                              )
844                    )
845               GROUP BY JATIT.INVOICE_ID, JATIT.ACTUAL_SECTION_CODE, JATIT.TAX_CATEGORY_ID';
846 
847           lv_sql  :=   REPLACE
848              ( lv_sql
849              , '$$pn_prepayment_inovice_id$$'
850              ,  pn_prepayment_inovice_id
851              );
852           lv_sql  :=   REPLACE
853              ( lv_sql
854              , '$$pn_unapply_amount$$'
855              ,  pn_unapply_amount
856              );
857           -----------------------------------------------------------------------------------------------------
858           --Updated by Chong.Lei for bug#13787158 end
859 
860           lv_sql  :=   REPLACE
861              ( lv_sql
862              , '$$P_INVOICE_ID$$'
863              , NVL(pn_invoice_id,-999)  --Updated by Zhiwei Hou for Bug#13787158 on 20120305
864              );
865           lv_sql  :=   REPLACE
866              ( lv_sql
867              , '$$cv_section_code$$'
868              , ''||pv_section_code||''
869              );
870 
871           lv_sql  :=   REPLACE
872              ( lv_sql
873              , '$$P_THRESHOLD_GRP_ID$$'
874              ,  pn_threshold_grp_id
875              );
876 
877 
878           open l_tab for lv_sql;
879 
880 	  jai_cmn_utils_pkg.WRITE_FND_LOG(G_LEVEL_PROCEDURE, G_MODULE_NAME||l_api_name||'.END', G_PKG_NAME || ': '||l_api_name||'()-');
881 
882 	  return l_tab;
883     END get_prepay_unapplied;
884 
885 
886 
887     ---------------------------------------------------------
888     --Added by Zhiwei Hou on 20120114 end
889 
890   ------------------------------------------------------------
891   --Added by Zhiwei Hou on 20120113 end
892 
893 
894 
895     --Added by zhiwei for Bug#13359892 DTC enhancement on 20111123 begin
896     --------------------------------------------------------------------------------------
897     procedure get_prepay_invoice_amt_new(
898         pn_invoice_id    NUMBER,
899         pn_section_type  VARCHAR2,
900         pn_prepay_amt    OUT NOCOPY NUMBER
901        ,pv_section_code  IN VARCHAR2  DEFAULT NULL --Added by Zhiwei for Bug#13359892 on 20111123
902         )
903     is
904     --PRAGMA AUTONOMOUS_TRANSACTION;  --commented by Cholei for ZX integration bug#14040855
905     --Commented and Added by Zhiwei Hou on 20120113 begin
906     -----------------------------------------------------------
907 /*    cursor c_get_dist_prepay(p_invoice_id number) is
908     select prepay_distribution_id, sum(amount) amount
909     from ap_invoice_distributions_all
910     where invoice_id = p_invoice_id
911     and
912         (
913              (    pn_section_type = 'TDS_SECTION'
914               and global_attribute1 is not null
915               and invoice_distribution_id in
916               (
917                  select invoice_distribution_id
918                  from jai_ap_tds_inv_taxes
919                  where invoice_id = p_invoice_id
920                  and   actual_section_code = pv_section_code
921               )
922              )
923           or (pn_section_type = 'WCT_SECTION'  and global_attribute2 is not null)
924           or (pn_section_type = 'ESSI_SECTION' and global_attribute3 is not null)
925         )
926     and prepay_distribution_id is not null
927     group by prepay_distribution_id;*/
928 
929     /*--Commented by Zhiwei Hou on 20120117 begin
930     cursor c_get_dist_prepay(p_invoice_id number)
931     is
932     select invoice_distribution_id prepay_distribution_id,
933            sum(amount) amount
934     from jai_ap_tds_inv_taxes
935     where invoice_distribution_id
936           in
937           (
938            select prepay_distribution_id
939            from ap_invoice_distributions_all
940            where invoice_id = p_invoice_id
941            and   prepay_distribution_id is not null
942           )
943     and  (
944                  (pn_section_type = 'TDS_SECTION' and actual_section_code = pv_section_code)
945               or (pn_section_type = 'WCT_SECTION' )
946               or (pn_section_type = 'ESSI_SECTION')
947             )
948     group by invoice_distribution_id;*/--Commented by Zhiwei Hou on 20120117 end
949     --Added by Zhiwei Hou on 20120117 begin
950     cursor c_get_dist_prepay(p_invoice_id number)
951     is
952     select invoice_distribution_id prepay_distribution_id,
953            sum(AMOUNT-PREPAY_AMOUNT_REMAINING) amount
954     FROM ap_invoice_distributions_all
955     WHERE INVOICE_DISTRIBUTION_ID IN
956     (
957     SELECT invoice_distribution_id
958     from jai_ap_tds_inv_taxes
959     where invoice_distribution_id
960           in
961           (
962            select prepay_distribution_id
963            from ap_invoice_distributions_all
964            where invoice_id = p_invoice_id
965            and   prepay_distribution_id is not null
966           )
967     and  (
968                  (pn_section_type = 'TDS_SECTION' and actual_section_code = pv_section_code)
969               or (pn_section_type = 'WCT_SECTION' )
970               or (pn_section_type = 'ESSI_SECTION')
971          )
972     )
973     group by invoice_distribution_id;
974     --Added by Zhiwei Hou on 20120117 end
975     -----------------------------------------------------------
976     --Commented and Added by Zhiwei Hou on 20120113 end
977 
978     cursor c_get_prepay_inv(p_prepay_dist_id number) is
979     select invoice_id
980     from ap_invoice_distributions_all
981     where invoice_distribution_id = p_prepay_dist_id;
982 
983     cursor c_prepay_tds_cal(p_invoice_id number) is --Xiao for Bug#6767347
984     select 1 from
985     jai_ap_tds_thhold_trxs where
986     invoice_id = p_invoice_id;
987 
988     --Addec by Jia for FP Bug#7431371, Begin
989     -------------------------------------------------------------------------------
990     cursor c_get_tax_code(p_invoice_id number, p_invoice_distribution_id number) is
991     select nvl(actual_tax_id, default_tax_id) tax_id
992     from jai_ap_tds_inv_taxes
993     where invoice_id = p_invoice_id
994     and invoice_distribution_id = p_invoice_distribution_id;
995 
996     cursor c_get_tax_rate(p_tax_id number) is
997     select tax_rate
998     from jai_cmn_taxes_all
999     where tax_id = p_tax_id;
1000 
1001     ln_tax_id number;
1002     ln_tax_rate number;
1003     -------------------------------------------------------------------------------
1004     --Addec by Jia for FP Bug#7431371, End
1005 
1006     ln_invoice_id number;
1007     ln_prepay_tds_exists number := 0;
1008     l_api_name                   CONSTANT  VARCHAR2(50) := 'get_prepay_invoice_amt_new()';
1009 
1010     BEGIN
1011 
1012 --	  jai_cmn_utils_pkg.WRITE_FND_LOG(G_LEVEL_PROCEDURE, G_MODULE_NAME||l_api_name||'.BEGIN', G_PKG_NAME || ': '||l_api_name||'()+');
1013 
1014         BEGIN
1015         pn_prepay_amt := 0;
1016         for r_get_dist_prepay in c_get_dist_prepay(pn_invoice_id)
1017         loop
1018          open c_get_prepay_inv(r_get_dist_prepay.prepay_distribution_id);
1019            fetch c_get_prepay_inv into ln_invoice_id;
1020            close c_get_prepay_inv;
1021 
1022          open c_prepay_tds_cal(ln_invoice_id);
1023          fetch c_prepay_tds_cal into ln_prepay_tds_exists;
1024          close c_prepay_tds_cal;
1025 
1026          if ln_prepay_tds_exists = 1 then
1027          pn_prepay_amt := pn_prepay_amt + abs(r_get_dist_prepay.amount);
1028 
1029          --Addec by Jia for FP Bug#7431371, Begin
1030          -------------------------------------------------------------------------------
1031          ELSE
1032             --Commented and Added by Zhiwei Hou on 20120113 begin
1033             ---------------------------------------------------------------------
1034             /*open c_get_tax_code(ln_invoice_id, r_get_dist_prepay.prepay_distribution_id);
1035             fetch c_get_tax_code into ln_tax_id;
1036 
1037             close c_get_tax_code;
1038 
1039             open c_get_tax_rate(ln_tax_id);
1040             fetch c_get_tax_rate into ln_tax_rate;
1041             close c_get_tax_rate;
1042 
1043             if ln_tax_rate = 0 then
1044             pn_prepay_amt := pn_prepay_amt + abs(r_get_dist_prepay.amount);
1045             end if;*/
1046             pn_prepay_amt := pn_prepay_amt + abs(r_get_dist_prepay.amount);
1047             ---------------------------------------------------------------------
1048             --Commented and Added by Zhiwei Hou on 20120113 end
1049          -------------------------------------------------------------------------------
1050          --Addec by Jia for FP Bug#7431371, End
1051          end if;
1052         end loop;
1053 
1054         EXCEPTION
1055       WHEN NO_DATA_FOUND THEN
1056         pn_prepay_amt:=0;
1057       END;
1058 --	  jai_cmn_utils_pkg.WRITE_FND_LOG(G_LEVEL_PROCEDURE, G_MODULE_NAME||l_api_name||'.END', G_PKG_NAME || ': '||l_api_name||'()-');
1059 
1060     END get_prepay_invoice_amt_new;
1061     --------------------------------------------------------------------------------------
1062     --Added by zhiwei for Bug#13359892 DTC enhancement on 2011123 end
1063 
1064 
1065 --Added by Xiao Lv for bug#8345080 on 13-Jan-10, begin
1066 procedure get_prepay_appln_amt(pn_invoice_id NUMBER,
1067                                pn_threshold_grp_id NUMBER,
1068 							   pn_curr_inv_flag VARCHAR2 DEFAULT 'N',   --Added by Xiao Lv for Bug#8513550, related 11i bug#8439276
1069 							   pn_apply_amt OUT NOCOPY NUMBER)
1070 is
1071 --PRAGMA AUTONOMOUS_TRANSACTION;  --commented by Cholei for ZX integration bug#14040855
1072   cursor c_jai_apply_amount(cp_invoice_id number) is
1073   select sum(a.application_amount) application_amount, d.threshold_grp_id, d.invoice_id
1074   from jai_ap_tds_prepayments a,
1075      ap_invoice_distributions_all b,
1076      ap_invoice_distributions_all c,
1077      jai_ap_tds_inv_taxes d
1078   where a.invoice_distribution_id_prepay = b.invoice_distribution_id
1079   and b.prepay_distribution_id = c.invoice_distribution_id
1080   and nvl(a.unapply_flag, 'N') <> 'Y'
1081   and c.invoice_id = cp_invoice_id                --modified by Xiao Lv for Bug#8513550, related 11i bug#8439276
1082   and c.invoice_id= d.invoice_id
1083   group by d.threshold_grp_id, d.invoice_id;
1084 
1085   /*Bug 12671504 - Start*/
1086   /*If a Prepayment which suffers TDS due to SINGLE Threshold then the same is not deducted
1087   during calculation of Effective Amount during Threshold Transition. This is resulting in
1088   incorrect TDS deducted during Threshold Transition. Derive the Prepayments(which suffered TDS)
1089   applied and subtract the same before calculating Effective amount for Threshold Transition*/
1090   cursor c_pp_single_apply_amount(cp_invoice_id number) is
1091   select sum(application_amount) amount
1092   from jai_ap_tds_prepayments a,
1093   ap_invoice_distributions_all b
1094   where a.invoice_id = cp_invoice_id
1095   and a.invoice_id = b.invoice_id
1096   and a.invoice_distribution_id_prepay = b.invoice_distribution_id
1097   and prepay_distribution_id is not null
1098   and nvl(a.unapply_flag, 'N') <> 'Y'
1099   and exists (select 1
1100               from jai_ap_tds_inv_taxes jatit, ap_invoice_distributions_all aida
1101               where aida.invoice_distribution_id = b.prepay_distribution_id
1102               and aida.invoice_id = jatit.invoice_id
1103               and aida.invoice_distribution_id = jatit.invoice_distribution_id
1104               and jatit.threshold_slab_id_single is not null
1105               and jatit.threshold_trx_id is not null
1106              );
1107   /*Bug 12671504 - End*/
1108   --Added by Xiao Lv for Bug#8513550, related 11i bug#8439276, begin
1109   cursor c_prepay_apply_amt(cp_invoice_id number) is
1110   select abs(amount) amount, invoice_distribution_id, prepay_distribution_id
1111   from ap_invoice_distributions_all
1112   where invoice_id = cp_invoice_id
1113   and line_type_lookup_code = 'PREPAY';
1114 
1115   cursor c_get_thhold_grp(cp_invoice_id number, cp_invoice_dist_id number) is
1116   select threshold_grp_id
1117   from jai_ap_tds_inv_taxes
1118   where invoice_distribution_id = cp_invoice_dist_id;
1119 
1120   r_prepay_apply_amt c_prepay_apply_amt%rowtype;
1121   lv_thhold_grp_id number;
1122   --Added by Xiao Lv for Bug#8513550, related 11i bug#8439276, end
1123   r_jai_apply_amount   c_jai_apply_amount%rowtype;
1124   r_pp_single_apply_amount c_pp_single_apply_amount%rowtype;
1125   l_api_name                   CONSTANT  VARCHAR2(50) := 'get_prepay_appln_amt()';
1126 
1127 BEGIN
1128     BEGIN
1129 	  jai_cmn_utils_pkg.WRITE_FND_LOG(G_LEVEL_PROCEDURE, G_MODULE_NAME||l_api_name||'.BEGIN', G_PKG_NAME || ': '||l_api_name||'()+');
1130 
1131 	  pn_apply_amt := 0;
1132 	   --Added by Xiao Lv for Bug#8513550, related 11i bug#8439276, begin
1133 	  if   pn_curr_inv_flag = 'Y' then
1134 	    for r_prepay_apply_amt in c_prepay_apply_amt(pn_invoice_id) loop
1135 		open c_get_thhold_grp(pn_invoice_id, r_prepay_apply_amt.prepay_distribution_id);
1136 		fetch c_get_thhold_grp into lv_thhold_grp_id;
1137 		close c_get_thhold_grp;
1138 
1139 		if lv_thhold_grp_id = pn_threshold_grp_id then
1140 		pn_apply_amt := pn_apply_amt + r_prepay_apply_amt.amount;
1141 		end if;
1142 		end loop;
1143 	  else
1144 	  --Added by Xiao Lv for Bug#8513550, related 11i bug#8439276, end
1145 		for r_jai_apply_amount in c_jai_apply_amount(pn_invoice_id) loop
1146 		if r_jai_apply_amount.threshold_grp_id = pn_threshold_grp_id then
1147 		pn_apply_amt := pn_apply_amt + nvl(r_jai_apply_amount.application_amount,0);
1148 		end if;
1149 		end loop;
1150 
1151         /*Bug 12671504 - Start*/
1152         OPEN c_pp_single_apply_amount(pn_invoice_id);
1153         FETCH c_pp_single_apply_amount INTO r_pp_single_apply_amount;
1154         CLOSE c_pp_single_apply_amount;
1155         pn_apply_amt := pn_apply_amt + nvl(r_pp_single_apply_amount.amount, 0);
1156 		/*Bug 12671504 - End*/
1157 	  end if;   --Added by Xiao Lv for Bug#8513550
1158 
1159 	  EXCEPTION
1160 	WHEN NO_DATA_FOUND THEN
1161 		pn_apply_amt:=0;
1162 	END;
1163     jai_cmn_utils_pkg.WRITE_FND_LOG(G_LEVEL_PROCEDURE, G_MODULE_NAME||l_api_name||'.END', G_PKG_NAME || ': '||l_api_name||'()-');
1164 END get_prepay_appln_amt;
1165 --Added by Xiao Lv for bug#8345080 on 13-Jan-10, end
1166 
1167  /*Added for Bug 8641199 - Start*/
1168  procedure get_org_id(p_invoice_id IN NUMBER, p_org_id OUT NOCOPY NUMBER)
1169  is
1170  --PRAGMA AUTONOMOUS_TRANSACTION;  --commented by Cholei for ZX integration bug#14040855
1171  BEGIN
1172  select org_id into p_org_id
1173  from ap_invoices_all
1174  where invoice_id = p_invoice_id;
1175  EXCEPTION
1176  WHEN NO_DATA_FOUND THEN
1177  p_org_id := NULL;
1178  END;
1179  /*Added for Bug 8641199 - End*/
1180 
1181   /*Modified for Bug 8641199 - Start*/
1182   procedure status_update_chk_validate
1183   (
1184     p_invoice_id                         in                  number,
1185     p_invoice_line_number                in                  number    default   null, /* AP lines uptake */
1186     p_invoice_distribution_id            in                  number    default   null,
1187     p_match_status_flag                  in                  varchar2  default   null,
1188     p_is_invoice_validated               out       nocopy    varchar2,
1189     p_process_flag                       out       nocopy    varchar2,
1190     p_process_message                    out       nocopy    varchar2,
1191     p_codepath                           in out    nocopy    varchar2
1192    )
1193    is
1194 
1195    lv_section_type VARCHAR2(15) ;
1196 
1197 
1198     cursor c_check_not_validate(p_invoice_id number, p_section_type VARCHAR2 ) is
1199       select count(tds_inv_tax_id) total_count, sum(decode(match_status_flag, 'A', 1, 0)) validated_a_count,
1200  	         sum(decode(match_status_flag, 'T', 1, 0)) validated_t_count
1201       from   jai_ap_tds_inv_taxes
1202       where  invoice_id = p_invoice_id
1203       -- Harshita for Bug 4870243
1204       and    nvl(invoice_line_number, -9999) = nvl(p_invoice_line_number, invoice_line_number)
1205       and    invoice_distribution_id =  nvl(p_invoice_distribution_id, invoice_distribution_id)  -- Bug 6119216
1206       and    section_type = p_section_type ;
1207 
1208     cursor c_fetch_po_encum(p_org_id number) is
1209     select nvl(purch_encumbrance_flag, 'N')
1210     from FINANCIALS_SYSTEM_PARAMS_ALL
1211     where org_id = p_org_id;
1212 
1213 
1214       /*select  tds_inv_tax_id
1215             from    jai_ap_tds_inv_taxes
1216             where   invoice_id =  p_invoice_id
1217             and     nvl(invoice_line_number, -9999) = nvl(p_invoice_line_number, -9999)
1218             and     nvl(invoice_distribution_id, -9999) =  nvl(p_invoice_distribution_id, -9999)
1219       and     section_type = p_section_type; */
1220 
1221 
1222 
1223     cursor c_ap_holds_all(p_invoice_id number) is
1224       select count(invoice_id)
1225       from   ap_holds_all
1226       where  invoice_id = p_invoice_id
1227       and    release_reason is null;
1228 
1229 
1230     ln_total_count      number;
1231     ln_validated_a_cnt  number;
1232     ln_validated_t_cnt  number;
1233     ln_no_of_holds      number;
1234     lp_org_id           number;
1235     l_po_encum_flag     VARCHAR2(1);
1236     l_api_name                   CONSTANT  VARCHAR2(50) := 'status_update_chk_validate()';
1237 
1238   begin
1239     jai_cmn_utils_pkg.WRITE_FND_LOG(G_LEVEL_PROCEDURE, G_MODULE_NAME||l_api_name||'.BEGIN', G_PKG_NAME || ': '||l_api_name||'()+');
1240     p_codepath := jai_general_pkg.plot_codepath(1, p_codepath, 'jai_ap_tds_generation_pkg.status_update_chk_validate', 'START'); /* 1 */
1241 
1242     get_org_id(p_invoice_id, lp_org_id);
1243     l_po_encum_flag := 'N';
1244     if lp_org_id is NOT NULL THEN
1245        open c_fetch_po_encum(lp_org_id);
1246        fetch c_fetch_po_encum into l_po_encum_flag;
1247        close c_fetch_po_encum;
1248     end if;
1249 
1250     if p_invoice_distribution_id is not null and p_match_status_flag is not null then
1251       update jai_ap_tds_inv_taxes
1252       set    match_status_flag = p_match_status_flag
1253       where  invoice_id = p_invoice_id
1254       and    invoice_distribution_id = p_invoice_distribution_id;
1255     end if;
1256 
1257     ln_total_count := 0;
1258     ln_validated_a_cnt := 0;
1259     ln_validated_t_cnt := 0;
1260 
1261     lv_section_type := 'TDS_SECTION' ;  -- Harshita for Bug 4870243
1262 
1263     open c_check_not_validate(p_invoice_id, lv_section_type); -- Harshita, added lv_section_type for Bug 4870243
1264     fetch c_check_not_validate into ln_total_count, ln_validated_a_cnt, ln_validated_t_cnt;
1265     close c_check_not_validate;
1266 
1267     fnd_file.put_line(FND_FILE.LOG, ' Value of total cnt '|| ln_total_count);
1268 
1269     fnd_file.put_line(FND_FILE.LOG, ' Value of validated A cnt '|| ln_validated_a_cnt);
1270     fnd_file.put_line(FND_FILE.LOG, ' Value of validated T cnt '|| ln_validated_t_cnt);
1271 
1272     p_codepath := jai_general_pkg.plot_codepath(2, p_codepath); /* 2 */
1273 
1274     if ln_total_count = (ln_validated_a_cnt + ln_validated_t_cnt) then
1275       p_codepath := jai_general_pkg.plot_codepath(3, p_codepath); /* 3 */
1276 
1277       p_is_invoice_validated := 'Y';
1278     else
1279       p_is_invoice_validated := 'N';
1280       p_codepath := jai_general_pkg.plot_codepath(4, p_codepath); /* 4 */
1281     end if;
1282 
1283     if l_po_encum_flag = 'Y' and ln_validated_t_cnt > 0 then
1284        p_is_invoice_validated := 'N';
1285        p_codepath := jai_general_pkg.plot_codepath(5, p_codepath); /* 5 */
1286     end if;
1287 
1288     if p_match_status_flag is not null then
1289       /* Scenarios other than holds release */
1290       open  c_ap_holds_all(p_invoice_id);
1291       fetch c_ap_holds_all into ln_no_of_holds;
1292       close c_ap_holds_all;
1293 
1294       if nvl(ln_no_of_holds, 0) > 0 then
1295         p_is_invoice_validated := 'N';
1296         p_codepath := jai_general_pkg.plot_codepath(6, p_codepath); /* 6 */
1297       end if;
1298 
1299     end if;
1300 
1301     fnd_file.put_line(FND_FILE.LOG,  'Status_update_chk_validate - Status of  parent invoice '|| p_is_invoice_validated);
1302     jai_cmn_utils_pkg.WRITE_FND_LOG(G_LEVEL_PROCEDURE, G_MODULE_NAME||l_api_name, 'Status_update_chk_validate - Status of  parent invoice '|| p_is_invoice_validated);
1303 
1304     << exit_from_procedure >>
1305     p_codepath := jai_general_pkg.plot_codepath(7, p_codepath, null, 'END'); /* 7 */
1306     jai_cmn_utils_pkg.WRITE_FND_LOG(G_LEVEL_PROCEDURE, G_MODULE_NAME||l_api_name||'.END', G_PKG_NAME || ': '||l_api_name||'()-');
1307     return;
1308 
1309    exception
1310       when others then
1311         p_process_flag := 'E';
1312         P_process_message := 'jai_ap_tds_generation_pkg.status_update_chk_validate :' ||  sqlerrm;
1313         return;
1314   end status_update_chk_validate;
1315 
1316   /*Modified for Bug 8641199 - End*/
1317 
1318   /* ************************************* process_invoice ************************************ */
1319 
1320 
1321 
1322 
1323 
1324   --Added by Zhiwei.Hou for Bug#13359892 DTC enhancement on 20111124 begin
1325   --------------------------------------------------------------------------------------------
1326   /* Get Taxable basis rounding setup */
1327   FUNCTION get_taxable_rounding(pn_invoice_id in number) RETURN NUMBER
1328   IS
1329 
1330     /* Commented out by Chong for bug#15939571 Start
1331     CURSOR get_rounding_cur(pn_invoice_id number)
1332     IS
1333     select
1334            --Update by Zhiwei Hou on 20120106 begin
1335            -----------------------------------------
1336            --taxable_basis
1337            decode(taxable_basis,
1338                   0,0,
1339                   1,0,
1340                   10,-1,
1341                   100,-2,
1342                   1000,-3,0) taxable_basis
1343            ------------------------------------------
1344            --Update by Zhiwei Hou on 20120106 end
1345     from   JAI_DTC_ROUNDING_SETUPS
1346     where legal_entity_id in(
1347                     select
1348                            default_legal_context_id
1349                     from   hr_operating_units
1350                     where  organization_id in(
1351                         select
1352                                org_id
1353                         from   ap_invoices_all
1354                         where  invoice_id = pn_invoice_id
1355                     )
1356     );
1357     ln_rounding_factor number;
1358   BEGIN
1359     FOR rec_rounding IN  get_rounding_cur(pn_invoice_id)
1360     LOOP
1361         ln_rounding_factor := rec_rounding.taxable_basis;
1362     END LOOP;
1363 
1364     return nvl(ln_rounding_factor,0);
1365     Commented by Chong for bug#15939571 End */
1366     --Added by Chong for bug#15939571  20121210 Start
1367     ---------------------------------------------------------------
1368     CURSOR get_rounding_cur(pn_invoice_id number)
1369     IS
1370     select decode(ROUNDING_RULE,
1371                   0,0,
1372                   1,0,
1373                   10,-1,
1374                   100,-2,
1375                   1000,-3,NULL) taxable_basis
1376     from   JAI_DTC_ROUNDING_SETUPS
1377     where legal_entity_id in(
1378                     select
1379                            default_legal_context_id
1380                     from   hr_operating_units
1381                     where  organization_id in(
1382                         select org_id
1383                         from   ap_invoices_all
1384                         where  invoice_id = pn_invoice_id
1385                     )
1386            )
1387     and    ROUNDING_BASIS in(
1388               select lookup_code
1389               from   ja_lookups
1390               where  lookup_type='JAI_ROUNDING_BASIS'
1391               and    meaning = 'Tax Basis'
1392            )
1393     and not exists(
1394         select 1
1395         from ap_invoice_distributions_all aida
1396         where aida.invoice_id = pn_invoice_id
1397         and   (JAI_DTC_ROUNDING_SETUPS.from_date > aida.accounting_date
1398                or NVL(JAI_DTC_ROUNDING_SETUPS.to_date, TO_DATE('01019999','DDMMYYYY')) < aida.accounting_date
1399         )
1400     );
1401     ln_rounding_factor number;
1402   BEGIN
1403     OPEN get_rounding_cur(pn_invoice_id);
1404     FETCH get_rounding_cur into ln_rounding_factor;
1405     CLOSE get_rounding_cur;
1406 
1407     return ln_rounding_factor;
1408     ---------------------------------------------------------------
1409     --Added by Chong for bug#15939571  20121210 End
1410   END get_taxable_rounding;
1411 
1412 
1413   --Add by Zhiwei Hou on 20120106 begin
1414   -----------------------------------------------------------------
1415   FUNCTION get_tax_rounding(pn_invoice_id in number) RETURN NUMBER
1416   IS
1417 
1418     /* Commented out by Chong for bug#15939571 Start
1419     CURSOR get_rounding_cur(pn_invoice_id number)
1420     IS
1421     select
1422            decode(tax_basis,
1423                   0,0,
1424                   1,0,
1425                   10,-1,
1426                   100,-2,
1427                   1000,-3,0) tax_basis
1428 
1429     from   JAI_DTC_ROUNDING_SETUPS
1430     where legal_entity_id in(
1431                     select
1432                            default_legal_context_id
1433                     from   hr_operating_units
1434                     where  organization_id in(
1435                         select
1436                                org_id
1437                         from   ap_invoices_all
1438                         where  invoice_id = pn_invoice_id
1439                     )
1440     );
1441 
1442     ln_rounding_factor number;
1443   BEGIN
1444     FOR rec_rounding IN  get_rounding_cur(pn_invoice_id)
1445     LOOP
1446         ln_rounding_factor := rec_rounding.tax_basis;
1447     END LOOP;
1448 
1449     return nvl(ln_rounding_factor,0);
1450     Commented by Chong for bug#15939571 End */
1451     --Added by Chong for bug#15939571  20121210 Start
1452     ---------------------------------------------------------------
1453     CURSOR get_rounding_cur(pn_invoice_id number)
1454     IS
1455     select decode(ROUNDING_RULE,
1456                   0,0,
1457                   1,0,
1458                   10,-1,
1459                   100,-2,
1460                   1000,-3,0) tax_basis
1461     from   JAI_DTC_ROUNDING_SETUPS
1462     where legal_entity_id in(
1463                     select
1464                            default_legal_context_id
1465                     from   hr_operating_units
1466                     where  organization_id in(
1467                         select org_id
1468                         from   ap_invoices_all
1469                         where  invoice_id = pn_invoice_id
1470                     )
1471            )
1472     and    ROUNDING_BASIS in(
1473               select lookup_code
1474               from   ja_lookups
1475               where  lookup_type='JAI_ROUNDING_BASIS'
1476               and    meaning = 'Tax'
1477            )
1478     and not exists(
1479         select 1
1480         from ap_invoice_distributions_all aida
1481         where aida.invoice_id = pn_invoice_id
1482         and   (JAI_DTC_ROUNDING_SETUPS.from_date > aida.accounting_date
1483                or NVL(JAI_DTC_ROUNDING_SETUPS.to_date, TO_DATE('01019999','DDMMYYYY')) < aida.accounting_date
1484         )
1485     );
1486     ln_rounding_factor number;
1487   BEGIN
1488     OPEN get_rounding_cur(pn_invoice_id);
1489     FETCH get_rounding_cur into ln_rounding_factor;
1490     CLOSE get_rounding_cur;
1491 
1492     return ln_rounding_factor;
1493     ---------------------------------------------------------------
1494     --Added by Chong for bug#15939571  20121210 End
1495   END get_tax_rounding;
1496   -----------------------------------------------------------------
1497   --Add by Zhiwei Hou on 20120106 begin
1498 
1499   /*FUNCTION get_natural_account(cn_ccid number)RETURN number
1500   is
1501   cursor get_natural_acc
1502   is
1503   select segment3
1504   from gl_code_combinations
1505   where code_combination_id = cn_ccid;
1506 
1507   ln_natural_ccid number;
1508   begin
1509         open get_natural_acc;
1510         fetch get_natural_acc into ln_natural_ccid;
1511         close get_natural_acc;
1512 
1513         return ln_natural_ccid;
1514 
1515   end get_natural_account;*/
1516 
1517   -------------------------------------
1518   procedure p_get_one_ccid_id (
1519        cp_inv_id IN         number,
1520        cp_ccid   OUT NOCOPY number
1521   )
1522   is
1523     --PRAGMA AUTONOMOUS_TRANSACTION;  --commented by Cholei for ZX integration bug#14040855
1524   begin
1525     begin
1526       select dist_code_combination_id  into cp_ccid
1527       from  ap_invoice_distributions_all
1528       where invoice_id = cp_inv_id
1529       and distribution_line_number = 1
1530        AND    ROWNUM = 1;
1531     EXCEPTION
1532       WHEN NO_DATA_FOUND THEN
1533         cp_ccid := null;
1534     end;
1535   end p_get_one_ccid_id;
1536 
1537 
1538       --Add by Zhiwei Hou on 20120109 begin
1539       ----------------------------------------------------------
1540       PROCEDURE get_threshold_hdr(
1541           cn_vendor_id       in  number,
1542           cn_vendor_site_id  in  number,
1543           cv_section_type    in  varchar2,
1544           cv_section_code    in  varchar2,
1545           p_accounting_date  in  DATE,   -- Added by Chong for bug#16580553 20130402
1546           xn_hdr_id          in out NOCOPY number
1547       )
1548       is
1549 
1550       ln_threshold_hdr_id number := 0;
1551 
1552       cursor c_get_threshold_xcep(
1553              p_vendor_id number,
1554              p_vendor_site_id number,
1555              p_tds_section_code varchar2,
1556              p_section_type jai_ap_tds_inv_taxes.section_type%type
1557       )
1558       IS
1559       select threshold_hdr_id
1560       from   JAI_AP_TDS_TH_VSITE_V
1561       where  vendor_id = p_vendor_id
1562       and    vendor_site_id = p_vendor_site_id
1563       and    section_type = p_section_type    --rchandan for bug#4428980
1564       and    section_code = p_tds_section_code
1565       and    nvl(exception_setup_flag,'N') = 'Y';
1566 
1567 /*      --commented by Chong for bug#16580553 20130402 Begin
1568       -------------------------------------------------------------
1569       --
1570       cursor c_get_threshold_normal(
1571              p_vendor_id number,
1572              p_vendor_site_id number,
1573              p_tds_section_code varchar2,
1574              p_section_type jai_ap_tds_inv_taxes.section_type%type
1575       )
1576       IS
1577       select threshold_hdr_id
1578       from   JAI_AP_TDS_TH_VSITE_V
1579       where  vendor_id = p_vendor_id
1580       and    vendor_site_id = p_vendor_site_id
1581       and    section_type = p_section_type
1582       and    section_code = p_tds_section_code
1583       and    nvl(exception_setup_flag,'N') = 'N';
1584       -------------------------------------------------------------
1585       --commented by Chong for bug#16580553 20130402 End*/
1586 
1587       --added by Chong for bug#16580553 20130402 Begin
1588       -------------------------------------------------------------
1589       -- cursor to validate accounting date for every threshold type
1590       -- cursor to validate accounting date for every threshold type
1591       cursor c_get_threshold_normal (cp_vendor_tlc JAI_AP_TDS_VENDOR_HDRS.TDS_VENDOR_TYPE_LOOKUP_CODE%TYPE,
1592                                      cp_sec_code varchar2)
1593       is
1594       SELECT threshold_hdr_id
1595       FROM   JAI_AP_TDS_TH_VSITE_V JATVV
1596       WHERE  tds_vendor_type_lookup_code = cp_vendor_tlc
1597       AND    section_code = cp_sec_code
1598       AND    section_type = 'TDS_SECTION'
1599       AND    nvl(exception_setup_flag,'N') = 'N'
1600       AND    rownum = 1;
1601 
1602       cursor c_valid_accounting_date (cp_thr_hdr_id number, cp_accounting_date date)
1603       is
1604       SELECT 'Y'
1605       FROM   jai_ap_tds_thhold_types
1606       WHERE  threshold_hdr_id = cp_thr_hdr_id
1607       AND    cp_accounting_date between nvl(from_date, cp_accounting_date) and nvl(to_date, cp_accounting_date);
1608 
1609       cursor c_po_vendors(p_vendor_id number) is
1610       select tds_vendor_type_lookup_code
1611       from   JAI_AP_TDS_VNDR_TYPE_V
1612       where  vendor_id = p_vendor_id;
1613       lv_vendor_type_lookup_code   JAI_AP_TDS_VENDOR_HDRS.TDS_VENDOR_TYPE_LOOKUP_CODE%TYPE;
1614       lv_valid_flg                 VARCHAR2(1);
1615       l_api_name                   CONSTANT  VARCHAR2(50) := 'get_threshold_hdr()';
1616       -------------------------------------------------------------
1617       --added by Chong for bug#16580553 20130402 End
1618       begin
1619            --Exception Setup will take high precedence than Normal Setup.
1620         open c_get_threshold_xcep(cn_vendor_id ,cn_vendor_site_id, cv_section_code,'TDS_SECTION');
1621         fetch c_get_threshold_xcep into ln_threshold_hdr_id;
1622         close c_get_threshold_xcep;
1623 
1624         --added by Chong for bug#16580553 20130402 Begin
1625         -------------------------------------------------------------
1626         /* Verify if Accounting Date is between the Start and End Date */
1627         if ln_threshold_hdr_id is not NULL then
1628           lv_valid_flg := null;
1629           open c_valid_accounting_date (ln_threshold_hdr_id, p_accounting_date);
1630           fetch c_valid_accounting_date into lv_valid_flg;
1631           close c_valid_accounting_date;
1632 
1633           if nvl(lv_valid_flg, 'N') = 'N' then
1634              ln_threshold_hdr_id := null;   --If no effective threshold type, use normal threshold setup
1635           end if;
1636         end if;
1637         jai_cmn_utils_pkg.WRITE_FND_LOG(G_LEVEL_STATEMENT, G_MODULE_NAME||l_api_name, 'Exception threshold heaer id: ' || ln_threshold_hdr_id);
1638         -------------------------------------------------------------
1639         --added by Chong for bug#16580553 20130402 End
1640 
1641         if nvl(ln_threshold_hdr_id,0) = 0 then
1642 
1643             --Added commented  by Chong for bug#16580553 20130402 Begin
1644             -------------------------------------------------------------
1645             --by given vendor and vendor site, if already existing exception transactions, will not show normal records in JAI_AP_TDS_TH_VSITE_V.
1646             --So we can't get noraml threshold setup by vendor and vendor site. we should derive normal threshold setup by vendor type
1647             open  c_po_vendors(cn_vendor_id);   --Added by Chong for bug#16580553 20130402
1648             fetch c_po_vendors into lv_vendor_type_lookup_code;
1649             close c_po_vendors;
1650 
1651             open  c_get_threshold_normal(lv_vendor_type_lookup_code, cv_section_code);
1652             -------------------------------------------------------------
1653             --Added commented  by Chong for bug#16580553 20130402 End
1654             --open  c_get_threshold_normal(cn_vendor_id ,cn_vendor_site_id, cv_section_code,'TDS_SECTION');  ----commented  by Chong for bug#16580553 20130402
1655             fetch c_get_threshold_normal into ln_threshold_hdr_id;
1656             close c_get_threshold_normal;
1657 
1658 
1659         end if;
1660 
1661         jai_cmn_utils_pkg.WRITE_FND_LOG(G_LEVEL_STATEMENT, G_MODULE_NAME||l_api_name, 'threshold heaer id: ' || ln_threshold_hdr_id);
1662 
1663         xn_hdr_id := ln_threshold_hdr_id;
1664 
1665         --return
1666 
1667       end get_threshold_hdr;
1668       -----------------------------------------------------------
1669       --Add by Zhiwei Hou on 20120109 end
1670 
1671 
1672 
1673 /* ********************************  maintain_thhold_grps *******************************************  */
1674 
1675   procedure maintain_thhold_grps
1676   (
1677     p_threshold_grp_id                  in out    nocopy    number    ,
1678     p_vendor_id                         in                  number    default null,
1679     p_org_tan_num                       in                  varchar2  default null,
1680     p_vendor_pan_num                    in                  varchar2  default null,
1681     p_section_type                      in                  varchar2  default null,
1682     p_section_code                      in                  varchar2  default null,
1683     p_fin_year                          in                  number    default null,
1684     p_org_id                            in                  number    default null,
1685     p_trx_invoice_amount                in                  number    default null,
1686     p_trx_invoice_cancel_amount         in                  number    default null,
1687     p_trx_invoice_apply_amount          in                  number    default null,
1688     p_trx_invoice_unapply_amount        in                  number    default null,
1689     p_trx_tax_paid                      in                  number    default null,
1690     p_trx_thhold_change_tax_paid        in                  number    default null,
1691     p_trx_threshold_slab_id             in                  number    default null,
1692     p_tds_event                         in                  varchar2,
1693     p_invoice_id                        in                  number    default null,
1694     p_invoice_line_number               in                  number    default null, /* AP lines Uptake */
1695     p_invoice_distribution_id           in                  number    default null,
1696     p_remarks                           in                  varchar2  default null,
1697     --Added by zhiwei for Bug#13359892 DTC enhancement on 20111130 begin
1698     -----------------------------------------------------------------------------------
1699     p_threshold_hdr_id                  in                  number    default null,
1700     -----------------------------------------------------------------------------------
1701     --Added by zhiwei for Bug#13359892 DTC enhancement on 20111130 end
1702     -- bug 5722028. Added by csahoo
1703     p_creation_date                     in                  date      default sysdate,
1704     p_threshold_grp_audit_id            out       nocopy    number,
1705     p_process_flag                      out       nocopy    varchar2,
1706     P_process_message                   out       nocopy    varchar2,
1707     p_codepath                          in out    nocopy    varchar2
1708   )
1709   is
1710 
1711 
1712     cursor c_jai_ap_tds_thhold_grps(p_threshold_grp_id  number) is
1713       select total_invoice_amount          ,
1714              total_invoice_cancel_amount   ,
1715              total_invoice_apply_amount    ,
1716              total_invoice_unapply_amount  ,
1717              total_tax_paid                ,
1718              total_thhold_change_tax_paid  ,
1719              current_threshold_slab_id     ,
1720              total_calc_tax_paid           -- Bug 5751783
1721       from   jai_ap_tds_thhold_grps
1722       where  threshold_grp_id = p_threshold_grp_id;
1723 
1724     cursor c_get_threshold_grp_id
1725     ( p_vendor_id number, p_org_tan_num varchar2, p_vendor_pan_num varchar2,
1726       p_section_type varchar2, p_section_code varchar2, p_fin_year number) is
1727       select threshold_grp_id
1728       from   jai_ap_tds_thhold_grps
1729       where  vendor_id        =      p_vendor_id        and
1730              org_tan_num      =      p_org_tan_num      and
1731              vendor_pan_num   =      p_vendor_pan_num   and
1732              section_type     =      p_section_type     and
1733              section_code     =      p_section_code     and
1734              fin_year         =      p_fin_year;
1735     --Added by Zhiwei Hou for Bug#13359892 on 20111224 begin
1736     ----------------------------------------------------------------
1737     cursor c_get_thhod_grp_id_new
1738     ( p_vendor_id number, p_org_tan_num varchar2, p_vendor_pan_num varchar2,
1739       p_section_type varchar2, p_section_code varchar2, p_fin_year number,
1740       p_threshold_hdr_id number) is
1741       select threshold_grp_id
1742       from   jai_ap_tds_thhold_grps
1743       where  vendor_id        =      p_vendor_id        and
1744              org_tan_num      =      p_org_tan_num      and
1745              vendor_pan_num   =      p_vendor_pan_num   and
1746              section_type     =      p_section_type     and
1747              section_code     =      p_section_code     and
1748              fin_year         =      p_fin_year         and
1749              (
1750                               p_threshold_hdr_id is null
1751                               or
1752                               (
1753                                      p_threshold_hdr_id is not null
1754                                  and threshold_hdr_id = p_threshold_hdr_id
1755                               )
1756              );
1757     --------------------------------------------------------------------
1758     --Added by Zhiwei Hou for Bug#13359892 on 20111224 end
1759     r_jai_ap_tds_thhold_grps              c_jai_ap_tds_thhold_grps%rowtype;
1760 
1761     ln_threshold_grp_id                   jai_ap_tds_thgrp_audits.threshold_grp_id%type;
1762     ln_old_invoice_amount                 jai_ap_tds_thgrp_audits.old_invoice_amount%type;
1763     ln_old_invoice_cancel_amount          jai_ap_tds_thgrp_audits.old_invoice_cancel_amount%type;
1764     ln_old_invoice_apply_amount           jai_ap_tds_thgrp_audits.old_invoice_apply_amount%type;
1765     ln_old_invoice_unapply_amount         jai_ap_tds_thgrp_audits.old_invoice_unapply_amount%type;
1766     ln_old_tax_paid                       jai_ap_tds_thgrp_audits.old_tax_paid%type;
1767     ln_old_thhold_change_tax_paid         jai_ap_tds_thgrp_audits.old_thhold_change_tax_paid%type;
1768     ln_old_threshold_slab_id              jai_ap_tds_thgrp_audits.old_threshold_slab_id%type;
1769 
1770     ln_new_invoice_amount                 jai_ap_tds_thgrp_audits.old_invoice_amount%type;
1771     ln_new_invoice_cancel_amount          jai_ap_tds_thgrp_audits.old_invoice_cancel_amount%type;
1772     ln_new_invoice_apply_amount           jai_ap_tds_thgrp_audits.old_invoice_apply_amount%type;
1773     ln_new_invoice_unapply_amount         jai_ap_tds_thgrp_audits.old_invoice_unapply_amount%type;
1774     ln_new_tax_paid                       jai_ap_tds_thgrp_audits.old_tax_paid%type;
1775     ln_new_thhold_change_tax_paid         jai_ap_tds_thgrp_audits.old_thhold_change_tax_paid%type;
1776     ln_new_threshold_slab_id              jai_ap_tds_thgrp_audits.old_threshold_slab_id%type;
1777     ln_effective_threshold_amount         number;
1778     ln_effective_tax_paid                 number;
1779 
1780     /*Bug 5751783. Added following variables.*/
1781     ln_calc_old_tax_paid       jai_ap_tds_thgrp_audits.calc_old_tax_paid%type;
1782     ln_calc_trx_tax_paid       jai_ap_tds_thgrp_audits.calc_trx_tax_paid%type;
1783     ln_calc_new_tax_paid     jai_ap_tds_thgrp_audits.calc_new_tax_paid%type;
1784 
1785     -- bug 5722028. Added by csahoo
1786     ln_tmp_tds_amt      number;
1787     ln_tmp_tds_change   number;
1788     l_api_name                   CONSTANT  VARCHAR2(50) := 'maintain_thhold_grps()';
1789 
1790   begin
1791 
1792     jai_cmn_utils_pkg.WRITE_FND_LOG(G_LEVEL_PROCEDURE, G_MODULE_NAME||l_api_name||'.BEGIN', G_PKG_NAME || ': '||l_api_name||'()+');
1793     p_codepath := jai_general_pkg.plot_codepath(1, p_codepath, 'jai_ap_dtc_generation_pkg.maintain_thhold_grps', 'START'); /* 1 */
1794 
1795 
1796     /* Validate the input */
1797     ln_threshold_grp_id := nvl(p_threshold_grp_id, 0);
1798 
1799 
1800     if ln_threshold_grp_id = 0 then
1801 
1802       p_codepath := jai_general_pkg.plot_codepath(2, p_codepath); /*2*/
1803 
1804       if p_vendor_id is null then
1805         p_process_flag    := 'E';
1806         P_process_message := 'Vendor must be specified as threshold group identifier is null(jai_ap_tds_generation_pkg.maintain_thhold_grps) ';
1807         goto exit_from_procedure;
1808       end if;
1809 
1810       if p_org_tan_num is null then
1811         p_process_flag    := 'E';
1812         P_process_message := 'Organization TAN number must be specified as threshold group identifier is null(jai_ap_tds_generation_pkg.maintain_thhold_grps) ';
1813         goto exit_from_procedure;
1814       end if;
1815 
1816       if p_vendor_pan_num is null then
1817         p_process_flag    := 'E';
1818         P_process_message := 'Vendor PAN number must be specified as threshold group identifier is null(jai_ap_tds_generation_pkg.maintain_thhold_grps) ';
1819         goto exit_from_procedure;
1820       end if;
1821 
1822       if p_section_type is null then
1823         p_process_flag    := 'E';
1824         P_process_message := 'Section Type must be specified as threshold group identifier is null(jai_ap_tds_generation_pkg.maintain_thhold_grps) ';
1825         goto exit_from_procedure;
1826       end if;
1827 
1828       if p_section_code is null then
1829         p_process_flag    := 'E';
1830         P_process_message := 'Section Code must be specified as threshold group identifier is null(jai_ap_tds_generation_pkg.maintain_thhold_grps) ';
1831         goto exit_from_procedure;
1832       end if;
1833 
1834       if p_fin_year is null then
1835         p_process_flag    := 'E';
1836         P_process_message := 'Fin Year must be specified as threshold group identifier is null(jai_ap_tds_generation_pkg.maintain_thhold_grps) ';
1837         goto exit_from_procedure;
1838       end if;
1839 
1840     end if; /* Validate the input */
1841 
1842     p_codepath := jai_general_pkg.plot_codepath(3, p_codepath); /*3*/
1843 
1844     if ln_threshold_grp_id = 0  then
1845 
1846       p_codepath := jai_general_pkg.plot_codepath(4, p_codepath); /* 4 */
1847       /* Threshold has not been given as an input, check if exists */
1848 
1849       /*open  c_get_threshold_grp_id
1850       (p_vendor_id, p_org_tan_num, p_vendor_pan_num, p_section_type, p_section_code, p_fin_year);
1851       fetch c_get_threshold_grp_id into ln_threshold_grp_id;
1852       close c_get_threshold_grp_id;*/--Commented by Zhiwei for Bug#13359892 on 20111224
1853       --Added by Zhiwei Hou for Bug#13359892 on 20111224 begin
1854       -------------------------------------------------------------------
1855       open  c_get_thhod_grp_id_new
1856       (p_vendor_id, p_org_tan_num, p_vendor_pan_num, p_section_type, p_section_code, p_fin_year,p_threshold_hdr_id);
1857       fetch c_get_thhod_grp_id_new into ln_threshold_grp_id;
1858       close c_get_thhod_grp_id_new;
1859       -------------------------------------------------------------------
1860       --Added by Zhiwei Hou for Bug#13359892 on 20111224 end
1861 
1862       if nvl(ln_threshold_grp_id, 0) = 0  then
1863 
1864           p_codepath := jai_general_pkg.plot_codepath(5, p_codepath); /* 5 */
1865 
1866           insert into jai_ap_tds_thhold_grps
1867           (
1868             threshold_grp_id                  ,
1869             threshold_hdr_id                  ,
1870             vendor_id                         ,
1871             org_tan_num                       ,
1872             vendor_pan_num                    ,
1873             section_type                      ,
1874             section_code                      ,
1875             fin_year                          ,
1876             created_by                        ,
1877             creation_date                     ,
1878             last_updated_by                   ,
1879             last_update_date                  ,
1880             last_update_login
1881           )
1882           values
1883           (
1884             jai_ap_tds_thhold_grps_s.nextval  ,
1885             p_threshold_hdr_id                ,
1886             p_vendor_id                       ,
1887             p_org_tan_num                     ,
1888             p_vendor_pan_num                  ,
1889             p_section_type                    ,
1890             p_section_code                    ,
1891             p_fin_year                        ,
1892             fnd_global.user_id                ,
1893             sysdate                           ,
1894             fnd_global.user_id                ,
1895             sysdate                           ,
1896             fnd_global.login_id
1897           )
1898           returning threshold_grp_id into ln_threshold_grp_id;
1899 
1900           p_threshold_grp_id := ln_threshold_grp_id;
1901 
1902       end if; /* ln_threshold_grp_id does not exist */
1903 
1904 			p_threshold_grp_id := ln_threshold_grp_id;--Added By Zhiwei Hou for DTC bug#13767951 on 20120305
1905 
1906       p_codepath := jai_general_pkg.plot_codepath(6, p_codepath); /* 6 */
1907 
1908     end if; /* ln_threshold_grp_id is not given as an input */
1909 
1910 
1911     /* Get the old value of teh threshold group  */
1912     p_codepath := jai_general_pkg.plot_codepath(7, p_codepath); /* 7 */
1913 
1914     open  c_jai_ap_tds_thhold_grps(ln_threshold_grp_id);
1915     fetch c_jai_ap_tds_thhold_grps into r_jai_ap_tds_thhold_grps;
1916     close c_jai_ap_tds_thhold_grps;
1917 
1918 
1919     ln_old_invoice_amount             :=   r_jai_ap_tds_thhold_grps.total_invoice_amount;
1920     ln_old_invoice_cancel_amount      :=   r_jai_ap_tds_thhold_grps.total_invoice_cancel_amount;
1921     ln_old_invoice_apply_amount       :=   r_jai_ap_tds_thhold_grps.total_invoice_apply_amount;
1922     ln_old_invoice_unapply_amount     :=   r_jai_ap_tds_thhold_grps.total_invoice_unapply_amount;
1923     ln_old_tax_paid                   :=   r_jai_ap_tds_thhold_grps.total_tax_paid;
1924     ln_old_thhold_change_tax_paid     :=   r_jai_ap_tds_thhold_grps.total_thhold_change_tax_paid;
1925     ln_old_threshold_slab_id          :=   r_jai_ap_tds_thhold_grps.current_threshold_slab_id;
1926 
1927     /*Bug 5751783*/
1928     ln_calc_old_tax_paid              := r_jai_ap_tds_thhold_grps.total_calc_tax_paid;
1929 
1930     /* Check that threshold should not become negative */
1931     ln_effective_threshold_amount :=
1932     ( nvl(ln_old_invoice_amount, 0)         + nvl(p_trx_invoice_amount, 0) ) -
1933     ( nvl(ln_old_invoice_cancel_amount, 0)  + nvl(p_trx_invoice_cancel_amount, 0) ) -
1934     ( nvl(ln_old_invoice_apply_amount, 0)   + nvl(p_trx_invoice_apply_amount, 0) ) +
1935     (nvl(ln_old_invoice_unapply_amount, 0) + nvl(p_trx_invoice_unapply_amount, 0) );
1936 
1937 
1938     if ln_effective_threshold_amount < 0 then
1939       p_process_flag := 'E';
1940       p_process_message := 'Effective Total invoice amount for threshold cannot be negative.(Total Invoice - Cancel - apply + Unapply )' ;
1941       goto exit_from_procedure;
1942     end if;
1943 
1944 
1945     /* Check that total tax paid should not become negative */
1946     ln_effective_tax_paid := nvl(ln_old_tax_paid, 0) + nvl(p_trx_tax_paid, 0);
1947 
1948     if ln_effective_tax_paid < 0 then
1949       p_process_flag := 'E';
1950       p_process_message := 'Effective Tax Paid amount cannot be negative.' ;
1951       goto exit_from_procedure;
1952     end if;
1953 
1954 
1955   -- Bug 5722028. Added by Lakshmi Gopalsami
1956   ln_tmp_tds_amt := ROUND(nvl(p_trx_tax_paid,0),g_inr_currency_rounding);
1957   ln_tmp_tds_change := ROUND(nvl(p_trx_thhold_change_tax_paid,0), g_inr_currency_rounding);
1958 
1959   IF p_tds_event NOT IN
1960     -- Bug 7280925. Commented by Lakshmi Gopalsami ('INVOICE CANCEL',
1961     ('PREPAYMENT UNAPPLICATION') THEN
1962   IF trunc(p_creation_date) >=
1963    trunc(jai_ap_dtc_generation_pkg.gd_tds_rounding_effective_date) THEN
1964    ln_tmp_tds_amt := get_rnded_value(ln_tmp_tds_amt);
1965   END IF;
1966   END IF;
1967 
1968     -- End if ;
1969 
1970     p_codepath := jai_general_pkg.plot_codepath(8, p_codepath); /* 8 */
1971     update  jai_ap_tds_thhold_grps
1972     set
1973       total_invoice_amount          =    nvl(total_invoice_amount, 0)         + nvl(p_trx_invoice_amount, 0),
1974       total_invoice_cancel_amount   =    nvl(total_invoice_cancel_amount, 0)  + nvl(p_trx_invoice_cancel_amount, 0),
1975       total_invoice_apply_amount    =    nvl(total_invoice_apply_amount, 0)   + nvl(p_trx_invoice_apply_amount, 0),
1976       total_invoice_unapply_amount  =    nvl(total_invoice_unapply_amount, 0) + nvl(p_trx_invoice_unapply_amount, 0),
1977       total_tax_paid                =    nvl(total_tax_paid, 0)               + nvl(p_trx_tax_paid, 0),
1978       total_thhold_change_tax_paid  =    nvl(total_thhold_change_tax_paid, 0) + nvl(p_trx_thhold_change_tax_paid, 0),
1979       --current_threshold_slab_id     =    nvl( p_trx_threshold_slab_id, current_threshold_slab_id)
1980       --commented the above and added the below by Ramananda for Bug#4562793
1981       current_threshold_slab_id     =    nvl( p_trx_threshold_slab_id, 0),
1982       /*Bug 5751783. Updated non-rounded value*/
1983       total_calc_tax_paid           =    nvl(total_calc_tax_paid,0)           + nvl(p_trx_tax_paid,0)
1984 
1985     where threshold_grp_id = ln_threshold_grp_id;
1986 
1987     /* Get the new value */
1988     r_jai_ap_tds_thhold_grps := null;
1989     open  c_jai_ap_tds_thhold_grps(ln_threshold_grp_id);
1990     fetch c_jai_ap_tds_thhold_grps into r_jai_ap_tds_thhold_grps;
1991     close c_jai_ap_tds_thhold_grps;
1992 
1993     ln_new_invoice_amount               :=   r_jai_ap_tds_thhold_grps.total_invoice_amount;
1994     ln_new_invoice_cancel_amount        :=   r_jai_ap_tds_thhold_grps.total_invoice_cancel_amount;
1995     ln_new_invoice_apply_amount         :=   r_jai_ap_tds_thhold_grps.total_invoice_apply_amount;
1996     ln_new_invoice_unapply_amount       :=   r_jai_ap_tds_thhold_grps.total_invoice_unapply_amount;
1997     ln_new_tax_paid                     :=   r_jai_ap_tds_thhold_grps.total_tax_paid;
1998     ln_new_thhold_change_tax_paid       :=   r_jai_ap_tds_thhold_grps.total_thhold_change_tax_paid;
1999     ln_new_threshold_slab_id            :=   r_jai_ap_tds_thhold_grps.current_threshold_slab_id;
2000 
2001     /*Bug 5751783*/
2002     ln_calc_new_tax_paid                :=   r_jai_ap_tds_thhold_grps.total_calc_tax_paid;
2003 
2004     /* Insert into the audite table */
2005     p_codepath := jai_general_pkg.plot_codepath(9, p_codepath); /* 9 */
2006     insert into jai_ap_tds_thgrp_audits
2007     (
2008       threshold_grp_audit_id               ,
2009       threshold_grp_id                     ,
2010       old_invoice_amount                   ,
2011       old_invoice_cancel_amount            ,
2012       old_invoice_apply_amount             ,
2013       old_invoice_unapply_amount           ,
2014       old_tax_paid                         ,
2015       old_thhold_change_tax_paid           ,
2016       old_threshold_slab_id                ,
2017       trx_invoice_amount                   ,
2018       trx_invoice_cancel_amount            ,
2019       trx_invoice_apply_amount             ,
2020       trx_invoice_unapply_amount           ,
2021       trx_tax_paid                         ,
2022       trx_thhold_change_tax_paid           ,
2023       trx_threshold_slab_id                ,
2024       new_invoice_amount                   ,
2025       new_invoice_cancel_amount            ,
2026       new_invoice_apply_amount             ,
2027       new_invoice_unapply_amount           ,
2028       new_tax_paid                         ,
2029       new_thhold_change_tax_paid           ,
2030       new_threshold_slab_id                ,
2031       tds_event                            ,
2032       invoice_id                           ,
2033       invoice_line_number                  ,
2034       invoice_distribution_id              ,
2035       remarks                              ,
2036       created_by                           ,
2037       creation_date                        ,
2038       last_updated_by                      ,
2039       last_update_date                     ,
2040       last_update_login                    ,
2041       /*Bug 5751783. Inserted non-rounded values also*/
2042       calc_old_tax_paid                    ,
2043       calc_trx_tax_paid                    ,
2044       calc_new_tax_paid
2045     )
2046     values
2047     (
2048       jai_ap_tds_thgrp_audits_s.nextval    ,
2049       ln_threshold_grp_id                  ,
2050       ln_old_invoice_amount                ,
2051       ln_old_invoice_cancel_amount         ,
2052       ln_old_invoice_apply_amount          ,
2053       ln_old_invoice_unapply_amount        ,
2054       ln_old_tax_paid                      ,
2055       ln_old_thhold_change_tax_paid        ,
2056       ln_old_threshold_slab_id             ,
2057       p_trx_invoice_amount                 ,
2058       p_trx_invoice_cancel_amount          ,
2059       p_trx_invoice_apply_amount           ,
2060       p_trx_invoice_unapply_amount         ,
2061       ln_tmp_tds_amt,  --added for bug#5722028 csahoo
2062       p_trx_thhold_change_tax_paid         ,
2063       p_trx_threshold_slab_id              ,
2064       ln_new_invoice_amount                ,
2065       ln_new_invoice_cancel_amount         ,
2066       ln_new_invoice_apply_amount          ,
2067       ln_new_invoice_unapply_amount        ,
2068       ln_new_tax_paid                      ,
2069       ln_new_thhold_change_tax_paid        ,
2070       ln_new_threshold_slab_id             ,
2071       p_tds_event                          ,
2072       p_invoice_id                         ,
2073       p_invoice_line_number                ,
2074       p_invoice_distribution_id            ,
2075       p_remarks                            ,
2076       fnd_global.user_id                   ,
2077       sysdate                              ,
2078       fnd_global.user_id                   ,
2079       sysdate                              ,
2080       fnd_global.login_id                  ,
2081       /*Bug 5751783*/
2082       ln_calc_old_tax_paid                 ,
2083       ln_calc_trx_tax_paid                 ,
2084       ln_calc_new_tax_paid
2085     )
2086     returning  threshold_grp_audit_id into p_threshold_grp_audit_id;
2087 
2088     p_codepath := jai_general_pkg.plot_codepath(10, p_codepath); /* 10 */
2089     <<exit_from_procedure>>
2090 
2091     p_codepath := jai_general_pkg.plot_codepath(100, p_codepath, null, 'END'); /* 1 */
2092     jai_cmn_utils_pkg.WRITE_FND_LOG(G_LEVEL_PROCEDURE, G_MODULE_NAME||l_api_name||'.END', G_PKG_NAME || ': '||l_api_name||'()-');
2093 
2094     return;
2095 
2096   exception
2097     when others then
2098 
2099       fnd_file.put_line(FND_FILE.LOG,' Error in maintain thhold grps '|| substr(SQLERRM,1,200));
2100       p_process_flag := 'E';
2101       p_process_message := 'Error from jai_ap_dtc_generation_pkg.maintain_thhold_grps :' || sqlerrm;
2102   end maintain_thhold_grps;
2103 
2104 /* ********************************  maintain_thhold_grps *******************************************  */
2105 
2106 
2107   /* Populate Repository
2108   ------------------------------------------------------------------------------------------------------------
2109   */
2110   /* --Commented by Chong for eDTC bug#16414088 on 20130118 Start
2111   procedure populate_repository
2112   (
2113        errbuf                   OUT NOCOPY VARCHAR2  ,
2114        retcode                  OUT NOCOPY VARCHAR2  ,
2115        pd_from_date             in varchar2,
2116        pd_to_date               in varchar2
2117   )
2118   is
2119 
2120   cursor get_vendor_name(cn_vendor_id number)
2121   is
2122   select  vendor_name
2123   FROM po_vendors
2124   where vendor_id = cn_vendor_id;
2125 
2126   cursor get_vendor_site_name(cn_vendor_site_id number)
2127   is
2128   select  vendor_site_code
2129   FROM po_vendor_sites_all
2130   where vendor_site_id = cn_vendor_site_id;
2131 
2132 
2133   lv_vendor_name      po_vendors.vendor_name%type;
2134   lv_vendor_site_name po_vendor_sites_all.vendor_site_code%type;
2135 
2136   lv_attr_code  VARCHAR2(25);
2137   lv_attr_type_code VARCHAR2(25);
2138   lv_tds_regime     VARCHAR2(25);
2139   lv_regn_type_others VARCHAR2(25);
2140 
2141 
2142   cursor c_get_fin_year(p_accounting_date  date, p_org_id number) is
2143   select fin_year
2144   from   JAI_AP_TDS_YEARS
2145   where  tan_no in  \* where clause and subquery added by ssumaith - bug# 4448789*\
2146         (
2147               SELECT  attribute_value
2148               FROM    JAI_RGM_ORG_REGNS_V
2149               WHERE   regime_code = lv_tds_regime
2150               AND     registration_type = lv_regn_type_others
2151               AND     attribute_type_code = lv_attr_type_Code
2152               AND     attribute_code = lv_attr_code
2153               AND     organization_id = p_org_id
2154         )
2155   and    p_accounting_date between start_date and end_date;
2156 
2157   cursor c_get_dist_info(cn_invoice_distribution_id number)
2158   is
2159   select *
2160   from ap_invoice_distributions_all
2161   where invoice_distribution_id = cn_invoice_distribution_id;
2162 
2163   rec_dist_info c_get_dist_info%rowtype;
2164   lv_fin_year   JAI_AP_TDS_YEARS.fin_year%type;
2165 
2166   cursor c_get_check_id(cn_invoice_id number)
2167   is
2168   select check_id
2169   from   ap_invoice_payments_all
2170   where  invoice_id = cn_invoice_id;
2171 
2172   ln_check_id number;
2173 
2174   cursor get_challan_info(cn_check_id number)
2175   is
2176   select bsr_code, payment_reference_id,challan_no,payment_amount
2177   from jai_ap_tds_payments
2178   where check_id = cn_check_id;
2179 
2180   cursor get_tax_rate(cn_tax_id number)
2181   is
2182   select tax_rate
2183   from jai_cmn_taxes_all
2184   where tax_id = cn_tax_id;
2185 
2186   rec_challan get_challan_info%rowtype;
2187 
2188   ln_tax_rate number;
2189   ln_org_id   number;
2190 
2191   ld_from_date date;
2192   ld_to_date   date;
2193   l_api_name                   CONSTANT  VARCHAR2(50) := 'populate_repository()';
2194 
2195   begin
2196 
2197        jai_cmn_utils_pkg.WRITE_FND_LOG(G_LEVEL_PROCEDURE, G_MODULE_NAME||l_api_name||'.BEGIN', G_PKG_NAME || ': '||l_api_name||'()+');
2198        ln_org_id := mo_global.get_current_org_id();
2199 
2200        ld_from_date := fnd_date.canonical_to_date(pd_from_date);
2201        ld_to_date   := fnd_date.canonical_to_date(pd_to_date);
2202        FOR rec_trxs in (
2203 
2204                 select hdrs.*
2205                 from
2206                      ap_invoices_all hdrs
2207                 where org_id = ln_org_id
2208                 and   exists
2209                                 (
2210                       select 1 from ap_invoice_distributions_all dist
2211                       where 1=1
2212                       and   dist.invoice_id = hdrs.invoice_id
2213                       and   dist.org_id     = ln_org_id
2214                       and(
2215                             (ld_from_date is null and ld_to_date is null)
2216                             or
2217                             (
2218                               ld_from_date is not null and ld_to_date is not null
2219                               and  dist.accounting_date BETWEEN ld_from_date and ld_to_date
2220                             )
2221                             or
2222                             (
2223                               ld_from_date is null and ld_to_date is not null
2224                               and  dist.accounting_date <= ld_to_date
2225                             )
2226                             or
2227                             (
2228                               ld_from_date is not null and ld_to_date is null
2229                               and  dist.accounting_date >= ld_from_date
2230                             )
2231 
2232                       )
2233 
2234                 )
2235 
2236 
2237 
2238        )
2239        LOOP
2240               for rec_tds_taxes in(
2241                   select * from jai_ap_tds_inv_taxes
2242                   where   invoice_id = rec_trxs.invoice_id
2243                   and     actual_tax_id is not null
2244                   and     threshold_trx_id is not null
2245                   and     not exists
2246                   (
2247                           select 1
2248                           from JAI_AP_TDS_REPOSITORY rep
2249                           where rep.invoice_id = rec_trxs.invoice_id
2250                   )
2251               )
2252               loop
2253 
2254 
2255 
2256                    open get_tax_rate(rec_tds_taxes.actual_tax_id);
2257                    fetch get_tax_rate into ln_tax_rate;
2258                    close get_tax_rate;
2259 
2260                    --Get Section Type, Section Code, Tax type, Tax Rate from JAI_AP_TDS_INV_TAXES or Description of Invoice Distribution
2261 
2262                    \* cursor get_line_info(cn_invoice_distribution_id number)
2263                     is
2264                     select line. from ap_invoice_lines_all line, ap_invoice_distributions_all dist
2265                     where line.invoice_id = dist.invoice_id
2266                     and   line.line_number = dist.invoice_line_number
2267                     and   dist.invoice_distribution_id = *\
2268 
2269 
2270                     open get_vendor_name(rec_trxs.vendor_id);
2271                     fetch get_vendor_name into lv_vendor_name;
2272                     close get_vendor_name;
2273 
2274                     open get_vendor_site_name(rec_trxs.vendor_site_id);
2275                     fetch get_vendor_site_name into lv_vendor_site_name;
2276                     close get_vendor_site_name;
2277 
2278                     open c_get_dist_info(rec_tds_taxes.invoice_distribution_id);
2279                     fetch c_get_dist_info into rec_dist_info;
2280                     close c_get_dist_info;
2281 
2282                     --Fetch TDS_PAID, CHALLAN_NUMBER, BSR_CODE, PAYMENT_REFERENCE_ID from JAI_AP_TDS_PAYMENTS
2283                     --add code here
2284 
2285 
2286                     \*
2287 
2288                    lv_attr_code  := 'TAN NO';
2289                    lv_attr_type_code := 'PRIMARY';
2290                    lv_tds_regime     := 'TDS';
2291                    lv_regn_type_others := 'OTHERS';
2292 
2293                     open c_get_fin_year(rec_dist_info.accounting_date,rec_dist_info.org_id);
2294                     fetch c_get_fin_year into lv_fin_year;
2295                     close c_get_fin_year;*\
2296 
2297                     open c_get_check_id(rec_trxs.invoice_id);
2298                     fetch c_get_check_id into ln_check_id;
2299                     close c_get_check_id;
2300 
2301 
2302 
2303                     \*lv_bsr_code             jai_ap_tds_payments.bsr_code%type;
2304                     ln_payment_reference_id   jai_ap_tds_payments.payment_reference_id%type;
2305                     lv_challan_number         jai_ap_tds_payments.bsr_code%type;
2306                     ln_payment_amount         jai_ap_tds_payments.payment_amount%type;*\
2307 
2308                     open get_challan_info(ln_check_id);
2309                     fetch get_challan_info into rec_challan;
2310                     close get_challan_info;
2311 
2312                     Insert  into JAI_AP_TDS_REPOSITORY
2313                     (
2314                             INVOICE_ID                ,
2315                             INVOICE_NUMBER            ,
2316                             PARENT_INVOICE_ID         ,
2317                             --INVOICE_LINE_ID            ,
2318                             --LINE_NUMBER                ,
2319                             --INVOICE_DISTRIBUTION_ID    ,
2320                             --DISTRIBUTION_LINE_NUMBER  ,
2321                             ACCOUNTING_DATE            ,
2322                             ORG_ID                    ,
2323                             --VENDOR_NAME                ,
2324                             --VENDOR_SITE_CODE          ,
2325                             SECTION_TYPE              ,
2326                             SECTION_CODE              ,
2327                             --TAX_TYPE                  ,
2328                             --TAX_RATE                  ,
2329                             TDS_PAID                  ,
2330                             INVOICE_DELETED           ,
2331                             CHALLAN_NUMBER            ,
2332                             BSR_CODE                  ,
2333                             PAYMENT_REFERENCE_ID      ,
2334                             TAX_AMOUNT                ,
2335                             BASE_TAX_AMOUNT            ,
2336                             CREATION_DATE              ,
2337                             CREATED_BY                ,
2338                             LAST_UPDATE_DATE          ,
2339                             LAST_UPDATE_LOGIN          ,
2340                             LAST_UPDATED_BY
2341 
2342                     )
2343                     values
2344                     (
2345 
2346 
2347                             rec_trxs.invoice_id,                   --INVOICE_ID	            	,
2348                             rec_trxs.invoice_num,                  --get from ap_invoices_all --INVOICE_NUMBER	        	,
2349                             nvl(rec_dist_info.parent_invoice_id,rec_trxs.invoice_id),
2350                             --1,                                     --get from ap_invoice_lines_all --INVOICE_LINE_ID            ,
2351                             --rec_dist_info.invoice_line_number,     --get from ap_invoice_lines_all -- LINE_NUMBER                ,
2352                             --rec_tds_taxes.invoice_distribution_id, --INVOICE_DISTRIBUTION_ID    ,
2353                             --rec_dist_info.distribution_line_number,--get from ap_invoice_distributions_all.,--DISTRIBUTION_LINE_NUMBER  ,
2354                             rec_dist_info.accounting_date,         --get from ap_invoice_distributions_all.,--ACCOUNTING_DATE						,
2355                             rec_dist_info.org_id,                  --get from ap_invoice_distributions_all.,--ORG_ID										,
2356                             --lv_vendor_name,                        --get vendor name by id, --VENDOR_NAME                ,
2357                             --lv_vendor_site_name,                   --get vendor site code by id --VENDOR_SITE_CODE          ,
2358                             rec_tds_taxes.section_type,     --get from jaji_ap_tds_inv_taxes,--SECTION_TYPE							,
2359                             rec_tds_taxes.actual_section_code,     --get from jai_ap_tds_inv_taxes, --SECTION_CODE							,
2360                             --rec_tds_taxes.tax_type,                --get from jai_ap_tds_inv_taxes, --TAX_TYPE                  ,
2361                             --ln_tax_rate,                           --get from jai_ap_tds_inv_taxes,--TAX_RATE                  ,
2362                             rec_challan.payment_amount,            --TDS_PAID                ,
2363                             'N',
2364                             rec_challan.challan_no,                --CHALLAN_NUMBER						,
2365                             rec_challan.bsr_code,                  --BSR_CODE									,
2366                             rec_challan.payment_reference_id,      --PAYMENT_REFERENCE_ID			,
2367                             rec_tds_taxes.tax_amount,          --get from jai_ap_tds_inv_taxes,--TAX_AMOUNT                ,
2368                             rec_tds_taxes.tax_amount,         --get from jai_ap_tds_inv_taxes,--BASE_TAX_AMOUNT            ,
2369                             sysdate,
2370                             fnd_global.user_id  ,
2371                             sysdate             ,
2372                             fnd_global.login_id ,
2373                             fnd_global.user_id
2374 
2375                     );
2376 
2377               end loop;
2378 
2379        END LOOP;
2380        jai_cmn_utils_pkg.WRITE_FND_LOG(G_LEVEL_PROCEDURE, G_MODULE_NAME||l_api_name||'.END', G_PKG_NAME || ': '||l_api_name||'()-');
2381 
2382   end populate_repository;
2383   --Commented by Chong for eDTC bug#16414088 on 20130118 End */
2384 
2385   /****************************************process_dtc_at_inv_validate***************************************/
2386   /*
2387   ||Create new procedure to process DTC to replace TDS
2388   ||Added by Zhiwei.Hou on 21-Nov-2011
2389   */
2390   procedure process_dtc_at_inv_validate
2391   (
2392     p_invoice_id                         in                  number,
2393     p_vendor_id                          in                  number,
2394     p_vendor_site_id                     in                  number,
2395     p_accounting_date                    in                  date,
2396     p_invoice_currency_code              in                  varchar2,
2397     p_exchange_rate                      in                  number,
2398     p_set_of_books_id                    in                  number,
2399     p_org_id                             in                  number,
2400     p_call_from                          in                  varchar2,
2401     p_creation_date                      in                  date,
2402     p_process_flag                       out       nocopy    varchar2,
2403     p_process_message                    out       nocopy    varchar2,
2404     p_codepath                           in out    nocopy    varchar2
2405   )
2406   is
2407 
2408     cursor c_check_if_exists(p_invoice_id  number) is
2409       select count(tds_inv_tax_id)
2410       from   jai_ap_tds_inv_taxes
2411       where  nvl(consider_amt_for_tds, 'Y') = 'Y' -- Added by mmurtuza for bug12858951
2412       and    invoice_id = p_invoice_id
2413       and    actual_tax_id is not null
2414       and    threshold_transition is null -- Added by zhiwei for bug#13359892
2415       ;
2416 
2417     cursor c_check_if_processed(p_invoice_id  number,p_process_status jai_ap_tds_inv_taxes.process_status%type) is
2418       select count(tds_inv_tax_id)
2419       from   jai_ap_tds_inv_taxes
2420       where  nvl(consider_amt_for_tds, 'Y') = 'Y' -- Added by mmurtuza for bug12858951
2421       and    invoice_id = p_invoice_id
2422       and    process_status = p_process_status
2423       and    threshold_transition is null -- Added by zhiwei for bug#13359892
2424       ;
2425 
2426     cursor c_calculate_tax(p_invoice_id  number) is
2427       select tds_inv_tax_id, actual_tax_id, amount, invoice_distribution_id,section_type
2428             ,actual_section_code,rounded_amount  --Added by Zhiwei for Bug#13359892
2429       from   jai_ap_tds_inv_taxes
2430       where  nvl(consider_amt_for_tds, 'Y') = 'Y' -- Added by mmurtuza for bug12858951
2431       and    invoice_id = p_invoice_id
2432       and    actual_tax_id is not null
2433       and    tax_line_no = 1;
2434       --and    (default_tax_id is not null or actual_tax_id is not null); --Commented by Zhiwei for Bug#13359892
2435 
2436     cursor c_ja_in_tax_codes(p_tax_id number) is
2437       select tax_rate,
2438              section_code,
2439              end_date,
2440              sysdate,
2441              'Tax : ' || tax_name || ' is end dated as on ' || to_char(end_date, 'dd-mon-yyyy') ||
2442              '. Setup needs modification.' tax_end_dated_message
2443       from   JAI_CMN_TAXES_ALL
2444       where  tax_id = p_tax_id;
2445     /*Bug 5751783 - Selected non-rounded value for calculation*/
2446     cursor c_for_each_tds_section(p_invoice_id  number, p_exchange_rate number,p_section_type jai_ap_tds_inv_taxes.section_type%type, p_prepay_amt number) is--rchandan for bug#4428980 --add by xiao for bug#6596019
2447       select actual_section_code, (sum(amount*p_exchange_rate)-p_prepay_amt) invoice_amount, sum(calc_tax_amount) section_amount,
2448              sum(tax_amount) tax_amount_orig
2449       from   jai_ap_tds_inv_taxes
2450       where  nvl(consider_amt_for_tds, 'Y') = 'Y' -- Added by mmurtuza for bug12858951
2451       and invoice_id = p_invoice_id
2452       and    section_type = p_section_type         --rchandan for bug#4428980
2453       and    actual_section_code is not null
2454       group by  actual_section_code;
2455       --having sum(tax_amount) <> 0;   --Commented by Bgowrava for Bug#8254510
2456 
2457     cursor c_po_vendors(p_vendor_id number) is
2458       select tds_vendor_type_lookup_code
2459       from   JAI_AP_TDS_VNDR_TYPE_V
2460       where  vendor_id = p_vendor_id;
2461 
2462     cursor c_get_threshold
2463     (p_vendor_id number, p_vendor_site_id number,  p_tds_section_code varchar2,p_section_type jai_ap_tds_inv_taxes.section_type%type) IS   --rchandan for bug#4428980
2464       select threshold_hdr_id
2465       from   JAI_AP_TDS_TH_VSITE_V
2466       where  vendor_id = p_vendor_id
2467       and    vendor_site_id = p_vendor_site_id
2468       and    section_type = p_section_type    --rchandan for bug#4428980
2469       and    section_code = p_tds_section_code;
2470 
2471     cursor    c_get_threshold_group(
2472                           p_vendor_id number,
2473                           p_tan_no varchar2,
2474                           p_pan_no varchar2,
2475                           p_tds_section_code varchar2 ,
2476                           p_fin_year  number,
2477                           p_section_type jai_ap_tds_inv_taxes.section_type%type)
2478     IS --rchandan for bug#4428980
2479       select  threshold_grp_id
2480       from    jai_ap_tds_thhold_grps
2481       where   vendor_id         =  p_vendor_id
2482       and     section_type      =  p_section_type --rchandan for bug#4428980
2483       and     section_code      =  p_tds_section_code
2484       and     org_tan_num       =  p_tan_no
2485       and     vendor_pan_num    =  p_pan_no
2486       and     fin_year          =  p_fin_year;
2487 
2488     cursor c_jai_ap_tds_thhold_grps(p_threshold_grp_id  number) is
2489       select (
2490               nvl(total_invoice_amount, 0) -
2491               nvl(total_invoice_cancel_amount, 0) -
2492               nvl(total_invoice_apply_amount, 0)  +
2493               nvl(total_invoice_unapply_amount, 0)
2494               )
2495               total_invoice_amount,
2496               total_tax_paid,
2497               total_thhold_change_tax_paid,
2498               current_threshold_slab_id,
2499               /*Bug 5751783. Selected non-rounded value for calculation*/
2500               total_calc_tax_paid
2501       from    jai_ap_tds_thhold_grps
2502       where   threshold_grp_id = p_threshold_grp_id;
2503 
2504 
2505     cursor c_jai_ap_tds_thhold_slabs
2506     ( p_threshold_hdr_id number, p_threshold_type varchar2, p_amount number) is
2507       select  threshold_slab_id, threshold_type_id, from_amount, to_amount
2508       from    jai_ap_tds_thhold_slabs
2509       where   threshold_hdr_id = p_threshold_hdr_id
2510       and     threshold_type_id in
2511       --    ( select threshold_type_id  --Commented by Chong for bug#15939571 20130319
2512             --Added by Chong for bug#15939571 20130319 Start
2513             ------------------------------------------------
2514             (SELECT FIRST_VALUE(threshold_type_id)
2515                     OVER (ORDER BY NVL(DEFAULT_TYPE,'N') DESC ,threshold_type_id ASC)
2516             ------------------------------------------------
2517             --Added by Chong for bug#15939571 20130319 End
2518               from   jai_ap_tds_thhold_types
2519               where   threshold_hdr_id = p_threshold_hdr_id
2520               and     threshold_type = p_threshold_type
2521         /* Bug 4522540. Added by Lakshmi Gopalsami
2522            Added the following date condition */
2523               and    trunc(p_accounting_Date) between from_date
2524         and nvl(to_date, p_accounting_date + 1)
2525             )
2526       and     p_amount between from_amount and nvl(to_amount, p_amount)
2527       order by from_amount asc;
2528 
2529 
2530      /*following cursor added for FP bug 6345725 - need to check if there are any active slab(s) defined */
2531      cursor c_check_slabs_end_dated (p_threshold_hdr_id number) is
2532         select 1
2533         from jai_ap_tds_thhold_types
2534         where threshold_hdr_id = p_threshold_hdr_id
2535         and   trunc(p_accounting_Date) between from_date and nvl(to_date, p_accounting_date + 1);
2536 
2537      ln_check_slab_exists NUMBER;
2538 
2539     /*Bug 5751783. Selected non-rounded value for calculation*/
2540 
2541     cursor c_get_taxes_to_generate_tds
2542     (p_invoice_id number, p_tds_section_code varchar2, p_generate_all_invoices varchar2,
2543      p_exchange_rate number, p_threshold_slab_id_single number,p_section_type jai_ap_tds_inv_taxes.section_type%type, p_prepay_amt number) IS --rchandan for bug#4428980--add by xiao for bug#6596019
2544      -- select nvl(actual_tax_id,default_tax_id) actual_tax_id,   --added nvl by Xiao for Bug#7154864
2545      select tax_category_id ,
2546 (             sum(amount*p_exchange_rate)-p_prepay_amt) taxable_amount, --Xiao for bug#6596019
2547              --sum(calc_tax_amount) tax_amount,--Comment by Zhiwei on 20120111
2548              sum(calc_tax_amount*p_exchange_rate) tax_amount,--Update by Zhiwei on 20120111
2549              sum(tax_amount) tax_amount_orig
2550       from   jai_ap_tds_inv_taxes
2551       where  nvl(consider_amt_for_tds, 'Y') = 'Y' -- Added by mmurtuza for bug12858951
2552       and invoice_id = p_invoice_id
2553       and    section_type      =  p_section_type   --rchandan for bug#4428980
2554       and    actual_section_code = p_tds_section_code
2555       and    tax_category_id is not null--Added by Zhwiei on 20120213
2556       and    (
2557                (p_generate_all_invoices = 'Y' )
2558                or
2559                (p_threshold_slab_id_single > 0 )
2560                -- or/*Commented the below condition for bug 11803135*/
2561               -- (actual_tax_id is NOT NULL) --added by Xiao for Bug#7154864
2562                /*FP of QA Bug 12431997 - Included in 11896260 - Tax to be deducted irrespective of Threshold if PAN is not available*/
2563                OR
2564                EXISTS (SELECT 1
2565                        FROM jai_ap_tds_vendor_hdrs
2566                        WHERE (pan_no IN ('PANAPPLIED','PANNOTAVBL','PANINVALID')
2567                               OR (pan_no IS NOT NULL AND confirm_pan_flag IS NULL))
2568                        AND vendor_site_id = 0
2569                        AND vendor_id = (SELECT vendor_id
2570                                         FROM ap_invoices_all
2571                                         WHERE invoice_id = p_invoice_id
2572                                        )
2573                       )
2574              )
2575              group by tax_category_id;
2576      -- group by nvl(actual_tax_id, default_tax_id);  --added nvl by Xiao for Bug#7154864
2577 
2578     cursor c_get_vendor_pan_tan(p_vendor_id number , p_vendor_site_id number) is
2579       select    c.pan_no pan_no,
2580                 d.org_tan_num tan_no,
2581                 c.confirm_pan_flag confirm_pan_flag /*Fixing QA Bug 12431997 - Included in 11896260*/
2582         from    po_vendors a,
2583                 po_vendor_sites_all b,
2584                 JAI_AP_TDS_VENDOR_HDRS c,
2585                 jai_ap_tds_org_tan_v d  --rchandan for bug#4323338
2586       where     a.vendor_id = b.vendor_id
2587         and     b.vendor_id = c.vendor_id
2588         and     b.vendor_site_id = c.vendor_site_id
2589         and     b.org_id = d.organization_id
2590         and     a.vendor_id = p_vendor_id
2591         and     b.vendor_site_id = p_vendor_site_id;
2592 
2593 
2594     lv_attr_code  VARCHAR2(25);
2595     lv_attr_type_code VARCHAR2(25);
2596     lv_tds_regime     VARCHAR2(25);
2597     lv_regn_type_others VARCHAR2(25);
2598 
2599 
2600     --Add by Zhiwei Hou on 20120111 begin
2601     -----------------------------------------------------
2602 
2603     cursor c_get_fin_year(p_accounting_date  date, p_org_id number)
2604     is
2605     select period_year
2606     from GL_PERIODS
2607     where period_set_name
2608           in
2609           (
2610               select period_set_name
2611               from GL_PERIOD_SETS
2612               where period_set_id
2613                     in
2614                     (
2615                           SELECT  attribute_value
2616                           FROM    JAI_RGM_ORG_REGNS_V
2617                           WHERE   regime_code = lv_tds_regime--'TDS'
2618                           AND registration_type = lv_regn_type_others--'OTHERS'
2619                           AND attribute_type_code = lv_attr_type_Code--'OTHERS'
2620                           AND attribute_code = lv_attr_code--'TDS_CALENDAR'
2621                           AND organization_id = p_org_id--7581
2622                     )
2623               )
2624     and   p_accounting_date between start_date and end_date;
2625     -----------------------------------------------------
2626     --Add by Zhiwei Hou on 20120111 end
2627 
2628     --Comment by Zhiwei Hou on 20120111 begin
2629     ------------------------------------------------------------------
2630     /*cursor c_get_fin_year(p_accounting_date  date, p_org_id number) is
2631       select fin_year
2632       from   JAI_AP_TDS_YEARS
2633       where  tan_no in  \* where clause and subquery added by ssumaith - bug# 4448789*\
2634             (
2635               SELECT  attribute_value
2636               FROM    JAI_RGM_ORG_REGNS_V
2637               WHERE   regime_code = lv_tds_regime
2638               AND     registration_type = lv_regn_type_others
2639               AND     attribute_type_code = lv_attr_type_Code
2640               AND     attribute_code = lv_attr_code
2641               AND     organization_id = p_org_id
2642             )
2643       and    p_accounting_date between start_date and end_date;*/
2644       -------------------------------------------------------------------------
2645       --Comment by Zhiwei Hou on 20120111 end
2646     cursor c_gl_sets_of_books(cp_set_of_books_id  number) is
2647     select currency_code
2648     from   gl_sets_of_books
2649     where  set_of_books_id = cp_set_of_books_id;
2650 
2651     /*Bug 5751783. Selected non-rounded value for calculation*/
2652 
2653     cursor c_get_non_tds_section_tax (p_invoice_id number, p_exchange_rate number,p_section_type jai_ap_tds_inv_taxes.section_type%type) IS     --rchandan for bug#4428980
2654     select section_type,
2655            actual_tax_id,
2656            sum(amount*p_exchange_rate) taxable_amount,
2657            sum(calc_tax_amount) tax_amount,
2658            sum(tax_amount) tax_amount_orig
2659     from   jai_ap_tds_inv_taxes
2660     where  nvl(consider_amt_for_tds, 'Y') = 'Y' -- Added by mmurtuza for bug12858951
2661       and invoice_id = p_invoice_id
2662     and    section_type      <>  p_section_type        --rchandan for bug#4428980
2663     and    actual_tax_id is not null
2664     group by section_type, actual_tax_id;
2665 
2666     --Add by Zhiwei Hou on 20120111 begin
2667     -----------------------------------------------
2668     cursor c_get_non_tds_sec_tax_cat (p_invoice_id number, p_exchange_rate number,p_section_type jai_ap_tds_inv_taxes.section_type%type) IS     --rchandan for bug#4428980
2669     select section_type,
2670            actual_section_code,
2671            tax_category_id,
2672            sum(amount*p_exchange_rate) taxable_amount,
2673            sum(calc_tax_amount) tax_amount,
2674            sum(tax_amount) tax_amount_orig
2675     from   jai_ap_tds_inv_taxes
2676     where  nvl(consider_amt_for_tds, 'Y') = 'Y' -- Added by mmurtuza for bug12858951
2677       and invoice_id = p_invoice_id
2678     and    section_type      <>  p_section_type        --rchandan for bug#4428980
2679     and    tax_category_id is not null
2680     group by section_type, actual_section_code,tax_category_id;
2681     -------------------------------------------------
2682     --Add by Zhiwei Hou on 20120111 end
2683 
2684 
2685 
2686 	/*START, Bgowrava for Bug#8254510*/
2687 	cursor c_jai_slab_start_amt(p_threshold_slab_id number) is
2688 	select jatts.from_amount from_amount,
2689            jatts.tax_rate tax_rate,
2690 		   jattt.tax_id tax_id,
2691 		   (jitc.tax_rate-(nvl(jitc.surcharge_rate,0) + nvl(jitc.cess_rate,0) + nvl(jitc.sh_cess_rate,0))) tax_rate_orig
2692 	from jai_ap_tds_thhold_slabs jatts,
2693          jai_ap_tds_thhold_taxes jattt,
2694          jai_cmn_taxes_all jitc
2695 	where jatts.threshold_slab_id = jattt.threshold_slab_id
2696 	and jattt.tax_id = jitc.tax_id
2697 	and jatts.threshold_slab_id = p_threshold_slab_id;
2698 
2699 	r_jai_slab_start_amt_after c_jai_slab_start_amt%rowtype;
2700 	r_jai_slab_start_amt_before c_jai_slab_start_amt%rowtype;
2701 	ln_tds_amt_before number;
2702 	ln_tds_amt_after number;
2703 	ln_tds_tax_amount number;
2704 	/*END, Bgowrava for Bug#8254510*/
2705 
2706     /*START, Added by xiao for Bug#6596019*/
2707 		cursor c_get_prepayment_amt(p_invoice_id number) is
2708 		select amount_paid
2709 		from ap_invoices_all
2710 		where invoice_id = p_invoice_id;
2711 
2712 
2713     CURSOR c_check_valid_tax(p_invoice_id  number)
2714     IS
2715 --    select jitc.section_code section_code            --Commented by ChongLei for DTC ER 2011/12/29
2716     select jatit.actual_section_code section_code      --Added by ChongLei for DTC ER 2011/12/29
2717     from jai_cmn_taxes_all jitc, jai_ap_tds_inv_taxes jatit
2718     where jitc.tax_id = jatit.actual_tax_id
2719     and jatit.section_type = 'TDS_SECTION'
2720     and jatit.invoice_id = p_invoice_id
2721     and jatit.actual_tax_id is not null
2722     ;
2723 
2724 
2725     --Addec by Jia for FP Bug#7431371, Begin
2726     -------------------------------------------------------------------------------
2727 	  /*Added parameter section_type fro bug 11070443*/
2728     cursor c_get_amount_already_applied(p_invoice_distribution_id number, p_section_type varchar2) is
2729     select  sum(application_amount)
2730     from    jai_ap_tds_prepayments
2731     where   invoice_distribution_id = p_invoice_distribution_id
2732 	  and     (
2733                   (p_section_type = 'TDS_SECTION'  and nvl(tds_applicable_flag,  '*') = 'Y') or
2734                   (p_section_type = 'WCT_SECTION'  and nvl(wct_applicable_flag,  '*') = 'Y') or
2735                   (p_section_type = 'ESSI_SECTION' and nvl(essi_applicable_flag, '*') = 'Y')
2736             )
2737     and     nvl(unapply_flag, 'N') <> 'Y';
2738 
2739     ln_remaining_tds_prepay_amt      number;
2740     ln_remaining_wct_prepay_amt      number;
2741     ln_remaining_ess_prepay_amt      number;
2742     ln_remaining_prepayment_amount      number;
2743     ln_effective_available_amount       number;
2744     ln_already_applied_amount           number;
2745     ln_application_amount               number;
2746     ln_prev_section_type                varchar2(20) := NULL;
2747     ln_prev_dist_id                     number := 0;
2748     -------------------------------------------------------------------------------
2749     --Addec by Jia for FP Bug#7431371, End
2750 
2751       ln_prepayment_app_amt             number :=0; --xiao for Bug#6596019
2752       r_jai_ap_tds_thhold_grps          c_jai_ap_tds_thhold_grps%rowtype;
2753       r_gl_sets_of_books                c_gl_sets_of_books%rowtype;
2754       r_ja_in_tax_codes                 c_ja_in_tax_codes%rowtype;
2755 
2756       ln_count                          number:= 0;
2757       ln_cnt_already_processed          number:= 0;
2758       ln_tax_id                         number;
2759       ln_tax_amount                     number;
2760       ln_threshold_grp_id               number;
2761       lv_vendor_type_lookup_code        po_vendors.vendor_type_lookup_code%type;
2762       ln_threshold_hdr_id               number;
2763       r_jai_ap_tds_thhold_slabs         c_jai_ap_tds_thhold_slabs%rowtype;
2764       ln_total_invoice_amount           number;
2765       ln_threshold_slab_id_before       number;
2766       ln_threshold_slab_id_after        number;
2767       ln_threshold_slab_id_single       number;
2768       lv_generate_all_invoices          varchar2(1);
2769       ln_threshold_trx_id               number;
2770       lv_tds_invoice_num                ap_invoices_all.invoice_num%type;
2771       lv_tds_cm_num                     ap_invoices_all.invoice_num%type;
2772 
2773       lv_pan_no                         JAI_AP_TDS_VENDOR_HDRS.pan_no%type;
2774       lv_tan_no                         jai_ap_tds_org_tan_v.org_tan_num %type;  --rchandan for bug#4323338
2775       lv_confirm_pan_flag               JAI_AP_TDS_VENDOR_HDRS.confirm_pan_flag%type; /*Bug 11896260*/
2776       ln_exchange_rate                  number;
2777       ln_fin_year                       JAI_AP_TDS_YEARS.fin_year%type;
2778       lv_slab_transition_tds_event      jai_ap_tds_thhold_trxs.tds_event%type;
2779 
2780       ln_no_of_tds_inv_generated        number := 0;
2781       lb_result                         boolean;
2782       ln_req_id                         number;
2783       ln_start_threshold_trx_id         number;
2784       ln_threshold_grp_audit_id         number;
2785       lv_tds_section_type               CONSTANT varchar2(30) := 'TDS_SECTION';    --rchandan for bug#4428980
2786       -- Bug 5722028. Added by Lakshmi Gopalsami
2787       ln_tmp_tds_amt                    number;
2788 
2789       sqlbuf VARCHAR2(1996);
2790 
2791       --Added by Zhiwei for Bug#13359892 DTC enhancement on 20111123 begin
2792       --------------------------------------------------------------------------------
2793 
2794       --Variable Block
2795       ln_dtc_tax_cat_id                 number;
2796 
2797 
2798 
2799       ln_prepay_amount     number;
2800       --ln_count             NUMBER;
2801       ln_line_id           number;
2802       ln_applied_amount    number;
2803       ln_rounding_factor   number;
2804       ln_tax_rounding_factor   number;  --Added by Chong for bug#15939571  20121210
2805 
2806       --Cursor Block
2807       Cursor insert_tds_section_tax_cur
2808       IS
2809       SELECT section_type,
2810              actual_section_code section_code,
2811              tax_category_id,
2812              sum(amount)     amount
2813       from  jai_ap_tds_inv_taxes
2814       where invoice_id = p_invoice_id
2815       and   actual_section_code is not null
2816       group by section_type, actual_section_code, tax_category_id;
2817 
2818 
2819       --Comment by Zhiwei Hou on 20120111 begin
2820       /*CURSOR chk_exist_in_section_tax(
2821                 cv_section_type    IN VARCHAR2,
2822                 cv_section_code    IN VARCHAR2,
2823                 cn_invoice_id      IN NUMBER,
2824                 cn_tax_category_id IN NUMBER
2825       )
2826       IS
2827       SELECT count(TAX_ID)
2828       FROM JAI_AP_TDS_SECTION_TAX
2829       WHERE HEADER_ID      = cn_invoice_id
2830       AND   SECTION_TYPE    = cv_section_type
2831       AND   SECTION_CODE    = cv_section_code
2832       AND   TAX_CATEGORY_ID = cn_tax_category_id;*/
2833       --Comment by Zhiwei Hou on 20120111 end
2834 
2835       CURSOR taxes_in_category_cur(cn_tax_category_id IN NUMBER)
2836       IS
2837       SELECT  CATE.TAX_ID,
2838               CATE.LINE_NO,
2839               TAX.TAX_RATE,
2840               TAX.SECTION_TYPE,
2841               TAX.SECTION_CODE,
2842               CATE.PRECEDENCE_1,
2843               CATE.PRECEDENCE_2,
2844               CATE.PRECEDENCE_3,
2845               CATE.PRECEDENCE_4,
2846               CATE.PRECEDENCE_5,
2847               CATE.PRECEDENCE_6,
2848               CATE.PRECEDENCE_7,
2849               CATE.PRECEDENCE_8,
2850               CATE.PRECEDENCE_9,
2851               CATE.PRECEDENCE_10
2852       FROM  JAI_CMN_TAXES_ALL     TAX,
2853             JAI_CMN_TAX_CTG_LINES CATE
2854       WHERE CATE.TAX_CATEGORY_ID = cn_tax_category_id
2855       AND   TAX.TAX_ID = CATE.TAX_ID;
2856 
2857       CURSOR c_get_already_applied_new(
2858                cn_invoice_id   number,
2859                cv_section_type varchar2,
2860                cv_section_code varchar2
2861       )
2862       IS
2863       select  sum(application_amount) applied_amount
2864       from    jai_ap_tds_prepayments
2865       where   invoice_id = cn_invoice_id
2866       and     (
2867                       (cv_section_type = 'TDS_SECTION'  and nvl(tds_applicable_flag,  '*') = 'Y' and tds_section_code_prepay = cv_section_code)
2868                    or (cv_section_type = 'WCT_SECTION'  and nvl(wct_applicable_flag,  '*') = 'Y')
2869                    or (cv_section_type = 'ESSI_SECTION' and nvl(essi_applicable_flag, '*') = 'Y')
2870               )
2871       and     nvl(unapply_flag, 'N') <> 'Y';
2872 
2873 
2874       CURSOR c_get_section_codes
2875       IS
2876       SELECT LOOKUP_CODE SECTION_CODE
2877       FROM   JA_LOOKUPS
2878       WHERE  LOOKUP_TYPE = 'JAI_TDS_SECTION';
2879 
2880       cursor c_for_each_tds_section_new(
2881              p_invoice_id  number,
2882              p_exchange_rate number,
2883              p_section_type jai_ap_tds_inv_taxes.section_type%type,
2884              p_section_code jai_ap_tds_inv_taxes.actual_section_code%type,
2885              p_prepay_amt number) is
2886       select actual_section_code,
2887              (sum(amount*p_exchange_rate)-p_prepay_amt) invoice_amount,
2888              sum(calc_tax_amount) section_amount,
2889              sum(tax_amount) tax_amount_orig
2890              --,invoice_distribution_id
2891       from   jai_ap_tds_inv_taxes
2892       where  nvl(consider_amt_for_tds, 'Y') = 'Y'
2893       and    invoice_id = p_invoice_id
2894       and    section_type = p_section_type
2895       and    actual_section_code is not null
2896       and    actual_section_code = p_section_code
2897       group by  actual_section_code;--,invoice_distribution_id;
2898 
2899       cursor c_get_exception_setup(cn_hdr_id number)
2900       is
2901       select nvl(exception_setup_flag,'N')
2902       from   jai_ap_tds_thhold_hdrs
2903       where  threshold_hdr_id = ln_threshold_hdr_id;
2904 
2905 
2906       cursor c_get_multiple_rate_setup(cn_hdr_id number)
2907       is
2908       select nvl(multiple_rate_setup,'N')
2909       from   jai_ap_tds_thhold_hdrs
2910       where  threshold_hdr_id = ln_threshold_hdr_id;
2911 
2912       lv_multiple_rate_setup  jai_ap_tds_thhold_hdrs.multiple_rate_setup%type;
2913 
2914       cursor c_jai_ap_tds_thhold_slabs_new(
2915              p_threshold_hdr_id number,
2916              p_threshold_type varchar2,
2917              p_amount number,
2918              p_natural_account varchar2
2919             ,p_legal_entity_id JAI_AP_TDS_THHOLD_ACCOUNT.LEGAL_ENTITY_ID%TYPE --Added p_legal_entity_id by Chong for Bug#13802244 2012/09/21
2920              )is
2921       select  threshold_slab_id, threshold_type_id, from_amount, to_amount
2922       from    jai_ap_tds_thhold_slabs
2923       where   threshold_hdr_id = p_threshold_hdr_id
2924       and     threshold_type_id in
2925             ( select jattt.threshold_type_id
2926               from   jai_ap_tds_thhold_types jattt
2927               where  jattt.threshold_hdr_id = p_threshold_hdr_id
2928               and    jattt.threshold_type = p_threshold_type
2929               and    trunc(p_accounting_Date) between jattt.from_date and nvl(jattt.to_date, p_accounting_date + 1)
2930               and    exists (select '1'
2931                          from JAI_AP_TDS_THHOLD_ACCOUNT jatta
2932                          where jatta.threshold_hdr_id = jattt.threshold_hdr_id  --Added alias (jattt) by Chong for Bug#13802244 2012/09/21
2933                          and jatta.threshold_type_id = jattt.threshold_type_id
2934                          and jatta.NATURAL_ACCOUNT_VALUE = p_natural_account
2935                          and jatta.legal_entity_id = p_legal_entity_id  --Added p_legal_entity_id by Chong for Bug#13802244 2012/09/21
2936                          )
2937 
2938             )
2939       and     p_amount between from_amount and nvl(to_amount, p_amount)
2940       order by from_amount asc;
2941 
2942 
2943       cursor c_get_threshold_xcep(
2944              p_vendor_id number,
2945              p_vendor_site_id number,
2946              p_tds_section_code varchar2,
2947              p_section_type jai_ap_tds_inv_taxes.section_type%type
2948       )
2949       IS
2950       select threshold_hdr_id
2951       from   JAI_AP_TDS_TH_VSITE_V
2952       where  vendor_id = p_vendor_id
2953       and    vendor_site_id = p_vendor_site_id
2954       and    section_type = p_section_type    --rchandan for bug#4428980
2955       and    section_code = p_tds_section_code
2956       and    nvl(exception_setup_flag,'N') = 'Y';
2957 
2958       --added by Chong for bug#16580553 20130402 Begin
2959       -------------------------------------------------------------
2960       -- cursor to validate accounting date for every threshold type
2961       cursor c_valid_accounting_date (cp_thr_hdr_id number, cp_accounting_date date)
2962       is
2963       SELECT 'Y'
2964       FROM   jai_ap_tds_thhold_types
2965       WHERE  threshold_hdr_id = cp_thr_hdr_id
2966       AND    cp_accounting_date between nvl(from_date, cp_accounting_date) and nvl(to_date, cp_accounting_date);
2967       -------------------------------------------------------------
2968       --added by Chong for bug#16580553 20130402 End
2969 /*      --commented by Chong for bug#16580553 20130402 Begin
2970       -------------------------------------------------------------
2971       cursor c_get_threshold_normal(
2972              p_vendor_id number,
2973              p_vendor_site_id number,
2974              p_tds_section_code varchar2,
2975              p_section_type jai_ap_tds_inv_taxes.section_type%type
2976       )
2977       IS
2978       select threshold_hdr_id
2979       from   JAI_AP_TDS_TH_VSITE_V
2980       where  vendor_id = p_vendor_id
2981       and    vendor_site_id = p_vendor_site_id
2982       and    section_type = p_section_type    --rchandan for bug#4428980
2983       and    section_code = p_tds_section_code
2984       and    nvl(exception_setup_flag,'N') = 'N';
2985       -------------------------------------------------------------
2986       --commented by Chong for bug#16580553 20130402 End*/
2987       --added by Chong for bug#16580553 20130402 Begin
2988       -------------------------------------------------------------
2989       -- cursor to validate accounting date for every threshold type
2990       cursor c_get_threshold_normal (cp_vendor_tlc JAI_AP_TDS_VENDOR_HDRS.TDS_VENDOR_TYPE_LOOKUP_CODE%TYPE,
2991                                      cp_sec_code varchar2)
2992       is
2993       SELECT threshold_hdr_id
2994       FROM   JAI_AP_TDS_TH_VSITE_V JATVV
2995       WHERE  tds_vendor_type_lookup_code = cp_vendor_tlc
2996       AND    section_code = cp_sec_code
2997       AND    section_type = 'TDS_SECTION'
2998       AND    nvl(exception_setup_flag,'N') = 'N'
2999       AND    rownum = 1;
3000       -------------------------------------------------------------
3001       --added by Chong for bug#16580553 20130402 End
3002 
3003       CURSOR chk_prospective(
3004           cn_threshold_hdr_id number,
3005           cn_vendor_id number,
3006           cv_tan_no    JAI_AP_TDS_THHOLD_XCEPS.org_tan%type,
3007           cv_pan_no    JAI_AP_TDS_THHOLD_XCEPS.vendor_pan%type
3008       )
3009       IS
3010       SELECT
3011             PROSPECTIVE_FLAG
3012       FROM  JAI_AP_TDS_THHOLD_XCEPS
3013       WHERE THRESHOLD_HDR_ID = cn_threshold_hdr_id
3014       AND   VENDOR_ID = cn_vendor_id
3015       AND   ORG_TAN = cv_tan_no
3016       AND   VENDOR_PAN = cv_pan_no;
3017 
3018 
3019       cursor cur_thhold_grp_with_prop(
3020                           p_vendor_id number,
3021                           p_tan_no varchar2,
3022                           p_pan_no varchar2,
3023                           p_tds_section_code varchar2 ,
3024                           p_fin_year  number,
3025                           p_section_type jai_ap_tds_inv_taxes.section_type%type,
3026                           p_thhold_hdr_id number
3027       )
3028       IS
3029       select  threshold_grp_id
3030       from    jai_ap_tds_thhold_grps
3031       where   vendor_id         =  p_vendor_id
3032       and     section_type      =  p_section_type
3033       and     section_code      =  p_tds_section_code
3034       and     org_tan_num       =  p_tan_no
3035       and     vendor_pan_num    =  p_pan_no
3036       and     fin_year          =  p_fin_year
3037       and     threshold_hdr_id  =  p_thhold_hdr_id;
3038 
3039       cursor cur_thhold_grp_no_prop(
3040                           p_vendor_id number,
3041                           p_tan_no varchar2,
3042                           p_pan_no varchar2,
3043                           p_tds_section_code varchar2 ,
3044                           p_fin_year  number,
3045                           p_section_type jai_ap_tds_inv_taxes.section_type%type
3046       )
3047       IS
3048       select  threshold_grp_id
3049       from    jai_ap_tds_thhold_grps
3050       where   vendor_id         =  p_vendor_id
3051       and     section_type      =  p_section_type
3052       and     section_code      =  p_tds_section_code
3053       and     org_tan_num       =  p_tan_no
3054       and     vendor_pan_num    =  p_pan_no
3055       and     fin_year          =  p_fin_year
3056       and     nvl(threshold_hdr_id,-1)  =  -1;
3057 
3058 
3059       Cursor get_invoice_type(cn_invoice_id number)
3060       IS
3061       select invoice_type_lookup_code
3062       from   ap_invoices_all
3063       where  invoice_id = cn_invoice_id;
3064 
3065       CURSOR get_default_from_rgm(cn_org_id number)
3066       is
3067       SELECT  attribute_value
3068       FROM    JAI_RGM_ORG_REGNS_V
3069       WHERE   regime_code = 'TDS'
3070       AND     registration_type = 'OTHERS'
3071       AND     attribute_type_code = 'OTHERS'
3072       AND     attribute_code = 'TDS_DEFAULTATION'
3073       AND     organization_id = cn_org_id;
3074 
3075       --Commented by Zhiwei Hou on 20120113 begin
3076       -----------------------------------------------------------------
3077       /*cursor get_non_match_dist(cn_invoice_id number)
3078       is
3079       SELECT count(1)
3080       FROM AP_INVOICE_DISTRIBUTIONS_ALL AIDA, JAI_AP_TDS_INV_TAXES JATIT
3081       WHERE AIDA.INVOICE_ID = JATIT.INVOICE_ID
3082       and   aida.invoice_id = cn_invoice_id
3083       AND AIDA.INVOICE_DISTRIBUTION_ID = JATIT.INVOICE_DISTRIBUTION_ID
3084       AND AIDA.DIST_CODE_COMBINATION_ID <> JATIT.DIST_CODE_COMBINATION_ID
3085       and JATIT.threshold_transition is null;*/
3086       ------------------------------------------------------------------
3087       --Commented by Zhiwei Hou on 20120113 end
3088 
3089       cursor get_non_match_ven(cn_invoice_id number)
3090       is
3091       SELECT count(1)
3092       FROM AP_INVOICES_ALL AIA, JAI_AP_TDS_INV_TAXES JATIT
3093       WHERE AIA.INVOICE_ID = JATIT.INVOICE_ID
3094       and   aia.invoice_id = cn_invoice_id
3095       AND ( AIA.VENDOR_ID <> JATIT.VENDOR_ID
3096           OR AIA.VENDOR_SITE_ID <> JATIT.VENDOR_SITE_ID) -- Updated for bug13735926 by Wenqiong on 21-FEB-2012
3097       and JATIT.threshold_transition is null;
3098 
3099       --Added by Chong for bug#15939571  20121210 Start
3100       -----------------------------------------------------------------------------------------------------
3101       --When get count > 0, means AP invoice containing matched invoice lines
3102       cursor c_check_is_matched is
3103       select count(line_number)
3104       from   ap_invoice_lines_all
3105       where  invoice_id = p_invoice_id
3106       and    match_type <> 'NOT_MATCHED';
3107 
3108       cursor c_check_effective_date(cp_legal_entity_id JAI_AP_TDS_THHOLD_ACCOUNT.LEGAL_ENTITY_ID%TYPE
3109                                    ,cp_tds_section_code jai_ap_tds_default.TDS_SECTION_CODE%TYPE
3110                                    ,cp_natural_account_value jai_ap_tds_default.natural_account_value%TYPE
3111                                    ,cp_accounting_date DATE
3112       ) is
3113           select 1
3114           from   JAI_DTC_SCTN_ACCOUNT_MAPPING jdsam
3115           where  jdsam.legal_entity_id = cp_legal_entity_id
3116           and    jdsam.dtc_section_code = cp_tds_section_code
3117           and    jdsam.natural_account_value = cp_natural_account_value
3118           and    cp_accounting_date between nvl(jdsam.from_date,cp_accounting_date) and nvl(jdsam.to_date, cp_accounting_date)
3119       ;
3120 
3121 
3122 
3123       ln_cnt_matched_lines NUMBER := 0;
3124       ln_cnt_mapped_section NUMBER := 0;
3125       ln_cnt_effective_date NUMBER := 0;
3126       lv_section_code           VARCHAR2(50);
3127       -----------------------------------------------------------------------------------------------------
3128       --Added by Chong for bug#15939571  20121210 End
3129 
3130       --Added for bug#16889298 for 0% rate 20130531 Start
3131       -----------------------------------------------------------------------------------------------------
3132       CURSOR c_is_zero_rate_section (cv_section_code VARCHAR2) IS
3133       SELECT count(1) cnt
3134       FROM   fnd_lookup_values_vl
3135       WHERE  lookup_type IN ('JAI_TDS_SECTION_ZERO_RATE_197', 'JAI_TDS_SECTION_ZERO_RATE_197A')
3136       AND    lookup_code = upper(cv_section_code)
3137       ;
3138 
3139       CURSOR c_get_vendor_classification (cv_vendor_id      VARCHAR2
3140                                          ,cv_vendor_site_id VARCHAR2
3141                                          ) IS
3142       SELECT jatvh.tds_vendor_classification
3143       FROM   jai_ap_tds_vendor_hdrs jatvh
3144       WHERE  jatvh.vendor_id = cv_vendor_id
3145       AND    jatvh.vendor_site_id = cv_vendor_site_id
3146       ;
3147 
3148       ln_tds_invoice_id  NUMBER;
3149       r_is_zero_rate_section         c_is_zero_rate_section%rowtype;
3150       r_get_vendor_classification    c_get_vendor_classification%rowtype;
3151       -----------------------------------------------------------------------------------------------------
3152       --Added for bug#16889298 for 0% rate 20130531 End
3153 
3154       --Added by Zhiwei Hou for Bug#13818183 on 20120308 begin
3155       ---------------------------------------------------------
3156       ln_section_diff number;
3157       ------------------------------------------------------------
3158       --Added by Zhiwei Hou for Bug#13818183 on 20120308 end
3159 
3160       lv_default_option JAI_RGM_ORG_REGNS_V.attribute_value%type;
3161       lv_invoice_type ap_invoices_all.invoice_type_lookup_code%type;
3162       lv_natural_account  JAI_DTC_SCTN_ACCOUNT_MAPPING.natural_account_value%type;
3163       lv_prospective_flag varchar2(1);
3164       ln_hdr_id           number;
3165       ln_default_option number; --1:vendor site default; 2:TDS regime.
3166       ln_non_match_dist_id number;
3167       ln_non_match_ven_site_id number;
3168 
3169       TYPE amt_tab_type  IS TABLE OF NUMBER INDEX BY VARCHAR2(64);
3170 
3171       ppay_amt amt_tab_type;
3172 
3173       rounding_amt     amt_tab_type;
3174       secwise_sum_amt  amt_tab_type;
3175 
3176       ln_test number;
3177       ln_exception_flag varchar2(2);
3178 
3179       cursor get_first_dist_ccid(cn_invoice_id number)
3180       is
3181       select dist_code_combination_id
3182       from  ap_invoice_distributions_all
3183       where invoice_id = cn_invoice_id
3184       and distribution_line_number = 1;
3185 
3186       ln_ccid number;
3187       --------------------------------------------------------------------------------
3188       --Added by Zhiwei for Bug#13359892 DTC enhancement on 20111123 end
3189       --Added by Zhiwei Hou on 20120113 begin
3190       ----------------------------------------------------------------------------
3191       ln_tax_count number := 0;
3192       ----------------------------------------------------------------------------
3193       --Added by Zhiwei Hou on 20120113 end
3194 
3195       --Added by Zhiwei Hou on 20120203 begin
3196       -------------------------------------------------------------------
3197       ln_dbg_level   NUMBER         := FND_LOG.g_current_runtime_level;
3198       ln_proc_level  NUMBER         := FND_LOG.level_procedure;
3199       lv_proc_name   VARCHAR2 (100) := 'process_dtc_at_inv_validate';
3200       -- cursor to get information (Operating Unit ID, Legal Entity ID, Ledger ID)from ap invoices
3201       cursor c_get_inv_info(cn_invoice_id number)
3202       is
3203       SELECT
3204              LEGAL_ENTITY_ID,
3205              SET_OF_BOOKS_ID
3206 
3207       FROM   AP_INVOICES_ALL
3208       WHERE  INVOICE_ID = cn_invoice_id;
3209 
3210       ln_legal_entity_id number;
3211       ln_set_book_id     number;
3212       lv_segment_name          FND_ID_FLEX_SEGMENTS.APPLICATION_COLUMN_NAME%TYPE;
3213       -------------------------------------------------------------------
3214       --Added by Zhiwei Hou on 20120203 end
3215 
3216 
3217       ln_diff number;--Added by Zhiwei Hou for Bug#13740826
3218       ln_AcDate_diff   number;--Added by Chong.Lei for Bug#13782492
3219       lv_valid_flg     VARCHAR2(1);   --Added by Chong fof bug#16580553
3220       l_api_name                   CONSTANT  VARCHAR2(50) := 'process_dtc_at_inv_validate()';
3221     BEGIN
3222 
3223       jai_cmn_utils_pkg.WRITE_FND_LOG(G_LEVEL_PROCEDURE, G_MODULE_NAME||l_api_name||'.BEGIN', G_PKG_NAME || ': '||l_api_name||'()+');
3224       jai_cmn_utils_pkg.WRITE_FND_LOG(G_LEVEL_PROCEDURE, G_MODULE_NAME||l_api_name||'.Parameters', 'p_invoice_id: '||p_invoice_id);
3225       jai_cmn_utils_pkg.WRITE_FND_LOG(G_LEVEL_PROCEDURE, G_MODULE_NAME||l_api_name||'.Parameters', 'p_vendor_id: '||p_vendor_id);
3226       jai_cmn_utils_pkg.WRITE_FND_LOG(G_LEVEL_PROCEDURE, G_MODULE_NAME||l_api_name||'.Parameters', 'p_vendor_site_id: '||p_vendor_site_id);
3227       jai_cmn_utils_pkg.WRITE_FND_LOG(G_LEVEL_PROCEDURE, G_MODULE_NAME||l_api_name||'.Parameters', 'p_accounting_date: '||p_accounting_date);
3228       jai_cmn_utils_pkg.WRITE_FND_LOG(G_LEVEL_PROCEDURE, G_MODULE_NAME||l_api_name||'.Parameters', 'p_invoice_currency_code: '||p_invoice_currency_code);
3229       jai_cmn_utils_pkg.WRITE_FND_LOG(G_LEVEL_PROCEDURE, G_MODULE_NAME||l_api_name||'.Parameters', 'p_exchange_rate: '||p_exchange_rate);
3230       jai_cmn_utils_pkg.WRITE_FND_LOG(G_LEVEL_PROCEDURE, G_MODULE_NAME||l_api_name||'.Parameters', 'p_set_of_books_id: '||p_set_of_books_id);
3231       jai_cmn_utils_pkg.WRITE_FND_LOG(G_LEVEL_PROCEDURE, G_MODULE_NAME||l_api_name||'.Parameters', 'p_org_id: '||p_org_id);
3232       jai_cmn_utils_pkg.WRITE_FND_LOG(G_LEVEL_PROCEDURE, G_MODULE_NAME||l_api_name||'.Parameters', 'p_call_from: '|| p_call_from);
3233       jai_cmn_utils_pkg.WRITE_FND_LOG(G_LEVEL_PROCEDURE, G_MODULE_NAME||l_api_name||'.Parameters', 'p_creation_date: ' || p_creation_date);
3234       p_codepath := jai_general_pkg.plot_codepath(1, p_codepath, 'jai_ap_dtc_generation_pkg.process_dtc_at_inv_validate', 'START'); /* 1 */
3235 
3236       --Added by Chong for Bug#13802244 2012/09/17 Start
3237       ---------------------------------------------------------------------------------
3238       IF p_call_from = G_CALL_FROM_ROLLBACK THEN
3239         --When call from threshold rollback, we want to process invoice which be rollbacked from cumulative slab.
3240         --For such records, there must existing data in jai_ap_tds_inv_taxes with process_status = P
3241         --We just skip the process_status check and redefault tax , check if fall into single slab.
3242         NULL;
3243       ELSE
3244       ---------------------------------------------------------------------------------
3245       --Added by Chong for Bug#13802244 2012/09/17 End
3246 
3247         open c_check_if_exists(p_invoice_id);
3248         fetch c_check_if_exists into ln_count;
3249         close c_check_if_exists;
3250 
3251 
3252         IF ( ln_proc_level >= ln_dbg_level)
3253         THEN
3254              FND_LOG.STRING ( ln_proc_level
3255                      , GV_MODULE_PREFIX ||'.'|| lv_proc_name
3256                      , 'Check for tax count ' || ln_count
3257                      );
3258         END IF; --( ln_proc_level >= ln_dbg_level)  ;
3259 
3260         --fnd_file.put_line(FND_FILE.LOG, '1. Check for tax count'|| ln_count);
3261 
3262         /*if nvl(ln_count, 0) = 0 then
3263             p_codepath := jai_general_pkg.plot_codepath(2, p_codepath); \* 2 *\
3264             fnd_file.put_line(FND_FILE.LOG, '2. TDS tax is not applicable');
3265             p_process_flag := 'X';
3266             p_process_message := ' TDS tax is not applicable';
3267             goto exit_from_procedure;
3268         end if;*/
3269 
3270         p_codepath := jai_general_pkg.plot_codepath(3, p_codepath); /* 3 */
3271         open  c_check_if_processed(p_invoice_id,'P');
3272         fetch c_check_if_processed into ln_cnt_already_processed;
3273         close c_check_if_processed;
3274 
3275 
3276 
3277         IF ( ln_proc_level >= ln_dbg_level)
3278         THEN
3279 
3280              FND_LOG.STRING ( ln_proc_level
3281                      , GV_MODULE_PREFIX ||'.'|| lv_proc_name
3282                      , 'Check for processed already ' || ln_cnt_already_processed
3283                      );
3284         END IF; --( ln_proc_level >= ln_dbg_level)  ;
3285 
3286         --fnd_file.put_line(FND_FILE.LOG, '3. Check for processed already '|| ln_cnt_already_processed);
3287 
3288         if nvl(ln_cnt_already_processed, 0) > 0 then
3289             p_codepath := jai_general_pkg.plot_codepath(4, p_codepath); /* 4 */
3290             p_process_flag := 'X';
3291             p_process_message := 'TDS invoices have already been processed for this invoice';
3292             goto exit_from_procedure;
3293         end if;
3294 
3295 
3296         /* Update actual value from default value if actual is null for TDS section taxes only*/
3297         p_codepath := jai_general_pkg.plot_codepath(5, p_codepath); /* 5 */
3298         --Commented by Zhiwei for Bug#13359892 on 20111123, removed logic for column Default_Tax_ID
3299         /*update jai_ap_tds_inv_taxes
3300         set    actual_tax_id = default_tax_id
3301         where  nvl(consider_amt_for_tds, 'Y') = 'Y' -- Added by mmurtuza for bug12858951
3302         and    invoice_id = p_invoice_id
3303         and    actual_tax_id is null
3304         and    user_deleted_tax_flag IS NOT NULL AND user_deleted_tax_flag <> 'Y' -- nvl(user_deleted_tax_flag, 'N') <> 'Y'
3305         and    section_type = lv_tds_section_type;  --rchandan for bug#4428980
3306         */--Commented by Zhiwei for Bug#13359892 on 20111123
3307 
3308         /* Update processed for those cases where NO TDS has to be deducted for TDS section taxes only */
3309         update  jai_ap_tds_inv_taxes
3310         set     process_status = 'P'
3311         where   nvl(consider_amt_for_tds, 'Y') = 'Y' -- Added by mmurtuza for bug12858951
3312         and     invoice_id = p_invoice_id
3313         and     section_type = lv_tds_section_type;  --rchandan for bug#4428980
3314         --and     nvl(user_deleted_tax_flag, 'N') = 'Y';--
3315 
3316       END IF; -- p_call_from = G_CALL_FROM_ROLLBACK  --Added by Chong for Bug#13802244 2012/09/17
3317 
3318       p_codepath := jai_general_pkg.plot_codepath(6, p_codepath); /* 6 */
3319 
3320       open c_gl_sets_of_books(p_set_of_books_id);
3321       fetch c_gl_sets_of_books into r_gl_sets_of_books;
3322       close c_gl_sets_of_books;
3323 
3324       if r_gl_sets_of_books.currency_code <> p_invoice_currency_code then
3325           /* Foreign currency invoice */
3326           p_codepath := jai_general_pkg.plot_codepath(6.1, p_codepath); /* 6.1 */
3327           ln_exchange_rate := p_exchange_rate;
3328       end if;
3329 
3330       --Added by Zhiwei Hou for bug#13767335 on 20120305 begin
3331       /*
3332       Previously, the Amount in JAI_AP_TDS_INV_TAXES is foreign currency, so we need to transfer to INR amount for passing GENERATE_DTC_INVOICES().
3333       Now, solution changed, Amount in table will be INR currency transfered in Defaultation, so for Generation, we don't
3334       need to transfer again. so set variable ln_exchange_rate to '1'
3335       */
3336       ln_exchange_rate := 1;--Added by Zhiwei Hou for bug#13767335 on 20120305.
3337       --Added by Zhiwei Hou for bug#13767335 on 20120305 end
3338 
3339       ln_exchange_rate := nvl(ln_exchange_rate, 1);
3340 
3341       /* Get Pan number and Tan number for the vendor */
3342       open c_get_vendor_pan_tan(p_vendor_id, p_vendor_site_id);
3343       fetch c_get_vendor_pan_tan into lv_pan_no, lv_tan_no, lv_confirm_pan_flag;
3344       close c_get_vendor_pan_tan;
3345 
3346 
3347       --Added by Chong for bug#15939571  20121210 Start
3348       ---------------------------------------------------------------------------
3349       ln_rounding_factor := get_taxable_rounding(p_invoice_id);
3350       IF ln_rounding_factor IS NULL THEN
3351         p_process_flag := 'E';
3352         p_process_message := 'Rounding Rule for Tax Basis is not defined for the entered GL Period. Invoice:' || p_invoice_id;
3353         jai_cmn_utils_pkg.WRITE_FND_LOG(G_LEVEL_ERROR, G_MODULE_NAME||l_api_name, p_process_message);
3354         goto exit_from_procedure;
3355       END IF;
3356 
3357       ln_tax_rounding_factor := get_tax_rounding(p_invoice_id);
3358       IF ln_tax_rounding_factor IS NULL THEN
3359         p_process_flag := 'E';
3360         p_process_message := 'Rounding Rule for Tax is not defined for the entered GL Period. Invoice:' || p_invoice_id;
3361         jai_cmn_utils_pkg.WRITE_FND_LOG(G_LEVEL_ERROR, G_MODULE_NAME||l_api_name, p_process_message);
3362         goto exit_from_procedure;
3363       END IF;
3364       ---------------------------------------------------------------------------
3365       --Added by Chong for bug#15939571  20121210 End
3366 
3367       /*Zhiwei: comments*/
3368       --At this time , the Tax must have being in table jai_ap_tds_inv_taxes by Default logic.
3369       --Here should check Slab and Tax attached to Category is available.
3370 
3371       --ln_dtc_tax_cat_id := 10001;
3372 
3373 
3374 
3375       open c_get_inv_info(p_invoice_id);
3376       fetch c_get_inv_info into ln_legal_entity_id,ln_set_book_id;
3377       close c_get_inv_info;
3378 
3379       lv_segment_name := JAI_AP_UTILS_PKG.GET_NATURAL_ACCOUNT(ln_set_book_id,ln_legal_entity_id);
3380 
3381 
3382       open get_invoice_type(p_invoice_id);
3383       fetch get_invoice_type into lv_invoice_type;
3384       close get_invoice_type;
3385 
3386 
3387 
3388       IF lv_invoice_type = 'PREPAYMENT' THEN
3389         ln_default_option := 1;
3390         lv_default_option := G_VENDOR_SITE_DEF_SEC_CODE;   --Added by Chong for Bug#13802244 2012/09/17
3391       ELSE
3392         /*Commented out by Chong for bug#15939571  20121210 Start
3393         open get_default_from_rgm(p_org_id);
3394         fetch get_default_from_rgm into lv_default_option;
3395         close get_default_from_rgm;
3396         --Derive Defaulting Option from TDS Regime
3397         *Commented out by Chong for bug#15939571  20121210 End */
3398 
3399         --Added by Chong for bug#15939571  20121210 Start
3400         -----------------------------------------------------------------------------------------------------
3401         ----Added by Chong for bug15939571 begin
3402         --When get count > 0, means AP invoice containing matched invoice lines
3403         open c_check_is_matched;
3404         fetch c_check_is_matched into ln_cnt_matched_lines;
3405         close c_check_is_matched;
3406         jai_cmn_utils_pkg.WRITE_FND_LOG(G_LEVEL_STATEMENT, G_MODULE_NAME||l_api_name, 'ln_cnt_matched_lines: ' || ln_cnt_matched_lines);
3407 
3408         if ln_cnt_matched_lines > 0 then
3409           --PO/receipt Match AP invoice
3410           lv_default_option := G_VENDOR_SITE_DEF_SEC_CODE;
3411         else
3412           --Standalone AP invoice
3413           --Check if any Natrual account - section mapping appliable.
3414           lv_default_option := G_NTL_ACC_SEC_MAP;
3415 
3416         end if;
3417         -----------------------------------------------------------------------------------------------------
3418         --Added by Chong for bug#15939571  20121210 End
3419       END IF;
3420 
3421       --Added by Zhiwei Hou on 20120113 begin
3422       -----------------------------------------------------------------------
3423       chk_tax_exists(p_invoice_id,ln_tax_count);
3424       -----------------------------------------------------------------------
3425       --Added by Zhiwei Hou on 20120113 end
3426 
3427       --Added by Zhiwei Hou for Bug#13740826 begin
3428       -----------------------------------------------------
3429       get_amount_change(p_invoice_id, ln_diff);
3430       -----------------------------------------------------
3431       --Added by Zhiwei Hou for Bug#13740826 end
3432       --Added by Chong.Lei for Bug#13782492 begin
3433       -----------------------------------------------------
3434       chk_accounting_date(p_invoice_id, ln_AcDate_diff);
3435       -----------------------------------------------------
3436       --Added by Chong.Lei for Bug#13782492 end
3437 
3438       --Added by Zhiwei Hou for Bug#13818183 on 20120308 begin
3439       ---------------------------------------------------------
3440       get_diff_section_code(p_invoice_id,ln_section_diff);
3441       ------------------------------------------------------------
3442       --Added by Zhiwei Hou for Bug#13818183 on 20120308 end
3443 
3444       if (nvl(lv_default_option,'###') = 'Natural Account - Section Code Mapping') then
3445 
3446 
3447           --Commented and Added by Zhiwei Hou on 20120113 begin
3448           ---------------------------------------------------------
3449           get_non_match_dist(p_invoice_id, ln_non_match_dist_id);
3450 
3451           /*open get_non_match_dist(p_invoice_id);
3452           fetch get_non_match_dist into ln_non_match_dist_id;
3453           close get_non_match_dist;*/
3454           ----------------------------------------------------------
3455           --Commented and Added by Zhiwei Hou on 20120113 end
3456 
3457           --Updated by Zhiwei Hou on 20120113 begin   -- added by Chong.Lei ln_AcDate_diff for Bug#13782492
3458           -----------------------------------------------------------------------
3459           IF ln_non_match_dist_id >= 1 or ln_tax_count > 0 or ln_diff <> 0  or ln_AcDate_diff > 0
3460              OR p_call_from = G_CALL_FROM_ROLLBACK THEN --Added CALL_FROM_ROLLBACK by Chong for Bug#13802244 2012/09/17
3461           --IF ln_non_match_dist_id > 1 or ln_tax_count > 0 or ln_diff <> 0 THEN
3462           --IF ln_non_match_dist_id > 1 THEN
3463           -----------------------------------------------------------------------
3464           --Updated by Zhiwei Hou for Bug#13741805 on 20120227 end
3465               jai_ap_dtc_defaultation_pkg.default_tds_from_setup
3466               (
3467                 P_INV_ID             => p_invoice_id,
3468                 P_REDEFAULT_TAX_CATEGORY => 'Y',
3469                 P_REDEFAULT_SECTION_CODE => 'Y',
3470                 P_PROCESS_FLAG           => p_process_flag,
3471                 P_PROCESS_MESSAGE        => p_process_message
3472                 ,p_call_from             => p_call_from  --Added by Chong for Bug#13802244 2012/09/17
3473               );
3474               if p_process_flag = 'E' then
3475 
3476 
3477                          IF ( ln_proc_level >= ln_dbg_level)
3478                          THEN
3479 
3480                                FND_LOG.STRING ( ln_proc_level
3481                                        , GV_MODULE_PREFIX ||'.'|| lv_proc_name
3482                                        , '20 Process flag ' || p_process_flag
3483                                        );
3484                                FND_LOG.STRING ( ln_proc_level
3485                                        , GV_MODULE_PREFIX ||'.'|| lv_proc_name
3486                                        , '20 Process message ' || p_process_message
3487                                        );
3488                          END IF; --( ln_proc_level >= ln_dbg_level)  ;
3489 
3490                          --fnd_file.put_line(FND_FILE.LOG, '20 Process flag '|| p_process_flag);
3491                          --fnd_file.put_line(FND_FILE.LOG, '20 Process message '|| p_process_message);
3492                          p_codepath := jai_general_pkg.plot_codepath(21, p_codepath); /* 21 */
3493                          goto exit_from_procedure;
3494               end if;
3495              --Call defaulting logic (default_tds_from_setup) with P_REDEFAULT_SECTION_CODE = 'Y' and P_REDEFAULT_TAX_CATEGORY = 'Y'.
3496           ELSE
3497              jai_ap_dtc_defaultation_pkg.default_tds_from_setup
3498               (
3499                 P_INV_ID             => p_invoice_id,
3500                 P_REDEFAULT_TAX_CATEGORY => 'Y',
3501                 P_REDEFAULT_SECTION_CODE => 'N',
3502                 P_PROCESS_FLAG           => p_process_flag,
3503                 P_PROCESS_MESSAGE        => p_process_message
3504                 ,p_call_from             => p_call_from  --Added by Chong for Bug#13802244 2012/09/17
3505               );
3506               if p_process_flag = 'E' then
3507                          IF ( ln_proc_level >= ln_dbg_level)
3508                          THEN
3509 
3510                                FND_LOG.STRING ( ln_proc_level
3511                                        , GV_MODULE_PREFIX ||'.'|| lv_proc_name
3512                                        , '21 Process flag ' || p_process_flag
3513                                        );
3514                                FND_LOG.STRING ( ln_proc_level
3515                                        , GV_MODULE_PREFIX ||'.'|| lv_proc_name
3516                                        , '21 Process message ' || p_process_message
3517                                        );
3518                          END IF; --( ln_proc_level >= ln_dbg_level)  ;
3519                          --fnd_file.put_line(FND_FILE.LOG, '21 Process flag '|| p_process_flag);
3520                          --fnd_file.put_line(FND_FILE.LOG, '21 Process message '|| p_process_message);
3521                          p_codepath := jai_general_pkg.plot_codepath(21, p_codepath); /* 21 */
3522                          goto exit_from_procedure;
3523               end if;
3524              --Call defaulting logic (default_tds_from_setup) with P_REDEFAULT_SECTION_CODE = 'N' and P_REDEFAULT_TAX_CATEGORY = 'Y'.
3525           END IF;
3526 
3527       else
3528 
3529 
3530 
3531           open get_non_match_ven(p_invoice_id);
3532           fetch get_non_match_ven into ln_non_match_ven_site_id;
3533           close get_non_match_ven;
3534 
3535           --Updated by Zhiwei Hou on 20120113 begin   --Added ln_AcDate_diff by Chong.Lei for Bug#13782492
3536           --Added by Zhiwei Hou for Bug#13818183  on 20120308
3537           -----------------------------------------------------------------------
3538           IF ln_non_match_ven_site_id >= 1 or ln_tax_count > 0 or ln_diff <> 0  or ln_AcDate_diff > 0  or ln_section_diff > 0
3539             OR p_call_from = G_CALL_FROM_ROLLBACK THEN --Added CALL_FROM_ROLLBACK by Chong for Bug#13802244 2012/09/17
3540           --IF ln_non_match_ven_site_id > 1 or ln_tax_count > 0 or ln_diff <> 0 THEN
3541           --IF ln_non_match_ven_site_id > 1 THEN
3542           -----------------------------------------------------------------------
3543           --Updated by Zhiwei Hou for Bug#13741805 on 20120227 end
3544 
3545              jai_ap_dtc_defaultation_pkg.default_tds_from_setup
3546               (
3547                 P_INV_ID             => p_invoice_id,
3548                 P_REDEFAULT_TAX_CATEGORY => 'Y',
3549                 P_REDEFAULT_SECTION_CODE => 'Y',
3550                 P_PROCESS_FLAG           => p_process_flag,
3551                 P_PROCESS_MESSAGE        => p_process_message
3552                 ,p_call_from             => p_call_from  --Added by Chong for Bug#13802244 2012/09/17
3553               );
3554               if p_process_flag = 'E' then
3555                          IF ( ln_proc_level >= ln_dbg_level)
3556                          THEN
3557 
3558                                FND_LOG.STRING ( ln_proc_level
3559                                        , GV_MODULE_PREFIX ||'.'|| lv_proc_name
3560                                        , '22 Process flag ' || p_process_flag
3561                                        );
3562                                FND_LOG.STRING ( ln_proc_level
3563                                        , GV_MODULE_PREFIX ||'.'|| lv_proc_name
3564                                        , '22 Process message ' || p_process_message
3565                                        );
3566                          END IF; --( ln_proc_level >= ln_dbg_level)  ;
3567                          --fnd_file.put_line(FND_FILE.LOG, '22 Process flag '|| p_process_flag);
3568                          --fnd_file.put_line(FND_FILE.LOG, '22 Process message '|| p_process_message);
3569                          p_codepath := jai_general_pkg.plot_codepath(21, p_codepath); /* 21 */
3570                          goto exit_from_procedure;
3571               end if;
3572              --Call defaulting logic (default_tds_from_setup) with P_REDEFAULT_SECTION_CODE = 'Y' and P_REDEFAULT_TAX_CATEGORY = 'Y'.
3573           ELSE
3574              jai_ap_dtc_defaultation_pkg.default_tds_from_setup
3575               (
3576                 P_INV_ID              => p_invoice_id,
3577                 P_REDEFAULT_TAX_CATEGORY => 'Y',
3578                 P_REDEFAULT_SECTION_CODE => 'N',
3579                 P_PROCESS_FLAG           => p_process_flag,
3580                 P_PROCESS_MESSAGE        => p_process_message
3581                 ,p_call_from             => p_call_from  --Added by Chong for Bug#13802244 2012/09/17
3582               );
3583               if p_process_flag = 'E' then
3584                          IF ( ln_proc_level >= ln_dbg_level)
3585                          THEN
3586 
3587                                FND_LOG.STRING ( ln_proc_level
3588                                        , GV_MODULE_PREFIX ||'.'|| lv_proc_name
3589                                        , '23 Process flag ' || p_process_flag
3590                                        );
3591                                FND_LOG.STRING ( ln_proc_level
3592                                        , GV_MODULE_PREFIX ||'.'|| lv_proc_name
3593                                        , '23 Process message ' || p_process_message
3594                                        );
3595                          END IF; --( ln_proc_level >= ln_dbg_level)  ;
3596                          --fnd_file.put_line(FND_FILE.LOG, '23 Process flag '|| p_process_flag);
3597                          --fnd_file.put_line(FND_FILE.LOG, '23 Process message '|| p_process_message);
3598                          p_codepath := jai_general_pkg.plot_codepath(21, p_codepath); /* 21 */
3599                          goto exit_from_procedure;
3600               end if;
3601              --Call defaulting logic (default_tds_from_setup) with P_REDEFAULT_SECTION_CODE = 'N' and P_REDEFAULT_TAX_CATEGORY = 'Y'.
3602           END IF;
3603 
3604 
3605 
3606       end if;
3607 
3608 
3609       FOR c_rec1 in c_check_valid_tax(p_invoice_id)
3610       LOOP
3611 
3612         r_ja_in_tax_codes := null;
3613 
3614         ln_threshold_hdr_id := 0;
3615         --open  c_get_threshold(p_vendor_id ,p_vendor_site_id, r_ja_in_tax_codes.section_code,'TDS_SECTION'); --Commented by Jia for FP Bug#7368735
3616 
3617 
3618         --Exception Setup will take high precedence than Normal Setup.
3619         open c_get_threshold_xcep(p_vendor_id ,p_vendor_site_id, c_rec1.section_code,'TDS_SECTION');
3620         fetch c_get_threshold_xcep into ln_threshold_hdr_id;
3621         close c_get_threshold_xcep;
3622 
3623         --added by Chong for bug#16580553 20130402 Begin
3624         -------------------------------------------------------------
3625         /* Verify if Accounting Date is between the Start and End Date */
3626         if ln_threshold_hdr_id is not NULL then
3627           lv_valid_flg := null;
3628           open c_valid_accounting_date (ln_threshold_hdr_id, p_accounting_date);
3629           fetch c_valid_accounting_date into lv_valid_flg;
3630           close c_valid_accounting_date;
3631 
3632           if nvl(lv_valid_flg, 'N') = 'N' then
3633              ln_threshold_hdr_id := null;   --If no effective threshold type, use normal threshold setup
3634           end if;
3635         end if;
3636         jai_cmn_utils_pkg.WRITE_FND_LOG(G_LEVEL_STATEMENT, G_MODULE_NAME||l_api_name, 'Exception threshold heaer id: ' || ln_threshold_hdr_id);
3637         -------------------------------------------------------------
3638         --added by Chong for bug#16580553 20130402 End
3639 
3640         if nvl(ln_threshold_hdr_id,0) = 0 then
3641 
3642 	         --Added commented  by Chong for bug#16580553 20130402 Begin
3643             -------------------------------------------------------------
3644             --by given vendor and vendor site, if already existing exception transactions, will not show normal records in JAI_AP_TDS_TH_VSITE_V.
3645             --So we can't get noraml threshold setup by vendor and vendor site. we should derive normal threshold setup by vendor type
3646             open  c_po_vendors(p_vendor_id);   --Added by Chong for bug#16580553 20130402
3647             fetch c_po_vendors into lv_vendor_type_lookup_code;
3648             close c_po_vendors;
3649 
3650             open  c_get_threshold_normal(lv_vendor_type_lookup_code, c_rec1.section_code);
3651             -------------------------------------------------------------
3652             --Added commented  by Chong for bug#16580553 20130402 End
3653             --open  c_get_threshold_normal(p_vendor_id ,p_vendor_site_id, c_rec1.section_code,'TDS_SECTION');  --commented  by Chong for bug#16580553 20130402
3654             fetch c_get_threshold_normal into ln_threshold_hdr_id;
3655             close c_get_threshold_normal;
3656 
3657             if nvl(ln_threshold_hdr_id, 0) = 0 then
3658                 p_codepath := jai_general_pkg.plot_codepath(10, p_codepath);  /*10 */
3659                 p_process_flag := 'E';
3660                 p_process_message := 'Error - Threshold is not defined for the applicable TDS section :' ||
3661                                     r_ja_in_tax_codes.section_code ;
3662                 goto exit_from_procedure;
3663             end if;
3664 
3665         end if;
3666 
3667         jai_cmn_utils_pkg.WRITE_FND_LOG(G_LEVEL_STATEMENT, G_MODULE_NAME||l_api_name, 'threshold heaer id: ' || ln_threshold_hdr_id);
3668 
3669 
3670 
3671         ln_check_slab_exists := NULL;
3672         open c_check_slabs_end_dated(ln_threshold_hdr_id);
3673         fetch c_check_slabs_end_dated into ln_check_slab_exists;
3674         if ln_check_slab_exists IS NULL THEN
3675              p_process_flag := 'E';
3676              p_process_message := 'There are no active thresholds defined for this vendor';
3677              goto exit_from_procedure;
3678         end if;
3679         close c_check_slabs_end_dated;
3680 
3681       END LOOP;
3682 
3683 
3684       --Initialize the PL/SQL table ppay_amt, for TDS_SECTION, it store the SECTION_CODE LEVEL, others SECTION_TYPE level
3685       FOR r_sec in (select lookup_code from JA_LOOKUPS where lookup_type = 'JAI_TDS_SECTION')
3686       LOOP
3687           ppay_amt(r_sec.lookup_code) := 0;--Section code level.
3688       END LOOP;
3689       ppay_amt('WCT_SECTION')  := 0;--Section type level.
3690       ppay_amt('ESSI_SECTION') := 0;--Section type level.
3691 
3692       --Allocate the prepay amount to Section code level for TDS_SECTION and Section type level for WCT_SECTION and ESSI_SECTION
3693       FOR r_sec in (select lookup_code from JA_LOOKUPS where lookup_type = 'JAI_TDS_SECTION')
3694       LOOP
3695           get_prepay_invoice_amt_new(
3696                 p_invoice_id,
3697                 'TDS_SECTION',
3698                 ln_prepayment_app_amt,
3699                 r_sec.lookup_code
3700           );
3701 
3702           ppay_amt(r_sec.lookup_code) := ln_prepayment_app_amt;
3703       END LOOP;
3704 
3705       get_prepay_invoice_amt_new(
3706                 p_invoice_id,
3707                 'WCT_SECTION',
3708                 ln_prepayment_app_amt
3709       );
3710       ppay_amt('WCT_SECTION')  := ln_prepayment_app_amt;--Section type level.
3711 
3712       get_prepay_invoice_amt_new(
3713                 p_invoice_id,
3714                 'ESSI_SECTION',
3715                 ln_prepayment_app_amt
3716       );
3717       ppay_amt('ESSI_SECTION') := ln_prepayment_app_amt;--Section type level.
3718 
3719       FOR r_sum_sectionwise IN(
3720           SELECT SUM(AMOUNT) amount, ACTUAL_SECTION_CODE
3721           FROM JAI_AP_TDS_INV_TAXES
3722           WHERE INVOICE_ID = p_invoice_id
3723           AND ACTUAL_SECTION_CODE IS NOT NULL
3724           AND Threshold_TRANSITION IS NULL
3725           GROUP BY ACTUAL_SECTION_CODE
3726       )
3727       LOOP
3728 
3729           --ln_rounding_factor := get_taxable_rounding(p_invoice_id);  --Commented out by Chong for bug#15939571  20121210
3730           --Get Rounding Factor of Taxable Basis.
3731           rounding_amt(r_sum_sectionwise.actual_section_code) := Round(r_sum_sectionwise.amount, ln_rounding_factor);
3732           secwise_sum_amt(r_sum_sectionwise.actual_section_code) := r_sum_sectionwise.amount;
3733 
3734       END LOOP;
3735 
3736 
3737 
3738       for rec_update in (
3739           select *
3740           from jai_ap_tds_inv_taxes a
3741           where a.invoice_id = p_invoice_id
3742           AND a.threshold_transition IS NULL
3743           AND a.actual_section_code IS NOT NULL
3744       )
3745       loop
3746 
3747           UPDATE jai_ap_tds_inv_taxes a
3748           SET a.rounded_amount = rec_update.amount * rounding_amt(rec_update.actual_section_code)/secwise_sum_amt(rec_update.actual_section_code)
3749           WHERE a.TDS_INV_TAX_ID = rec_update.TDS_INV_TAX_ID;
3750 
3751 
3752       end loop;
3753 
3754 
3755 
3756 /*      --Populate data into JAI_AP_TDS_SECTION_TAX
3757       FOR rec_insert_tds_section_tax IN insert_tds_section_tax_cur
3758       LOOP
3759 
3760           IF rec_insert_tds_section_tax.section_type = 'TDS_SECTION' THEN
3761              ln_prepay_amount := PPAY_AMT(rec_insert_tds_section_tax.section_code);
3762           ELSE
3763              ln_prepay_amount := PPAY_AMT(rec_insert_tds_section_tax.section_type);
3764           END IF;
3765 
3766 
3767           \*OPEN chk_exist_in_section_tax(
3768                 cv_section_type    => rec_insert_tds_section_tax.section_type,
3769                 cv_section_code    => rec_insert_tds_section_tax.section_code,
3770                 cn_invoice_id      => p_invoice_id,
3771                 cn_tax_category_id => rec_insert_tds_section_tax.tax_category_id
3772           );
3773           FETCH chk_exist_in_section_tax INTO ln_count;
3774           CLOSE chk_exist_in_section_tax;*\
3775 
3776 
3777              --No record found
3778              --ln_line_id := JAI_AP_TDS_SECTION_TAX_S.nextval;
3779 
3780              for r_applied_amount in c_get_already_applied_new(
3781                                                                 p_invoice_id,
3782                                                                 rec_insert_tds_section_tax.section_type,
3783                                                                 rec_insert_tds_section_tax.section_code
3784                                                                )
3785              loop
3786 
3787                      ln_applied_amount := r_applied_amount.applied_amount;
3788 
3789              end loop;
3790 
3791 
3792              \*FOR r_tax_detail IN taxes_in_category_cur(rec_insert_tds_section_tax.tax_category_id)
3793              LOOP
3794 
3795                  insert into JAI_AP_TDS_SECTION_TAX
3796                  (
3797                         HEADER_ID	        ,
3798                         LINE_ID	          ,
3799                         SOURCE	          ,
3800                         LINE_AMOUNT	      ,
3801                         PREPAY_AMOUNT	    ,
3802                         SECTION_CODE			,
3803                         SECTION_TYPE	    ,
3804                         TAX_CATEGORY_ID	  ,
3805                         TAX_ID	          ,
3806                         TAX_LINE_NO	      ,
3807                         TAX_RATE	        ,
3808                         PRECEDENCE_1	    ,
3809                         PRECEDENCE_2	    ,
3810                         PRECEDENCE_3	    ,
3811                         PRECEDENCE_4	    ,
3812                         PRECEDENCE_5	    ,
3813                         PRECEDENCE_6	    ,
3814                         PRECEDENCE_7	    ,
3815                         PRECEDENCE_8	    ,
3816                         PRECEDENCE_9	    ,
3817                         PRECEDENCE_10	    ,
3818                         TAX_AMOUNT	      ,
3819                         FUNC_TAX_AMOUNT	  ,
3820                         BASE_TAX_AMOUNT	  ,
3821                         CREATION_DATE	    ,
3822                         CREATED_BY	      ,
3823                         LAST_UPDATE_DATE	,
3824                         LAST_UPDATE_LOGIN	,
3825                         LAST_UPDATED_BY
3826                  )values
3827                  (
3828                         p_invoice_id,
3829                         ln_line_id,
3830                         'VALIDATE',
3831                         rec_insert_tds_section_tax.amount, --line amount
3832                         ln_applied_amount,                 --prepay amount for already applied
3833                         rec_insert_tds_section_tax.section_code,
3834                         rec_insert_tds_section_tax.section_type,
3835                         rec_insert_tds_section_tax.tax_category_id,
3836                         r_tax_detail.tax_id,
3837                         r_tax_detail.line_no,
3838                         r_tax_detail.tax_rate,
3839                         r_tax_detail.precedence_1,
3840                         r_tax_detail.precedence_2,
3841                         r_tax_detail.precedence_3,
3842                         r_tax_detail.precedence_4,
3843                         r_tax_detail.precedence_5,
3844                         r_tax_detail.precedence_6,
3845                         r_tax_detail.precedence_7,
3846                         r_tax_detail.precedence_8,
3847                         r_tax_detail.precedence_9,
3848                         r_tax_detail.precedence_10,
3849                         null,--Tax  amount
3850                         null,--Func amount
3851                         null,--Base amount
3852                         sysdate,
3853                         fnd_global.user_id  ,
3854                         sysdate             ,
3855                         fnd_global.login_id ,
3856                         fnd_global.user_id
3857 
3858                  );
3859              END LOOP;--loop for category*\
3860 
3861 
3862 
3863       END LOOP;*/
3864 
3865       -- added by zhiwei.xin for bug 13792748 on 09-Mar-2012 begin
3866       for rec_category in
3867       (
3868         select nvl(tax_category_id,-999) tax_category_id
3869         from jai_ap_tds_inv_taxes
3870         where section_type  = 'TDS_SECTION'
3871         and invoice_id = p_invoice_id
3872       )
3873       loop
3874           if( (   lv_pan_no in ('PANAPPLIED','PANNOTAVBL','PANINVALID')
3875               OR  (lv_pan_no is NOT NULL and lv_confirm_pan_flag IS NULL) )
3876               and rec_category.tax_category_id = -999
3877              )
3878 
3879               then
3880               p_process_flag := 'E';
3881               p_process_message := 'Invalid PAN, deduction can not be processed due to no tax category provided on Regime.';
3882               goto exit_from_procedure;
3883           end if;
3884 
3885       end loop;
3886       -- added by zhiwei.xin for bug 13792748 on 09-Mar-2012 end.
3887 
3888       FOR cur_rec IN c_calculate_tax(p_invoice_id)
3889       LOOP
3890 
3891            IF cur_rec.section_type = 'TDS_SECTION' THEN
3892               ln_prepay_amount := PPAY_AMT(cur_rec.actual_section_code);
3893            ELSE
3894               ln_prepay_amount := PPAY_AMT(cur_rec.section_type);
3895            END IF;
3896 
3897            for r_applied_amount in c_get_already_applied_new(
3898                                                                 p_invoice_id,
3899                                                                 cur_rec.section_type,
3900                                                                 cur_rec.actual_section_code
3901                                                                )
3902            loop
3903 
3904                ln_applied_amount := r_applied_amount.applied_amount;
3905 
3906            end loop;
3907            ln_applied_amount := ln_prepay_amount;--Add by Zhiwei Hou on 20120112
3908            ln_tax_amount := nvl(cur_rec.rounded_amount,0)-nvl(ln_applied_amount,0);
3909 
3910            --ln_rounding_factor := get_taxable_rounding(p_invoice_id);
3911 
3912            --ln_tax_amount := round(ln_tax_amount,ln_rounding_factor);
3913 
3914 
3915            jai_cmn_tax_defaultation_pkg.ja_in_calc_prec_taxes
3916            (
3917              transaction_name        => 'TDS INVOICE',
3918              p_tax_category_id       => -1,
3919              p_header_id             => p_invoice_id,
3920              p_line_id               => cur_rec.invoice_distribution_id,
3921              p_tax_amount            => ln_tax_amount,
3922              p_inventory_item_id     => NULL,
3923              p_line_quantity         => NULL,
3924              p_uom_code              => NULL,
3925              p_vendor_id             => P_VENDOR_ID,
3926              p_currency              => P_INVOICE_CURRENCY_CODE,
3927              p_currency_conv_factor  => P_EXCHANGE_RATE,
3928              p_creation_date         => SYSDATE,
3929              p_created_by            => FND_GLOBAL.USER_ID,
3930              p_last_update_date      => SYSDATE,
3931              p_last_updated_by       => FND_GLOBAL.USER_ID,
3932              p_last_update_login     => FND_GLOBAL.LOGIN_ID,
3933              p_source_trx_type       => 'TDS INVOICE',
3934              p_action                => JAI_CONSTANTS.RECALCULATE_TAXES
3935            );
3936 
3937 
3938 
3939       END LOOP;
3940 
3941 
3942       /* Get vendor_type_lookup_code */
3943       p_codepath := jai_general_pkg.plot_codepath(8, p_codepath); /* 8 */
3944 
3945 
3946       open  c_po_vendors(p_vendor_id);
3947       fetch c_po_vendors into lv_vendor_type_lookup_code;
3948       close c_po_vendors;
3949 
3950 
3951       IF ( ln_proc_level >= ln_dbg_level)
3952       THEN
3953 
3954           FND_LOG.STRING ( ln_proc_level
3955                          , GV_MODULE_PREFIX ||'.'|| lv_proc_name
3956                          , ' 8. TDS Vendor type ' || lv_vendor_type_lookup_code
3957                           );
3958 
3959       END IF; --( ln_proc_level >= ln_dbg_level)  ;
3960 
3961       --fnd_file.put_line(FND_FILE.LOG,' 8. TDS Vendor type '|| lv_vendor_type_lookup_code);
3962 
3963 
3964 
3965        lv_attr_code  := 'TDS_CALENDAR';--'TAN NO';--Update by Zhiwei Hou on 20120111
3966        lv_attr_type_code := 'OTHERS';--'PRIMARY'; --Update by Zhiwei Hou on 20120111
3967        lv_tds_regime     := 'TDS';
3968        lv_regn_type_others := 'OTHERS';
3969 
3970 
3971 
3972       IF ( ln_proc_level >= ln_dbg_level)
3973       THEN
3974 
3975           FND_LOG.STRING ( ln_proc_level
3976                          , GV_MODULE_PREFIX ||'.'|| lv_proc_name
3977                          , ' 8.1 Pan number-> ' || lv_pan_no
3978                           );
3979           FND_LOG.STRING ( ln_proc_level
3980                          , GV_MODULE_PREFIX ||'.'|| lv_proc_name
3981                          , ' 8.1 Tan number-> ' || lv_tan_no
3982                           );
3983       END IF; --( ln_proc_level >= ln_dbg_level)  ;
3984 
3985 
3986       --fnd_file.put_line(FND_FILE.LOG,' 8.1 Pan number-> '|| lv_pan_no);
3987 
3988       --fnd_file.put_line(FND_FILE.LOG,' 8.1 Tan number-> '|| lv_tan_no);
3989 
3990       /* Get the fin year */
3991       open c_get_fin_year(p_accounting_date, p_org_id);
3992       fetch c_get_fin_year into ln_fin_year;
3993       close c_get_fin_year;
3994 
3995       IF ( ln_proc_level >= ln_dbg_level)
3996       THEN
3997 
3998           FND_LOG.STRING ( ln_proc_level
3999                          , GV_MODULE_PREFIX ||'.'|| lv_proc_name
4000                          , ' 8.2 Fin Year -> ' || ln_fin_year
4001                           );
4002 
4003       END IF; --( ln_proc_level >= ln_dbg_level)  ;
4004       --fnd_file.put_line(FND_FILE.LOG,' 8.2 Fin Year -> '|| ln_fin_year);
4005 
4006 
4007 
4008       FOR r_section_cod IN c_get_section_codes
4009       LOOP
4010 
4011 
4012           FOR cur_rec_section
4013           IN  c_for_each_tds_section_new(
4014                            p_invoice_id,
4015                            ln_exchange_rate,
4016                            'TDS_SECTION',
4017                            r_section_cod.SECTION_CODE,
4018                            nvl(PPAY_AMT(r_section_cod.SECTION_CODE),0)
4019               )
4020           LOOP
4021 
4022                 jai_cmn_utils_pkg.WRITE_FND_LOG(G_LEVEL_STATEMENT, G_MODULE_NAME||l_api_name, 'Process section: '||r_section_cod.SECTION_CODE);
4023                 p_codepath := jai_general_pkg.plot_codepath(9, p_codepath); /* 9 */
4024                 ln_threshold_grp_id := 0;
4025 
4026                 --Added by Zhiwei Hou on 20120109 begin
4027                 ------------------------------------------
4028                 get_threshold_hdr(
4029                       cn_vendor_id       => p_vendor_id,
4030                       cn_vendor_site_id  => p_vendor_site_id,
4031                       cv_section_type    => 'TDS_SECTION',
4032                       cv_section_code    => r_section_cod.SECTION_CODE,
4033                       p_accounting_date  => p_accounting_date,    --Added by Chong for bug#16580553
4034                       xn_hdr_id          => ln_threshold_hdr_id
4035                 );
4036                 if nvl(ln_threshold_hdr_id, 0) = 0 then
4037                     p_codepath := jai_general_pkg.plot_codepath(10, p_codepath);  /*10 */
4038                     p_process_flag := 'E';
4039                     p_process_message := 'Error - Threshold is not defined for the applicable TDS section :' ||
4040                                         r_section_cod.section_code ;
4041                     goto exit_from_procedure;
4042                 end if;
4043                 ------------------------------------------
4044                 --Added by Zhiwei Hou on 20120109 end
4045                 open c_get_exception_setup(ln_threshold_hdr_id);
4046                 fetch c_get_exception_setup into ln_exception_flag;
4047                 close c_get_exception_setup;
4048 
4049 
4050                 IF( nvl(ln_exception_flag,'N') = 'Y' ) THEN
4051 
4052                   open cur_thhold_grp_with_prop(
4053                        p_vendor_id,
4054                        lv_tan_no,
4055                        lv_pan_no,
4056                        cur_rec_section.actual_section_code,
4057                        ln_fin_year,
4058                        'TDS_SECTION',
4059                        ln_threshold_hdr_id
4060                        );
4061                   fetch cur_thhold_grp_with_prop into ln_threshold_grp_id;
4062                   close cur_thhold_grp_with_prop;
4063 
4064                 ELSE
4065 
4066                   open cur_thhold_grp_no_prop(p_vendor_id, lv_tan_no, lv_pan_no, cur_rec_section.actual_section_code, ln_fin_year,'TDS_SECTION'); --rchandan for bug#4428980
4067                   fetch cur_thhold_grp_no_prop into ln_threshold_grp_id;
4068                   close cur_thhold_grp_no_prop;
4069 
4070                 END IF;
4071 
4072 
4073                 if nvl(ln_threshold_grp_id, 0) <> 0 then
4074 
4075                     p_codepath := jai_general_pkg.plot_codepath(13, p_codepath); /* 13 */
4076 
4077                     r_jai_ap_tds_thhold_grps := null;
4078 
4079                     open  c_jai_ap_tds_thhold_grps(ln_threshold_grp_id);
4080                     fetch c_jai_ap_tds_thhold_grps into r_jai_ap_tds_thhold_grps;
4081                     close c_jai_ap_tds_thhold_grps;
4082 
4083                     ln_total_invoice_amount := r_jai_ap_tds_thhold_grps.total_invoice_amount;
4084 
4085                 else
4086 
4087                     p_codepath := jai_general_pkg.plot_codepath(14, p_codepath); /* 14 */
4088 
4089                     ln_total_invoice_amount := 0;
4090 
4091                 end if;
4092 
4093                 --Added by Chong for Bug#13802244 2012/09/17 Start
4094                 ------------------------------------------------------------------------------------------
4095                 IF p_call_from = G_CALL_FROM_ROLLBACK THEN
4096                   --when call from threshold rollback, do not need to maintain invoice amount for group.
4097                   NULL;
4098                 ELSE
4099                 ------------------------------------------------------------------------------------------
4100                 --Added by Chong for Bug#13802244 2012/09/17 End
4101                   if nvl(ln_threshold_grp_id, 0) = 0 then
4102 
4103                      p_codepath := jai_general_pkg.plot_codepath(19.1, p_codepath); /* 19.1 */
4104 
4105                      fnd_file.put_line(FND_FILE.LOG, '19.1 Call maintain thhold grps ');
4106 
4107                      if (ln_exception_flag = 'Y') then
4108                         ln_hdr_id := ln_threshold_hdr_id;
4109                      else
4110                         ln_hdr_id := null;
4111                      end if;
4112 
4113 
4114                      maintain_thhold_grps
4115                      (
4116                         p_threshold_grp_id             =>   ln_threshold_grp_id,
4117                         p_vendor_id                    =>   p_vendor_id,
4118                         p_org_tan_num                  =>   lv_tan_no,
4119                         p_vendor_pan_num               =>   lv_pan_no,
4120                         p_section_type                 =>   'TDS_SECTION',
4121                         p_section_code                 =>   cur_rec_section.actual_section_code,
4122                         p_fin_year                     =>   ln_fin_year,
4123                         p_org_id                       =>   p_org_id,
4124                         p_trx_invoice_amount           =>   cur_rec_section.invoice_amount,
4125                         p_tds_event                    =>   'INVOICE VALIDATE',
4126                         p_invoice_id                   =>   p_invoice_id,
4127                         p_threshold_grp_audit_id       =>   ln_threshold_grp_audit_id,
4128                         --Added by Zhiwei.Hou for Bug#13359892 DTC enhancement on 20111130 begin
4129                         ---------------------------------------------------------------------------
4130                         p_threshold_hdr_id             =>   ln_hdr_id,
4131                         ---------------------------------------------------------------------------
4132                         --Added by Zhiwei.Hou for Bug#13359892 DTC enhancement on 20111130 end
4133                         -- Bug 5722028. Added by CSahoo
4134                         p_creation_Date                =>   p_creation_date,
4135                         p_process_flag                 =>   p_process_flag,
4136                         P_process_message              =>   P_process_message,
4137                         p_codepath                     =>   p_codepath
4138                       );
4139 
4140 
4141                       IF ( ln_proc_level >= ln_dbg_level)
4142                       THEN
4143 
4144                           FND_LOG.STRING ( ln_proc_level
4145                                          , GV_MODULE_PREFIX ||'.'|| lv_proc_name
4146                                          , ' 19.1 Process flag -> ' || p_process_flag
4147                                           );
4148                           FND_LOG.STRING ( ln_proc_level
4149                                          , GV_MODULE_PREFIX ||'.'|| lv_proc_name
4150                                          , ' 19.1 Process message -> ' || p_process_message
4151                                           );
4152                       END IF; --( ln_proc_level >= ln_dbg_level)  ;
4153 
4154                       --fnd_file.put_line(FND_FILE.LOG, '19.1 Process flag '|| p_process_flag);
4155                       --fnd_file.put_line(FND_FILE.LOG, '19.1 Process message '|| p_process_message);
4156 
4157                   else
4158 
4159                     p_codepath := jai_general_pkg.plot_codepath(19.2, p_codepath); /* 19.2 */
4160 
4161                      jai_ap_dtc_generation_pkg.maintain_thhold_grps
4162                      (
4163                         p_threshold_grp_id             =>   ln_threshold_grp_id,
4164                         p_trx_invoice_amount           =>   cur_rec_section.invoice_amount,
4165                         p_tds_event                    =>   'INVOICE VALIDATE',
4166                         p_invoice_id                   =>   p_invoice_id,
4167                         p_threshold_grp_audit_id       =>   ln_threshold_grp_audit_id,
4168                         p_process_flag                 =>   p_process_flag,
4169                         P_process_message              =>   P_process_message,
4170                         p_codepath                     =>   p_codepath
4171                       );
4172                       IF ( ln_proc_level >= ln_dbg_level)
4173                       THEN
4174 
4175                           FND_LOG.STRING ( ln_proc_level
4176                                          , GV_MODULE_PREFIX ||'.'|| lv_proc_name
4177                                          , ' 19.2 Process flag -> ' || p_process_flag
4178                                           );
4179                           FND_LOG.STRING ( ln_proc_level
4180                                          , GV_MODULE_PREFIX ||'.'|| lv_proc_name
4181                                          , ' 19.2 Process message -> ' || p_process_message
4182                                           );
4183                       END IF; --( ln_proc_level >= ln_dbg_level)  ;
4184                       fnd_file.put_line(FND_FILE.LOG, '19.2 Process flag '|| p_process_flag);
4185                       fnd_file.put_line(FND_FILE.LOG, '19.2 Process message '|| p_process_message);
4186 
4187 
4188                   end if;
4189 
4190                   IF p_process_flag = 'E' THEN
4191 
4192                      p_codepath := jai_general_pkg.plot_codepath(19.3, p_codepath); /* 19.3 */
4193                      goto exit_from_procedure;
4194 
4195                   END IF;
4196                 END IF; --p_call_from = G_CALL_FROM_ROLLBACK    --Added by Chong for Bug#13802244 2012/09/17
4197                 ----------------------------------------------------------------------------
4198 
4199 
4200                 --ln_threshold_hdr_id := 0;  --commented by xiao for bug#6596019
4201                 ln_threshold_slab_id_before := null;
4202                 ln_threshold_slab_id_after:= null;
4203                 ln_threshold_slab_id_single := null;
4204 
4205                 IF ( ln_proc_level >= ln_dbg_level)
4206                 THEN
4207 
4208                         FND_LOG.STRING ( ln_proc_level
4209                                        , GV_MODULE_PREFIX ||'.'|| lv_proc_name
4210                                        , ' 9 Threshold hdr id -> ' || ln_threshold_hdr_id
4211                                         );
4212 
4213                 END IF; --( ln_proc_level >= ln_dbg_level)  ;
4214                 --fnd_file.put_line(FND_FILE.LOG,' 9. Threshold hdr id-> '|| ln_threshold_hdr_id);
4215 
4216 
4217                 /* Get the threshold group id */
4218                 p_codepath := jai_general_pkg.plot_codepath(11, p_codepath); /* 11 */
4219                 /*
4220                 Threshold Group to be maintained based on Threshold Header ID, PAN Number, Vendor ID, TAN Number, Financial Year and TDS Section if the Vendor has Exception Setup and Tax Calculation is Prospective.
4221                 If Tax Calculation is not prospective use the existing Threshold Group or create a Threshold Group based on PAN Number, Vendor ID, TAN Number, Financial Year and TDS Section
4222                 */
4223 
4224                 --if prospective enabled then add threshold header id to combination
4225                 --else remain existing logic.
4226 
4227 
4228 
4229                 OPEN chk_prospective(
4230                      ln_threshold_hdr_id,
4231                      p_vendor_id,
4232                      lv_tan_no,
4233                      lv_pan_no
4234                 );
4235                 fetch chk_prospective into lv_prospective_flag;
4236                 close chk_prospective;
4237 
4238                 lv_prospective_flag := nvl(lv_prospective_flag,'N');
4239 
4240                 /*if( nvl(lv_prospective_flag,'N') = 'Y' ) then
4241 
4242                   open cur_thhold_grp_with_prop(
4243                        p_vendor_id,
4244                        lv_tan_no,
4245                        lv_pan_no,
4246                        cur_rec_section.actual_section_code,
4247                        ln_fin_year,
4248                        'TDS_SECTION',
4249                        ln_threshold_hdr_id
4250                        );
4251                   fetch cur_thhold_grp_with_prop into ln_threshold_grp_id;
4252                   close cur_thhold_grp_with_prop;
4253 
4254                 else
4255 
4256                   open cur_thhold_grp_no_prop(p_vendor_id, lv_tan_no, lv_pan_no, cur_rec_section.actual_section_code, ln_fin_year,'TDS_SECTION'); --rchandan for bug#4428980
4257                   fetch cur_thhold_grp_no_prop into ln_threshold_grp_id;
4258                   close cur_thhold_grp_no_prop;
4259 
4260                 end if;*/
4261 
4262 
4263 
4264                 IF ( ln_proc_level >= ln_dbg_level)
4265                 THEN
4266 
4267                         FND_LOG.STRING ( ln_proc_level
4268                                        , GV_MODULE_PREFIX ||'.'|| lv_proc_name
4269                                        , '11. Threshold grp id ->' || ln_threshold_grp_id
4270                                         );
4271 
4272                 END IF; --( ln_proc_level >= ln_dbg_level)  ;
4273                 --fnd_file.put_line(FND_FILE.LOG, '11. Threshold grp id ->'||ln_threshold_grp_id);
4274 
4275                 /* Get the threshold group details */
4276                 p_codepath := jai_general_pkg.plot_codepath(12, p_codepath); /* 12 */
4277 
4278                 /*if nvl(ln_threshold_grp_id, 0) <> 0 then
4279 
4280                     p_codepath := jai_general_pkg.plot_codepath(13, p_codepath); \* 13 *\
4281 
4282                     r_jai_ap_tds_thhold_grps := null;
4283 
4284                     open  c_jai_ap_tds_thhold_grps(ln_threshold_grp_id);
4285                     fetch c_jai_ap_tds_thhold_grps into r_jai_ap_tds_thhold_grps;
4286                     close c_jai_ap_tds_thhold_grps;
4287 
4288                     ln_total_invoice_amount := r_jai_ap_tds_thhold_grps.total_invoice_amount;
4289 
4290                 else
4291 
4292                     p_codepath := jai_general_pkg.plot_codepath(14, p_codepath); \* 14 *\
4293 
4294                     ln_total_invoice_amount := 0;
4295 
4296                 end if;*/
4297                 IF ( ln_proc_level >= ln_dbg_level)
4298                 THEN
4299 
4300                         FND_LOG.STRING ( ln_proc_level
4301                                        , GV_MODULE_PREFIX ||'.'|| lv_proc_name
4302                                        , '12. Total invoice amount -> ' || ln_total_invoice_amount
4303                                         );
4304 
4305                 END IF; --( ln_proc_level >= ln_dbg_level)  ;
4306                 --fnd_file.put_line(FND_FILE.LOG, '12. Total invoice amount -> '||ln_total_invoice_amount);
4307 
4308                 /* Get the threshold position before this invoice impact */
4309                 p_codepath := jai_general_pkg.plot_codepath(15, p_codepath); /* 15 */
4310 
4311                 ---=======================================================================
4312 
4313 
4314 --                open get_first_dist_ccid(p_invoice_id);
4315 --                fetch get_first_dist_ccid into ln_ccid;
4316 --                close get_first_dist_ccid;
4317                   p_get_one_ccid_id(p_invoice_id,ln_ccid);
4318 
4319                 lv_natural_account := JAI_AP_UTILS_PKG.GET_NATURAL_ACCOUNT_VALUE(ln_ccid,lv_segment_name);
4320 
4321 
4322 
4323                 open c_get_multiple_rate_setup(ln_threshold_hdr_id);
4324                 fetch c_get_multiple_rate_setup into lv_multiple_rate_setup;
4325                 close c_get_multiple_rate_setup;
4326 
4327 
4328                 if(lv_multiple_rate_setup = 'Y' AND lv_default_option = G_NTL_ACC_SEC_MAP)then --Added lv_default_option by Chong for Bug#13802244 2012/09/21
4329                     open  c_jai_ap_tds_thhold_slabs_new(ln_threshold_hdr_id , 'CUMULATIVE' , ln_total_invoice_amount,lv_natural_account ,ln_legal_entity_id);
4330                     --Added ln_legal_entity_id by Chong for Bug#13802244 2012/09/21
4331                     fetch c_jai_ap_tds_thhold_slabs_new into r_jai_ap_tds_thhold_slabs;
4332                     close c_jai_ap_tds_thhold_slabs_new  ;
4333 
4334                     --Added by Chong for bug#16248896 Start
4335                     if r_jai_ap_tds_thhold_slabs.threshold_slab_id is null then
4336                       open  c_jai_ap_tds_thhold_slabs(ln_threshold_hdr_id , 'CUMULATIVE' , ln_total_invoice_amount);
4337                       fetch c_jai_ap_tds_thhold_slabs into r_jai_ap_tds_thhold_slabs;
4338                       close c_jai_ap_tds_thhold_slabs;
4339                     end if;
4340                     --Added by Chong for bug#16248896 End
4341                 else
4342                     open  c_jai_ap_tds_thhold_slabs(ln_threshold_hdr_id , 'CUMULATIVE' , ln_total_invoice_amount);
4343                     fetch c_jai_ap_tds_thhold_slabs into r_jai_ap_tds_thhold_slabs;
4344                     close c_jai_ap_tds_thhold_slabs;
4345                 end if;
4346 
4347 
4348                 ln_threshold_slab_id_before := nvl(r_jai_ap_tds_thhold_slabs.threshold_slab_id, 0);
4349 
4350                 IF ( ln_proc_level >= ln_dbg_level)
4351                 THEN
4352 
4353                         FND_LOG.STRING ( ln_proc_level
4354                                        , GV_MODULE_PREFIX ||'.'|| lv_proc_name
4355                                        , '15. Threshold slab id before ' || ln_threshold_slab_id_before
4356                                         );
4357 
4358                 END IF; --( ln_proc_level >= ln_dbg_level)  ;
4359                 --fnd_file.put_line(FND_FILE.LOG, '15. Threshold slab id before '||ln_threshold_slab_id_before);
4360 
4361                 /* Get the threshold position after this invoice impact */
4362                 p_codepath := jai_general_pkg.plot_codepath(16, p_codepath); /* 16 */
4363 
4364                 r_jai_ap_tds_thhold_slabs := null;
4365 
4366                 --Added by Chong for Bug#13802244 2012/09/17 Start
4367                 -------------------------------------------------------------------------------------------
4368                 r_jai_ap_tds_thhold_grps := null;
4369                 open  c_jai_ap_tds_thhold_grps(ln_threshold_grp_id);
4370                 fetch c_jai_ap_tds_thhold_grps into r_jai_ap_tds_thhold_grps;
4371                 close c_jai_ap_tds_thhold_grps;
4372                 ln_total_invoice_amount := r_jai_ap_tds_thhold_grps.total_invoice_amount;
4373                 -------------------------------------------------------------------------------------------
4374                 --Added by Chong for Bug#13802244 2012/09/17 End
4375 
4376 
4377                 if(lv_multiple_rate_setup = 'Y' AND lv_default_option = G_NTL_ACC_SEC_MAP)then  --Added lv_default_option by Chong for Bug#13802244 2012/09/21
4378                     open c_jai_ap_tds_thhold_slabs_new(
4379                      ln_threshold_hdr_id ,
4380                      'CUMULATIVE' ,
4381                      --ln_total_invoice_amount + cur_rec_section.invoice_amount,  --Commented by Chong for Bug#13802244 2012/09/17
4382                      ln_total_invoice_amount,  --Added by Chong for Bug#13802244 2012/09/17
4383                      lv_natural_account,
4384                      ln_legal_entity_id        --Added ln_legal_entity_id by Chong for Bug#13802244 2012/09/21
4385                      );
4386                     fetch c_jai_ap_tds_thhold_slabs_new into r_jai_ap_tds_thhold_slabs;
4387                     close c_jai_ap_tds_thhold_slabs_new;
4388 
4389                     --Added by Chong for bug#16248896 Start
4390                     if r_jai_ap_tds_thhold_slabs.threshold_slab_id is null then
4391                         open c_jai_ap_tds_thhold_slabs(
4392                          ln_threshold_hdr_id ,
4393                          'CUMULATIVE' ,
4394                          ln_total_invoice_amount
4395                          );
4396                         fetch c_jai_ap_tds_thhold_slabs into r_jai_ap_tds_thhold_slabs;
4397                         close c_jai_ap_tds_thhold_slabs;
4398                     end if;
4399                     --Added by Chong for bug#16248896 End
4400                 else
4401                     open c_jai_ap_tds_thhold_slabs(
4402                      ln_threshold_hdr_id ,
4403                      'CUMULATIVE' ,
4404                      --ln_total_invoice_amount + cur_rec_section.invoice_amount  --Commented by Chong for Bug#13802244 2012/09/17
4405                      ln_total_invoice_amount  --Added by Chong for Bug#13802244 2012/09/17
4406                      );
4407                     fetch c_jai_ap_tds_thhold_slabs into r_jai_ap_tds_thhold_slabs;
4408                     close c_jai_ap_tds_thhold_slabs;
4409                 end if;
4410 
4411 
4412 
4413                 ln_threshold_slab_id_after := nvl(r_jai_ap_tds_thhold_slabs.threshold_slab_id, 0);
4414                 IF ( ln_proc_level >= ln_dbg_level)
4415                 THEN
4416 
4417                         FND_LOG.STRING ( ln_proc_level
4418                                        , GV_MODULE_PREFIX ||'.'|| lv_proc_name
4419                                        , '15. Threshold slab id after ' || ln_threshold_slab_id_after
4420                                         );
4421 
4422                 END IF; --( ln_proc_level >= ln_dbg_level)  ;
4423                 --fnd_file.put_line(FND_FILE.LOG, '16. Threshold slab id after ->'|| ln_threshold_slab_id_after);
4424 
4425                 p_codepath := jai_general_pkg.plot_codepath(17, p_codepath); /* 17 */
4426 
4427                 if ln_threshold_slab_id_after <> 0 then
4428                 /* Threshold has reached */
4429                   p_codepath := jai_general_pkg.plot_codepath(18, p_codepath); /* 18 */
4430                   lv_generate_all_invoices := 'Y';
4431                 else
4432                   lv_generate_all_invoices := 'N';
4433                   p_codepath := jai_general_pkg.plot_codepath(19, p_codepath); /* 19 */
4434                 end if; /* if ln_threshold_slab_id_after <> 0 */
4435                 IF ( ln_proc_level >= ln_dbg_level)
4436                 THEN
4437 
4438                         FND_LOG.STRING ( ln_proc_level
4439                                        , GV_MODULE_PREFIX ||'.'|| lv_proc_name
4440                                        , '19. Generate invoices -> ' || lv_generate_all_invoices
4441                                         );
4442 
4443                 END IF; --( ln_proc_level >= ln_dbg_level)  ;
4444                 --fnd_file.put_line(FND_FILE.LOG, '19. Generate invoices -> ' || lv_generate_all_invoices);
4445 
4446 
4447                 /* Check for Single Invoice threshold if cumulative has not been reached */
4448                 if lv_generate_all_invoices = 'N' then
4449                   /* Cumulative threshold not reached */
4450                   r_jai_ap_tds_thhold_slabs := null;
4451 
4452                   if(lv_multiple_rate_setup = 'Y' AND lv_default_option = G_NTL_ACC_SEC_MAP)then  --Added lv_default_option by Chong for Bug#13802244 2012/09/21
4453                       open c_jai_ap_tds_thhold_slabs_new(ln_threshold_hdr_id , 'SINGLE' , cur_rec_section.invoice_amount,lv_natural_account, ln_legal_entity_id);
4454                       --Added ln_legal_entity_id by Chong for Bug#13802244 2012/09/21
4455                       fetch c_jai_ap_tds_thhold_slabs_new into r_jai_ap_tds_thhold_slabs;
4456                       close c_jai_ap_tds_thhold_slabs_new;
4457 
4458                       --Added by Chong for bug#16248896 Start
4459                       if r_jai_ap_tds_thhold_slabs.threshold_slab_id is null then
4460                           open c_jai_ap_tds_thhold_slabs(ln_threshold_hdr_id , 'SINGLE' , cur_rec_section.invoice_amount);
4461                           fetch c_jai_ap_tds_thhold_slabs into r_jai_ap_tds_thhold_slabs;
4462                           close c_jai_ap_tds_thhold_slabs;
4463                       end if;
4464                       --Added by Chong for bug#16248896 End
4465                   else
4466                       open c_jai_ap_tds_thhold_slabs(ln_threshold_hdr_id , 'SINGLE' , cur_rec_section.invoice_amount);
4467                       fetch c_jai_ap_tds_thhold_slabs into r_jai_ap_tds_thhold_slabs;
4468                       close c_jai_ap_tds_thhold_slabs;
4469                   end if;
4470 
4471 
4472                   ln_threshold_slab_id_single := nvl(r_jai_ap_tds_thhold_slabs.threshold_slab_id, 0);
4473                   jai_cmn_utils_pkg.WRITE_FND_LOG(G_LEVEL_STATEMENT, G_MODULE_NAME||l_api_name, '19.1. ln_threshold_slab_id_single: ' || ln_threshold_slab_id_single);
4474                 end if;
4475 
4476                 --====================================================
4477                 /* Loop and generate invoices */
4478 
4479 
4480                 FOR cur_rec IN
4481                     c_get_taxes_to_generate_tds(
4482                             p_invoice_id ,
4483                             cur_rec_section.actual_section_code,
4484                             lv_generate_all_invoices,
4485                             ln_exchange_rate,
4486                             ln_threshold_slab_id_single,
4487                             'TDS_SECTION',
4488                             nvl(PPAY_AMT(r_section_cod.SECTION_CODE),0)
4489                     )
4490                 LOOP
4491 
4492                     p_codepath := jai_general_pkg.plot_codepath(20, p_codepath); /* 20 */
4493 
4494                     /*START, Bgowrava for Bug# 8254510*/
4495                     ln_tds_tax_amount := cur_rec.tax_amount;
4496 
4497                     --Add by Zhiwei Hou on 20120109 begin
4498                     --ln_tds_tax_amount := round(ln_tds_tax_amount,get_tax_rounding(p_invoice_id));  --Commented by Chong for bug#15939571  20121210
4499                     --Add by Zhiwei Hou on 20120109 end
4500                     ln_tds_tax_amount := round(ln_tds_tax_amount,ln_tax_rounding_factor);  --Added by Chong for bug#15939571  20121210
4501 
4502                     /*if ln_threshold_slab_id_before <> ln_threshold_slab_id_after then
4503 
4504                         open c_jai_slab_start_amt(ln_threshold_slab_id_after);
4505                         fetch c_jai_slab_start_amt into r_jai_slab_start_amt_after;
4506                         close c_jai_slab_start_amt;
4507 
4508                         open c_jai_slab_start_amt(ln_threshold_slab_id_before);
4509                         fetch c_jai_slab_start_amt into r_jai_slab_start_amt_before;
4510                         close c_jai_slab_start_amt;
4511 
4512                         if ln_threshold_slab_id_before <> 0 and r_jai_slab_start_amt_before.tax_rate_orig <> r_jai_slab_start_amt_after.tax_rate_orig then
4513                             ln_tds_amt_before := r_jai_slab_start_amt_after.from_amount - ln_total_invoice_amount;
4514                             ln_tds_amt_after := cur_rec.taxable_amount - ln_tds_amt_before;
4515 
4516                             ln_tds_tax_amount := (ln_tds_amt_before*(nvl(r_jai_slab_start_amt_before.tax_rate, 0)/100))
4517                                      + (ln_tds_amt_after*(nvl(r_jai_slab_start_amt_after.tax_rate, 0)/100));
4518                         end if;
4519                     end if;*/
4520                     /*END, Bgowrava for Bug#8254510 */
4521 
4522                     ln_threshold_trx_id := 0;
4523                     lv_tds_invoice_num  := null;
4524                     lv_tds_cm_num       := null;
4525                     p_process_flag      := null;
4526 
4527 
4528                     IF ( ln_proc_level >= ln_dbg_level)
4529                     THEN
4530 
4531                             FND_LOG.STRING ( ln_proc_level
4532                                            , GV_MODULE_PREFIX ||'.'|| lv_proc_name
4533                                            , '20. Call generate tds invoices' || ''
4534                                             );
4535                             FND_LOG.STRING ( ln_proc_level
4536                                            , GV_MODULE_PREFIX ||'.'|| lv_proc_name
4537                                            , ' Tax amount while calling generate tds invoices ' || cur_rec.tax_amount
4538                                             );
4539                     END IF; --( ln_proc_level >= ln_dbg_level)  ;
4540 
4541                     --fnd_file.put_line(FND_FILE.LOG, '20. Call generate tds invoices' );
4542 
4543                     --fnd_file.put_line(FND_FILE.LOG, ' Tax amount while calling generate tds invoices '|| cur_rec.tax_amount);
4544 
4545                     jai_ap_dtc_generation_pkg.generate_dtc_invoices
4546 
4547                     (
4548                       pn_invoice_id              =>      p_invoice_id           ,
4549                       pn_threshold_hdr_id        =>      ln_threshold_hdr_id    ,
4550                       pn_taxable_amount          =>      cur_rec.taxable_amount ,
4551                       pn_tax_amount              =>      ln_tds_tax_amount     ,  --Added by Bgowrava for Bug#8254510
4552                       pn_tax_category_id         =>      cur_rec.tax_category_id  ,
4553                       pv_section_type            =>      'TDS_SECTION',
4554                       pv_section_code            =>      cur_rec_section.actual_section_code,
4555                       pd_accounting_date         =>      p_accounting_date      ,
4556                       pv_tds_event               =>      'INVOICE VALIDATE'     ,
4557                       pn_threshold_grp_id        =>      ln_threshold_grp_id    ,
4558                       pv_tds_invoice_num         =>      lv_tds_invoice_num     ,
4559                       pv_cm_invoice_num          =>      lv_tds_cm_num          ,
4560                       pn_threshold_trx_id        =>      ln_threshold_trx_id    ,
4561                       pd_creation_date           =>      p_creation_date        ,
4562                       pn_calc_tax_amount         =>      0, /* Added for bug 12965614 */
4563                       p_process_flag             =>      p_process_flag         ,
4564                       p_process_message          =>      p_process_message
4565                     );
4566 
4567 
4568                     if p_process_flag = 'E' then
4569                          IF ( ln_proc_level >= ln_dbg_level)
4570                          THEN
4571 
4572                                   FND_LOG.STRING ( ln_proc_level
4573                                                  , GV_MODULE_PREFIX ||'.'|| lv_proc_name
4574                                                  , '20 Process flag ' || p_process_flag
4575                                                   );
4576                                   FND_LOG.STRING ( ln_proc_level
4577                                                  , GV_MODULE_PREFIX ||'.'|| lv_proc_name
4578                                                  , '20 Process message ' || p_process_message
4579                                                   );
4580                          END IF; --( ln_proc_level >= ln_dbg_level)  ;
4581                          --fnd_file.put_line(FND_FILE.LOG, '20 Process flag '|| p_process_flag);
4582                          --fnd_file.put_line(FND_FILE.LOG, '20 Process message '|| p_process_message);
4583                          p_codepath := jai_general_pkg.plot_codepath(21, p_codepath); /* 21 */
4584                          goto exit_from_procedure;
4585                     end if;
4586 
4587                     p_codepath := jai_general_pkg.plot_codepath(22, p_codepath); /* 22 */
4588 
4589                     if ln_start_threshold_trx_id is null then
4590                          ln_start_threshold_trx_id := ln_threshold_trx_id;
4591                     end if;
4592 
4593 
4594                     IF ( ln_proc_level >= ln_dbg_level)
4595                     THEN
4596 
4597                                   FND_LOG.STRING ( ln_proc_level
4598                                                  , GV_MODULE_PREFIX ||'.'|| lv_proc_name
4599                                                  , ' 22. start thhold trx id ' || ln_start_threshold_trx_id
4600                                                   );
4601 
4602                     END IF; --( ln_proc_level >= ln_dbg_level)  ;
4603 
4604                     --fnd_file.put_line(FND_FILE.LOG,' 22. start thhold trx id '||ln_start_threshold_trx_id);
4605 
4606                     --fnd_file.put_line(FND_FILE.LOG, ' Bug 7280925 - value of tmp tds before maintain thhold grps'||ln_tax_amount);
4607 
4608                     p_codepath := jai_general_pkg.plot_codepath(23, p_codepath); /* 23 */
4609 
4610                     jai_ap_dtc_generation_pkg.maintain_thhold_grps
4611                     (
4612                         p_threshold_grp_id             =>   ln_threshold_grp_id,
4613                         p_trx_tax_paid                 =>   ln_tds_tax_amount,
4614                         p_tds_event                    =>   'INVOICE VALIDATE', --Added by Bgowrava for Bug#8254510
4615                         p_invoice_id                   =>   p_invoice_id,
4616                         p_threshold_grp_audit_id       =>   ln_threshold_grp_audit_id,
4617                         -- Bug 5722028. Added by Lakshmi Gopalsami
4618                         p_creation_date                =>   p_creation_date,
4619                         p_process_flag                 =>   p_process_flag,
4620                         P_process_message              =>   P_process_message,
4621                         p_codepath                     =>   p_codepath
4622                     );
4623                     IF ( ln_proc_level >= ln_dbg_level)
4624                     THEN
4625 
4626                                   FND_LOG.STRING ( ln_proc_level
4627                                                  , GV_MODULE_PREFIX ||'.'|| lv_proc_name
4628                                                  , '23 Process flag ' || p_process_flag
4629                                                   );
4630                                   FND_LOG.STRING ( ln_proc_level
4631                                                  , GV_MODULE_PREFIX ||'.'|| lv_proc_name
4632                                                  , '23 Process message ' || p_process_message
4633                                                   );
4634                     END IF; --( ln_proc_level >= ln_dbg_level)  ;
4635                     --fnd_file.put_line(FND_FILE.LOG, '23 Process flag '|| p_process_flag);
4636                     --fnd_file.put_line(FND_FILE.LOG, '23 Process message '|| p_process_message);
4637 
4638                     --Added by Sanjikum for Bug#5131075(4722011)
4639                     IF p_process_flag = 'E' THEN
4640                       p_codepath := jai_general_pkg.plot_codepath(23.1, p_codepath); /* 23.1 */
4641                       goto exit_from_procedure;
4642                     END IF;
4643 
4644 
4645                     /* Punch threshold_trx_id in jai_ap_tds_inv_taxes */
4646                     update  jai_ap_tds_inv_taxes
4647                     set     threshold_trx_id =  ln_threshold_trx_id,
4648                             threshold_slab_id_single = ln_threshold_slab_id_single
4649                     where   nvl(consider_amt_for_tds, 'Y') = 'Y' -- Added by mmurtuza for bug12858951
4650                     and     invoice_id = p_invoice_id
4651                     and     section_type      =  lv_tds_section_type   --rchandan for bug#4428980
4652                     and     actual_section_code = cur_rec_section.actual_section_code
4653                     --and     nvl(actual_tax_id, default_tax_id) = cur_rec.actual_tax_id   --Added nvl by Xiao for bug#7154864
4654                     and     tax_category_id  = cur_rec.tax_category_id
4655                     and     (
4656                               (lv_generate_all_invoices = 'Y' )
4657                                or
4658                               (ln_threshold_slab_id_single > 0)
4659                               or
4660                               (tax_category_id is not null)
4661                               --(actual_tax_id is NOT NULL) --added by Xiao for bug#7154864
4662                             );
4663 
4664                     ln_no_of_tds_inv_generated := ln_no_of_tds_inv_generated + 2;
4665                     /* TDS invoices are always generated in pair */
4666 
4667                     p_codepath := jai_general_pkg.plot_codepath(24, p_codepath); /* 24 */
4668                 END LOOP;
4669                 /* Loop and generate invoices */
4670 
4671                 --Added by Chong for bug#16414088 eTDS ER Start
4672                 ----------------------------------------------------------------------
4673                 --Hook code add here after the loop of call generate_dtc_invoices
4674                 IF ln_threshold_trx_id IS NULL  THEN   -- no TDS generated
4675                   jai_cmn_utils_pkg.WRITE_FND_LOG(G_LEVEL_STATEMENT, G_MODULE_NAME||l_api_name, 'ln_threshold_trx_id: ' || ln_threshold_trx_id);
4676                   jai_cmn_utils_pkg.WRITE_FND_LOG(G_LEVEL_STATEMENT, G_MODULE_NAME||l_api_name, 'cur_rec_section.actual_section_code: ' || cur_rec_section.actual_section_code);
4677                   jai_cmn_utils_pkg.WRITE_FND_LOG(G_LEVEL_STATEMENT, G_MODULE_NAME||l_api_name, 'ln_threshold_grp_id: ' || ln_threshold_grp_id);
4678                   jai_cmn_utils_pkg.WRITE_FND_LOG(G_LEVEL_STATEMENT, G_MODULE_NAME||l_api_name, 'ln_threshold_hdr_id: ' || ln_threshold_hdr_id);
4679 
4680                   --Added for bug#16889298 for 0% rate 20130531 Start
4681                   --------------------------------------------------------------------------
4682                   OPEN  c_is_zero_rate_section(cur_rec_section.actual_section_code);
4683                   FETCH c_is_zero_rate_section INTO r_is_zero_rate_section;
4684                   CLOSE c_is_zero_rate_section;
4685 
4686                   ln_tds_invoice_id := NULL;
4687                   IF r_is_zero_rate_section.cnt > 0 THEN
4688                     --current section belong to zero section code.
4689                     ln_tds_invoice_id := -9997;
4690                   ELSE
4691                     OPEN c_get_vendor_classification(p_vendor_id, p_vendor_site_id);
4692                     FETCH c_get_vendor_classification INTO r_get_vendor_classification;
4693                     CLOSE c_get_vendor_classification;
4694 
4695                     IF r_get_vendor_classification.tds_vendor_classification IN ('Transporter','Software') THEN
4696                       --current vendor calssfication in 'Transporter','Software'
4697                       ln_tds_invoice_id := -9999;
4698                     END IF;
4699                   END IF;
4700                   --------------------------------------------------------------------------
4701                   --Added for bug#16889298 for 0% rate 20130531 End
4702 
4703                       jai_ap_tds_pop_rpst_pkg.populate_repository(
4704                           pn_source_invoice_id      => p_invoice_id
4705                          ,pn_invoice_id             => ln_tds_invoice_id --NULL  --Updated by bug#16889298 for 0% rate
4706                          ,pv_event                  => G_INVOICE_VALIDATE
4707                          ,pv_section_type           => G_TDS_SECTION
4708                          ,pv_section_code           => cur_rec_section.actual_section_code
4709                          ,pn_threshold_grp_id       => ln_threshold_grp_id
4710                          ,pn_threshold_hdr_id       => ln_threshold_hdr_id
4711                          ,pn_threshold_type_id      => NULL
4712                          ,pn_threshold_slab_id      => NULL
4713                          ,pn_tax_category_id        => NULL
4714                       );
4715 
4716                 END IF; --n_threshold_trx_id IS NULL
4717                 ----------------------------------------------------------------------
4718                 --Added by Chong for bug#16414088 eTDS ER End
4719 
4720                 p_codepath := jai_general_pkg.plot_codepath(25, p_codepath); /* 25 */
4721                 update  jai_ap_tds_inv_taxes
4722                 set     threshold_grp_id   =  ln_threshold_grp_id,
4723                         threshold_hdr_id   =  ln_threshold_hdr_id,
4724                         threshold_slab_id  =  ln_threshold_slab_id_after,
4725                         process_status = 'P'
4726                 where  nvl(consider_amt_for_tds, 'Y') = 'Y' -- Added by mmurtuza for bug12858951
4727                 and    invoice_id = p_invoice_id
4728                 and     section_type = lv_tds_section_type --rchandan for bug#4428980
4729                 and     actual_section_code = cur_rec_section.actual_section_code;
4730 
4731                 if ln_threshold_slab_id_before <> ln_threshold_slab_id_after then
4732                   /* Transition in threshold has happened */
4733                   p_codepath := jai_general_pkg.plot_codepath(26, p_codepath); /* 26 */
4734 
4735                   --4407184
4736                   lv_slab_transition_tds_event :=  'THRESHOLD TRANSITION(from slab id -' || ln_threshold_slab_id_before ||
4737                                                         'to slab id - ' || ln_threshold_slab_id_after || ')';
4738 
4739                   IF ( ln_proc_level >= ln_dbg_level)
4740                   THEN
4741 
4742                                 FND_LOG.STRING ( ln_proc_level
4743                                                  , GV_MODULE_PREFIX ||'.'|| lv_proc_name
4744                                                  , '26.  Call process transition ' || ''
4745                                                   );
4746                                 FND_LOG.STRING ( ln_proc_level
4747                                                  , GV_MODULE_PREFIX ||'.'|| lv_proc_name
4748                                                  , '26. Event is ' || lv_slab_transition_tds_event
4749                                                   );
4750                   END IF; --( ln_proc_level >= ln_dbg_level)  ;
4751                   --fnd_file.put_line(FND_FILE.LOG, '26.  Call process transition ');
4752                   --fnd_file.put_line(FND_FILE.LOG, '26. Event is '|| lv_slab_transition_tds_event);
4753 
4754 
4755                   --Commented by Zhiwei Hou on 20120302 for bug#13720981 begin
4756                   --------------------------------------------------------------
4757                   /*if nvl(lv_default_option,'###') = 'Natural Account - Section Code Mapping'  then
4758 
4759 
4760 
4761                      for rec_in_tax in(
4762                          select distinct invoice_distribution_id
4763                          from   jai_ap_tds_inv_taxes
4764                          where  invoice_id = p_invoice_id
4765                      )
4766                      loop
4767 
4768                          update JAI_DTC_SCTN_ACCOUNT_MAPPING
4769                          set    invoice_exists = 'Y'
4770                          where  natural_account_value = get_natural_account_value(
4771                                                                 p_invoice_id,
4772                                                                 rec_in_tax.invoice_distribution_id,
4773                                                                 lv_segment_name
4774                                                         )
4775                          and    legal_entity_id = ln_legal_entity_id;--Added by Zhiwei Hou for Bug#13838036 on 20120316
4776 
4777 
4778                      end loop;
4779 
4780                   end if; */
4781                   --------------------------------------------------------------
4782                   --Commented by Zhiwei Hou on 20120302 for bug#13720981 end
4783 
4784                      if( lv_prospective_flag = 'N' ) then --Added by Zhiwei
4785 
4786                      --Added by Zhiwei for Bug#13359892 on 20111222 begin
4787                      --------------------------------------------------------
4788                      UPDATE JAI_AP_TDS_THHOLD_TRXS
4789                      SET ROLLBACK_REVERSED ='Y'
4790                      WHERE THRESHOLD_GRP_ID = ln_threshold_grp_id
4791                      AND TDS_EVENT LIKE 'THRESHOLD ROLLBACK%';
4792                      --------------------------------------------------------
4793                      --Added by Zhiwei for Bug#13359892 on 20111222 end
4794 
4795                       process_threshold_transition
4796                       (
4797                         p_threshold_grp_id    =>      ln_threshold_grp_id,
4798                         p_threshold_slab_id   =>      ln_threshold_slab_id_after,
4799                         p_invoice_id          =>      p_invoice_id,
4800                         p_vendor_id           =>      p_vendor_id,
4801                         p_vendor_site_id      =>      p_vendor_site_id,
4802                         p_accounting_date     =>      p_accounting_date,
4803                         p_tds_event           =>      lv_slab_transition_tds_event,
4804                         p_org_id              =>      p_org_id,
4805                         pv_tds_invoice_num    =>      lv_tds_invoice_num,
4806                         pv_cm_invoice_num     =>      lv_tds_cm_num,
4807                         p_process_flag        =>      p_process_flag,
4808                         p_process_message     =>      p_process_message
4809                       );
4810 
4811                       if p_process_flag = 'E' then
4812 
4813 
4814                         IF ( ln_proc_level >= ln_dbg_level)
4815                         THEN
4816 
4817                                       FND_LOG.STRING ( ln_proc_level
4818                                                        , GV_MODULE_PREFIX ||'.'|| lv_proc_name
4819                                                        , '27 Process flag ' || p_process_flag
4820                                                         );
4821                                       FND_LOG.STRING ( ln_proc_level
4822                                                        , GV_MODULE_PREFIX ||'.'|| lv_proc_name
4823                                                        , '27 Process message ' || p_process_message
4824                                                         );
4825                         END IF; --( ln_proc_level >= ln_dbg_level)  ;
4826 
4827                         --fnd_file.put_line(FND_FILE.LOG, '27 Process flag '|| p_process_flag);
4828                         --fnd_file.put_line(FND_FILE.LOG, '27 Process message '|| p_process_message);
4829 
4830                         p_codepath := jai_general_pkg.plot_codepath(27, p_codepath); /* 27 */
4831                         goto exit_from_procedure;
4832                       end if;
4833 
4834 
4835 
4836                       ln_no_of_tds_inv_generated := ln_no_of_tds_inv_generated + 2;
4837 
4838                      end if;--Added by Zhiwei
4839                   --end if;--Added by Zhiwei --Comment by Zhiwei Hou on 20120113
4840 
4841 
4842                   p_codepath := jai_general_pkg.plot_codepath(28, p_codepath); /* 28 */
4843                 end if;
4844 
4845                 p_codepath := jai_general_pkg.plot_codepath(29, p_codepath); /* 29 */
4846 
4847                 -------------------------------------------------------------
4848           END LOOP;
4849 
4850       END LOOP;
4851 
4852       --Added by Zhiwei Hou on 20120302 for bug#13720981 begin
4853       --------------------------------------------------------------
4854       /* Commented by Chong for bug#15939571 20121217 Start
4855       if nvl(lv_default_option,'###') = 'Natural Account - Section Code Mapping'  then
4856 
4857 
4858           for rec_in_tax in(
4859                     select distinct invoice_distribution_id
4860                     from   jai_ap_tds_inv_taxes
4861                     where  invoice_id = p_invoice_id
4862           )
4863           loop
4864 
4865                          update JAI_DTC_SCTN_ACCOUNT_MAPPING
4866                          set    invoice_exists = 'Y'
4867                          where  natural_account_value = get_natural_account_value(
4868                                                                 p_invoice_id,
4869                                                                 rec_in_tax.invoice_distribution_id,
4870                                                                 lv_segment_name
4871                                                         );
4872 
4873 
4874            end loop;
4875 
4876         end if;
4877         Commented by Chong for bug#15939571 20121217 End */
4878         --------------------------------------------------------------
4879         --Added by Zhiwei Hou on 20120302 for bug#13720981 end
4880 
4881 
4882       p_codepath := jai_general_pkg.plot_codepath(30, p_codepath); /* 30 */
4883 
4884       /* Check if any non-TDS Section taxes are applicable and generate invoices if required. */
4885       --Update by Zhiwei Hou on 20120111 begin
4886       --------------------------------------------------------------------------------------------------------
4887       --FOR cur_non_tds_rec IN c_get_non_tds_section_tax(p_invoice_id, ln_exchange_rate,'TDS_SECTION')
4888       FOR cur_non_tds_rec IN c_get_non_tds_sec_tax_cat(p_invoice_id, ln_exchange_rate,'TDS_SECTION')
4889       --------------------------------------------------------------------------------------------------------
4890       --Update by Zhiwei Hou on 20120111 end
4891       LOOP    --rchandan for bug#4428980
4892 
4893           p_codepath := jai_general_pkg.plot_codepath(31, p_codepath); /* 31 */
4894           ln_threshold_trx_id := null;
4895           lv_tds_invoice_num  := null;
4896           lv_tds_cm_num       := null;
4897           p_process_flag      := null;
4898 
4899           IF ( ln_proc_level >= ln_dbg_level)
4900           THEN
4901 
4902                FND_LOG.STRING ( ln_proc_level
4903                               , GV_MODULE_PREFIX ||'.'|| lv_proc_name
4904                               , '31 Call generate tds invoices ' || ''
4905                               );
4906                FND_LOG.STRING ( ln_proc_level
4907                               , GV_MODULE_PREFIX ||'.'|| lv_proc_name
4908                               , ' WCT Tax amt ' || cur_non_tds_rec.tax_amount
4909                               );
4910           END IF; --( ln_proc_level >= ln_dbg_level)  ;
4911           --fnd_file.put_line(FND_FILE.LOG, '31 Call generate tds invoices ');
4912 
4913           --fnd_file.put_line(FND_FILE.LOG, ' WCT Tax amt '||cur_non_tds_rec.tax_amount);
4914 
4915 
4916 
4917 
4918 
4919           --Add by Zhiwei Hou on 20120111 begin
4920           --------------------------------------------------------------
4921           jai_ap_dtc_generation_pkg.generate_dtc_invoices
4922           (
4923                       pn_invoice_id              =>      p_invoice_id           ,
4924                       pn_threshold_hdr_id        =>      ln_threshold_hdr_id    ,
4925                       pn_taxable_amount          =>      cur_non_tds_rec.taxable_amount ,
4926                       --Updated by Zhiwei Hou on 20120112 begin
4927                       --pn_tax_amount              =>      cur_non_tds_rec.tax_amount     ,  --Added by Bgowrava for Bug#8254510
4928                       --pn_tax_amount              =>      round(cur_non_tds_rec.tax_amount,get_tax_rounding(p_invoice_id)),  --Commented by Chong for bug#15939571  20121210
4929                       pn_tax_amount              =>      round(cur_non_tds_rec.tax_amount,ln_tax_rounding_factor),  --Added by Chong for bug#15939571  20121210
4930                       --Updated by Zhiwei Hou on 20120112 end
4931                       pn_tax_category_id         =>      cur_non_tds_rec.tax_category_id  ,
4932                       pv_section_type            =>      cur_non_tds_rec.section_type,
4933                       pv_section_code            =>      cur_non_tds_rec.actual_section_code,
4934                       pd_accounting_date         =>      p_accounting_date      ,
4935                       pv_tds_event               =>      'INVOICE VALIDATE'     ,
4936                       pn_threshold_grp_id        =>      null    ,
4937                       pv_tds_invoice_num         =>      lv_tds_invoice_num     ,
4938                       pv_cm_invoice_num          =>      lv_tds_cm_num          ,
4939                       pn_threshold_trx_id        =>      ln_threshold_trx_id    ,
4940                       pd_creation_date           =>      p_creation_date        ,
4941                       pn_calc_tax_amount         =>      0, /* Added for bug 12965614 */
4942                       p_process_flag             =>      p_process_flag         ,
4943                       p_process_message          =>      p_process_message
4944          );
4945          --------------------------------------------------------------------
4946          --Add by Zhiwei Hou on 20120111 end
4947 
4948          --Comment by Zhiwei Hou on 20120111 begin
4949        /*   jai_ap_dtc_generation_pkg.generate_tds_invoices
4950           (
4951             pn_invoice_id              =>      p_invoice_id                   ,
4952             pn_threshold_hdr_id        =>      ln_threshold_hdr_id    ,
4953             pn_taxable_amount          =>      cur_non_tds_rec.taxable_amount ,
4954             pn_tax_amount              =>      cur_non_tds_rec.tax_amount     ,
4955             pn_tax_id                  =>      cur_non_tds_rec.actual_tax_id  ,
4956             pd_accounting_date         =>      p_accounting_date      ,
4957             pv_tds_event               =>      'INVOICE VALIDATE'     ,
4958             pn_threshold_grp_id        =>      null    ,
4959             pv_tds_invoice_num         =>      lv_tds_invoice_num     ,
4960             pv_cm_invoice_num          =>      lv_tds_cm_num          ,
4961             pn_threshold_trx_id        =>      ln_threshold_trx_id    ,
4962             -- Bug 5722028. Added by csahoo
4963             pd_creation_date           =>      p_creation_date        ,
4964             pn_calc_tax_amount         =>      0, \* Added for bug 12965614 *\
4965             p_process_flag             =>      p_process_flag         ,
4966             p_process_message          =>      p_process_message
4967           );*/
4968           --Comment by Zhiwei Hou on 20120111 end
4969           if p_process_flag = 'E' then
4970             IF ( ln_proc_level >= ln_dbg_level)
4971             THEN
4972 
4973                  FND_LOG.STRING ( ln_proc_level
4974                                 , GV_MODULE_PREFIX ||'.'|| lv_proc_name
4975                                 , '31 Process flag ' || p_process_flag
4976                                 );
4977                  FND_LOG.STRING ( ln_proc_level
4978                                 , GV_MODULE_PREFIX ||'.'|| lv_proc_name
4979                                 , '31 Process message ' || p_process_message
4980                                 );
4981             END IF; --( ln_proc_level >= ln_dbg_level)  ;
4982             --fnd_file.put_line(FND_FILE.LOG, '31 Process flag '|| p_process_flag);
4983             --fnd_file.put_line(FND_FILE.LOG, '31 Process message '|| p_process_message);
4984 
4985             p_codepath := jai_general_pkg.plot_codepath(32, p_codepath); /* 32 */
4986             goto exit_from_procedure;
4987           end if;
4988 
4989           p_codepath := jai_general_pkg.plot_codepath(33, p_codepath); /* 33 */
4990 
4991           if ln_start_threshold_trx_id is null then
4992             p_codepath := jai_general_pkg.plot_codepath(34, p_codepath); /* 34 */
4993             ln_start_threshold_trx_id := ln_threshold_trx_id;
4994           end if;
4995           IF ( ln_proc_level >= ln_dbg_level)
4996           THEN
4997 
4998                  FND_LOG.STRING ( ln_proc_level
4999                                 , GV_MODULE_PREFIX ||'.'|| lv_proc_name
5000                                 , '34. Start thhold trx id ' || ln_start_threshold_trx_id
5001                                 );
5002 
5003           END IF; --( ln_proc_level >= ln_dbg_level)  ;
5004           --fnd_file.put_line(FND_FILE.LOG, '34. Start thhold trx id '|| ln_start_threshold_trx_id);
5005 
5006           /* Punch threshold_trx_id in jai_ap_tds_inv_taxes */
5007           update  jai_ap_tds_inv_taxes
5008           set     threshold_trx_id =  ln_threshold_trx_id,
5009                   process_status   = 'P'
5010           where   nvl(consider_amt_for_tds, 'Y') = 'Y' -- Added by mmurtuza for bug12858951
5011           and     invoice_id       =  p_invoice_id
5012           and     section_type     =  cur_non_tds_rec.section_type
5013           -- Add by Zhiwei Hou on 20120111 begin
5014           and     actual_section_code = cur_non_tds_rec.actual_section_code
5015           and     tax_category_id     = cur_non_tds_rec.tax_category_id;
5016           -- Add by Zhiwei Hou on 20120111 end
5017           --and     actual_tax_id    =  cur_non_tds_rec.actual_tax_id;---- Comment by Zhiwei Hou on 20120111
5018 
5019       END LOOP; /* cur_non_tds_rec */
5020 
5021       p_codepath := jai_general_pkg.plot_codepath(35, p_codepath); /* 35 */
5022 
5023 
5024       /* If the process is called from batch do not fire import request */
5025       IF ( ln_proc_level >= ln_dbg_level)
5026       THEN
5027 
5028              FND_LOG.STRING ( ln_proc_level
5029                             , GV_MODULE_PREFIX ||'.'|| lv_proc_name
5030                             , '35. called from ' || p_call_from
5031                             );
5032 
5033       END IF; --( ln_proc_level >= ln_dbg_level)  ;
5034       --fnd_file.put_line(FND_FILE.LOG, '35. called from '|| p_call_from);
5035 
5036       IF p_call_from <> 'BATCH' THEN
5037         /* Not Called from Batch */
5038 
5039         p_codepath := jai_general_pkg.plot_codepath(36, p_codepath); /* 36 */
5040 
5041         IF ln_start_threshold_trx_id is not null THEN
5042           IF ( ln_proc_level >= ln_dbg_level)
5043           THEN
5044 
5045                  FND_LOG.STRING ( ln_proc_level
5046                                 , GV_MODULE_PREFIX ||'.'|| lv_proc_name
5047                                 , '36 start thhold trx id ' || ln_start_threshold_trx_id
5048                                 );
5049 
5050           END IF; --( ln_proc_level >= ln_dbg_level)  ;
5051           --fnd_file.put_line(FND_FILE.LOG, '36 start thhold trx id '|| ln_start_threshold_trx_id);
5052 
5053           p_codepath := jai_general_pkg.plot_codepath(37, p_codepath); /* 37 */
5054           import_and_approve
5055           (
5056             p_invoice_id                   =>     p_invoice_id,
5057             p_start_thhold_trx_id          =>     ln_start_threshold_trx_id,
5058             p_tds_event                    =>     'INVOICE VALIDATE',
5059             p_process_flag                 =>     p_process_flag,
5060             p_process_message              =>     p_process_message
5061           );
5062           IF ( ln_proc_level >= ln_dbg_level)
5063           THEN
5064 
5065                  FND_LOG.STRING ( ln_proc_level
5066                                 , GV_MODULE_PREFIX ||'.'|| lv_proc_name
5067                                 , '37 Process flag ' || p_process_flag
5068                                 );
5069                  FND_LOG.STRING ( ln_proc_level
5070                                 , GV_MODULE_PREFIX ||'.'|| lv_proc_name
5071                                 , '37 Process message ' || p_process_message
5072                                 );
5073           END IF; --( ln_proc_level >= ln_dbg_level)  ;
5074           --fnd_file.put_line(FND_FILE.LOG, '37 Process flag '|| p_process_flag);
5075           --fnd_file.put_line(FND_FILE.LOG, '37 Process message '|| p_process_message);
5076 
5077           --Added by Sanjikum for Bug#5131075(4722011)
5078           IF p_process_flag = 'E' THEN
5079             p_codepath := jai_general_pkg.plot_codepath(37.1, p_codepath); /* 37.1 */
5080             goto exit_from_procedure;
5081           END IF;
5082 
5083         END IF; /* if ln_no_of_tds_inv_generated > 0 then  */
5084 
5085       END IF; /*   p_call_from <> 'BATCH'  then */
5086 
5087       <<exit_from_procedure>>
5088       p_codepath := jai_general_pkg.plot_codepath(100, p_codepath); /* 100 */
5089       jai_cmn_utils_pkg.WRITE_FND_LOG(G_LEVEL_PROCEDURE, G_MODULE_NAME||l_api_name||'.END', G_PKG_NAME || ': '||l_api_name||'()-');
5090       return;
5091 
5092     exception
5093       when others then
5094 
5095         p_process_flag := 'E';
5096         P_process_message := 'jai_ap_dtc_generation_pkg.process_dtc_at_inv_validate :' ||  sqlerrm;
5097         return;
5098     end process_dtc_at_inv_validate;
5099 
5100 
5101 
5102     PROCEDURE process_threshold_transition
5103     (
5104           p_threshold_grp_id                   	 IN                  NUMBER,
5105           p_threshold_slab_id                  	 IN                  NUMBER,
5106           p_invoice_id                         	 IN                  NUMBER,
5107           p_vendor_id                         	 IN                  NUMBER,
5108           p_vendor_site_id                    	 IN                  NUMBER,
5109           p_accounting_date                   	 IN                  DATE,
5110           p_tds_event                          	 IN                  VARCHAR2,
5111           p_org_id                              	 IN                  NUMBER,
5112           --Added by Chong.Lei for bug#13787158 begin
5113           pn_prepayment_inovice_id                 IN                 NUMBER DEFAULT NULL,
5114           pn_unapply_amount                        IN                 NUMBER DEFAULT NULL,
5115           --Added by Chong.Lei for bug#13787158 end
5116           pv_tds_invoice_num                   	 OUT       NOCOPY  VARCHAR2,
5117           pv_cm_invoice_num                  	 OUT       NOCOPY  VARCHAR2,
5118           p_process_flag                       	 OUT       NOCOPY  VARCHAR2,
5119           p_process_message                    	 OUT       NOCOPY  VARCHAR2
5120     )IS
5121     TYPE TRAN_RECORD IS RECORD (
5122         INVOICE_ID         		NUMBER,
5123         AMOUNT                NUMBER,
5124         SECTION_CODE           JAI_AP_TDS_INV_TAXES.ACTUAL_SECTION_CODE%TYPE,--Updated by Zhiwei Hou on 20120116
5125         TAX_CATEGORY_ID      	NUMBER
5126     );
5127     TYPE TRAN_TYPE IS TABLE OF TRAN_RECORD;
5128     TRAN_TAB TRAN_TYPE := TRAN_TYPE();
5129 
5130 
5131 
5132 
5133 
5134     Cursor get_section_info(cn_threshold_grp_id number)
5135     Is
5136     select section_type,section_code
5137     from   jai_ap_tds_thhold_grps
5138     where  threshold_grp_id = cn_threshold_grp_id;
5139 
5140     lv_section_type jai_ap_tds_thhold_grps.section_type%type;
5141     lv_section_code jai_ap_tds_thhold_grps.section_code%type;
5142 
5143     cursor get_tax_category(cn_threshold_slab_id number)
5144     is
5145     SELECT --JATTTY.THRESHOLD_TYPE_ID, JATTTY.FROM_DATE, JATTTY.TO_DATE, JATTTY.THRESHOLD_TYPE, JATTTA.THRESHOLD_SLAB_ID, JATTS.FROM_AMOUNT, JATTS.TO_AMOUNT,
5146            JATTTA.TAX_CATEGORY_ID
5147            --, JATTTA.OPERATING_UNIT_ID
5148           ,jatth.threshold_hdr_id  --Added by Chong for bug#16414088 20130313
5149     FROM    JAI_AP_TDS_THHOLD_HDRS JATTH,
5150             JAI_AP_TDS_THHOLD_TYPES JATTTY,
5151             JAI_AP_TDS_THHOLD_SLABS JATTS,
5152             JAI_AP_TDS_THHOLD_TAXES JATTTA
5153     WHERE   JATTS.THRESHOLD_SLAB_ID = p_threshold_slab_id
5154     AND     JATTH.THRESHOLD_HDR_ID = JATTTY.THRESHOLD_HDR_ID
5155     AND     JATTTY.THRESHOLD_TYPE_ID = JATTS.THRESHOLD_TYPE_ID
5156     AND     JATTS.THRESHOLD_SLAB_ID = JATTTA.THRESHOLD_SLAB_ID
5157     AND     JATTTA.OPERATING_UNIT_ID = p_org_id   --Added by Chong for bug#16414088 20130313
5158     ;
5159 
5160     ln_tax_category_id   number;
5161     LN_ARRAY_SIZE        NUMBER:=2000;
5162 
5163     Cursor get_ap_info(cn_invoice_id number)
5164     is
5165     select vendor_id,invoice_currency_code,exchange_rate,vendor_site_id
5166     from   ap_invoices_all
5167     where  invoice_id = cn_invoice_id;
5168 
5169     ln_vendor_id      number;
5170     ln_vendor_site_id number;
5171     lv_invoice_curr_code ap_invoices_all.invoice_currency_code%type;
5172     ln_exchange_rate     ap_invoices_all.exchange_rate%type;
5173 
5174     cursor get_tax_info(cn_tax_id number)
5175     is
5176     select tax_type,section_type
5177     from   jai_cmn_taxes_all
5178     where tax_id = cn_tax_id;
5179 
5180     lv_tax_type         jai_cmn_taxes_all.tax_type%type;
5181     lv_section_type_tax jai_cmn_taxes_all.section_type%type;
5182     ln_rounding_factor  number;
5183     ln_tax_rounding_factor number; -- Added by Chong for bug#15939571  20121210
5184     ln_tax_amount       number;
5185 
5186     cursor c_get_threshold(p_vendor_id number, p_vendor_site_id number,  p_tds_section_code varchar2) is
5187     select threshold_hdr_id
5188     from   JAI_AP_TDS_TH_VSITE_V
5189     where  vendor_id = p_vendor_id
5190     and    vendor_site_id = p_vendor_site_id
5191     and    section_type = 'TDS_SECTION'
5192     and    section_code = p_tds_section_code;
5193 
5194     cursor get_sum_amount(cn_invoice_id number)
5195     is
5196     select sum(tax_amount) from jai_ap_tds_inv_taxes
5197     where  invoice_id = cn_invoice_id
5198     and    invoice_distribution_id = 1
5199     and    threshold_transition = 'Y';
5200 
5201     ln_sum_tax_amount               number;
5202     ln_flag                         number;
5203     ln_tax_first                    number;
5204     ln_threshold_trx_id             number;
5205     ln_threshold_grp_audit_id       number;
5206     ln_surcharge_rate               number;
5207 
5208     cursor chk_surcharge_tax(cn_category_id number)
5209     is
5210     select tax.tax_id,tax.tax_rate, tax.section_code
5211     from JAI_CMN_TAX_CTG_LINES cat,
5212          JAI_CMN_TAXES_ALL     tax
5213     where cat.tax_id = tax.tax_id
5214     and   tax.tax_type in ('TDS_SURCHARGE')
5215     and   cat.tax_category_id =  cn_category_id;
5216 
5217     rec_surcharge  chk_surcharge_tax%rowtype;
5218 
5219     /*Commented by Chong for bug#13359892 20120927 start
5220     cursor get_sum_amount_trx
5221     is
5222     select sum(tax_amount)
5223     from   JAI_AP_TDS_THHOLD_TRXS
5224     where  threshold_grp_id = p_threshold_grp_id
5225     --Updated by Zhiwei Hou for Bug#13787158 on 20120305 begin
5226     ------------------------------------------------------------
5227     AND  (   p_invoice_id is null
5228           or (p_invoice_id is not null AND    invoice_id <> p_invoice_id)
5229     )
5230     ------------------------------------------------------------
5231     --Updated by Zhiwei Hou for Bug#13787158 on 20120305 end
5232     Commented by Chong for bug#13359892 20120927 end*/
5233 
5234     --Added by Chong for bug#13359892 20120927 start
5235     ------------------------------------------------------------
5236     --Get the amount to generate surcharge_calculate TDS invoice,
5237     --from ther transactions which in the salb with no surcharge tax code.
5238     CURSOR get_sum_amount_trx
5239     IS
5240     SELECT SUM(decode(jattt.TDS_EVENT ,'PREPAYMENT APPLICATION', -jattt.tax_amount, jattt.tax_amount))
5241     FROM   JAI_AP_TDS_THHOLD_TRXS jattt
5242     WHERE jattt.threshold_grp_id = p_threshold_grp_id
5243     AND TDS_EVENT NOT IN (G_SURCHARGE_ROLLBACK,G_SURCHARGE_CALCULATE)
5244     AND jattt.tds_rollbacked IS NULL
5245     /*Commented out by Chong for bug#15976304 20121212 Start
5246     AND NOT EXISTS(
5247         SELECT 1
5248         FROM   JAI_AP_TDS_INV_TAXES jatit
5249               ,jai_cmn_taxes_all    jcta
5250         WHERE  jatit.invoice_id = jattt.invoice_id
5251         AND    jcta.tax_id      = jatit.actual_tax_id
5252         AND    jcta.tax_type = 'TDS_SURCHARGE'
5253     )
5254     Commented out by Chong for bug#15976304 20121212 End*/
5255     --Added by Chong for bug#15976304 20121212 Start
5256     ------------------------------------------------
5257     AND NOT EXISTS(
5258         SELECT 1
5259         FROM   JAI_CMN_TAX_CTG_LINES jctcl
5260               ,jai_cmn_taxes_all    jcta
5261         WHERE  jctcl.tax_category_id = jattt.tax_category_id
5262         AND    jctcl.tax_id      = jcta.tax_id
5263         AND    jcta.tax_type = 'TDS_SURCHARGE'
5264     )
5265     ------------------------------------------------
5266     --Added by Chong for bug#15976304 20121212 End
5267     AND NOT EXISTS(
5268         SELECT 1
5269         FROM   ap_invoices_all aia
5270         WHERE  jattt.invoice_id = aia.invoice_id
5271         AND    aia.cancelled_date IS NOT NULL
5272     )
5273     ;
5274     ------------------------------------------------------------
5275     --Added by Chong for bug#13359892 20120927 end
5276 
5277     lv_tds_invoice_num              ap_invoices_all.invoice_num%type;
5278     lv_tds_cm_num                   ap_invoices_all.invoice_num%type;
5279 
5280     ln_threshold_grp_id number;
5281 
5282     ln_surcharge_amount number;
5283     ln_threshold_hdr_id number;
5284 
5285     lv_codepath jai_ap_tds_inv_taxes.codepath%type;
5286 
5287     --Add by Zhiwei Hou on 20120114 begin
5288     ----------------------------------------------------
5289     get_ref_cur_not_deduct ref_cur;
5290     get_ref_cur_unpaid     ref_cur;
5291     get_ref_cur            ref_cur;
5292     ----------------------------------------------------
5293     --Add by Zhiwei Hou on 20120114 end
5294     l_api_name                   CONSTANT  VARCHAR2(50) := 'process_threshold_transition()';
5295     BEGIN
5296 
5297         jai_cmn_utils_pkg.WRITE_FND_LOG(G_LEVEL_PROCEDURE, G_MODULE_NAME||l_api_name||'.BEGIN', G_PKG_NAME || ': '||l_api_name||'()+');
5298         jai_cmn_utils_pkg.WRITE_FND_LOG(G_LEVEL_STATEMENT, G_MODULE_NAME||l_api_name||'.Parameters', 'p_threshold_grp_id: ' ||p_threshold_grp_id);
5299         jai_cmn_utils_pkg.WRITE_FND_LOG(G_LEVEL_STATEMENT, G_MODULE_NAME||l_api_name||'.Parameters', 'p_threshold_slab_id: ' ||p_threshold_slab_id);
5300         jai_cmn_utils_pkg.WRITE_FND_LOG(G_LEVEL_STATEMENT, G_MODULE_NAME||l_api_name||'.Parameters', 'p_invoice_id: ' ||p_invoice_id);
5301         jai_cmn_utils_pkg.WRITE_FND_LOG(G_LEVEL_STATEMENT, G_MODULE_NAME||l_api_name||'.Parameters', 'pn_prepayment_inovice_id: ' ||pn_prepayment_inovice_id);
5302         jai_cmn_utils_pkg.WRITE_FND_LOG(G_LEVEL_STATEMENT, G_MODULE_NAME||l_api_name||'.Parameters', 'pn_unapply_amount: ' ||pn_unapply_amount);
5303           open get_section_info(p_threshold_grp_id);
5304           fetch get_section_info into lv_section_type,lv_section_code;
5305           close get_section_info;
5306 
5307 
5308 
5309           open get_tax_category(p_threshold_slab_id);
5310           fetch get_tax_category into ln_tax_category_id, ln_threshold_hdr_id; --Added threshold hdr ID by Chong for bug#16414088
5311           close get_tax_category;
5312 
5313           jai_cmn_utils_pkg.WRITE_FND_LOG(G_LEVEL_PROCEDURE, G_MODULE_NAME||l_api_name,
5314                'Threshold transition tax catetory id: ' || ln_tax_category_id);
5315 
5316 
5317 
5318           for j in 1..3
5319           loop
5320               TRAN_TAB.DELETE;
5321               if j = 3 then
5322                   get_ref_cur_not_deduct := get_invoice_tax_not_deducted(
5323                           pn_invoice_id      => p_invoice_id,
5324                           pv_section_code    => lv_section_code,
5325                           pn_threshold_grp_id=> P_THRESHOLD_GRP_ID
5326                   );
5327                   loop
5328 
5329                        EXIT WHEN get_ref_cur_not_deduct%NOTFOUND;
5330                        FETCH get_ref_cur_not_deduct BULK COLLECT INTO TRAN_TAB LIMIT LN_ARRAY_SIZE;
5331 
5332                   END LOOP;
5333                   CLOSE get_ref_cur_not_deduct;
5334               end if;
5335               if j = 1 then
5336                   get_ref_cur_unpaid := get_invoice_unpaid(
5337                                          pn_invoice_id      => p_invoice_id,
5338                                          pv_section_code    => lv_section_code,
5339                                          pn_threshold_grp_id=> P_THRESHOLD_GRP_ID
5340                   );
5341                   loop
5342                       EXIT WHEN get_ref_cur_unpaid%NOTFOUND;
5343                       FETCH get_ref_cur_unpaid BULK COLLECT INTO TRAN_TAB LIMIT LN_ARRAY_SIZE;
5344                   END LOOP;
5345                   CLOSE get_ref_cur_unpaid;
5346               end if;
5347               if j = 2 then
5348                   get_ref_cur := get_prepay_unapplied(
5349                                          pn_invoice_id      => p_invoice_id,
5350                                          pv_section_code    => lv_section_code,
5351                                          --Updated by Chong.Lei for bug#13787158 begin
5352                                          pn_threshold_grp_id=> P_THRESHOLD_GRP_ID,
5353                                          pn_prepayment_inovice_id => NVL(pn_prepayment_inovice_id, -999),
5354                                          pn_unapply_amount  => NVL(pn_unapply_amount,0)
5355                                          --Updated by Chong.Lei for bug#13787158 end
5356                                  );
5357                   loop
5358                       EXIT WHEN get_ref_cur%NOTFOUND;
5359                       FETCH get_ref_cur BULK COLLECT INTO TRAN_TAB LIMIT LN_ARRAY_SIZE;
5360 
5361                   END LOOP;
5362                   CLOSE get_ref_cur;
5363               end if;
5364           FOR I IN 1..TRAN_TAB.count
5365           LOOP
5366 
5367 
5368               ln_rounding_factor := get_taxable_rounding(TRAN_TAB(i).INVOICE_ID);
5369               --Added by Chong for bug#15939571  20121210 Start
5370               ---------------------------------------------------------------------------
5371               IF ln_rounding_factor IS NULL THEN
5372                 p_process_flag := 'E';
5373                 p_process_message := 'Rounding Rule for Tax Basis is not defined for the entered GL Period. Invoice:' || TRAN_TAB(i).INVOICE_ID;
5374                 jai_cmn_utils_pkg.WRITE_FND_LOG(G_LEVEL_ERROR, G_MODULE_NAME||l_api_name, p_process_message);
5375                 goto exit_from_procedure;
5376               END IF;
5377 
5378               ln_tax_rounding_factor := get_tax_rounding(TRAN_TAB(i).INVOICE_ID);
5379               IF ln_tax_rounding_factor IS NULL THEN
5380                 p_process_flag := 'E';
5381                 p_process_message := 'Rounding Rule for Tax is not defined for the entered GL Period. Invoice:' || TRAN_TAB(i).INVOICE_ID;
5382                 jai_cmn_utils_pkg.WRITE_FND_LOG(G_LEVEL_ERROR, G_MODULE_NAME||l_api_name, p_process_message);
5383                 goto exit_from_procedure;
5384               END IF;
5385               ---------------------------------------------------------------------------
5386               --Added by Chong for bug#15939571  20121210 End
5387 
5388               delete from jai_ap_tds_inv_taxes
5389               where  invoice_id =  TRAN_TAB(i).invoice_id
5390               and    invoice_distribution_id = 1;
5391 
5392               --Derive Vendor, Invoice Currency Code, Exchange Rate and Vendor Site ID from TRAN_TAB(i).INVOICE_ID
5393 
5394 
5395               open get_ap_info(TRAN_TAB(i).INVOICE_ID);
5396               fetch get_ap_info into ln_vendor_id,lv_invoice_curr_code,ln_exchange_rate,ln_vendor_site_id;
5397               close get_ap_info;
5398 
5399 
5400 
5401               ln_flag := 0;
5402 
5403               FOR R_TAX_CTG_LINES IN(
5404                 SELECT *
5405                 FROM JAI_CMN_TAX_CTG_LINES
5406                 WHERE TAX_CATEGORY_ID = nvl(TRAN_TAB(i).TAX_CATEGORY_ID, LN_TAX_CATEGORY_ID)
5407                 ORDER BY LINE_NO
5408               )
5409               LOOP
5410 
5411                 if ln_flag = 0 then
5412                    ln_tax_first := R_TAX_CTG_LINES.tax_id;
5413                 end if;
5414 
5415                 ln_flag := ln_flag + 1;
5416                 --Get Tax Type, Section Type from Tax ID.
5417 
5418                 open get_tax_info(R_TAX_CTG_LINES.tax_id);
5419                 fetch get_tax_info into lv_tax_type,lv_section_type_tax ;
5420                 close get_tax_info;
5421 
5422                 /*
5423                 Note: Data is populated into JAI_AP_TDS_INV_TAXES to calculate Taxes using jai_cmn_tax_defaultation_pkg.ja_in_calc_prec_taxes.
5424                 Invoice Distribution ID,
5425                 Distribution Line Number
5426                 and Line Number
5427                 are populated as 1 for these Invoices
5428                 */
5429                 INSERT INTO JAI_AP_TDS_INV_TAXES
5430                 (
5431                     TDS_INV_TAX_ID,
5432                     INVOICE_ID,
5433                     INVOICE_DISTRIBUTION_ID,
5434                     JAI_DISTRIBUTION_ID,
5435                     DISTRIBUTION_LINE_NUMBER,
5436                     AMOUNT,
5437                     VENDOR_ID,
5438                     VENDOR_SITE_ID,
5439                     DIST_CODE_COMBINATION_ID,
5440                     SECTION_TYPE,
5441                     TAX_LINE_NO,
5442                     TAX_TYPE,
5443                     TAX_CATEGORY_ID,
5444                     PRECEDENCE_1,
5445                     PRECEDENCE_2,
5446                     PRECEDENCE_3,
5447                     PRECEDENCE_4,
5448                     PRECEDENCE_5,
5449                     PRECEDENCE_6,
5450                     PRECEDENCE_7,
5451                     PRECEDENCE_8,
5452                     PRECEDENCE_9,
5453                     PRECEDENCE_10,
5454                     ACTUAL_SECTION_CODE,
5455                     ACTUAL_TAX_ID,
5456                     PROCESS_STATUS,
5457                     PROCESS_MESSAGE,
5458                     MATCH_STATUS_FLAG,
5459                     CREATED_BY,
5460                     CREATION_DATE,
5461                     LAST_UPDATED_BY,
5462                     LAST_UPDATE_DATE,
5463                     LAST_UPDATE_LOGIN,
5464                     INVOICE_LINE_NUMBER,
5465                     ROUNDED_AMOUNT,
5466                     THRESHOLD_TRANSITION
5467                 )
5468                 VALUES
5469                 (
5470                     JAI_AP_TDS_INV_TAXES_S.NEXTVAL,
5471                     TRAN_TAB(i).INVOICE_ID,
5472                     1,
5473                     1,
5474                     1,
5475                     decode(R_TAX_CTG_LINES.LINE_NO, 1, TRAN_TAB(i).AMOUNT, 0),
5476                     LN_VENDOR_ID,
5477                     LN_VENDOR_SITE_ID,
5478                     1,
5479                     lv_section_type_tax,
5480                     R_TAX_CTG_LINES.LINE_NO,
5481                     lv_tax_type,
5482                     R_TAX_CTG_LINES.TAX_CATEGORY_ID,
5483                     R_TAX_CTG_LINES.PRECEDENCE_1,
5484                     R_TAX_CTG_LINES.PRECEDENCE_2,
5485                     R_TAX_CTG_LINES.PRECEDENCE_3,
5486                     R_TAX_CTG_LINES.PRECEDENCE_4,
5487                     R_TAX_CTG_LINES.PRECEDENCE_5,
5488                     R_TAX_CTG_LINES.PRECEDENCE_6,
5489                     R_TAX_CTG_LINES.PRECEDENCE_7,
5490                     R_TAX_CTG_LINES.PRECEDENCE_8,
5491                     R_TAX_CTG_LINES.PRECEDENCE_9,
5492                     R_TAX_CTG_LINES.PRECEDENCE_10,
5493                     TRAN_TAB(i).SECTION_CODE,
5494                     R_TAX_CTG_LINES.TAX_ID,
5495                     'D',
5496                     NULL,
5497                     'Q',
5498                     FND_GLOBAL.USER_ID,
5499                     SYSDATE,
5500                     FND_GLOBAL.USER_ID,
5501                     SYSDATE,
5502                     FND_GLOBAL.LOGIN_ID,
5503                     1,
5504                     round(decode(R_TAX_CTG_LINES.LINE_NO, 1, TRAN_TAB(i).AMOUNT, 0),ln_rounding_factor),
5505                     'Y'
5506                 );
5507 
5508 
5509 
5510               END LOOP;
5511 
5512               ln_tax_amount := round(TRAN_TAB(i).AMOUNT,ln_rounding_factor);
5513               jai_cmn_tax_defaultation_pkg.ja_in_calc_prec_taxes
5514               (
5515                    transaction_name        	=> 'TDS INVOICE',
5516                    p_tax_category_id       	=> -1,
5517                    p_header_id              => TRAN_TAB(i).invoice_id,
5518                    p_line_id                => 1,
5519                    p_tax_amount             => ln_tax_amount,
5520                    p_inventory_item_id     	=> NULL,
5521                    p_line_quantity         	=> NULL,
5522                    p_uom_code               => NULL,
5523                    p_vendor_id              => ln_vendor_id,
5524                    p_currency               => lv_invoice_curr_code,
5525                    p_currency_conv_factor 	=> ln_exchange_rate,
5526                    p_creation_date         	=> SYSDATE,
5527                    p_created_by             => FND_GLOBAL.USER_ID,
5528                    p_last_update_date      	=> SYSDATE,
5529                    p_last_updated_by       	=> FND_GLOBAL.USER_ID,
5530                    p_last_update_login     	=> FND_GLOBAL.LOGIN_ID,
5531                    p_source_trx_type       	=> 'TDS INVOICE',
5532                    p_action                 => JAI_CONSTANTS.RECALCULATE_TAXES
5533               );
5534 
5535 /*            --Commented out by Chong for bug#16414088 as threshold transition should occur under same threshold header.
5536               --No need get header in loop
5537               ln_threshold_hdr_id := 0;
5538 
5539               open  c_get_threshold(ln_vendor_id ,ln_vendor_site_id, TRAN_TAB(i).section_code);
5540               fetch c_get_threshold into ln_threshold_hdr_id;
5541               close c_get_threshold;
5542 */
5543 
5544               open get_sum_amount(TRAN_TAB(i).invoice_id);
5545               fetch get_sum_amount into ln_sum_tax_amount;
5546               close get_sum_amount;
5547 
5548               --Updated by Zhiwei Hou for Bug#13787158 on 20120305 begin
5549               ---------------------------------------------------------------------------
5550               --ln_sum_tax_amount := round(ln_sum_tax_amount,get_tax_rounding(p_invoice_id));
5551               --ln_sum_tax_amount := round(ln_sum_tax_amount,get_tax_rounding(nvl(p_invoice_id,TRAN_TAB(i).invoice_id)));  --Commented by Chong for bug#15939571  20121210
5552 
5553               ln_sum_tax_amount := round(ln_sum_tax_amount,ln_tax_rounding_factor);  --Added by Chong for bug#15939571  20121210
5554               ---------------------------------------------------------------------------
5555               --Updated by Zhiwei Hou for Bug#13787158 on 20120305 end
5556 
5557               --jai_ap_dtc_generation_pkg.generate_tds_invoices
5558               jai_ap_dtc_generation_pkg.generate_dtc_invoices
5559               (
5560                     pn_invoice_id              =>      TRAN_TAB(i).invoice_id                   ,
5561                     pn_threshold_hdr_id        =>      ln_threshold_hdr_id    ,
5562                     pn_taxable_amount          =>      TRAN_TAB(i).AMOUNT ,
5563                     pn_tax_amount              =>      ln_sum_tax_amount     ,
5564                     pn_tax_category_id         =>      nvl(TRAN_TAB(i).TAX_CATEGORY_ID, LN_TAX_CATEGORY_ID)  ,
5565                     pv_section_type            =>      lv_section_type,
5566                     pv_section_code            =>      TRAN_TAB(i).section_code,
5567                     pd_accounting_date         =>      p_accounting_date      ,
5568                     pv_tds_event               =>      p_tds_event     ,--Changed by Zhiwei Hou 20120216
5569                     pn_threshold_grp_id        =>      P_THRESHOLD_GRP_ID    , --null,
5570                     pv_tds_invoice_num         =>      lv_tds_invoice_num     ,
5571                     pv_cm_invoice_num          =>      lv_tds_cm_num          ,
5572                     pn_threshold_trx_id        =>      ln_threshold_trx_id    ,
5573                     pd_creation_date           =>      sysdate        ,
5574                     pn_calc_tax_amount         =>      0,
5575                     p_process_flag             =>      p_process_flag         ,
5576                     p_process_message          =>      p_process_message
5577               );
5578 
5579               if p_process_flag = 'E' then
5580                  goto exit_from_procedure;
5581               end if;
5582 
5583               IF ln_threshold_trx_id IS NOT NULL --AND
5584                 --p_tds_event like 'THRESHOLD TRANSITION-PPUA%'
5585               THEN
5586 
5587                   import_and_approve
5588                   (
5589                     p_invoice_id                   =>     TRAN_TAB(i).INVOICE_ID,--p_invoice_id,
5590                     p_start_thhold_trx_id          =>     ln_threshold_trx_id,
5591                     p_tds_event                    =>     p_tds_event,
5592                     p_process_flag                 =>     p_process_flag,
5593                     p_process_message              =>     p_process_message
5594                   );
5595 
5596               IF p_process_flag = 'E' THEN
5597                 goto exit_from_procedure;
5598               END IF;
5599 
5600               end if;
5601 
5602 
5603               ln_threshold_grp_id:= p_threshold_grp_id;
5604               maintain_thhold_grps
5605               (
5606                 p_threshold_grp_id             =>   ln_threshold_grp_id,
5607                 p_trx_tax_paid                 =>   ln_sum_tax_amount,
5608                 p_trx_thhold_change_tax_paid   =>   ln_sum_tax_amount,
5609                 p_trx_threshold_slab_id        =>   p_threshold_slab_id,
5610                 p_tds_event                    =>   p_tds_event,
5611                 p_invoice_id                   =>   TRAN_TAB(i).INVOICE_ID,--p_invoice_id,
5612                 p_threshold_grp_audit_id       =>   ln_threshold_grp_audit_id,
5613                 p_creation_date                =>   sysdate,
5614                 p_process_flag                 =>   p_process_flag,
5615                 P_process_message              =>   P_process_message,
5616                 p_codepath                     =>   lv_codepath
5617               );
5618 
5619 
5620               IF p_process_flag = 'E' THEN
5621                 goto exit_from_procedure;
5622               END IF;
5623 
5624               --Added by Zhiwei Hou on 20120118 begin
5625               ------------------------------------------------------------------------
5626               update  jai_ap_tds_inv_taxes
5627               set     threshold_trx_id   =  ln_threshold_trx_id,
5628                       threshold_grp_id   =  ln_threshold_grp_id,
5629                       threshold_hdr_id   =  ln_threshold_hdr_id,
5630                       threshold_slab_id  =  p_threshold_slab_id,
5631                       process_status = 'P'
5632               where   nvl(consider_amt_for_tds, 'Y') = 'Y'
5633               and     invoice_id = TRAN_TAB(i).INVOICE_ID
5634               and     section_type      =  lv_section_type
5635               and     actual_section_code = TRAN_TAB(i).section_code
5636               and     tax_category_id  =  nvl(TRAN_TAB(i).TAX_CATEGORY_ID, LN_TAX_CATEGORY_ID);
5637 
5638 
5639               /*for rec_upd in
5640               (
5641                   select --invoice_id,
5642                          invoice_distribution_id,
5643                          distribution_line_number,
5644                          threshold_trx_id,
5645                          threshold_grp_id,
5646                          threshold_hdr_id,
5647                          threshold_slab_id,
5648                          process_status
5649                    from  JAI_AP_TDS_INV_TAXES
5650                    where invoice_id  = TRAN_TAB(i).INVOICE_ID
5651                    and   nvl(consider_amt_for_tds, 'Y') = 'Y'
5652                    and   jai_distribution_id = 1
5653                    and   tax_line_no = 1
5654                    and   section_type = lv_section_type
5655                    and   actual_section_code = TRAN_TAB(i).section_code
5656                    and   tax_category_id  =  nvl(TRAN_TAB(i).TAX_CATEGORY_ID, LN_TAX_CATEGORY_ID)
5657 
5658               )
5659               loop
5660                    update JAI_AP_TDS_INV_TAXES
5661                    set   threshold_trx_id = rec_upd.threshold_trx_id,
5662                          threshold_slab_id = rec_upd.threshold_slab_id,
5663                          process_status = rec_upd.process_status
5664                    where invoice_id =   TRAN_TAB(i).INVOICE_ID
5665                    and   jai_distribution_id is null
5666                    and   tax_line_no = 0
5667                    and   section_type = lv_section_type
5668                    and   actual_section_code = TRAN_TAB(i).section_code
5669                    and   nvl(consider_amt_for_tds, 'Y') = 'Y';
5670 
5671               end loop;*/
5672 
5673               ----------------------------------------------------------------------------
5674               --Added by Zhiwei Hou on 20120118 end
5675 
5676 
5677 
5678 
5679 
5680             END LOOP;
5681           end loop;
5682 
5683 
5684           --Check surcharge DTC tax exists
5685 
5686           FOR rec_surcharge in chk_surcharge_tax(LN_TAX_CATEGORY_ID)
5687           LOOP
5688 
5689               jai_cmn_utils_pkg.WRITE_FND_LOG(G_LEVEL_PROCEDURE, G_MODULE_NAME||l_api_name,
5690                'Surcharge tax id:' || rec_surcharge.tax_id || ' Surcharge tax rate: ' || rec_surcharge.tax_rate);
5691 
5692 
5693                if rec_surcharge.tax_rate > 0 then
5694 
5695                   open get_sum_amount_trx;
5696                   fetch get_sum_amount_trx into ln_sum_tax_amount;
5697                   close get_sum_amount_trx;
5698 
5699                   ln_sum_tax_amount := ROUND(ln_sum_tax_amount, get_taxable_rounding(p_invoice_id));  --Added by Chong for bug#15939571 2012/12/19
5700 
5701                   ln_surcharge_amount := ln_sum_tax_amount * rec_surcharge.tax_rate / 100;  --Added /100 by Chong for bug#13359892 20120927 start
5702 
5703                   ln_surcharge_amount := ROUND(ln_surcharge_amount, get_tax_rounding(p_invoice_id));  --Added by Chong for bug#15939571 2012/12/19
5704 
5705 
5706                   jai_ap_dtc_generation_pkg.generate_tds_invoices
5707                   (
5708                      pn_invoice_id              =>      p_invoice_id,
5709                      pn_threshold_hdr_id        =>      ln_threshold_hdr_id    ,
5710                      pn_taxable_amount          =>      ln_sum_tax_amount,
5711                      pn_tax_amount              =>      ln_surcharge_amount,
5712                      pn_tax_id                  =>      rec_surcharge.tax_id,
5713                      pv_section_code            =>      lv_section_code,   --Added by Chong for bug#16048702
5714                      pd_accounting_date         =>      p_accounting_date      ,
5715                      pv_tds_event               =>      G_SURCHARGE_CALCULATE            ,
5716                      pn_threshold_grp_id        =>      p_threshold_grp_id    ,
5717                      pv_tds_invoice_num         =>      lv_tds_invoice_num     ,
5718                      pv_cm_invoice_num          =>      lv_tds_cm_num          ,
5719                      pn_threshold_trx_id        =>      ln_threshold_trx_id    ,
5720                      pd_creation_date           =>      sysdate,
5721                      pn_calc_tax_amount         =>      0,
5722                      p_process_flag             =>      p_process_flag         ,
5723                      p_process_message          =>      p_process_message
5724                   );
5725 
5726                   if p_process_flag = 'E' then
5727                      goto exit_from_procedure;
5728                   end if;
5729 
5730                   --Added by Chong for bug#13359892 20120927 start for unapply cause surcharge transition
5731                   --------------------------------------------------------------------------------------
5732                   IF ln_threshold_trx_id IS NOT NULL --AND
5733                     --p_tds_event like 'THRESHOLD TRANSITION-PPUA%'
5734                   THEN
5735 
5736                     import_and_approve
5737                     (
5738                       p_invoice_id                   =>     p_invoice_id,
5739                       p_start_thhold_trx_id          =>     ln_threshold_trx_id,
5740                       p_tds_event                    =>     G_SURCHARGE_CALCULATE,
5741                       p_process_flag                 =>     p_process_flag,
5742                       p_process_message              =>     p_process_message
5743                     );
5744 
5745                     IF p_process_flag = 'E' THEN
5746                       goto exit_from_procedure;
5747                     END IF;
5748 
5749                     --Added by Chong for bug#16414088 eTDS ER Start
5750                     ----------------------------------------------------------------------
5751                     --Hook code add here after call generate_tds_invoice for surcharge calculation invoice.
5752                     jai_ap_tds_pop_rpst_pkg.Process_surcharge(
5753                                                   pn_source_invoice_id => p_invoice_id
5754                                                  ,pv_event             => G_SURCHARGE_CALCULATE
5755                                                  ,pn_taxable_amount    => ln_sum_tax_amount
5756                                                  ,pn_tax_amount        => ln_surcharge_amount
5757                                                  ,pn_threshold_grp_id  => p_threshold_grp_id
5758                                                  ,pn_surcharge_tax_id  => rec_surcharge.tax_id
5759 
5760                      );
5761                     ----------------------------------------------------------------------
5762                     --Added by Chong for bug#16414088 eTDS ER End
5763 
5764                   END IF;
5765                   --------------------------------------------------------------------------------------
5766                   --Added by Chong for bug#13359892 20120927 End
5767                    /* Update the total tax amount for which invoice was raised */
5768                   ln_threshold_grp_id:= p_threshold_grp_id;
5769                    maintain_thhold_grps
5770                   (
5771                    p_threshold_grp_id             =>   ln_threshold_grp_id,
5772                    p_trx_tax_paid                 =>   ln_surcharge_amount,
5773                    p_trx_thhold_change_tax_paid   =>   ln_surcharge_amount,
5774                    p_trx_threshold_slab_id        =>   p_threshold_slab_id,
5775                    p_tds_event                    =>   G_SURCHARGE_CALCULATE,
5776                    p_invoice_id                   =>   p_invoice_id,
5777                    p_threshold_grp_audit_id       =>   ln_threshold_grp_audit_id,
5778                    p_creation_date                =>   sysdate,
5779                    p_process_flag                 =>   p_process_flag,
5780                    P_process_message              =>   P_process_message,
5781                    p_codepath                     =>   lv_codepath
5782                   );
5783 
5784                   UPDATE JAI_AP_TDS_THHOLD_TRXS
5785                   SET ROLLBACK_REVERSED = 'Y'
5786                   WHERE TDS_EVENT LIKE G_SURCHARGE_ROLLBACK
5787                   AND ROLLBACK_REVERSED IS NULL
5788                   AND THRESHOLD_GRP_ID = p_threshold_grp_id;
5789 
5790 
5791 
5792               end if;
5793           END LOOP;
5794 
5795 
5796           <<exit_from_procedure>>
5797           jai_cmn_utils_pkg.WRITE_FND_LOG(G_LEVEL_PROCEDURE, G_MODULE_NAME||l_api_name||'.END', G_PKG_NAME || ': '||l_api_name||'()-');
5798           return;
5799 
5800           exception
5801             when others then
5802               p_process_flag := 'E';
5803               p_process_message := 'Error from jai_ap_tds_generation_pkg.process_threshold_trans :' || sqlerrm;
5804 
5805 
5806     END process_threshold_transition;
5807 
5808 
5809 
5810 
5811 
5812 
5813   /****************************************process_dtc_at_inv_validate***************************************/
5814   --------------------------------------------------------------------------------------------
5815   --Added by Zhiwei.Hou for Bug#13359892 DTC enhancement on 20111124 end
5816 
5817 
5818 
5819 
5820 
5821 
5822 
5823 
5824 
5825 
5826 
5827 
5828   /* *********************************** procedure generate_tds_invoices ********************************** */
5829   --Remain to generate tds invoice for WCT ESSI and Surcharge TDS which not using category.
5830 procedure generate_tds_invoices
5831   (
5832     pn_invoice_id                         in                 number,
5833     pn_invoice_line_number                in                 number   default null, /* AP lines  */
5834     pn_invoice_distribution_id            in                 number   default null, /* Prepayment apply / unapply scenario */
5835     pv_invoice_num_prepay_apply           in                 varchar2 default null, /* Prepayment application secanrio */
5836     pv_invoice_num_to_tds_apply           in                 varchar2 default null, /* Prepayment unapplication secanrio */
5837     pv_invoice_num_to_vendor_apply        in                 varchar2 default null, /* Prepayment unapplication secanrio */
5838     pv_invoice_num_to_vendor_can          in                 varchar2 default null, /* Invoice Cancel Secnario */
5839     pn_threshold_hdr_id                   in                 number   default null, /* For validate scenario only */
5840     pn_taxable_amount                     in                 number,
5841     pn_tax_amount                         in                 number,
5842     pn_tax_id                             in                 number,
5843     pv_section_code                       in                 varchar2,   --Added by Chong for bug#16048702
5844     pd_accounting_date                    in                 date,
5845     pv_tds_event                          in                 varchar2,
5846     pn_threshold_grp_id                   in                 number,
5847     pv_tds_invoice_num                    out      nocopy    varchar2,
5848     pv_cm_invoice_num                     out      nocopy    varchar2,
5849     pn_threshold_trx_id                   out      nocopy    number,
5850     -- Bug 5722028. Added by csahoo
5851     pd_creation_date                      in                 date,
5852     pn_calc_tax_amount                    in                 number default 0, /* Added for bug 12965614 */
5853     p_process_flag                        out      nocopy    varchar2,
5854     p_process_message                     out      nocopy    varchar2
5855   )
5856   is
5857 
5858   cursor c_ap_invoices_all(cp_invoice_id number) is
5859     select  invoice_num,
5860             vendor_id,
5861             vendor_site_id,
5862             invoice_currency_code,
5863             exchange_rate_type,
5864             exchange_date,
5865             terms_id,
5866             payment_method_lookup_code,
5867             pay_group_lookup_code,
5868             invoice_date,
5869             goods_received_date,
5870             invoice_received_date,
5871             org_id,
5872             nvl(exchange_rate, 1) exchange_rate,
5873             set_of_books_id,
5874             payment_method_code, -- Bug 7109056
5875             accts_pay_code_combination_id -- Bug 9759709
5876     from    ap_invoices_all
5877     where   invoice_id = cp_invoice_id;
5878 
5879   cursor c_po_vendor_sites_all(cp_vendor_id  number, cp_vendor_site_id number) is
5880     select  terms_id,
5881             --payment_method_lookup_code, --commented by Sanjikum for Bug#4482462
5882             pay_group_lookup_code
5883     from    po_vendor_sites_all
5884     where   vendor_id = cp_vendor_id
5885     and     vendor_site_id = cp_vendor_site_id;
5886 
5887   cursor c_po_vendors(cp_vendor_id  number) is
5888     select  terms_id,
5889             --payment_method_lookup_code, --commented by Sanjikum for Bug#4482462
5890             pay_group_lookup_code
5891     from    po_vendors
5892     where   vendor_id = cp_vendor_id;
5893 
5894 
5895   cursor c_ja_in_tax_codes (pn_tax_id number) is
5896     select  section_code,
5897             vendor_id,
5898             vendor_site_id,
5899             tax_rate,
5900             stform_type,
5901             tax_account_id,
5902             section_type,
5903             tax_type
5904     from    JAI_CMN_TAXES_ALL
5905     where   tax_id = pn_tax_id;
5906 
5907 
5908   cursor c_gl_sets_of_books(cp_set_of_books_id  number) is
5909     select currency_code
5910     from   gl_sets_of_books
5911     where  set_of_books_id = cp_set_of_books_id;
5912 
5913   cursor c_get_ja_in_ap_inv_id is
5914     select to_char(JAI_AP_TDS_THHOLD_TRXS_S1.nextval)--to_char(JAI_AP_TDS_INVOICE_NUM_S.nextval)commented by  rchandan for bug#4487676
5915     from  dual;
5916 
5917   cursor c_ap_payment_schedules_all(p_invoice_id number) is
5918     select payment_priority
5919     from   ap_payment_schedules_all
5920     where  invoice_id = p_invoice_id;
5921 
5922   --Add by Chong on 20130130 for bug#16048702 begin
5923   ----------------------------------------------------------------------
5924   CURSOR get_revised_section_code(p_section_code varchar2
5925                                  ,p_accounting_date date
5926                                  )
5927   IS
5928   SELECT jatsm.section_code_revised
5929   FROM jai_ap_tds_sec_map jatsm
5930   WHERE jatsm.regime_id in (
5931               SELECT jrd.regime_id
5932                 FROM ja_lookups          jl
5933                     ,jai_rgm_definitions jrd
5934                WHERE jl.lookup_code = jrd.regime_code
5935                  AND jl.lookup_type = 'JAI_INDIA_TAX_REGIMES'
5936                  AND jl.lookup_code = 'TDS'
5937         )
5938   AND   jatsm.section_code = p_section_code
5939   AND   jatsm.from_date <= p_accounting_date
5940   AND   (jatsm.to_date IS NULL
5941          OR jatsm.to_date >= p_accounting_date
5942         );
5943   ----------------------------------------------------------------------
5944   --Add by Chong on 20130130 for bug#16048702 end
5945 
5946   r_ap_invoices_all               c_ap_invoices_all%rowtype;
5947   r_ja_in_tax_codes               c_ja_in_tax_codes%rowtype;
5948   r_po_vendor_sites_all           c_po_vendor_sites_all%rowtype;
5949   r_po_vendors                    c_po_vendors%rowtype;
5950   r_gl_sets_of_books              c_gl_sets_of_books%rowtype;
5951   r_ap_payment_schedules_all      c_ap_payment_schedules_all%rowtype;
5952 
5953 
5954   lv_source                       varchar2(30); --File.Sql.35 Cbabu  := 'TDS';
5955 
5956   lv_invoice_to_tds_num           ap_invoices_all.invoice_num%type;
5957   lv_invoice_to_vendor_num        ap_invoices_all.invoice_num%type;
5958 
5959   lv_invoice_to_tds_type          ap_invoices_all.invoice_type_lookup_code%type;
5960   lv_invoice_to_vendor_type       ap_invoices_all.invoice_type_lookup_code%type;
5961 
5962   ln_invoice_to_tds_id            ap_invoices_all.invoice_id%type;
5963   ln_invoice_to_vendor_id         ap_invoices_all.invoice_id%type;
5964 
5965   ln_invoice_to_tds_line_id       ap_invoice_lines_interface.invoice_line_id%type;
5966   ln_invoice_to_vendor_line_id    ap_invoice_lines_interface.invoice_line_id%type;
5967 
5968   lv_invoice_to_tds_line_type     ap_invoice_distributions_all.line_type_lookup_code%type; --File.Sql.35 Cbabu  := 'ITEM';
5969   lv_invoice_to_vendor_line_type  ap_invoice_distributions_all.line_type_lookup_code%type; --File.Sql.35 Cbabu  := 'ITEM';
5970 
5971   ln_invoice_to_tds_amount        number;
5972   ln_invoice_to_vendor_amount     number;
5973 
5974   ln_exchange_rate                number;
5975   lv_this_procedure               varchar2(50); --File.Sql.35 Cbabu  := 'jaiap.generate_tds_invoice';
5976 
5977   ln_terms_id                     po_vendors.terms_id%type;
5978   -- lv_payment_method_lookup_code   po_vendors.payment_method_lookup_code%type; --commented by Sanjikum for Bug#4482462
5979   lv_pay_group_lookup_code        po_vendors.pay_group_lookup_code%type;
5980 
5981   lv_ja_in_ap_inv_id              varchar2(15);
5982   ld_accounting_date              date;
5983   lv_open_period                  ap_invoice_distributions_all.period_name%type;
5984   ln_tax_amount                   number;
5985 
5986   lv_invoice_num                  ap_invoices_all.invoice_num%type;
5987   lv_source_attribute             jai_ap_tds_invoices.source_attribute%TYPE ;   --rchandan for bug#4428980
5988 
5989   ln_invoice_amount               ap_invoices_all.invoice_amount%TYPE; --Added by Ramananda for Bug#4562801
5990 
5991  	lv_group_id                     VARCHAR2(80); --Added by Sanjikum for Bug#5131075(4722011)
5992 
5993  	/* Bug 5722028. Added by Lakshmi Gopalsami
5994 	 * Added following variables
5995 	 */
5996 	ln_tds_rnded_amt      NUMBER;
5997 	ln_tds_mod_value      NUMBER;
5998 	ln_tds_rnding_factor  NUMBER;
5999 
6000     lv_section_name varchar2(10); --Added for Bug# 7410219
6001     pv_invoice_date   DATE;  --Added by Bgowrava for Bug#9186263
6002     ln_accts_pay_ccid NUMBER; -- Bug 9759709
6003     l_api_name                   CONSTANT  VARCHAR2(50) := 'generate_tds_invoices()';
6004 
6005 begin
6006 
6007   jai_cmn_utils_pkg.WRITE_FND_LOG(G_LEVEL_PROCEDURE, G_MODULE_NAME||l_api_name||'.BEGIN', G_PKG_NAME || ': '||l_api_name||'()+');
6008   jai_cmn_utils_pkg.WRITE_FND_LOG(G_LEVEL_PROCEDURE, G_MODULE_NAME||l_api_name||'.Parameter', 'pn_invoice_id: ' || pn_invoice_id);
6009   jai_cmn_utils_pkg.WRITE_FND_LOG(G_LEVEL_PROCEDURE, G_MODULE_NAME||l_api_name||'.Parameter', 'pn_taxable_amount: ' || pn_taxable_amount);
6010   jai_cmn_utils_pkg.WRITE_FND_LOG(G_LEVEL_PROCEDURE, G_MODULE_NAME||l_api_name||'.Parameter', 'pn_tax_amount: ' || pn_tax_amount);
6011   jai_cmn_utils_pkg.WRITE_FND_LOG(G_LEVEL_PROCEDURE, G_MODULE_NAME||l_api_name||'.Parameter', 'pn_tax_id: ' || pn_tax_id);
6012   jai_cmn_utils_pkg.WRITE_FND_LOG(G_LEVEL_PROCEDURE, G_MODULE_NAME||l_api_name||'.Parameter', 'pv_tds_event: ' || pv_tds_event);
6013   jai_cmn_utils_pkg.WRITE_FND_LOG(G_LEVEL_PROCEDURE, G_MODULE_NAME||l_api_name||'.Parameter', 'pn_threshold_hdr_id: ' || pn_threshold_hdr_id);
6014   jai_cmn_utils_pkg.WRITE_FND_LOG(G_LEVEL_PROCEDURE, G_MODULE_NAME||l_api_name||'.Parameter', 'pn_threshold_grp_id: ' || pn_threshold_grp_id);
6015 
6016   lv_source                        := 'INDIA TDS'; /* --:= 'TDS'; --Ramanand for bug#4388958 */
6017   lv_invoice_to_tds_line_type     := 'ITEM';
6018   lv_invoice_to_vendor_line_type  := 'ITEM';
6019   lv_this_procedure               := 'jaiap.generate_tds_invoice';
6020 
6021 
6022   /* Amount to be paid to TDS Authority should always be +ve */
6023   /* In case of prepayment application, this is still passed as +ve amount */
6024 
6025   /* Bug 4513458. added by Lakshmi Gopalsami
6026    * Removed the rounding and assigned the exact amount
6027    * and the rounding is handled at later point to
6028    * accommodate the currency code
6029   */
6030   --ln_tax_amount := round(pn_tax_amount, 2);
6031   ln_tax_amount := pn_tax_amount;
6032 
6033   /* Bug 4522507. Added by Lakshmi Gopalsami
6034      Checked whether round(ln_tax_amount) is less than
6035      zero instead of ln_tax_amount */
6036   if round(ln_tax_amount,2) <= 0 then
6037     p_process_flag := 'X';
6038     p_process_message := 'TDS amount must be greater than 0 ';
6039     goto exit_from_procedure;
6040   end if;
6041 
6042   open  c_ap_invoices_all(pn_invoice_id);
6043   fetch c_ap_invoices_all into r_ap_invoices_all;
6044   close c_ap_invoices_all;
6045 
6046   /*
6047   || moved this up from the under the cursor - c_po_vendor_sites_all by Ramananda for Bug#4562793
6048   */
6049   open  c_ja_in_tax_codes(pn_tax_id);
6050   fetch c_ja_in_tax_codes into r_ja_in_tax_codes;
6051   close c_ja_in_tax_codes;
6052 
6053   /*
6054   || open c_po_vendors(r_ap_invoices_all.vendor_id);
6055   || Commented the above and added the below by Ramananda for Bug#4562793
6056   */
6057   open c_po_vendors(r_ja_in_tax_codes.vendor_id);
6058   fetch c_po_vendors into r_po_vendors;
6059   close c_po_vendors;
6060 
6061   /*
6062   || open  c_po_vendor_sites_all(r_ap_invoices_all.vendor_id, r_ap_invoices_all.vendor_site_id);
6063   || Commented the above and added the below by sanjikum for Bug#4562793
6064   */
6065   open  c_po_vendor_sites_all(r_ja_in_tax_codes.vendor_id, r_ja_in_tax_codes.vendor_site_id);
6066   fetch c_po_vendor_sites_all into r_po_vendor_sites_all;
6067   close c_po_vendor_sites_all;
6068 
6069   open  c_gl_sets_of_books(r_ap_invoices_all.set_of_books_id);
6070   fetch c_gl_sets_of_books into r_gl_sets_of_books;
6071   close c_gl_sets_of_books;
6072 
6073   /*Bug # 7410219 - Derive the Section Name*/
6074   if (r_ja_in_tax_codes.section_type = 'TDS_SECTION') then
6075      --lv_section_name := 'TDS';  --commented by Chong for bug#16048702 20130130
6076      --Add by Chong on 20130130 for bug#16048702 begin
6077      ----------------------------------------------------------------------
6078      open get_revised_section_code(pv_section_code,pd_accounting_date);
6079      fetch get_revised_section_code into lv_section_name;
6080      close get_revised_section_code;
6081      lv_section_name := NVL(lv_section_name, 'TDS');
6082      ----------------------------------------------------------------------
6083      --Add by Chong on 20130130 for bug#16048702 end
6084   elsif (r_ja_in_tax_codes.section_type = 'WCT_SECTION') then
6085      lv_section_name := 'WCT';
6086   elsif (r_ja_in_tax_codes.section_type = 'ESSI_SECTION') then
6087      lv_section_name := 'ESSI';
6088   end if;
6089   /*Bug # 7410219 - End*/
6090 
6091   /* Get the payment details from the vendor site */
6092   ln_terms_id                   := r_po_vendor_sites_all.terms_id;
6093   -- lv_payment_method_lookup_code := r_po_vendor_sites_all.payment_method_lookup_code;--commented by Sanjikum for Bug#4482462
6094   lv_pay_group_lookup_code      := r_po_vendor_sites_all.pay_group_lookup_code;
6095 
6096 
6097   if (
6098         ln_terms_id is null or
6099         -- lv_payment_method_lookup_code is null or --commented by Sanjikum for Bug#4482462
6100         lv_pay_group_lookup_code is null
6101      )
6102   then
6103 
6104     /* Get the payment details from the vendor as it has been not defined for the site */
6105     ln_terms_id                   := r_po_vendors.terms_id;
6106     -- lv_payment_method_lookup_code := r_po_vendors.payment_method_lookup_code; --commented by Sanjikum for Bug#4482462
6107     lv_pay_group_lookup_code      := r_po_vendors.pay_group_lookup_code;
6108 
6109   end if;
6110 
6111 
6112   /* Get the unique number to suffix the tds invoices with */
6113   open c_get_ja_in_ap_inv_id;
6114   fetch c_get_ja_in_ap_inv_id into lv_ja_in_ap_inv_id;
6115   close c_get_ja_in_ap_inv_id;
6116 
6117   lv_invoice_num := substr(r_ap_invoices_all.invoice_num, 1, 30);
6118 
6119   /* Invoice Numbers, type  for the invoice pair that is being created */
6120   if ( (pv_tds_event = 'INVOICE VALIDATE') or (pv_tds_event like 'THRESHOLD TRANSITION%') ) then
6121 
6122     /* Standard invoice to TDS authority, Credit memo to supplier */
6123 
6124     lv_invoice_to_tds_type := 'STANDARD';
6125     lv_invoice_to_vendor_type := 'CREDIT';
6126     /*Bug 7410219 - Modified Invoice Number as per Section*/
6127     lv_invoice_to_tds_num     := lv_invoice_num ||'-'||lv_section_name||'-SI-'||lv_ja_in_ap_inv_id;
6128     lv_invoice_to_vendor_num := lv_invoice_num ||'-'||lv_section_name||'-CM-'||lv_ja_in_ap_inv_id;
6129 
6130     ln_invoice_to_tds_amount :=  ln_tax_amount;
6131     ln_invoice_to_vendor_amount := (-1) * ln_tax_amount;
6132 
6133   elsif pv_tds_event = 'PREPAYMENT APPLICATION' OR pv_tds_event like 'THRESHOLD ROLLBACK%' then --Added by Sanjikum for Bug#5131075(4718907)
6134 
6135     /* Credit memo to TDS authority, Standard invoice to supplier */
6136     if pv_invoice_num_prepay_apply is not null then
6137       lv_invoice_num := substr(pv_invoice_num_prepay_apply, 1, 30);
6138     end if;
6139 
6140     lv_invoice_to_tds_type := 'CREDIT';
6141     lv_invoice_to_vendor_type := 'STANDARD';
6142     /*Bug 7410219 - Modified Invoice Number as per Section*/
6143     lv_invoice_to_tds_num     := lv_invoice_num ||'-RTN-'||lv_section_name||'-CM-'||lv_ja_in_ap_inv_id;
6144     lv_invoice_to_vendor_num  := lv_invoice_num ||'-RTN-'||lv_section_name||'-SI-'||lv_ja_in_ap_inv_id;
6145 
6146     ln_invoice_to_tds_amount :=  -1 * ln_tax_amount;
6147     ln_invoice_to_vendor_amount :=  ln_tax_amount;
6148 
6149   elsif pv_tds_event = 'PREPAYMENT UNAPPLICATION' then
6150 
6151     /* Standard invoice to TDS authority, Credit memo to supplier */
6152     lv_invoice_to_tds_type := 'STANDARD';
6153     lv_invoice_to_vendor_type := 'CREDIT';
6154 
6155     if pv_invoice_num_to_tds_apply is not null then
6156       lv_invoice_to_tds_num    := 'CAN/' || substr(pv_invoice_num_to_tds_apply, 1, 45);
6157     else
6158       /*Bug 7410219 - Modified Invoice Number as per Section*/
6159       lv_invoice_to_tds_num    := lv_invoice_num ||'-RTN-'||lv_section_name||'-SI-'||lv_ja_in_ap_inv_id;
6160     end if;
6161 
6162     if pv_invoice_num_to_vendor_apply is not null then
6163       lv_invoice_to_vendor_num := 'CAN/' || substr(pv_invoice_num_to_vendor_apply, 1, 45);
6164     else
6165       /*Bug 7410219 - Modified Invoice Number as per Section*/
6166       lv_invoice_to_vendor_num := lv_invoice_num ||'-RTN-'||lv_section_name||'-CM-'||lv_ja_in_ap_inv_id;
6167     end if;
6168 
6169     ln_invoice_to_tds_amount :=  ln_tax_amount;
6170     ln_invoice_to_vendor_amount := (-1) * ln_tax_amount;
6171 
6172   elsif pv_tds_event = 'INVOICE CANCEL' then
6173 
6174       /* No invoice to TDS authority, Standard invoice to supplier */
6175 
6176       lv_invoice_to_tds_num     := null;
6177 
6178       if pv_invoice_num_to_vendor_can is not null then
6179         lv_invoice_to_vendor_num := 'CAN/' || substr(pv_invoice_num_to_vendor_can, 1, 45);
6180       else
6181         /*Bug 7410219 - Modified Invoice Number as per Section*/
6182         lv_invoice_to_vendor_num := lv_invoice_num||'-CAN-'||lv_section_name||'-SI-'||lv_ja_in_ap_inv_id;
6183       end if;
6184 
6185       lv_invoice_to_tds_type := null;
6186       lv_invoice_to_vendor_type := 'STANDARD';
6187 
6188       ln_invoice_to_tds_amount :=  null;
6189       ln_invoice_to_vendor_amount := ln_tax_amount;
6190 
6191 /*START, Bgowrava for Bug#8254510*/
6192   elsif ( pv_tds_event = G_SURCHARGE_CALCULATE) then
6193 
6194 	    /* Standard invoice to TDS authority, Credit memo to supplier */
6195 
6196 	    lv_invoice_to_tds_type := 'STANDARD';
6197 	    lv_invoice_to_vendor_type := 'CREDIT';
6198 
6199 	    lv_invoice_to_tds_num     := lv_invoice_num ||'-SUR-'||lv_section_name||'-SI-'||lv_ja_in_ap_inv_id;   --Added lv_section_name by Chong on 20130130 for bug#16048702
6200 	    lv_invoice_to_vendor_num := lv_invoice_num ||'-SUR-'||lv_section_name||'-CM-'||lv_ja_in_ap_inv_id;  --Added lv_section_name by Chong on 20130130 for bug#16048702
6201 
6202 	    ln_invoice_to_tds_amount :=  ln_tax_amount;
6203     ln_invoice_to_vendor_amount := (-1) * ln_tax_amount;
6204 /*END,  Bgowrava for Bug#8254510*/
6205 --Added by Chong for Bug#13359892 2012/09/27 Start
6206 -----------------------------------------------------------------------------
6207   elsif ( pv_tds_event = G_SURCHARGE_ROLLBACK) then
6208     /* Credit memo to TDS authority, Standard invoice to supplier */
6209     lv_invoice_to_tds_type := 'CREDIT';
6210     lv_invoice_to_vendor_type := 'STANDARD';
6211 
6212     lv_invoice_to_tds_num     := lv_invoice_num ||'-SUR-RTN-'||lv_section_name||'-CM-'||lv_ja_in_ap_inv_id; --Added lv_section_name by Chong on 20130130 for bug#16048702
6213     lv_invoice_to_vendor_num := lv_invoice_num ||'-SUR-RTN-'||lv_section_name||'-SI-'||lv_ja_in_ap_inv_id; --Added lv_section_name by Chong on 20130130 for bug#16048702
6214 
6215     ln_invoice_to_tds_amount :=  (-1) * ln_tax_amount;
6216     ln_invoice_to_vendor_amount := ln_tax_amount;
6217 -----------------------------------------------------------------------------
6218 --Added by Chong for Bug#13359892 2012/09/27 End
6219 
6220   end if; /* TDS event type */
6221 
6222   pv_tds_invoice_num := lv_invoice_to_tds_num;
6223   pv_cm_invoice_num  := lv_invoice_to_vendor_num;
6224 
6225   /* Check if the given date is in current open period */
6226 
6227   /* Bug 4559756. Added by Lakshmi Gopalsami
6228      Added org_id to ap_utilities_pkg
6229   */
6230   lv_open_period:=  ap_utilities_pkg.get_current_gl_date
6231                                      (pd_accounting_date,
6232               r_ap_invoices_all.org_id
6233               );
6234 
6235   /* Bug 4559756. Added by Lakshmi Gopalsami
6236      Added org_id to ap_utilities_pkg
6237   */
6238 
6239   if lv_open_period is null then
6240 
6241     ap_utilities_pkg.get_open_gl_date
6242     (
6243       pd_accounting_date,
6244       lv_open_period,
6245       ld_accounting_date,
6246       r_ap_invoices_all.org_id
6247     );
6248 
6249     if lv_open_period is null then
6250       p_process_flag := 'E';
6251       p_process_message := 'No open accounting Period after : ' || pd_accounting_date ;
6252       goto exit_from_procedure;
6253     end if;
6254 
6255     else
6256       ld_accounting_date := pd_accounting_date;
6257     end if; /* ld_accounting_date */
6258 
6259     --Added by Sanjikum for Bug#5131075(4722011)
6260     IF pv_tds_event = 'PREPAYMENT APPLICATION' OR pv_tds_event = 'PREPAYMENT UNAPPLICATION' THEN
6261       lv_group_id := to_char(pn_invoice_id)||pv_tds_event;
6262 	  pv_invoice_date := ld_accounting_date;   --Added by Bgowrava for Bug#9186263
6263     ELSE
6264       lv_group_id := to_char(pn_invoice_id);
6265 	  pv_invoice_date := r_ap_invoices_all.invoice_date;  --Added by Bgowrava for Bug#9186263
6266     END IF;
6267 
6268 
6269     /* Invoice to TDS Authority */
6270     /* Bug 4513458. Added by Lakshmi Gopalsami
6271      * Rounded the amount to zero as the TDS invoice amount should
6272      * be in INR currency */
6273 
6274    -- ln_invoice_to_tds_amount := ROUND(ln_invoice_to_tds_amount,0);
6275    /* Bug 5722028. Added by csahoo
6276     * Rounded depending on the setup.
6277     */
6278       IF pv_tds_event NOT IN
6279         -- Bug 7280925. Commented by Lakshmi Gopalsami ('INVOICE CANCEL',
6280            ('PREPAYMENT UNAPPLICATION')
6281       THEN
6282        ln_invoice_to_tds_amount := ROUND(ln_invoice_to_tds_amount,g_inr_currency_rounding);
6283         fnd_file.put_line(FND_FILE.LOG, ' Bug 7280925 - value before round '||ln_invoice_to_tds_amount);
6284 	IF trunc(pd_creation_date) >= trunc(jai_ap_tds_generation_pkg.gd_tds_rounding_effective_date)
6285         /* Bug 7280925. Added by Lakshmi Gopalsami
6286 	 * we should not round for WCT and ESSI. For those threshold_grp_id
6287 	 * will be null
6288 	 */
6289          and pn_threshold_grp_id is not null
6290 	THEN
6291 	  ln_invoice_to_tds_amount := get_rnded_value(ln_invoice_to_tds_amount);
6292         fnd_file.put_line(FND_FILE.LOG, ' Bug 7280925 - value after round per setup TDS auth inv'||ln_invoice_to_tds_amount);
6293 	END IF;
6294       END IF ; -- pv_tds_event  not in
6295 
6296     -- End for Bug 5722028
6297 
6298     --if lv_invoice_to_tds_num is not null and lv_invoice_to_tds_type is not null then
6299 	--commented the above and added the below by bgowrava  for bug#4549019
6300 	if lv_invoice_to_tds_num is not null and lv_invoice_to_tds_type is not null and NVL(ln_invoice_to_tds_amount,0) <> 0 then
6301 
6302       /* Generate the Invoice for the TDS authority - always in functional currency - INR  */
6303 
6304       jai_ap_utils_pkg.insert_ap_inv_interface
6305       (
6306         p_jai_source                        => lv_this_procedure,
6307         p_invoice_id                        => ln_invoice_to_tds_id,
6308         p_invoice_num                       => lv_invoice_to_tds_num,
6309         p_invoice_type_lookup_code          => lv_invoice_to_tds_type,
6310         p_invoice_date                      => ld_accounting_date,  --Bug 10020606 - Replaced Base Supplier Invoice Date with GL Date
6311 		p_gl_date                           => ld_accounting_date, --Added by Bgowrava for Bug#9186263
6312         p_vendor_id                         => r_ja_in_tax_codes.vendor_id,
6313         p_vendor_site_id                    => r_ja_in_tax_codes.vendor_site_id,
6314         p_invoice_amount                    => ln_invoice_to_tds_amount,
6315         p_invoice_currency_code             => r_gl_sets_of_books.currency_code,
6316         p_exchange_rate                     => null,
6317         p_exchange_rate_type                => null,
6318         p_exchange_date                     => null,
6319         p_terms_id                          => ln_terms_id,
6320         p_description                       => lv_invoice_to_tds_num,
6321         p_last_update_date                  => sysdate,
6322         p_last_updated_by                   => fnd_global.user_id,
6323         p_last_update_login                 => fnd_global.login_id,
6324         p_creation_date                     => sysdate,
6325         p_created_by                        => fnd_global.user_id,
6326         p_source                            => lv_source,
6327         p_voucher_num                       => lv_invoice_to_tds_num,
6328         --p_payment_method_lookup_code        => lv_payment_method_lookup_code,
6329         --commented by Sanjikum for Bug#4482462
6330         p_pay_group_lookup_code             => lv_pay_group_lookup_code,
6331         p_org_id                            => r_ap_invoices_all.org_id,
6332         p_attribute_category                => 'India Original Invoice for TDS',
6333         p_attribute1                        => pn_invoice_id,
6334 	--added the below by Sanjikum for Bug#5131075(4722011)
6335         p_group_id                          => lv_group_id, -- Bug# 6119216, changed to lv_group_id instead of to_char(p_invoice_id)
6336 	p_Calc_Tax_During_Import_Flag       => 'Y'   --Added by Qiong for AP Open Interface
6337       );
6338 
6339       /* Lines Interface */
6340       jai_ap_utils_pkg.insert_ap_inv_lines_interface
6341       (
6342         p_jai_source                        => lv_this_procedure,
6343         p_invoice_id                        => ln_invoice_to_tds_id,
6344         p_invoice_line_id                   => ln_invoice_to_tds_line_id,
6345         p_line_number                       => 1,
6346         p_line_type_lookup_code             => lv_invoice_to_tds_line_type,
6347         p_amount                            => ln_invoice_to_tds_amount,
6348         p_accounting_date                   => ld_accounting_date,
6349         --p_description                       => lv_invoice_to_tds_num,
6350         p_description                       => lv_invoice_to_tds_num||'/'||pv_section_code||'/'||r_ja_in_tax_codes.tax_type||'/'||pn_tax_id||'/'||r_ja_in_tax_codes.tax_rate,--Update by Chong on 20130320
6351         p_dist_code_combination_id          => r_ja_in_tax_codes.tax_account_id,
6352         p_last_update_date                  => sysdate,
6353         p_last_updated_by                   => fnd_global.user_id,
6354         p_last_update_login                 => fnd_global.login_id,
6355         p_creation_date                     => sysdate,
6356         p_created_by                        => fnd_global.user_id
6357       );
6358 
6359     end if; /* Invoice to TDS authority */
6360 
6361 
6362 
6363     /* Invoice to Supplier */
6364 
6365     if lv_invoice_to_vendor_num is not null and lv_invoice_to_vendor_type is not null then
6366 
6367       /* Generate the TDS invoice for the supplier  in supplier invoice currency */
6368 
6369       /* Bug 5722028. Added by csahoo
6370        * Rounded depending on the setup.
6371        */
6372     /*  IF pv_tds_event NOT IN
6373          -- Bug 7280925. Commented by Lakshmi Gopalsami ('INVOICE CANCEL',
6374            ('PREPAYMENT UNAPPLICATION') THEN */
6375          -- Bug 7280925. Commented by Lakshmi Gopalsami
6376 		 /* Bug 12965614. Added by Avanija
6377          * Added the following condition to handle for prepayment unapplication for foreign currency invoices.
6378          */
6379 		 IF pv_tds_event = 'PREPAYMENT UNAPPLICATION' THEN  --2
6380            IF r_ap_invoices_all.invoice_currency_code <> r_gl_sets_of_books.currency_code  THEN --3
6381               ln_invoice_to_vendor_amount := round( ln_invoice_to_vendor_amount, g_inr_currency_rounding);
6382             IF trunc(pd_creation_date) >= trunc(jai_ap_tds_generation_pkg.gd_tds_rounding_effective_date) THEN
6383 			    ln_invoice_to_vendor_amount := get_rnded_value(ln_invoice_to_vendor_amount);
6384             END IF;
6385             ln_invoice_to_vendor_amount := round( ln_invoice_to_vendor_amount / r_ap_invoices_all.exchange_rate, g_fcy_currency_rounding);
6386            END IF;	--3
6387 
6388         ELSE --2
6389 
6390           if r_ap_invoices_all.invoice_currency_code <> r_gl_sets_of_books.currency_code  then
6391 	   /*START, Bgowrava for Bug#8995604 , Adding below IF statement to round the INR TDS CM invoice to
6392 			        the TDS rounding factor before converting it to a foreign currency CM*/
6393 		ln_invoice_to_vendor_amount := round( ln_invoice_to_vendor_amount, g_inr_currency_rounding);
6394 		IF trunc(pd_creation_date) >= trunc(jai_ap_tds_generation_pkg.gd_tds_rounding_effective_date)
6395            and pn_threshold_grp_id is not null THEN
6396 		    ln_invoice_to_vendor_amount := get_rnded_value(ln_invoice_to_vendor_amount);
6397 		END IF;
6398 	   /*END, Bgowrava for Bug#8995604 */
6399 	  ln_invoice_to_vendor_amount := round( ln_invoice_to_vendor_amount / r_ap_invoices_all.exchange_rate, g_fcy_currency_rounding);
6400        ELSE
6401 	  ln_invoice_to_vendor_amount := round( ln_invoice_to_vendor_amount, g_inr_currency_rounding);
6402 	  /*START, Bgowrava for Bug#8995604 , Adding below IF statement to round the INR TDS CM invoice to   the TDS rounding factor*/
6403 		IF trunc(pd_creation_date) >= trunc(jai_ap_tds_generation_pkg.gd_tds_rounding_effective_date)
6404 		   and pn_threshold_grp_id is not null THEN
6405 		    ln_invoice_to_vendor_amount := get_rnded_value(ln_invoice_to_vendor_amount);
6406         END IF;
6407       /*END, Bgowrava for Bug#8995604 */
6408 
6409         END IF; --2
6410      END IF;
6411 
6412 
6413        fnd_file.put_line(FND_FILE.LOG, ' Bug 7280925 - value before round '||ln_invoice_to_vendor_amount);
6414        /*IF trunc(pd_creation_date) >=
6415           trunc(jai_ap_tds_generation_pkg.gd_tds_rounding_effective_date)
6416                 and pn_threshold_grp_id is not null
6417        THEN
6418 	  ln_invoice_to_vendor_amount := get_rnded_value(ln_invoice_to_vendor_amount);
6419         fnd_file.put_line(FND_FILE.LOG, ' Bug 7280925 - value after round per setup - vendor invoice'||ln_invoice_to_vendor_amount);
6420        END IF; */  --commented by bgowrava for Bug#8995604
6421 
6422 
6423       if upper(r_ap_invoices_all.exchange_rate_type) = 'USER' then
6424         ln_exchange_rate := r_ap_invoices_all.exchange_rate;
6425       else
6426         ln_exchange_rate := null;
6427       end if;
6428 
6429       fnd_file.put_line(FND_FILE.LOG, ' CALL utils for inserting interface lines');
6430 
6431       /*Bug 9759709 - Liability Account for the Credit Note must be fetched from the Standard Invoice
6432       If it is not present, then it needs to be defaulted from Vendor Site Setup. Passing NULL to
6433       parameter p_accts_pay_ccid in jai_ap_utils_pkg.insert_ap_inv_interface would cause it to default
6434       from setup*/
6435       if (r_ap_invoices_all.accts_pay_code_combination_id is not NULL) then
6436         ln_accts_pay_ccid := r_ap_invoices_all.accts_pay_code_combination_id;
6437       else
6438         ln_accts_pay_ccid := NULL;
6439       end if;
6440 
6441 IF NVL(ln_invoice_to_vendor_amount,0) <> 0 THEN --condition added by bgowrava  for bug#4549019
6442       /* Invoices Interface */
6443       jai_ap_utils_pkg.insert_ap_inv_interface
6444       (
6445         p_jai_source                        => lv_this_procedure,
6446         p_invoice_id                        => ln_invoice_to_vendor_id,
6447         p_invoice_num                       => lv_invoice_to_vendor_num,
6448         p_invoice_type_lookup_code          => lv_invoice_to_vendor_type,
6449         p_invoice_date                      => pv_invoice_date,--r_ap_invoices_all.invoice_date,  --Modified to ld_accounting_date for Bug#9186263
6450         p_gl_date                           => ld_accounting_date,
6451         p_vendor_id                         => r_ap_invoices_all.vendor_id,
6452         p_vendor_site_id                    => r_ap_invoices_all.vendor_site_id,
6453         p_invoice_amount                    => ln_invoice_to_vendor_amount,
6454         p_invoice_currency_code             => r_ap_invoices_all.invoice_currency_code,
6455         p_exchange_rate                     => ln_exchange_rate,
6456         p_exchange_rate_type                => r_ap_invoices_all.exchange_rate_type,
6457         p_exchange_date                     => r_ap_invoices_all.exchange_date,
6458         p_terms_id                          => r_ap_invoices_all.terms_id,
6459         p_description                       => lv_invoice_to_vendor_num,
6460         p_last_update_date                  => sysdate,
6461         p_last_updated_by                   => fnd_global.user_id,
6462         p_last_update_login                 => fnd_global.login_id,
6463         p_creation_date                     => sysdate,
6464         p_created_by                        => fnd_global.user_id,
6465         p_source                            => lv_source,
6466         p_voucher_num                       => lv_invoice_to_vendor_num,
6467         -- Bug 7109056. Added by Lakshmi Gopalsami
6468         p_payment_method_code        => r_ap_invoices_all.payment_method_code,
6469         --commented by Sanjikum for Bug#4482462
6470         p_pay_group_lookup_code             => r_ap_invoices_all.pay_group_lookup_code,
6471         p_goods_received_date               => r_ap_invoices_all.goods_received_date,
6472         p_invoice_received_date             => r_ap_invoices_all.invoice_received_date,
6473         p_org_id                            => r_ap_invoices_all.org_id,
6474         p_attribute_category                => 'India Original Invoice for TDS',
6475         p_attribute1                        => pn_invoice_id,
6476 	--commented the above and added the below by Sanjikum for Bug#5131075(4722011)
6477         p_group_id                          => lv_group_id,
6478         p_accts_pay_ccid                    => ln_accts_pay_ccid, /*Bug 9759709*/
6479 	p_Calc_Tax_During_Import_Flag       => 'Y'   --Added by Qiong for AP Open Interface
6480       );
6481 
6482       /* Lines Interface */
6483       jai_ap_utils_pkg.insert_ap_inv_lines_interface
6484       (
6485         p_jai_source                        => lv_this_procedure,
6486         p_invoice_id                        => ln_invoice_to_vendor_id,
6487         p_invoice_line_id                   => ln_invoice_to_vendor_line_id,
6488         p_line_number                       => 1,
6489         p_line_type_lookup_code             => lv_invoice_to_vendor_line_type,
6490         p_amount                            => ln_invoice_to_vendor_amount,
6491         p_accounting_date                   => ld_accounting_date,
6492         --p_description                       => lv_invoice_to_vendor_num,
6493         p_description                       => lv_invoice_to_vendor_num||'/'||pv_section_code||'/'||r_ja_in_tax_codes.tax_type||'/'||pn_tax_id||'/'||r_ja_in_tax_codes.tax_rate,--Update by Chong on 20130320
6494         p_dist_code_combination_id          => r_ja_in_tax_codes.tax_account_id,
6495         p_last_update_date                  => sysdate,
6496         p_last_updated_by                   => fnd_global.user_id,
6497         p_last_update_login                 => fnd_global.login_id,
6498         p_creation_date                     => sysdate,
6499         p_created_by                        => fnd_global.user_id
6500       );
6501 
6502 end if;
6503     end if;   /* Invoice to Supplier */
6504 
6505     /* Store the parent invoices payment priority as this is to be used in the credit memo generated for the supplier */
6506     open  c_ap_payment_schedules_all(pn_invoice_id);
6507     fetch c_ap_payment_schedules_all  into r_ap_payment_schedules_all;
6508     close c_ap_payment_schedules_all;
6509 
6510     /* Bug 5751783
6511      * Moved the assignment of ln_invoice_amount outside IF as this is used
6512      * in the insert to jai_ap_tds_thhold_trxs. This has to be derived irrespective
6513      * of the tds event.
6514      */
6515 
6516     Fnd_File.put_line(Fnd_File.LOG,  'pn_taxable_amount '||pn_taxable_amount);
6517     /*IF pn_taxable_amount IS NOT NULL THEN
6518        ln_invoice_amount :=  pn_taxable_amount;
6519     ELSE*/ /*Commented the above if condition for bug 13070779 */
6520        ln_invoice_amount := pn_tax_amount * ( 100 / r_ja_in_tax_codes.tax_rate);
6521    -- END IF;
6522     fnd_file.put_line(FND_FILE.LOG, ' invoice amount'|| ln_invoice_amount);
6523 
6524     /* For downward compatibility with the pre-cleanup code */
6525     if ( (pv_tds_event = 'INVOICE VALIDATE') or (pv_tds_event like 'THRESHOLD TRANSITION%') ) then
6526 
6527       /*
6528       || Added the IF-ELSE-ENDIF block by Ramananda for Bug#4562801
6529       */
6530 
6531 
6532       IF r_ja_in_tax_codes.section_type = 'TDS_SECTION' THEN --rchandan for bug#4428980
6533         lv_source_attribute := 'ATTRIBUTE1';
6534       ELSIF r_ja_in_tax_codes.section_type = 'WCT_SECTION' THEN
6535         lv_source_attribute := 'ATTRIBUTE2';
6536       ELSIF r_ja_in_tax_codes.section_type = 'ESSI_SECTION' THEN
6537         lv_source_attribute := 'ATTRIBUTE3';
6538       END IF;
6539 
6540       fnd_file.put_line(FND_FILE.LOG, ' invoice id '|| pn_invoice_id);
6541       fnd_file.put_line(FND_FILE.LOG, ' invoice amount'|| ln_invoice_amount);
6542       fnd_file.put_line(FND_FILE.LOG, 'invoice to tds inv num'|| lv_invoice_to_tds_num);
6543       fnd_file.put_line(FND_FILE.LOG, 'vendor num' ||lv_invoice_to_vendor_num);
6544       fnd_file.put_line(FND_FILE.LOG, 'tax id '||pn_tax_id);
6545       fnd_file.put_line(FND_FILE.LOG, 'tax rate'|| r_ja_in_tax_codes.tax_rate);
6546       fnd_file.put_line(FND_FILE.LOG, 'tds amt'||ln_invoice_to_tds_amount);
6547       fnd_file.put_line(FND_FILE.LOG, 'sec code '||r_ja_in_tax_codes.section_code);
6548       fnd_file.put_line(FND_FILE.LOG, 'stformtype '||r_ja_in_tax_codes.stform_type);
6549       fnd_file.put_line(FND_FILE.LOG, 'org id '|| r_ap_invoices_all.org_id);
6550       fnd_file.put_line(FND_FILE.LOG, 'src att'||lv_source_attribute);
6551 
6552       jai_cmn_utils_pkg.WRITE_FND_LOG(G_LEVEL_STATEMENT, G_MODULE_NAME||l_api_name, 'ln_invoice_amount: ' || ln_invoice_amount);
6553       jai_cmn_utils_pkg.WRITE_FND_LOG(G_LEVEL_STATEMENT, G_MODULE_NAME||l_api_name,  'invoice to tds inv num'|| lv_invoice_to_tds_num);
6554       jai_cmn_utils_pkg.WRITE_FND_LOG(G_LEVEL_STATEMENT, G_MODULE_NAME||l_api_name, 'vendor num' ||lv_invoice_to_vendor_num);
6555       jai_cmn_utils_pkg.WRITE_FND_LOG(G_LEVEL_STATEMENT, G_MODULE_NAME||l_api_name, 'tax id '||pn_tax_id);
6556       jai_cmn_utils_pkg.WRITE_FND_LOG(G_LEVEL_STATEMENT, G_MODULE_NAME||l_api_name, 'tax rate'|| r_ja_in_tax_codes.tax_rate);
6557       jai_cmn_utils_pkg.WRITE_FND_LOG(G_LEVEL_STATEMENT, G_MODULE_NAME||l_api_name, 'tds amt'||ln_invoice_to_tds_amount);
6558       jai_cmn_utils_pkg.WRITE_FND_LOG(G_LEVEL_STATEMENT, G_MODULE_NAME||l_api_name, 'sec code '||r_ja_in_tax_codes.section_code);
6559       jai_cmn_utils_pkg.WRITE_FND_LOG(G_LEVEL_STATEMENT, G_MODULE_NAME||l_api_name, 'stformtype '||r_ja_in_tax_codes.stform_type);
6560       jai_cmn_utils_pkg.WRITE_FND_LOG(G_LEVEL_STATEMENT, G_MODULE_NAME||l_api_name, 'org id '|| r_ap_invoices_all.org_id);
6561       jai_cmn_utils_pkg.WRITE_FND_LOG(G_LEVEL_STATEMENT, G_MODULE_NAME||l_api_name, 'src att'||lv_source_attribute);
6562 
6563 	   IF NVL(ln_invoice_amount,0) <> 0 THEN --Added the condition by bgowrava for Bug#4549019
6564       insert into JAI_AP_TDS_INVOICES
6565       (TDS_INVOICE_ID,
6566         invoice_id,
6567         invoice_amount,
6568         tds_invoice_num,
6569         dm_invoice_num,
6570         tds_tax_id,
6571         tds_tax_rate,
6572         tds_amount,
6573         tds_section,
6574         certificate_number,
6575         --org_id,
6576         organization_id,
6577         source_attribute,
6578         /* Ramananda for bug#4560109 during R12 Sanity Testing. Added the WHO columns */
6579         created_by        ,
6580         creation_date     ,
6581         last_updated_by   ,
6582         last_update_date  ,
6583         last_update_login
6584       )
6585       values
6586       ( JAI_AP_TDS_INVOICES_S.nextval,
6587         pn_invoice_id,
6588         --round(ln_invoice_to_tds_amount * ( 100 / r_ja_in_tax_codes.tax_rate), 2),
6589         --commented the above and added the below by Ramananda for Bug#4562801
6590         ln_invoice_amount,
6591         lv_invoice_to_tds_num,
6592         lv_invoice_to_vendor_num,
6593         pn_tax_id,
6594         r_ja_in_tax_codes.tax_rate,
6595         ln_invoice_to_tds_amount,
6596         r_ja_in_tax_codes.section_code,
6597         r_ja_in_tax_codes.stform_type,
6598         --r_ap_invoices_all.org_id,
6599         r_ap_invoices_all.org_id,
6600         lv_source_attribute,  --rchandan for bug#4428980
6601         /* Ramananda for bug#4560109 during R12 Sanity Testing. Added the WHO columns */
6602         fnd_global.user_id                             ,
6603         sysdate                                        ,
6604         fnd_global.user_id                             ,
6605         sysdate                                        ,
6606         fnd_global.login_id
6607       );
6608 end if;
6609     end if; /* Only for validate event as done in earlier regime */
6610 
6611     -- Bug 5722028. Added by csahoo
6612 	ln_tds_rnding_factor := 0;
6613 	ln_tds_rnded_amt := pn_tax_amount;
6614 	/* Added the below if condition for bug 12965614 */
6615 	IF pv_tds_event = 'PREPAYMENT UNAPPLICATION' THEN  --2
6616 	      IF r_ap_invoices_all.invoice_currency_code <>  r_gl_sets_of_books.currency_code THEN  --3
6617 		   ln_tds_rnded_amt := ROUND(pn_calc_tax_amount , g_inr_currency_rounding);
6618 		   IF (trunc(pd_creation_date) >= trunc(jai_ap_tds_generation_pkg.gd_tds_rounding_effective_date)) THEN  --4
6619               ln_tds_rnding_factor := jai_ap_tds_generation_pkg.gn_tds_rounding_factor;
6620               ln_tds_rnded_amt := get_rnded_value(ln_tds_rnded_amt);
6621             END IF; --4
6622 		   ln_tds_rnded_amt := ROUND(pn_calc_tax_amount / r_ap_invoices_all.exchange_rate, g_fcy_currency_rounding);
6623 		  END IF; --3
6624        ELSE --2
6625 	/*IF pv_tds_event NOT IN
6626 	   -- Bug 7280925. commented by Lakshmi Gopalsami ('INVOICE CANCEL',
6627 	    ('PREPAYMENT UNAPPLICATION') THEN */
6628   	   IF r_ap_invoices_all.invoice_currency_code = r_gl_sets_of_books.currency_code THEN
6629 	    ln_tds_rnded_amt := ROUND(pn_tax_amount , g_inr_currency_rounding);
6630 		  --moved this if-endif block from below to here for bug#8995604
6631 	   ELSE
6632 	   ln_tds_rnded_amt := ROUND(pn_tax_amount , g_inr_currency_rounding);
6633         IF (trunc(pd_creation_date) >=
6634 	     trunc(jai_ap_tds_generation_pkg.gd_tds_rounding_effective_date)
6635            /* Bug 7280925. Added by Lakshmi Gopalsami
6636 	    * we should not round for WCT and ESSI. For those threshold_grp_id
6637 	    * will be null
6638 	    */
6639             and pn_threshold_grp_id is not null )
6640 	    THEN
6641 		 ln_tds_rnding_factor := jai_ap_tds_generation_pkg.gn_tds_rounding_factor;
6642 		 ln_tds_rnded_amt := get_rnded_value(ln_tds_rnded_amt);
6643           fnd_file.put_line(FND_FILE.LOG, ' Bug 7280925 - value after round before insert into trxs'||ln_tds_rnded_amt);
6644 	    END IF;
6645 	    ln_tds_rnded_amt := ROUND(pn_tax_amount / r_ap_invoices_all.exchange_rate, g_fcy_currency_rounding);
6646 	   END IF ;
6647            fnd_file.put_line(FND_FILE.LOG, ' Bug 7280925 - value before round '||ln_tds_rnded_amt);
6648 
6649 	END IF;
6650      -- End for bug 5722028.
6651 
6652 
6653     insert into jai_ap_tds_thhold_trxs
6654     (
6655       threshold_trx_id                               ,
6656       invoice_id                                     ,
6657       invoice_line_number                            ,
6658       invoice_distribution_id                        ,
6659       threshold_grp_id                               ,
6660       threshold_hdr_id                               ,
6661       tds_event                                      ,
6662       tax_id                                         ,
6663       tax_rate                                       ,
6664       taxable_amount                                 ,
6665       tax_amount                                     ,
6666       tds_authority_vendor_id                        ,
6667       tds_authority_vendor_site_id                   ,
6668       invoice_to_tds_authority_num                   ,
6669       invoice_to_tds_authority_type                  ,
6670       invoice_to_tds_authority_curr                  ,
6671       invoice_to_tds_authority_amt                   ,
6672       vendor_id                                      ,
6673       vendor_site_id                                 ,
6674       invoice_to_vendor_num                          ,
6675       invoice_to_vendor_type                         ,
6676       invoice_to_vendor_curr                         ,
6677       invoice_to_vendor_amt                          ,
6678       parent_inv_payment_priority                    ,
6679       parent_inv_exchange_rate                       ,
6680       created_by                                     ,
6681       creation_date                                  ,
6682       last_updated_by                                ,
6683       last_update_date                               ,
6684       last_update_login															 ,
6685       calc_tax_amount                                , /*Bug 5751783*/
6686       tds_rounding_factor -- Bug 5722028. Added by csahoo
6687      ,tds_section_code    --Added by Chong for bug#16414088 20130313
6688     )
6689     values
6690     (
6691       jai_ap_tds_thhold_trxs_s.nextval               ,
6692       pn_invoice_id                                  ,
6693       pn_invoice_line_number                         ,
6694       pn_invoice_distribution_id                     ,
6695       pn_threshold_grp_id                            ,
6696       pn_threshold_hdr_id                            ,
6697       pv_tds_event                                   ,
6698       pn_tax_id                                      ,
6699       r_ja_in_tax_codes.tax_rate                     ,
6700       /* Bug 5751783. Changed to ln_invoice_amount instead of pn_taxable_amount
6701        * This is done as now pn_taxable_amount will always be populated irrespective
6702        * of tds_event. Added rounding for pn_tax_amount.
6703        */
6704       ln_invoice_amount                              ,
6705       ln_tds_rnded_amt,  --Bug 5722028. Added by csahoo
6706       r_ja_in_tax_codes.vendor_id                    ,
6707       r_ja_in_tax_codes.vendor_site_id               ,
6708       lv_invoice_to_tds_num                          ,
6709       lv_invoice_to_tds_type                         ,
6710       r_gl_sets_of_books.currency_code               ,
6711       ln_invoice_to_tds_amount                       ,
6712       r_ap_invoices_all.vendor_id                    ,
6713       r_ap_invoices_all.vendor_site_id               ,
6714       lv_invoice_to_vendor_num                       ,
6715       lv_invoice_to_vendor_type                      ,
6716       r_ap_invoices_all.invoice_currency_code        ,
6717       ln_invoice_to_vendor_amount                    ,
6718       r_ap_payment_schedules_all.payment_priority    ,
6719       r_ap_invoices_all.exchange_rate                ,
6720       fnd_global.user_id                             ,
6721       sysdate                                        ,
6722       fnd_global.user_id                             ,
6723       sysdate                                        ,
6724       fnd_global.login_id		                     ,
6725       decode ( pv_tds_event, 'PREPAYMENT UNAPPLICATION', pn_calc_tax_amount, pn_tax_amount), /*Added decode condition for bug 12965614 */ /*Bug 5751783*/
6726       ln_tds_rnding_factor -- Bug 5722028. Added by csahoo
6727      ,pv_section_code     --Added by Chong for bug#16414088 20130313
6728     )
6729     returning threshold_trx_id into pn_threshold_trx_id;
6730 
6731     <<exit_from_procedure>>
6732     jai_cmn_utils_pkg.WRITE_FND_LOG(G_LEVEL_PROCEDURE, G_MODULE_NAME||l_api_name||'.END', G_PKG_NAME || ': '||l_api_name||'()-');
6733       return;
6734 
6735     exception
6736       when others then
6737         p_process_flag := 'E';
6738         p_process_message := 'Error from jai_ap_tds_generation_pkg.generate_tds_invoices :' || sqlerrm;
6739 
6740   end generate_tds_invoices;
6741 
6742 /* *********************************** procedure generate_tds_invoices ********************************** */
6743 
6744 
6745 
6746   /* *********************************** procedure generate_dtc_invoices ********************************** */
6747 
6748 procedure generate_dtc_invoices
6749   (
6750     pn_invoice_id                         in                 number,
6751     pn_invoice_line_number                in                 number   default null, /* AP lines  */
6752     pn_invoice_distribution_id            in                 number   default null, /* Prepayment apply / unapply scenario */
6753     pv_invoice_num_prepay_apply           in                 varchar2 default null, /* Prepayment application secanrio */
6754     pv_invoice_num_to_tds_apply           in                 varchar2 default null, /* Prepayment unapplication secanrio */
6755     pv_invoice_num_to_vendor_apply        in                 varchar2 default null, /* Prepayment unapplication secanrio */
6756     pv_invoice_num_to_vendor_can          in                 varchar2 default null, /* Invoice Cancel Secnario */
6757     pn_threshold_hdr_id                   in                 number   default null, /* For validate scenario only */
6758     pn_taxable_amount                     in                 number,
6759     pn_tax_amount                         in                 number,
6760     --pn_tax_id                             in                 number,
6761     pn_tax_category_id                    in                 number,
6762     pv_section_type                       in                 varchar2,
6763     pv_section_code                       in                 varchar2,
6764     pd_accounting_date                    in                 date,
6765     pv_tds_event                          in                 varchar2,
6766     pn_threshold_grp_id                   in                 number,
6767     pv_tds_invoice_num                    out      nocopy    varchar2,
6768     pv_cm_invoice_num                     out      nocopy    varchar2,
6769     pn_threshold_trx_id                   out      nocopy    number,
6770     -- Bug 5722028. Added by csahoo
6771     pd_creation_date                      in                 date,
6772     pn_calc_tax_amount                    in                 number default 0, /* Added for bug 12965614 */
6773     p_process_flag                        out      nocopy    varchar2,
6774     p_process_message                     out      nocopy    varchar2
6775   )
6776   is
6777 
6778   cursor c_ap_invoices_all(cp_invoice_id number) is
6779     select  invoice_num,
6780             vendor_id,
6781             vendor_site_id,
6782             invoice_currency_code,
6783             exchange_rate_type,
6784             exchange_date,
6785             terms_id,
6786             payment_method_lookup_code,
6787             pay_group_lookup_code,
6788             invoice_date,
6789             goods_received_date,
6790             invoice_received_date,
6791             org_id,
6792             nvl(exchange_rate, 1) exchange_rate,
6793             set_of_books_id,
6794             payment_method_code, -- Bug 7109056
6795             accts_pay_code_combination_id -- Bug 9759709
6796     from    ap_invoices_all
6797     where   invoice_id = cp_invoice_id;
6798 
6799   cursor c_po_vendor_sites_all(cp_vendor_id  number, cp_vendor_site_id number) is
6800     select  terms_id,
6801             --payment_method_lookup_code, --commented by Sanjikum for Bug#4482462
6802             pay_group_lookup_code
6803     from    po_vendor_sites_all
6804     where   vendor_id = cp_vendor_id
6805     and     vendor_site_id = cp_vendor_site_id;
6806 
6807   cursor c_po_vendors(cp_vendor_id  number) is
6808     select  terms_id,
6809             --payment_method_lookup_code, --commented by Sanjikum for Bug#4482462
6810             pay_group_lookup_code
6811     from    po_vendors
6812     where   vendor_id = cp_vendor_id;
6813 
6814 
6815   cursor c_ja_in_tax_codes (pn_tax_id number) is
6816     select  section_code,
6817             vendor_id,
6818             vendor_site_id,
6819             tax_rate,
6820             stform_type,
6821             tax_account_id,
6822             section_type
6823     from    JAI_CMN_TAXES_ALL
6824     where   tax_id = pn_tax_id;
6825 
6826 
6827   cursor c_gl_sets_of_books(cp_set_of_books_id  number) is
6828     select currency_code
6829     from   gl_sets_of_books
6830     where  set_of_books_id = cp_set_of_books_id;
6831 
6832   cursor c_get_ja_in_ap_inv_id is
6833     select to_char(JAI_AP_TDS_THHOLD_TRXS_S1.nextval)--to_char(JAI_AP_TDS_INVOICE_NUM_S.nextval)commented by  rchandan for bug#4487676
6834     from  dual;
6835 
6836   cursor c_ap_payment_schedules_all(p_invoice_id number) is
6837     select payment_priority
6838     from   ap_payment_schedules_all
6839     where  invoice_id = p_invoice_id;
6840 
6841   r_ap_invoices_all               c_ap_invoices_all%rowtype;
6842   r_ja_in_tax_codes               c_ja_in_tax_codes%rowtype;
6843   r_po_vendor_sites_all           c_po_vendor_sites_all%rowtype;
6844   r_po_vendors                    c_po_vendors%rowtype;
6845   r_gl_sets_of_books              c_gl_sets_of_books%rowtype;
6846   r_ap_payment_schedules_all      c_ap_payment_schedules_all%rowtype;
6847 
6848 
6849   lv_source                       varchar2(30); --File.Sql.35 Cbabu  := 'TDS';
6850 
6851   lv_invoice_to_tds_num           ap_invoices_all.invoice_num%type;
6852   lv_invoice_to_vendor_num        ap_invoices_all.invoice_num%type;
6853 
6854   lv_invoice_to_tds_type          ap_invoices_all.invoice_type_lookup_code%type;
6855   lv_invoice_to_vendor_type       ap_invoices_all.invoice_type_lookup_code%type;
6856 
6857   ln_invoice_to_tds_id            ap_invoices_all.invoice_id%type;
6858   ln_invoice_to_vendor_id         ap_invoices_all.invoice_id%type;
6859 
6860   ln_invoice_to_tds_line_id       ap_invoice_lines_interface.invoice_line_id%type;
6861   ln_invoice_to_vendor_line_id    ap_invoice_lines_interface.invoice_line_id%type;
6862 
6863   lv_invoice_to_tds_line_type     ap_invoice_distributions_all.line_type_lookup_code%type; --File.Sql.35 Cbabu  := 'ITEM';
6864   lv_invoice_to_vendor_line_type  ap_invoice_distributions_all.line_type_lookup_code%type; --File.Sql.35 Cbabu  := 'ITEM';
6865 
6866   ln_invoice_to_tds_amount        number;
6867   ln_invoice_to_vendor_amount     number;
6868 
6869   ln_exchange_rate                number;
6870   lv_this_procedure               varchar2(50); --File.Sql.35 Cbabu  := 'jaiap.generate_tds_invoice';
6871 
6872   ln_terms_id                     po_vendors.terms_id%type;
6873   -- lv_payment_method_lookup_code   po_vendors.payment_method_lookup_code%type; --commented by Sanjikum for Bug#4482462
6874   lv_pay_group_lookup_code        po_vendors.pay_group_lookup_code%type;
6875 
6876   lv_ja_in_ap_inv_id              varchar2(15);
6877   ld_accounting_date              date;
6878   lv_open_period                  ap_invoice_distributions_all.period_name%type;
6879   ln_tax_amount                   number;
6880 
6881   lv_invoice_num                  ap_invoices_all.invoice_num%type;
6882   lv_source_attribute             jai_ap_tds_invoices.source_attribute%TYPE ;   --rchandan for bug#4428980
6883 
6884   ln_invoice_amount               ap_invoices_all.invoice_amount%TYPE; --Added by Ramananda for Bug#4562801
6885 
6886    lv_group_id                     VARCHAR2(80); --Added by Sanjikum for Bug#5131075(4722011)
6887 
6888    /* Bug 5722028. Added by Lakshmi Gopalsami
6889    * Added following variables
6890    */
6891   ln_tds_rnded_amt      NUMBER;
6892   ln_tds_mod_value      NUMBER;
6893   ln_tds_rnding_factor  NUMBER;
6894 
6895   lv_section_name varchar2(10); --Added for Bug# 7410219
6896   pv_invoice_date   DATE;  --Added by Bgowrava for Bug#9186263
6897   ln_accts_pay_ccid NUMBER; -- Bug 9759709
6898 
6899   ln_count number;
6900   lv_stform_type  varchar2(30);
6901 
6902 
6903   ln_vendor_id      number;
6904   ln_vendor_site_id number;
6905   ln_tax_id_new     number;
6906 
6907   ln_vendor_inv_sum_amount number;
6908   ln_author_inv_sum_amount number;
6909 
6910   --Add by Zhiwei on 20120104 begin
6911   ----------------------------------------
6912   cursor get_one_tax(cv_tax_type varchar2)
6913   is
6914   select actual_tax_id
6915   from   jai_ap_tds_inv_taxes
6916   where invoice_id = pn_invoice_id
6917   and   actual_section_code = pv_section_code
6918   and   tax_category_id = pn_tax_category_id
6919   and   section_type = pv_section_type    --Added by Chong for bug#16371927
6920   and   tax_type = cv_tax_type;
6921 
6922   cursor get_amt_for_type(cv_tax_type varchar2)
6923   is
6924   select sum(tax_amount)
6925   from jai_ap_tds_inv_taxes
6926   where invoice_id = pn_invoice_id
6927   and   section_type = pv_section_type --Added by Zhiwei Hou on 20120111
6928   and   actual_section_code = pv_section_code
6929   and   tax_category_id = pn_tax_category_id
6930   and   actual_tax_id in
6931   (
6932         select tax_id
6933         from jai_cmn_taxes_all
6934         where tax_type = cv_tax_type
6935   );
6936 
6937 
6938   cursor get_amt_for_all
6939   is
6940   select sum(tax_amount)
6941   from jai_ap_tds_inv_taxes
6942   where invoice_id = pn_invoice_id
6943   and   section_type  = pv_section_type --Added by Zhiwei Hou on 20120111
6944   and   actual_section_code = pv_section_code
6945   and   tax_category_id = pn_tax_category_id;
6946 
6947   cursor get_amt_for_dist(cn_distribution_id number)
6948   is
6949   select sum(amount)
6950   from jai_ap_tds_inv_taxes
6951   where invoice_id = pn_invoice_id
6952   and   actual_section_code = pv_section_code
6953   and   tax_category_id = pn_tax_category_id
6954   and   invoice_distribution_id = cn_distribution_id;
6955 
6956 
6957   cursor get_amt_for_all_inv
6958   is
6959   select sum(amount)
6960   from jai_ap_tds_inv_taxes
6961   where invoice_id = pn_invoice_id
6962   and   actual_section_code = pv_section_code
6963   and   tax_category_id = pn_tax_category_id;
6964 
6965   ln_tax_amt_tax_type number;
6966   ln_tax_amt_all      number;
6967 
6968   ln_amt_dist     number;
6969   ln_amt_all      number;
6970 
6971   ln_amt_for_each     number;
6972   ln_tax_amt_for_each number;
6973 
6974   ln_amount_for_sub_au   number;
6975   ln_amount_for_sub_cm   number;
6976   -----------------------------------------
6977   --Add by Zhiwei on 20120104 end
6978 
6979   --Add by Zhiwei on 20120111 begin
6980   cursor get_amt_for_type_curr(cv_tax_type varchar2)
6981   is
6982   select sum(func_tax_amount)
6983   from jai_ap_tds_inv_taxes
6984   where invoice_id = pn_invoice_id
6985   and   section_type = pv_section_type --Added by Zhiwei Hou on 20120111
6986   and   actual_section_code = pv_section_code
6987   and   tax_category_id = pn_tax_category_id
6988   and   actual_tax_id in
6989   (
6990         select tax_id
6991         from jai_cmn_taxes_all
6992         where tax_type = cv_tax_type
6993   );
6994 
6995 
6996   cursor get_amt_for_all_curr
6997   is
6998   select sum(func_tax_amount)
6999   from jai_ap_tds_inv_taxes
7000   where invoice_id = pn_invoice_id
7001   and   section_type  = pv_section_type --Added by Zhiwei Hou on 20120111
7002   and   actual_section_code = pv_section_code
7003   and   tax_category_id = pn_tax_category_id;
7004   --Add by Zhiwei on 20120111 end
7005 
7006   --Add by Chong on 20130130 for bug#16048702 begin
7007   ----------------------------------------------------------------------
7008   CURSOR get_revised_section_code(p_section_code varchar2
7009                                  ,p_accounting_date date
7010                                  )
7011   IS
7012   SELECT jatsm.section_code_revised
7013   FROM jai_ap_tds_sec_map jatsm
7014   WHERE jatsm.regime_id in (
7015               SELECT jrd.regime_id
7016                 FROM ja_lookups          jl
7017                     ,jai_rgm_definitions jrd
7018                WHERE jl.lookup_code = jrd.regime_code
7019                  AND jl.lookup_type = 'JAI_INDIA_TAX_REGIMES'
7020                  AND jl.lookup_code = 'TDS'
7021         )
7022   AND   jatsm.section_code = p_section_code
7023   AND   jatsm.from_date <= p_accounting_date
7024   AND   (jatsm.to_date IS NULL
7025          OR jatsm.to_date >= p_accounting_date
7026         );
7027   ----------------------------------------------------------------------
7028   --Add by Chong on 20130130 for bug#16048702 end
7029 
7030   --Added by Zhiwei Hou on 20120113 begin
7031   ---------------------------------------------
7032   cursor get_tax_rate(cv_taxs_type varchar2)
7033   is
7034          select tax_rate
7035          from jai_cmn_taxes_all
7036          where tax_id in
7037          (
7038              select actual_tax_id
7039              from jai_ap_tds_inv_taxes
7040              where invoice_id = pn_invoice_id
7041              and   section_type = pv_section_type --Added by Zhiwei Hou on 20120111
7042              and   actual_section_code = pv_section_code
7043              and   tax_category_id = pn_tax_category_id
7044              and   tax_type = cv_taxs_type
7045           );
7046 
7047 
7048    ln_tax_rate number;
7049    ---------------------------------------------
7050    --Added by Zhiwei Hou on 20120113 end
7051    --Added by Zhiwei Hou on 20120203 begin
7052    -------------------------------------------------------------------
7053    ln_dbg_level   NUMBER         := FND_LOG.g_current_runtime_level;
7054    ln_proc_level  NUMBER         := FND_LOG.level_procedure;
7055    lv_proc_name   VARCHAR2 (100) := 'generate_dtc_invoices';
7056    -------------------------------------------------------------------
7057    --Added by Zhiwei Hou on 20120203 end
7058    l_api_name                   CONSTANT  VARCHAR2(50) := 'generate_dtc_invoices()';
7059 begin
7060 
7061   jai_cmn_utils_pkg.WRITE_FND_LOG(G_LEVEL_PROCEDURE, G_MODULE_NAME||l_api_name||'.BEGIN', G_PKG_NAME || ': '||l_api_name||'()+');
7062   jai_cmn_utils_pkg.WRITE_FND_LOG(G_LEVEL_PROCEDURE, G_MODULE_NAME||l_api_name||'.Parameter', 'pn_invoice_id: ' || pn_invoice_id);
7063   jai_cmn_utils_pkg.WRITE_FND_LOG(G_LEVEL_PROCEDURE, G_MODULE_NAME||l_api_name||'.Parameter', 'pn_taxable_amount: ' || pn_taxable_amount);
7064   jai_cmn_utils_pkg.WRITE_FND_LOG(G_LEVEL_PROCEDURE, G_MODULE_NAME||l_api_name||'.Parameter', 'pn_tax_amount: ' || pn_tax_amount);
7065   jai_cmn_utils_pkg.WRITE_FND_LOG(G_LEVEL_PROCEDURE, G_MODULE_NAME||l_api_name||'.Parameter', 'pn_tax_category_id: ' || pn_tax_category_id);
7066   jai_cmn_utils_pkg.WRITE_FND_LOG(G_LEVEL_PROCEDURE, G_MODULE_NAME||l_api_name||'.Parameter', 'pv_section_type: ' || pv_section_type);
7067   jai_cmn_utils_pkg.WRITE_FND_LOG(G_LEVEL_PROCEDURE, G_MODULE_NAME||l_api_name||'.Parameter', 'pv_section_code: ' || pv_section_code);
7068   jai_cmn_utils_pkg.WRITE_FND_LOG(G_LEVEL_PROCEDURE, G_MODULE_NAME||l_api_name||'.Parameter', 'pv_tds_event: ' || pv_tds_event);
7069   lv_source                        := 'INDIA TDS'; /* --:= 'TDS'; --Ramanand for bug#4388958 */
7070   lv_invoice_to_tds_line_type     := 'ITEM';
7071   lv_invoice_to_vendor_line_type  := 'ITEM';
7072   lv_this_procedure               := 'jaiap.generate_dtc_invoice';
7073 
7074 
7075   /* Amount to be paid to TDS Authority should always be +ve */
7076   /* In case of prepayment application, this is still passed as +ve amount */
7077 
7078   /* Bug 4513458. added by Lakshmi Gopalsami
7079    * Removed the rounding and assigned the exact amount
7080    * and the rounding is handled at later point to
7081    * accommodate the currency code
7082   */
7083   --ln_tax_amount := round(pn_tax_amount, 2);
7084   ln_tax_amount := pn_tax_amount;
7085 
7086   /* Bug 4522507. Added by Lakshmi Gopalsami
7087      Checked whether round(ln_tax_amount) is less than
7088      zero instead of ln_tax_amount */
7089   if round(ln_tax_amount,2) <= 0 then
7090     p_process_flag := 'X';
7091     p_process_message := 'TDS amount must be greater than 0 ';
7092     goto exit_from_procedure;
7093   end if;
7094 
7095   --Add by Zhiwei Hou on 20120106 begin
7096   ----------------------------------------------------------------------
7097   --ln_tax_amount := round(ln_tax_amount,get_tax_rounding(pn_invoice_id));--Comment by Zhiwei Hou on 20120109
7098   ----------------------------------------------------------------------
7099   --Add by Zhiwei Hou on 20120106 end
7100 
7101   open  c_ap_invoices_all(pn_invoice_id);
7102   fetch c_ap_invoices_all into r_ap_invoices_all;
7103   close c_ap_invoices_all;
7104 
7105   /*
7106   || moved this up from the under the cursor - c_po_vendor_sites_all by Ramananda for Bug#4562793
7107   */
7108 
7109 
7110   open  c_gl_sets_of_books(r_ap_invoices_all.set_of_books_id);
7111   fetch c_gl_sets_of_books into r_gl_sets_of_books;
7112   close c_gl_sets_of_books;
7113 
7114   /*Bug # 7410219 - Derive the Section Name*/
7115   if (pv_section_type = 'TDS_SECTION') then
7116      --lv_section_name := 'TDS';  --commented by Chong for bug#16048702 20130130
7117      --Add by Chong on 20130130 for bug#16048702 begin
7118      ----------------------------------------------------------------------
7119      open get_revised_section_code(pv_section_code,pd_accounting_date);
7120      fetch get_revised_section_code into lv_section_name;
7121      close get_revised_section_code;
7122      lv_section_name := NVL(lv_section_name, 'TDS');
7123      ----------------------------------------------------------------------
7124      --Add by Chong on 20130130 for bug#16048702 end
7125   elsif (pv_section_type = 'WCT_SECTION') then
7126      lv_section_name := 'WCT';
7127   elsif (pv_section_type = 'ESSI_SECTION') then
7128      lv_section_name := 'ESSI';
7129   end if;
7130   /*Bug # 7410219 - End*/
7131 
7132 
7133 
7134   /* Get the unique number to suffix the tds invoices with */
7135   open c_get_ja_in_ap_inv_id;
7136   fetch c_get_ja_in_ap_inv_id into lv_ja_in_ap_inv_id;
7137   close c_get_ja_in_ap_inv_id;
7138 
7139   lv_invoice_num := substr(r_ap_invoices_all.invoice_num, 1, 30);
7140 
7141   /* Invoice Numbers, type  for the invoice pair that is being created */
7142   if ( (pv_tds_event = 'INVOICE VALIDATE') or (pv_tds_event like 'THRESHOLD TRANSITION%') ) then
7143 
7144     /* Standard invoice to TDS authority, Credit memo to supplier */
7145 
7146     lv_invoice_to_tds_type := 'STANDARD';
7147     lv_invoice_to_vendor_type := 'CREDIT';
7148     /*Bug 7410219 - Modified Invoice Number as per Section*/
7149     lv_invoice_to_tds_num     := lv_invoice_num ||'-'||lv_section_name||'-SI-'||lv_ja_in_ap_inv_id;
7150     lv_invoice_to_vendor_num := lv_invoice_num ||'-'||lv_section_name||'-CM-'||lv_ja_in_ap_inv_id;
7151 
7152     ln_invoice_to_tds_amount :=  ln_tax_amount;
7153     ln_invoice_to_vendor_amount := (-1) * ln_tax_amount;
7154 
7155   elsif pv_tds_event = 'PREPAYMENT APPLICATION' OR pv_tds_event like 'THRESHOLD ROLLBACK%' then --Added by Sanjikum for Bug#5131075(4718907)
7156 
7157     /* Credit memo to TDS authority, Standard invoice to supplier */
7158     if pv_invoice_num_prepay_apply is not null then
7159       lv_invoice_num := substr(pv_invoice_num_prepay_apply, 1, 30);
7160     end if;
7161 
7162     lv_invoice_to_tds_type := 'CREDIT';
7163     lv_invoice_to_vendor_type := 'STANDARD';
7164     /*Bug 7410219 - Modified Invoice Number as per Section*/
7165     lv_invoice_to_tds_num     := lv_invoice_num ||'-RTN-'||lv_section_name||'-CM-'||lv_ja_in_ap_inv_id;
7166     lv_invoice_to_vendor_num  := lv_invoice_num ||'-RTN-'||lv_section_name||'-SI-'||lv_ja_in_ap_inv_id;
7167 
7168     ln_invoice_to_tds_amount :=  -1 * ln_tax_amount;
7169     ln_invoice_to_vendor_amount :=  ln_tax_amount;
7170 
7171   elsif pv_tds_event = 'PREPAYMENT UNAPPLICATION' then
7172 
7173     /* Standard invoice to TDS authority, Credit memo to supplier */
7174     lv_invoice_to_tds_type := 'STANDARD';
7175     lv_invoice_to_vendor_type := 'CREDIT';
7176 
7177     if pv_invoice_num_to_tds_apply is not null then
7178       lv_invoice_to_tds_num    := 'CAN/' || substr(pv_invoice_num_to_tds_apply, 1, 45);
7179     else
7180       /*Bug 7410219 - Modified Invoice Number as per Section*/
7181       lv_invoice_to_tds_num    := lv_invoice_num ||'-RTN-'||lv_section_name||'-SI-'||lv_ja_in_ap_inv_id;
7182     end if;
7183 
7184     if pv_invoice_num_to_vendor_apply is not null then
7185       lv_invoice_to_vendor_num := 'CAN/' || substr(pv_invoice_num_to_vendor_apply, 1, 45);
7186     else
7187       /*Bug 7410219 - Modified Invoice Number as per Section*/
7188       lv_invoice_to_vendor_num := lv_invoice_num ||'-RTN-'||lv_section_name||'-CM-'||lv_ja_in_ap_inv_id;
7189     end if;
7190 
7191     ln_invoice_to_tds_amount :=  ln_tax_amount;
7192     ln_invoice_to_vendor_amount := (-1) * ln_tax_amount;
7193 
7194   elsif pv_tds_event = 'INVOICE CANCEL' then
7195 
7196       /* No invoice to TDS authority, Standard invoice to supplier */
7197 
7198       lv_invoice_to_tds_num     := null;
7199 
7200       if pv_invoice_num_to_vendor_can is not null then
7201         lv_invoice_to_vendor_num := 'CAN/' || substr(pv_invoice_num_to_vendor_can, 1, 45);
7202       else
7203         /*Bug 7410219 - Modified Invoice Number as per Section*/
7204         lv_invoice_to_vendor_num := lv_invoice_num||'-CAN-'||lv_section_name||'-SI-'||lv_ja_in_ap_inv_id;
7205       end if;
7206 
7207       lv_invoice_to_tds_type := null;
7208       lv_invoice_to_vendor_type := 'STANDARD';
7209 
7210       ln_invoice_to_tds_amount :=  null;
7211       ln_invoice_to_vendor_amount := ln_tax_amount;
7212 
7213 /*START, Bgowrava for Bug#8254510*/
7214   elsif ( pv_tds_event = G_SURCHARGE_CALCULATE) then
7215 
7216       /* Standard invoice to TDS authority, Credit memo to supplier */
7217 
7218       lv_invoice_to_tds_type := 'STANDARD';
7219       lv_invoice_to_vendor_type := 'CREDIT';
7220 
7221       lv_invoice_to_tds_num     := lv_invoice_num ||'-SUR-SI-'||lv_ja_in_ap_inv_id;
7222       lv_invoice_to_vendor_num := lv_invoice_num ||'-SUR-CM-'||lv_ja_in_ap_inv_id;
7223 
7224       ln_invoice_to_tds_amount :=  ln_tax_amount;
7225     ln_invoice_to_vendor_amount := (-1) * ln_tax_amount;
7226 /*END,  Bgowrava for Bug#8254510*/
7227 
7228   end if; /* TDS event type */
7229 
7230   pv_tds_invoice_num := lv_invoice_to_tds_num;
7231   pv_cm_invoice_num  := lv_invoice_to_vendor_num;
7232 
7233   /* Check if the given date is in current open period */
7234 
7235   /* Bug 4559756. Added by Lakshmi Gopalsami
7236      Added org_id to ap_utilities_pkg
7237   */
7238   lv_open_period:=  ap_utilities_pkg.get_current_gl_date
7239                                      (pd_accounting_date,
7240               r_ap_invoices_all.org_id
7241               );
7242 
7243   /* Bug 4559756. Added by Lakshmi Gopalsami
7244      Added org_id to ap_utilities_pkg
7245   */
7246 
7247   if lv_open_period is null then
7248 
7249     ap_utilities_pkg.get_open_gl_date
7250     (
7251       pd_accounting_date,
7252       lv_open_period,
7253       ld_accounting_date,
7254       r_ap_invoices_all.org_id
7255     );
7256 
7257     if lv_open_period is null then
7258       p_process_flag := 'E';
7259       p_process_message := 'No open accounting Period after : ' || pd_accounting_date ;
7260       goto exit_from_procedure;
7261     end if;
7262 
7263     else
7264       ld_accounting_date := pd_accounting_date;
7265     end if; /* ld_accounting_date */
7266 
7267     --Added by Sanjikum for Bug#5131075(4722011)
7268     IF pv_tds_event = 'PREPAYMENT APPLICATION' OR pv_tds_event = 'PREPAYMENT UNAPPLICATION' THEN
7269       lv_group_id := to_char(pn_invoice_id)||pv_tds_event;
7270     pv_invoice_date := ld_accounting_date;   --Added by Bgowrava for Bug#9186263
7271     ELSE
7272       lv_group_id := to_char(pn_invoice_id);
7273     pv_invoice_date := r_ap_invoices_all.invoice_date;  --Added by Bgowrava for Bug#9186263
7274     END IF;
7275 
7276 
7277     /* Invoice to TDS Authority */
7278     /* Bug 4513458. Added by Lakshmi Gopalsami
7279      * Rounded the amount to zero as the TDS invoice amount should
7280      * be in INR currency */
7281 
7282    -- ln_invoice_to_tds_amount := ROUND(ln_invoice_to_tds_amount,0);
7283    /* Bug 5722028. Added by csahoo
7284     * Rounded depending on the setup.
7285     */
7286       IF pv_tds_event NOT IN
7287         -- Bug 7280925. Commented by Lakshmi Gopalsami ('INVOICE CANCEL',
7288            ('PREPAYMENT UNAPPLICATION')
7289       THEN
7290        ln_invoice_to_tds_amount := ROUND(ln_invoice_to_tds_amount,g_inr_currency_rounding);
7291         fnd_file.put_line(FND_FILE.LOG, ' Bug 7280925 - value before round '||ln_invoice_to_tds_amount);
7292   IF trunc(pd_creation_date) >= trunc(jai_ap_dtc_generation_pkg.gd_tds_rounding_effective_date)
7293         /* Bug 7280925. Added by Lakshmi Gopalsami
7294    * we should not round for WCT and ESSI. For those threshold_grp_id
7295    * will be null
7296    */
7297          and pn_threshold_grp_id is not null
7298   THEN
7299     ln_invoice_to_tds_amount := get_rnded_value(ln_invoice_to_tds_amount);
7300     IF ( ln_proc_level >= ln_dbg_level)
7301     THEN
7302 
7303            FND_LOG.STRING ( ln_proc_level
7304                           , GV_MODULE_PREFIX ||'.'|| lv_proc_name
7305                           , 'value after round per setup TDS auth inv' || ln_invoice_to_tds_amount
7306                           );
7307 
7308     END IF; --( ln_proc_level >= ln_dbg_level)  ;
7309     --fnd_file.put_line(FND_FILE.LOG, ' Bug 7280925 - value after round per setup TDS auth inv'||ln_invoice_to_tds_amount);
7310   END IF;
7311       END IF ; -- pv_tds_event  not in
7312 
7313     -- End for Bug 5722028
7314 
7315 
7316   --Added by Zhiwei Hou for bug#13767335 begin
7317   --Move this part from loop inside to do exchange before loop
7318   --------------------------------------------------------------------------------------------
7319   if lv_invoice_to_vendor_num is not null and lv_invoice_to_vendor_type is not null then
7320 
7321              IF pv_tds_event = 'PREPAYMENT UNAPPLICATION' THEN  --2
7322                IF r_ap_invoices_all.invoice_currency_code <> r_gl_sets_of_books.currency_code  THEN --3
7323                     ln_invoice_to_vendor_amount := round( ln_invoice_to_vendor_amount, g_inr_currency_rounding);
7324                     IF trunc(pd_creation_date) >= trunc(jai_ap_dtc_generation_pkg.gd_tds_rounding_effective_date) THEN
7325                         ln_invoice_to_vendor_amount := get_rnded_value(ln_invoice_to_vendor_amount);
7326                     END IF;
7327                     ln_invoice_to_vendor_amount := round( ln_invoice_to_vendor_amount / r_ap_invoices_all.exchange_rate, g_fcy_currency_rounding);
7328                END IF;  --3
7329 
7330             ELSE --2
7331 
7332                if r_ap_invoices_all.invoice_currency_code <> r_gl_sets_of_books.currency_code  then
7333                   /*START, Bgowrava for Bug#8995604 , Adding below IF statement to round the INR TDS CM invoice to
7334                   the TDS rounding factor before converting it to a foreign currency CM*/
7335                     ln_invoice_to_vendor_amount := round( ln_invoice_to_vendor_amount, g_inr_currency_rounding);
7336                     IF trunc(pd_creation_date) >= trunc(jai_ap_dtc_generation_pkg.gd_tds_rounding_effective_date)
7337                          and pn_threshold_grp_id is not null THEN
7338 
7339                          ln_invoice_to_vendor_amount := get_rnded_value(ln_invoice_to_vendor_amount);
7340                     END IF;
7341                     /*END, Bgowrava for Bug#8995604 */
7342                     ln_invoice_to_vendor_amount := round( ln_invoice_to_vendor_amount / r_ap_invoices_all.exchange_rate, g_fcy_currency_rounding);
7343                ELSE
7344                     ln_invoice_to_vendor_amount := round( ln_invoice_to_vendor_amount, g_inr_currency_rounding);
7345                     /*START, Bgowrava for Bug#8995604 , Adding below IF statement to round the INR TDS CM invoice to   the TDS rounding factor*/
7346                     IF trunc(pd_creation_date) >= trunc(jai_ap_dtc_generation_pkg.gd_tds_rounding_effective_date)
7347                         and pn_threshold_grp_id is not null THEN
7348 
7349                         ln_invoice_to_vendor_amount := get_rnded_value(ln_invoice_to_vendor_amount);
7350                     END IF;
7351                     /*END, Bgowrava for Bug#8995604 */
7352 
7353                END IF; --2
7354             END IF;
7355             IF ( ln_proc_level >= ln_dbg_level)
7356             THEN
7357 
7358                    FND_LOG.STRING ( ln_proc_level
7359                                   , GV_MODULE_PREFIX ||'.'|| lv_proc_name
7360                                   , 'value before round ' || ln_invoice_to_vendor_amount
7361                                   );
7362 
7363             END IF;
7364 
7365               if upper(r_ap_invoices_all.exchange_rate_type) = 'USER' then
7366                 ln_exchange_rate := r_ap_invoices_all.exchange_rate;
7367             else
7368                 ln_exchange_rate := null;
7369             end if;
7370 
7371             IF ( ln_proc_level >= ln_dbg_level)
7372             THEN
7373 
7374                    FND_LOG.STRING ( ln_proc_level
7375                                   , GV_MODULE_PREFIX ||'.'|| lv_proc_name
7376                                   , ' CALL utils for inserting interface lines' || ''
7377                                   );
7378 
7379             END IF; --( ln_proc_level >= ln_dbg_level)  ;
7380             --fnd_file.put_line(FND_FILE.LOG, ' CALL utils for inserting interface lines');
7381 
7382             /*Bug 9759709 - Liability Account for the Credit Note must be fetched from the Standard Invoice
7383             If it is not present, then it needs to be defaulted from Vendor Site Setup. Passing NULL to
7384             parameter p_accts_pay_ccid in jai_ap_utils_pkg.insert_ap_inv_interface would cause it to default
7385             from setup*/
7386             if (r_ap_invoices_all.accts_pay_code_combination_id is not NULL) then
7387                ln_accts_pay_ccid := r_ap_invoices_all.accts_pay_code_combination_id;
7388             else
7389                ln_accts_pay_ccid := NULL;
7390             end if;
7391     end if;
7392     --------------------------------------------------------------------------------------------
7393     --Added by Zhiwei Hou for bug#13767335 end
7394 
7395 
7396     ln_count := 0;
7397 
7398     ln_author_inv_sum_amount := 0;
7399     ln_vendor_inv_sum_amount := 0;
7400 
7401     ln_amount_for_sub_au := 0;
7402     ln_amount_for_sub_cm := 0;
7403 
7404     for rec_tax in (
7405 
7406          /*select distinct tax_type
7407          from   jai_cmn_taxes_all
7408          where tax_id in
7409          (*/
7410              select distinct tax_type
7411              from (
7412                      select actual_tax_id ,tax_type,tax_line_no
7413                      from jai_ap_tds_inv_taxes
7414                      where invoice_id = pn_invoice_id
7415                      and   section_type = pv_section_type --Added by Zhiwei Hou on 20120111
7416                      and   actual_section_code = pv_section_code
7417                      and   tax_category_id = pn_tax_category_id
7418                      order by tax_line_no
7419              ) a
7420              order by tax_type
7421          --)
7422      )
7423      loop
7424 
7425          ln_count := ln_count + 1;
7426 
7427 
7428          open get_one_tax(rec_tax.tax_type);
7429          fetch get_one_tax into ln_tax_id_new;
7430          close get_one_tax;
7431 
7432 
7433          open get_tax_rate(rec_tax.tax_type);
7434          fetch get_tax_rate into ln_tax_rate;
7435          close get_tax_rate;
7436 
7437 
7438 
7439          --ln_tax_id_new := rec_tax.actual_tax_id;--Comment by Zhiwei on 20120104
7440 
7441          open  c_ja_in_tax_codes(ln_tax_id_new);
7442          fetch c_ja_in_tax_codes into r_ja_in_tax_codes;
7443          close c_ja_in_tax_codes;
7444 
7445          ln_vendor_id      := r_ja_in_tax_codes.vendor_id;
7446          ln_vendor_site_id := r_ja_in_tax_codes.vendor_site_id;
7447 
7448          lv_stform_type := r_ja_in_tax_codes.stform_type;
7449 
7450          open c_po_vendors(r_ja_in_tax_codes.vendor_id);
7451          fetch c_po_vendors into r_po_vendors;
7452          close c_po_vendors;
7453 
7454 
7455          open  c_po_vendor_sites_all(r_ja_in_tax_codes.vendor_id, r_ja_in_tax_codes.vendor_site_id);
7456          fetch c_po_vendor_sites_all into r_po_vendor_sites_all;
7457          close c_po_vendor_sites_all;
7458 
7459 
7460          ln_terms_id := r_po_vendor_sites_all.terms_id;
7461          lv_pay_group_lookup_code      := r_po_vendor_sites_all.pay_group_lookup_code;
7462 
7463 
7464          if ((ln_terms_id is null) or (lv_pay_group_lookup_code is null))then
7465 
7466              ln_terms_id                   := r_po_vendors.terms_id;
7467              lv_pay_group_lookup_code      := r_po_vendors.pay_group_lookup_code;
7468 
7469          end if;
7470 
7471          open get_amt_for_type(rec_tax.tax_type);
7472          fetch get_amt_for_type into ln_tax_amt_tax_type;
7473          close get_amt_for_type;
7474 
7475          open get_amt_for_all;
7476          fetch get_amt_for_all into ln_tax_amt_all;
7477          close get_amt_for_all;
7478 
7479 
7480          if lv_invoice_to_tds_num is not null and lv_invoice_to_tds_type is not null and NVL(ln_invoice_to_tds_amount,0) <> 0 then
7481 
7482 
7483               if(ln_count = 1)then
7484                       jai_ap_utils_pkg.insert_ap_inv_interface
7485                       (
7486                         p_jai_source                        => lv_this_procedure,
7487                         p_invoice_id                        => ln_invoice_to_tds_id,
7488                         p_invoice_num                       => lv_invoice_to_tds_num,
7489                         p_invoice_type_lookup_code          => lv_invoice_to_tds_type,
7490                         p_invoice_date                      => ld_accounting_date,  --Bug 10020606 - Replaced Base Supplier Invoice Date with GL Date
7491                         p_gl_date                           => ld_accounting_date, --Added by Bgowrava for Bug#9186263
7492                         p_vendor_id                         => ln_vendor_id,
7493                         p_vendor_site_id                    => ln_vendor_site_id,
7494                         p_invoice_amount                    => ln_invoice_to_tds_amount,
7495                         p_invoice_currency_code             => r_gl_sets_of_books.currency_code,
7496                         p_exchange_rate                     => null,
7497                         p_exchange_rate_type                => null,
7498                         p_exchange_date                     => null,
7499                         p_terms_id                          => ln_terms_id,
7500                         p_description                       => lv_invoice_to_tds_num,
7501                         p_last_update_date                  => sysdate,
7502                         p_last_updated_by                   => fnd_global.user_id,
7503                         p_last_update_login                 => fnd_global.login_id,
7504                         p_creation_date                     => sysdate,
7505                         p_created_by                        => fnd_global.user_id,
7506                         p_source                            => lv_source,
7507                         p_voucher_num                       => lv_invoice_to_tds_num,
7508                         p_pay_group_lookup_code             => lv_pay_group_lookup_code,
7509                         p_org_id                            => r_ap_invoices_all.org_id,
7510                         p_attribute_category                => 'India Original Invoice for TDS',
7511                         p_attribute1                        => pn_invoice_id,
7512                         p_group_id                          => lv_group_id, -- Bug# 6119216, changed to lv_group_id instead of to_char(p_invoice_id)
7513 			p_Calc_Tax_During_Import_Flag       => 'Y'   --Added by Qiong for AP Open Interface
7514                       );
7515               end if;
7516               /* Line Interface */
7517 
7518 
7519               ln_tax_amt_for_each := round(ln_invoice_to_tds_amount * ln_tax_amt_tax_type/ln_tax_amt_all,g_inr_currency_rounding);
7520 
7521 
7522               jai_ap_utils_pkg.insert_ap_inv_lines_interface
7523               (
7524                 p_jai_source                        => lv_this_procedure,
7525                 p_invoice_id                        => ln_invoice_to_tds_id,
7526                 p_invoice_line_id                   => ln_invoice_to_tds_line_id,
7527                 p_line_number                       => ln_count,
7528                 p_line_type_lookup_code             => lv_invoice_to_tds_line_type,
7529                 p_amount                            => ln_tax_amt_for_each,
7530                 p_accounting_date                   => ld_accounting_date,
7531                 p_description                       => lv_invoice_to_tds_num||'/'||pv_section_type||'/'||pv_section_code||'/'||rec_tax.tax_type||'/'||ln_tax_id_new||'/'||ln_tax_rate,--Update by Zhiwei on 20120104
7532                 p_dist_code_combination_id          => r_ja_in_tax_codes.tax_account_id,
7533                 p_last_update_date                  => sysdate,
7534                 p_last_updated_by                   => fnd_global.user_id,
7535                 p_last_update_login                 => fnd_global.login_id,
7536                 p_creation_date                     => sysdate,
7537                 p_created_by                        => fnd_global.user_id
7538               );
7539 
7540 
7541               --ln_author_inv_sum_amount := ln_author_inv_sum_amount + ln_tax_amt_for_each;
7542 
7543               if(ln_count <> 1)then
7544 
7545                   ln_amount_for_sub_au := ln_amount_for_sub_au + ln_tax_amt_for_each;
7546 
7547               end if;
7548 
7549          end if; /* Invoice to TDS authority */
7550 
7551 
7552          if lv_invoice_to_vendor_num is not null and lv_invoice_to_vendor_type is not null then
7553 
7554 
7555 
7556 
7557 
7558 
7559 
7560 
7561             IF NVL(ln_invoice_to_vendor_amount,0) <> 0 THEN
7562 
7563 
7564                       /* Invoices Interface */
7565                   if(ln_count = 1)then
7566                       jai_ap_utils_pkg.insert_ap_inv_interface
7567                       (
7568                         p_jai_source                        => lv_this_procedure,
7569                         p_invoice_id                        => ln_invoice_to_vendor_id,
7570                         p_invoice_num                       => lv_invoice_to_vendor_num,
7571                         p_invoice_type_lookup_code          => lv_invoice_to_vendor_type,
7572                         p_invoice_date                      => pv_invoice_date,--r_ap_invoices_all.invoice_date,  --Modified to ld_accounting_date for Bug#9186263
7573                         p_gl_date                           => ld_accounting_date,
7574                         p_vendor_id                         => r_ap_invoices_all.vendor_id,
7575                         p_vendor_site_id                    => r_ap_invoices_all.vendor_site_id,
7576                         p_invoice_amount                    => ln_invoice_to_vendor_amount,
7577                         p_invoice_currency_code             => r_ap_invoices_all.invoice_currency_code,
7578                         p_exchange_rate                     => ln_exchange_rate,
7579                         p_exchange_rate_type                => r_ap_invoices_all.exchange_rate_type,
7580                         p_exchange_date                     => r_ap_invoices_all.exchange_date,
7581                         p_terms_id                          => r_ap_invoices_all.terms_id,
7582                         p_description                       => lv_invoice_to_vendor_num,
7583                         p_last_update_date                  => sysdate,
7584                         p_last_updated_by                   => fnd_global.user_id,
7585                         p_last_update_login                 => fnd_global.login_id,
7586                         p_creation_date                     => sysdate,
7587                         p_created_by                        => fnd_global.user_id,
7588                         p_source                            => lv_source,
7589                         p_voucher_num                       => lv_invoice_to_vendor_num,
7590                         p_payment_method_code               => r_ap_invoices_all.payment_method_code,
7591                         p_pay_group_lookup_code             => r_ap_invoices_all.pay_group_lookup_code,
7592                         p_goods_received_date               => r_ap_invoices_all.goods_received_date,
7593                         p_invoice_received_date             => r_ap_invoices_all.invoice_received_date,
7594                         p_org_id                            => r_ap_invoices_all.org_id,
7595                         p_attribute_category                => 'India Original Invoice for TDS',
7596                         p_attribute1                        => pn_invoice_id,
7597                         p_group_id                          => lv_group_id,
7598                         p_accts_pay_ccid                    => ln_accts_pay_ccid, /*Bug 9759709*/
7599 			p_Calc_Tax_During_Import_Flag       => 'Y'   --Added by Qiong for AP Open Interface
7600                       );
7601                     end if;
7602 
7603                 /* Lines Interface */
7604                 /*open get_amt_for_dist(rec_tax.invoice_distribution_id);
7605                 fetch get_amt_for_dist into ln_amt_dist;
7606                 close get_amt_for_dist;
7607 
7608                 open get_amt_for_all_inv;
7609                 fetch get_amt_for_all_inv into ln_amt_all;
7610                 close get_amt_for_all_inv;*/
7611 
7612                 ln_amt_for_each := round(ln_invoice_to_vendor_amount * ln_tax_amt_tax_type/ln_tax_amt_all,g_inr_currency_rounding);
7613 
7614 
7615                 jai_ap_utils_pkg.insert_ap_inv_lines_interface
7616                 (
7617                   p_jai_source                        => lv_this_procedure,
7618                   p_invoice_id                        => ln_invoice_to_vendor_id,
7619                   p_invoice_line_id                   => ln_invoice_to_vendor_line_id,
7620                   p_line_number                       => ln_count,
7621                   p_line_type_lookup_code             => lv_invoice_to_vendor_line_type,
7622                   p_amount                            => ln_amt_for_each,--ln_invoice_to_vendor_amount,
7623                   p_accounting_date                   => ld_accounting_date,
7624                   p_description                       => lv_invoice_to_vendor_num||'/'||pv_section_type||'/'||pv_section_code||'/'||rec_tax.tax_type||'/'||ln_tax_id_new||'/'||ln_tax_rate,
7625                   p_dist_code_combination_id          => r_ja_in_tax_codes.tax_account_id,
7626                   p_last_update_date                  => sysdate,
7627                   p_last_updated_by                   => fnd_global.user_id,
7628                   p_last_update_login                 => fnd_global.login_id,
7629                   p_creation_date                     => sysdate,
7630                   p_created_by                        => fnd_global.user_id
7631                 );
7632 
7633                 --ln_vendor_inv_sum_amount := ln_vendor_inv_sum_amount  + ln_amt_for_each;
7634 
7635                 if(ln_count <> 1)then
7636 
7637                   ln_amount_for_sub_cm := ln_amount_for_sub_cm + ln_amt_for_each;
7638 
7639                 end if;
7640 
7641             END IF;
7642 
7643 
7644          end if; /* Invoice to Supplier */
7645 
7646 
7647 
7648      end loop;
7649 
7650      if lv_invoice_to_tds_num is not null and lv_invoice_to_tds_type is not null and NVL(ln_invoice_to_tds_amount,0) <> 0 then
7651 
7652         update ap_invoice_lines_interface
7653         set    amount = round(ln_invoice_to_tds_amount - ln_amount_for_sub_au , g_inr_currency_rounding)
7654         where  invoice_id = ln_invoice_to_tds_id
7655         and    line_number = 1;
7656 
7657      end if;
7658 
7659 
7660      if lv_invoice_to_vendor_num is not null and lv_invoice_to_vendor_type is not null and NVL(ln_invoice_to_vendor_amount,0) <> 0  then
7661 
7662         update ap_invoice_lines_interface
7663         set    amount = round(ln_invoice_to_vendor_amount - ln_amount_for_sub_cm, g_inr_currency_rounding)
7664         where  invoice_id = ln_invoice_to_vendor_id
7665         and    line_number = 1;
7666 
7667      end if;
7668 
7669 
7670 
7671     /* Store the parent invoices payment priority as this is to be used in the credit memo generated for the supplier */
7672     open  c_ap_payment_schedules_all(pn_invoice_id);
7673     fetch c_ap_payment_schedules_all  into r_ap_payment_schedules_all;
7674     close c_ap_payment_schedules_all;
7675 
7676     /* Bug 5751783
7677      * Moved the assignment of ln_invoice_amount outside IF as this is used
7678      * in the insert to jai_ap_tds_thhold_trxs. This has to be derived irrespective
7679      * of the tds event.
7680      */
7681 
7682     --Fnd_File.put_line(Fnd_File.LOG,  'pn_taxable_amount '||pn_taxable_amount);
7683     /*IF pn_taxable_amount IS NOT NULL THEN
7684        ln_invoice_amount :=  pn_taxable_amount;
7685     ELSE*/ /*Commented the above if condition for bug 13070779 */
7686        ln_invoice_amount := pn_tax_amount * ( 100 / r_ja_in_tax_codes.tax_rate);
7687    -- END IF;
7688     --fnd_file.put_line(FND_FILE.LOG, ' invoice amount'|| ln_invoice_amount);
7689     IF ( ln_proc_level >= ln_dbg_level)
7690     THEN
7691 
7692            FND_LOG.STRING ( ln_proc_level
7693                           , GV_MODULE_PREFIX ||'.'|| lv_proc_name
7694                           , 'pn_taxable_amount ' || pn_taxable_amount
7695                           );
7696            FND_LOG.STRING ( ln_proc_level
7697                           , GV_MODULE_PREFIX ||'.'|| lv_proc_name
7698                           , ' invoice amount ' || ln_invoice_amount
7699                           );
7700     END IF; --( ln_proc_level >= ln_dbg_level)  ;
7701     /* For downward compatibility with the pre-cleanup code */
7702     if ( (pv_tds_event = 'INVOICE VALIDATE') or (pv_tds_event like 'THRESHOLD TRANSITION%') ) then
7703 
7704       /*
7705       || Added the IF-ELSE-ENDIF block by Ramananda for Bug#4562801
7706       */
7707 
7708 
7709       IF pv_section_type = 'TDS_SECTION' THEN --rchandan for bug#4428980
7710         lv_source_attribute := 'ATTRIBUTE1';
7711       ELSIF pv_section_type = 'WCT_SECTION' THEN
7712         lv_source_attribute := 'ATTRIBUTE2';
7713       ELSIF pv_section_type = 'ESSI_SECTION' THEN
7714         lv_source_attribute := 'ATTRIBUTE3';
7715       END IF;
7716 
7717 
7718       IF ( ln_proc_level >= ln_dbg_level)
7719       THEN
7720 
7721              FND_LOG.STRING ( ln_proc_level
7722                             , GV_MODULE_PREFIX ||'.'|| lv_proc_name
7723                             , ' invoice id  ' || pn_invoice_id
7724                             );
7725              FND_LOG.STRING ( ln_proc_level
7726                             , GV_MODULE_PREFIX ||'.'|| lv_proc_name
7727                             , ' invoice amount ' || ln_invoice_amount
7728                             );
7729              FND_LOG.STRING ( ln_proc_level
7730                             , GV_MODULE_PREFIX ||'.'|| lv_proc_name
7731                             , ' invoice to tds inv num ' || lv_invoice_to_tds_num
7732                             );
7733              FND_LOG.STRING ( ln_proc_level
7734                             , GV_MODULE_PREFIX ||'.'|| lv_proc_name
7735                             , ' vendor num ' || lv_invoice_to_vendor_num
7736                             );
7737              FND_LOG.STRING ( ln_proc_level
7738                             , GV_MODULE_PREFIX ||'.'|| lv_proc_name
7739                             , ' tax category id ' || pn_tax_category_id
7740                             );
7741              FND_LOG.STRING ( ln_proc_level
7742                             , GV_MODULE_PREFIX ||'.'|| lv_proc_name
7743                             , ' tds amt ' || ln_invoice_to_tds_amount
7744                             );
7745              FND_LOG.STRING ( ln_proc_level
7746                             , GV_MODULE_PREFIX ||'.'|| lv_proc_name
7747                             , ' sec code ' || pv_section_code
7748                             );
7749 
7750       END IF; --( ln_proc_level >= ln_dbg_level)  ;
7751       --fnd_file.put_line(FND_FILE.LOG, ' invoice id '|| pn_invoice_id);
7752       --fnd_file.put_line(FND_FILE.LOG, ' invoice amount'|| ln_invoice_amount);
7753       --fnd_file.put_line(FND_FILE.LOG, 'invoice to tds inv num'|| lv_invoice_to_tds_num);
7754       --fnd_file.put_line(FND_FILE.LOG, 'vendor num' ||lv_invoice_to_vendor_num);
7755       --fnd_file.put_line(FND_FILE.LOG, 'tax id '||pn_tax_category_id);
7756       --fnd_file.put_line(FND_FILE.LOG, 'tax rate'|| r_ja_in_tax_codes.tax_rate);
7757       --fnd_file.put_line(FND_FILE.LOG, 'tds amt'||ln_invoice_to_tds_amount);
7758       --fnd_file.put_line(FND_FILE.LOG, 'sec code '||pv_section_code);
7759       --fnd_file.put_line(FND_FILE.LOG, 'stformtype '||lv_stform_type);
7760       --fnd_file.put_line(FND_FILE.LOG, 'org id '|| r_ap_invoices_all.org_id);
7761       --fnd_file.put_line(FND_FILE.LOG, 'src att'||lv_source_attribute);
7762 
7763      IF NVL(ln_invoice_amount,0) <> 0 THEN --Added the condition by bgowrava for Bug#4549019
7764       insert into JAI_AP_TDS_INVOICES
7765       (TDS_INVOICE_ID,
7766         invoice_id,
7767         invoice_amount,
7768         tds_invoice_num,
7769         dm_invoice_num,
7770         tds_tax_id,--As it's a index column, not allowed null. so assign 1
7771         tax_category_id,
7772         --tds_tax_rate,
7773         tds_amount,
7774         tds_section,
7775         certificate_number,
7776         --org_id,
7777         organization_id,
7778         source_attribute,
7779         /* Ramananda for bug#4560109 during R12 Sanity Testing. Added the WHO columns */
7780         created_by        ,
7781         creation_date     ,
7782         last_updated_by   ,
7783         last_update_date  ,
7784         last_update_login
7785       )
7786       values
7787       ( JAI_AP_TDS_INVOICES_S.nextval,
7788         pn_invoice_id,
7789         --round(ln_invoice_to_tds_amount * ( 100 / r_ja_in_tax_codes.tax_rate), 2),
7790         --commented the above and added the below by Ramananda for Bug#4562801
7791         pn_taxable_amount,--ln_invoice_amount,--UPdate by Zhiwei Hou on 20120111
7792         lv_invoice_to_tds_num,
7793         lv_invoice_to_vendor_num,
7794         1,--pn_tax_id,
7795         pn_tax_category_id,
7796         --r_ja_in_tax_codes.tax_rate,
7797         ln_invoice_to_tds_amount,
7798         pv_section_code,--r_ja_in_tax_codes.section_code,
7799         lv_stform_type,--r_ja_in_tax_codes.stform_type,
7800         --r_ap_invoices_all.org_id,
7801         r_ap_invoices_all.org_id,
7802         lv_source_attribute,  --rchandan for bug#4428980
7803         /* Ramananda for bug#4560109 during R12 Sanity Testing. Added the WHO columns */
7804         fnd_global.user_id                             ,
7805         sysdate                                        ,
7806         fnd_global.user_id                             ,
7807         sysdate                                        ,
7808         fnd_global.login_id
7809       );
7810 end if;
7811     end if; /* Only for validate event as done in earlier regime */
7812 
7813     -- Bug 5722028. Added by csahoo
7814   ln_tds_rnding_factor := 0;
7815   ln_tds_rnded_amt := pn_tax_amount;
7816   /* Added the below if condition for bug 12965614 */
7817   IF pv_tds_event = 'PREPAYMENT UNAPPLICATION' THEN  --2
7818         IF r_ap_invoices_all.invoice_currency_code <>  r_gl_sets_of_books.currency_code THEN  --3
7819        ln_tds_rnded_amt := ROUND(pn_calc_tax_amount , g_inr_currency_rounding);
7820        IF (trunc(pd_creation_date) >= trunc(jai_ap_dtc_generation_pkg.gd_tds_rounding_effective_date)) THEN  --4
7821               ln_tds_rnding_factor := jai_ap_dtc_generation_pkg.gn_tds_rounding_factor;
7822               ln_tds_rnded_amt := get_rnded_value(ln_tds_rnded_amt);
7823             END IF; --4
7824        ln_tds_rnded_amt := ROUND(pn_calc_tax_amount / r_ap_invoices_all.exchange_rate, g_fcy_currency_rounding);
7825       END IF; --3
7826        ELSE --2
7827   /*IF pv_tds_event NOT IN
7828      -- Bug 7280925. commented by Lakshmi Gopalsami ('INVOICE CANCEL',
7829       ('PREPAYMENT UNAPPLICATION') THEN */
7830        IF r_ap_invoices_all.invoice_currency_code = r_gl_sets_of_books.currency_code THEN
7831       ln_tds_rnded_amt := ROUND(pn_tax_amount , g_inr_currency_rounding);
7832       --moved this if-endif block from below to here for bug#8995604
7833      ELSE
7834      ln_tds_rnded_amt := ROUND(pn_tax_amount , g_inr_currency_rounding);
7835         IF (trunc(pd_creation_date) >=
7836        trunc(jai_ap_dtc_generation_pkg.gd_tds_rounding_effective_date)
7837            /* Bug 7280925. Added by Lakshmi Gopalsami
7838       * we should not round for WCT and ESSI. For those threshold_grp_id
7839       * will be null
7840       */
7841             and pn_threshold_grp_id is not null )
7842       THEN
7843      ln_tds_rnding_factor := jai_ap_dtc_generation_pkg.gn_tds_rounding_factor;
7844      ln_tds_rnded_amt := get_rnded_value(ln_tds_rnded_amt);
7845           --fnd_file.put_line(FND_FILE.LOG, ' Bug 7280925 - value after round before insert into trxs'||ln_tds_rnded_amt);
7846       END IF;
7847       ln_tds_rnded_amt := ROUND(pn_tax_amount / r_ap_invoices_all.exchange_rate, g_fcy_currency_rounding);
7848      END IF ;
7849            --fnd_file.put_line(FND_FILE.LOG, ' Bug 7280925 - value before round '||ln_tds_rnded_amt);
7850 
7851   END IF;
7852      -- End for bug 5722028.
7853 
7854 
7855 
7856     insert into jai_ap_tds_thhold_trxs
7857     (
7858       threshold_trx_id                               ,
7859       invoice_id                                     ,
7860       invoice_line_number                            ,
7861       invoice_distribution_id                        ,
7862       threshold_grp_id                               ,
7863       threshold_hdr_id                               ,
7864       tds_event                                      ,
7865       --tax_id                                         ,
7866       tax_category_id                                ,
7867       --tax_rate                                       ,
7868       taxable_amount                                 ,
7869       tax_amount                                     ,
7870       tds_authority_vendor_id                        ,
7871       tds_authority_vendor_site_id                   ,
7872       invoice_to_tds_authority_num                   ,
7873       invoice_to_tds_authority_type                  ,
7874       invoice_to_tds_authority_curr                  ,
7875       invoice_to_tds_authority_amt                   ,
7876       vendor_id                                      ,
7877       vendor_site_id                                 ,
7878       invoice_to_vendor_num                          ,
7879       invoice_to_vendor_type                         ,
7880       invoice_to_vendor_curr                         ,
7881       invoice_to_vendor_amt                          ,
7882       parent_inv_payment_priority                    ,
7883       parent_inv_exchange_rate                       ,
7884       created_by                                     ,
7885       creation_date                                  ,
7886       last_updated_by                                ,
7887       last_update_date                               ,
7888       last_update_login                               ,
7889       calc_tax_amount                                , /*Bug 5751783*/
7890       tds_rounding_factor -- Bug 5722028. Added by csahoo
7891       ,TDS_SECTION_CODE --Add by zhiwei hou on 20120111
7892     )
7893     values
7894     (
7895       jai_ap_tds_thhold_trxs_s.nextval               ,
7896       pn_invoice_id                                  ,
7897       pn_invoice_line_number                         ,
7898       pn_invoice_distribution_id                     ,
7899       pn_threshold_grp_id                            ,
7900       pn_threshold_hdr_id                            ,
7901       pv_tds_event                                   ,
7902       --pn_tax_id                                      ,
7903       pn_tax_category_id                             ,
7904       --r_ja_in_tax_codes.tax_rate                     ,
7905       /* Bug 5751783. Changed to ln_invoice_amount instead of pn_taxable_amount
7906        * This is done as now pn_taxable_amount will always be populated irrespective
7907        * of tds_event. Added rounding for pn_tax_amount.
7908        */
7909       pn_taxable_amount,--ln_invoice_amount  --UPdate by Zhiwei Hou on 20120111                                ,
7910       ln_tds_rnded_amt,  --Bug 5722028. Added by csahoo
7911       ln_vendor_id                    ,
7912       ln_vendor_site_id               ,
7913       lv_invoice_to_tds_num                          ,
7914       lv_invoice_to_tds_type                         ,
7915       r_gl_sets_of_books.currency_code               ,
7916       ln_invoice_to_tds_amount                       ,
7917       r_ap_invoices_all.vendor_id                    ,
7918       r_ap_invoices_all.vendor_site_id               ,
7919       lv_invoice_to_vendor_num                       ,
7920       lv_invoice_to_vendor_type                      ,
7921       r_ap_invoices_all.invoice_currency_code        ,
7922       ln_invoice_to_vendor_amount                    ,
7923       r_ap_payment_schedules_all.payment_priority    ,
7924       r_ap_invoices_all.exchange_rate                ,
7925       fnd_global.user_id                             ,
7926       sysdate                                        ,
7927       fnd_global.user_id                             ,
7928       sysdate                                        ,
7929       fnd_global.login_id                         ,
7930       decode ( pv_tds_event, 'PREPAYMENT UNAPPLICATION', pn_calc_tax_amount, pn_tax_amount), /*Added decode condition for bug 12965614 */ /*Bug 5751783*/
7931       ln_tds_rnding_factor -- Bug 5722028. Added by csahoo
7932       ,decode(pv_section_type, G_TDS_SECTION, pv_section_code, NULL)     --Update by Chong, not populate TDS section code for WCT/ESSI section.
7933       --,pv_section_code --Add by zhiwei hou on 20120111
7934     )
7935     returning threshold_trx_id into pn_threshold_trx_id;
7936 
7937     <<exit_from_procedure>>
7938 	jai_cmn_utils_pkg.WRITE_FND_LOG(G_LEVEL_PROCEDURE, G_MODULE_NAME||l_api_name||'.END', G_PKG_NAME || ': '||l_api_name||'()-');
7939       return;
7940 
7941     exception
7942       when others then
7943         p_process_flag := 'E';
7944         p_process_message := 'Error from jai_ap_dtc_generation_pkg.generate_dtc_invoices :' || sqlerrm;
7945 
7946   end generate_dtc_invoices;
7947 
7948 /* *********************************** procedure generate_dtc_invoices ********************************** */
7949 
7950 
7951 
7952 
7953 
7954 
7955 /* *********************************** procedure import_and_approve ********************************** */
7956 
7957   procedure import_and_approve
7958   (
7959     p_invoice_id                    in                       number,
7960     p_start_thhold_trx_id           in                       number,
7961     p_tds_event                     in                       varchar2,
7962     p_process_flag                  out            nocopy    varchar2,
7963     p_process_message               out            nocopy    varchar2
7964   )
7965   is
7966 
7967     cursor  c_ap_invoices_all(p_invoice_id number) is
7968       select  vendor_id,
7969               vendor_site_id,
7970         org_id
7971       from    ap_invoices_all
7972       where   invoice_id = p_invoice_id;
7973 
7974     cursor    c_ja_in_po_vendor_sites(p_vendor_id number, p_vendor_site_id number) is
7975       select  nvl( approved_invoice_flag, 'N' ) approved_invoice_flag
7976       from    JAI_CMN_VENDOR_SITES
7977       where   vendor_id       =   p_vendor_id
7978       and     vendor_site_id  =   p_vendor_site_id;
7979 
7980 
7981     r_ap_invoices_all                 c_ap_invoices_all%rowtype;
7982 
7983     lb_result                         boolean;
7984     ln_import_request_id              number;
7985     ln_approve_request_id             number;
7986     lv_approved_invoice_flag          JAI_CMN_VENDOR_SITES.approved_invoice_flag%type;
7987     lv_batch_name                     ap_batches_all.batch_name%TYPE; --added by Ramananda for Bug#4584221
7988     lv_group_id                       VARCHAR2(80); --Added by Sanjikum for Bug#5131075(4722011)
7989     l_api_name                   CONSTANT  VARCHAR2(50) := 'import_and_approve()';
7990 
7991     /*Added for bug#15915537 TDS Performance ER on 26-Nov-2012 by Qimeng begin*/
7992     lb_import_invoices_success        BOOLEAN;
7993 	  lv_batch_error_flag               VARCHAR2(10);
7994 	  ln_invoices_fetched               NUMBER;
7995 	  ln_invoices_created               NUMBER;
7996 	  ln_total_invoice_amount           NUMBER;
7997 	  lv_print_batch                    VARCHAR2(50);
7998 	  lv_errbuf                         VARCHAR2(2000);
7999 	  lv_retcode                        VARCHAR2(50);
8000     ln_report_request_id              NUMBER;
8001     /*Added for bug#15915537 TDS Performance ER on 26-Nov-2012 by Qimeng begin*/
8002 
8003   begin
8004     jai_cmn_utils_pkg.WRITE_FND_LOG(G_LEVEL_PROCEDURE, G_MODULE_NAME||l_api_name||'.BEGIN', G_PKG_NAME || ': '||l_api_name||'()+');
8005     jai_cmn_utils_pkg.WRITE_FND_LOG(G_LEVEL_PROCEDURE, G_MODULE_NAME||l_api_name, 'p_tds_event='||p_tds_event);
8006     fnd_file.put_line (fnd_file.log,   'p_tds_event='||p_tds_event);
8007     --Added by Sanjikum for Bug#5131075(4722011)
8008     IF p_tds_event = 'PREPAYMENT APPLICATION' OR p_tds_event = 'PREPAYMENT UNAPPLICATION' THEN
8009       lv_group_id := to_char(p_invoice_id)||p_tds_event;
8010     ELSE
8011       lv_group_id := to_char(p_invoice_id);
8012     END IF;
8013 
8014 
8015     /* Invoke payables open interface */
8016 
8017     lb_result := fnd_request.set_mode(true);
8018 
8019 	open c_ap_invoices_all(p_invoice_id);
8020 	fetch c_ap_invoices_all into r_ap_invoices_all;
8021 	close c_ap_invoices_all;
8022 
8023     lv_batch_name := jai_ap_utils_pkg.get_tds_invoice_batch(p_invoice_id, r_ap_invoices_all.org_id); --Ramananda for bug#4584221 --added org_id parameter for Bug#9149941
8024     /*Comment for bug#15915537 TDS Performance ER on 26-Nov-2012 by Qimeng begin
8025     ln_import_request_id :=
8026     fnd_request.submit_request
8027     (
8028       'SQLAP',
8029       'APXIIMPT',
8030       'Import TDS invoices - ' || lower(p_tds_event),
8031       '',
8032       false,
8033       /* Bug 4774647. Added by Lakshmi Gopalsami
8034           Passed operating unit also as this parameter has been
8035     added by base .
8036       */
8037       /*'',
8038       'INDIA TDS', /*--'TDS', --Ramanand for bug#4388958*/
8039       --'',
8040 			--Commented the above and added the below by Sanjikum for Bug#5131075(4722011)
8041 			/*lv_group_id,        -- Chaged from to_char(p_invoice_id) for bug# 6119216
8042       --'TDS'||TO_CHAR(TRUNC(SYSDATE)),
8043       --commented the above and added the below by Ramananda for Bug#4584221
8044       lv_batch_name,
8045       '',
8046       '',
8047       '',
8048       'Y',
8049       'N',
8050       'N',
8051       'N',
8052       1000,
8053       fnd_global.user_id,
8054       fnd_global.login_id
8055     );
8056 
8057     Comment for bug#15915537 TDS Performance ER on 26-Nov-2012 by Qimeng end*/
8058 
8059    --For eTDS start Chong  (back to CP mode)
8060     ln_import_request_id :=
8061     fnd_request.submit_request
8062     (
8063       'SQLAP',
8064       'APXIIMPT',
8065       'Import TDS invoices - ' || lower(p_tds_event),
8066       '',
8067       false,
8068       /* Bug 4774647. Added by Lakshmi Gopalsami
8069           Passed operating unit also as this parameter has been
8070     added by base .
8071       */
8072       '',
8073       'INDIA TDS', /*--'TDS', --Ramanand for bug#4388958*/
8074       --'',
8075 			--Commented the above and added the below by Sanjikum for Bug#5131075(4722011)
8076 			lv_group_id,        -- Chaged from to_char(p_invoice_id) for bug# 6119216
8077       --'TDS'||TO_CHAR(TRUNC(SYSDATE)),
8078       --commented the above and added the below by Ramananda for Bug#4584221
8079       lv_batch_name,
8080       '',
8081       '',
8082       '',
8083       'Y',
8084       'N',
8085       'N',
8086       'N',
8087       1000,
8088       fnd_global.user_id,
8089       fnd_global.login_id
8090     );
8091     --Added for eTDS end by Chong
8092 
8093 
8094     /*Added for bug#15915537 TDS Performance ER on 26-Nov-2012 by Qimeng begin*/
8095 /*    lb_import_invoices_success :=       --Commented out by Chong for eTDS. rollback to CP mode
8096 	    ap_import_invoices_pkg.import_invoices(
8097 	                                       p_batch_name           => lv_batch_name
8098                                         ,p_gl_date              => NULL
8099                                         ,p_hold_code            => NULL
8100                                         ,p_hold_reason          => NULL
8101                                         ,p_commit_cycles        => NULL
8102                                         ,p_source               => 'INDIA TDS'
8103                                         ,p_group_id             => lv_group_id
8104                                         ,p_conc_request_id      => NULL
8105                                         ,p_debug_switch         => NULL
8106                                         ,p_org_id               => NULL
8107                                         ,p_batch_error_flag     => lv_batch_error_flag
8108                                         ,p_invoices_fetched     => ln_invoices_fetched
8109                                         ,p_invoices_created     => ln_invoices_created
8110                                         ,p_total_invoice_amount => ln_total_invoice_amount
8111                                         ,p_print_batch          => lv_print_batch
8112                                         ,p_calling_sequence     => NULL);*/
8113     /*Added for bug#15915537 TDS Performance ER on 26-Nov-2012 by Qimeng end*/
8114 
8115     /* Get vendor and site for the invoice */
8116    /* open  c_ap_invoices_all(p_invoice_id);
8117     fetch c_ap_invoices_all into r_ap_invoices_all;
8118     close c_ap_invoices_all;*/ --moved this code to the start of the procedure for Bug#9149941
8119 
8120     /* Check if Pre-approved TDS invoices setup has been set for the vendor */
8121 
8122     /* Check for vendor and site */
8123     open   c_ja_in_po_vendor_sites(r_ap_invoices_all.vendor_id, r_ap_invoices_all.vendor_site_id);
8124     fetch  c_ja_in_po_vendor_sites into lv_approved_invoice_flag;
8125     close  c_ja_in_po_vendor_sites;
8126 
8127     if nvl(lv_approved_invoice_flag, 'N') <> 'Y' then
8128       /* Pre-approved TDS invoice is not set for vendor and site, Check for vendor and null site */
8129       open   c_ja_in_po_vendor_sites(r_ap_invoices_all.vendor_id, 0);
8130       fetch  c_ja_in_po_vendor_sites into lv_approved_invoice_flag;
8131       close  c_ja_in_po_vendor_sites;
8132     end if;
8133 
8134     if nvl(lv_approved_invoice_flag, 'N') <> 'Y' then
8135       /* Setup for pre-approved TDS invoice is not there for the vendor for site or null site. */
8136       goto exit_from_procedure;
8137     end if;
8138 
8139 
8140     /*  Control comes here only when Pre-approved TDS invoice is setup for the vendor,
8141         we need to invoke the request for approval */
8142     /*Comment for bug#15915537 TDS Performance ER on 26-Nov-2012 by Qimeng begin */     --revert to CP mode by Chong 2013/04/19
8143     lb_result := fnd_request.set_mode(true);
8144 
8145     ln_approve_request_id :=
8146     fnd_request.submit_request
8147     (
8148       'JA',
8149       'JAITDSA',
8150       'Approval Of TDS Invoices ',
8151       sysdate,
8152       false,
8153       ln_import_request_id,
8154       p_invoice_id,
8155       r_ap_invoices_all.vendor_id,
8156       r_ap_invoices_all.vendor_site_id,
8157       p_start_thhold_trx_id
8158     );
8159     /*Added for bug#15915537 TDS Performance ER on 26-Nov-2012 by Qimeng begin*/
8160     /*Commented by Chong to revert back to CP mode 2013/04/19 Start
8161     if lb_import_invoices_success then
8162 	    approve_tds_invoices(errbuf                => lv_errbuf
8163                           ,retcode               => lv_retcode
8164                           ,p_parent_request_id   => NULL
8165                           ,p_invoice_id          => p_invoice_id
8166                           ,p_vendor_id           => r_ap_invoices_all.vendor_id
8167                           ,p_vendor_site_id      => r_ap_invoices_all.vendor_site_id
8168                           ,p_start_thhold_trx_id => p_start_thhold_trx_id);
8169 	  end if;
8170     Commented by Chong to revert back to CP mode 2013/04/19 End
8171     */
8172     /*Added for bug#15915537 TDS Performance ER on 26-Nov-2012 by Qimeng end*/
8173 
8174 
8175     <<exit_from_procedure>>
8176     jai_cmn_utils_pkg.WRITE_FND_LOG(G_LEVEL_PROCEDURE, G_MODULE_NAME||l_api_name||'.END', G_PKG_NAME || ': '||l_api_name||'()-');
8177     return;
8178 
8179   exception
8180     when others then
8181       p_process_flag := 'E';
8182       p_process_message := 'Error from jai_ap_tds_generation_pkg.import_and_approve :' || sqlerrm;
8183   end import_and_approve;
8184 
8185 /* *********************************** procedure import_and_approve ********************************** */
8186 
8187 /* *********************************** procedure approve_tds_invoices ********************************** */
8188 
8189   procedure approve_tds_invoices
8190   (
8191     errbuf                          out            nocopy    varchar2,
8192     retcode                         out            nocopy    varchar2,
8193     p_parent_request_id             in             number,
8194     p_invoice_id                    in             number,
8195     p_vendor_id                     in             number,
8196     p_vendor_site_id                in             number,
8197     p_start_thhold_trx_id           in             number
8198   )
8199   is
8200 
8201     cursor  c_jai_ap_tds_thhold_trxs
8202     (p_invoice_id number, p_start_thhold_trx_id number, p_vendor_id number,  p_vendor_site_id number) is
8203       select invoice_to_tds_authority_id,
8204              invoice_to_vendor_id,
8205              invoice_to_tds_authority_num,
8206              invoice_to_vendor_num
8207       from   jai_ap_tds_thhold_trxs
8208       where  threshold_trx_id >= p_start_thhold_trx_id
8209       and    invoice_id = p_invoice_id
8210       and    vendor_id =  p_vendor_id
8211       and    vendor_site_id =  p_vendor_site_id;
8212 
8213    CURSOR c_jai_chk_tds_inv (p_invoice_id number) IS
8214     SELECT invoice_id, org_id,
8215            set_of_books_id -- bug 6819855. Added by Lakshmi Gopalsami
8216        FROM ap_invoices_all
8217       WHERE invoice_id = p_invoice_id;
8218 
8219     lb_request_status             boolean;
8220     lv_phase                      varchar2(100);
8221     lv_status                     varchar2(100);
8222     lv_dev_phase                  varchar2(100);
8223     lv_dev_status                 varchar2(100);
8224     lv_message                    varchar2(100);
8225 
8226     ln_holds_count                number;
8227     lv_approval_status            varchar2(100);
8228     lv_conc_flag  varchar2(10);
8229 
8230     /* Bug 4872659. Added by Lakshmi Gopalsami  */
8231     ln_tds_invoice_id    NUMBER;
8232     ln_vendor_invoice_id     NUMBER;
8233     ln_org_id               NUMBER;
8234 
8235     /* Bug 4943949. Added by Lakshmi gopalsami */
8236     lv_funds_ret_code varchar2(5);
8237 
8238     /* Bug 6819855. Added by Lakshmi Gopalsami */
8239     ln_sob_id  NUMBER;
8240     ln_holds_count1    NUMBER;
8241     l_api_name                   CONSTANT  VARCHAR2(50) := 'approve_tds_invoices()';
8242 
8243     begin
8244       jai_cmn_utils_pkg.WRITE_FND_LOG(G_LEVEL_PROCEDURE, G_MODULE_NAME||l_api_name||'.BEGIN', G_PKG_NAME || ': '||l_api_name||'()+');
8245       /* Check for the status of  the import request */
8246       Fnd_File.put_line(Fnd_File.LOG,  'jai_ap_tds_generation_pkg.approve_tds_invoices');
8247       Fnd_File.put_line(Fnd_File.LOG,  'p_parent_request_id =>' || p_parent_request_id);
8248       Fnd_File.put_line(Fnd_File.LOG,  'p_invoice_id=> ' || p_invoice_id );
8249       Fnd_File.put_line(Fnd_File.LOG,  'p_vendor_id=> ' || p_vendor_id);
8250       Fnd_File.put_line(Fnd_File.LOG,  'p_vendor_site_id=> ' || p_vendor_site_id);
8251       Fnd_File.put_line(Fnd_File.LOG,  'p_start_thhold_trx_id=> ' || p_start_thhold_trx_id);
8252 
8253       /*Comment for TDS bug#15915537 Performance ER on 26-Nov-2012 by Qimeng begin
8254       lb_request_status :=
8255       fnd_concurrent.wait_for_request
8256       (
8257         request_id  =>  p_parent_request_id,
8258         interval    =>  60,   /*  default value - sleep time in secs */
8259         /*max_wait    =>  0,    /* default value - max wait in secs */
8260         /*phase       =>  lv_phase,
8261         status      =>  lv_status,
8262         dev_phase   =>  lv_dev_phase,
8263         dev_status  =>  lv_dev_status,
8264         message     =>  lv_message
8265       );
8266 
8267 
8268       if not ( lv_dev_phase = 'COMPLETE' and  lv_dev_status = 'NORMAL' ) then
8269 
8270         Fnd_File.put_line(Fnd_File.LOG, 'Exiting with warning as parent request not completed with normal status');
8271         Fnd_File.put_line(Fnd_File.LOG, 'Message from parent request :' || lv_message);
8272         retcode := 1;
8273         errbuf := 'Exiting with warnings as parent request not completed with normal status';
8274         goto exit_from_procedure;
8275 
8276       end if;
8277       Comment for bug#15915537 TDS Performance ER on 26-Nov-2012 by Qimeng end*/
8278 
8279       /* Control comes here only when the concurrent request has completed with Normal Status */
8280       Fnd_File.put_line(Fnd_File.LOG, 'Before Loop ');
8281 
8282       /* Get all the tds invoices that have been created and call the base API to approve it */
8283       for cur_rec in
8284       c_jai_ap_tds_thhold_trxs(p_invoice_id , p_start_thhold_trx_id , p_vendor_id ,  p_vendor_site_id)
8285       loop
8286 
8287 
8288         /* Get the status of both the invoices and call approval API, if it is not already approved */
8289         ln_holds_count := 0;
8290         lv_approval_status := null;
8291 
8292   /* Bug 4872659. Added by Lakshmi Gopalsami
8293       There is a possibility that the invoice gets rejected via Interface and
8294       the invoice  is not existing. Base requires the org_id from the
8295       invoice_id we pass. Ensure that the invoice_id exists before calling approval
8296   */
8297 
8298         fnd_file.put_line(FND_FILE.LOG, ' Check for the TDS authority invoice ');
8299 
8300          /*Added by nprashar for bug # 6720018*/
8301 	 IF (FND_GLOBAL.CONC_REQUEST_ID is NULL) THEN
8302 	  lv_conc_flag := 'N';
8303 	ELSE
8304 	  lv_conc_flag := 'Y';
8305 	END IF;
8306 
8307         If cur_rec.invoice_to_tds_authority_id is not null Then
8308 
8309 	OPEN c_jai_chk_tds_inv(cur_rec.invoice_to_tds_authority_id);
8310 	 FETCH c_jai_chk_tds_inv INTO ln_tds_invoice_id,
8311 	                              ln_org_id,
8312 				      --Bug 6819855. Added by Lakshmi Gopalsami
8313 				      ln_sob_id;
8314 	CLOSE c_jai_chk_tds_inv;
8315 
8316 	fnd_file.put_line(FND_FILE.LOG, ' Org id ' || ln_org_id);
8317 
8318 
8319 	mo_global.set_policy_context('S', ln_org_id);
8320 
8321         fnd_file.put_line(FND_FILE.LOG,' TDS authority invoice id '
8322 	                               || cur_rec.invoice_to_tds_authority_id);
8323 
8324         /* Invoice to TDS Authority */
8325         /* Bug 6819855. Added by Lakshmi Gopalsami
8326 	   Commented the following code and added a call to function batch_approval
8327 	 ap_approval_pkg.approve
8328         (
8329           p_run_option             =>   null,
8330           p_invoice_batch_id       =>   null,
8331           p_begin_invoice_date     =>   null,
8332           p_end_invoice_date       =>   null,
8333           p_vendor_id              =>   null,
8334           p_pay_group              =>   null,
8335           p_invoice_id             =>   cur_rec.invoice_to_tds_authority_id,
8336           p_entered_by             =>   null,
8337           p_set_of_books_id        =>   null,
8338           p_trace_option           =>   null,
8339           p_conc_flag              =>    lv_conc_flag 'N', /*Changed by nprashar for  bug # 6720018
8340           p_holds_count            =>   ln_holds_count,
8341           p_approval_status        =>   lv_approval_status,
8342     /* Bug  4943949. Added by Lakshmi Gopalsami
8343     p_funds_return_code         =>   lv_funds_ret_code,
8344           p_calling_sequence       =>   'jai_ap_tds_generation_pkg.approve_tds_invoices'
8345         ) ;
8346 	*/
8347           BEGIN
8348 	   IF ap_approval_pkg.batch_approval(
8349 	        p_run_option          => 'New',
8350 		p_sob_id              => ln_sob_id,
8351 		p_inv_start_date      => NULL,
8352 		p_inv_end_date        => NULL,
8353 		p_inv_batch_id        => NULL,
8354 		p_vendor_id           => NULL,
8355 		p_pay_group           => NULL,
8356 		p_invoice_id          => cur_rec.invoice_to_tds_authority_id,
8357 		p_entered_by          => NULL,
8358 		p_debug_switch        => 'N',
8359 		p_conc_request_id     => FND_GLOBAL.CONC_REQUEST_ID,
8360 		p_commit_size         => 1000,
8361 		p_org_id              => ln_org_id,
8362 		p_report_holds_count  => ln_holds_count
8363 	       ) THEN
8364 
8365              Fnd_File.put_line(Fnd_File.LOG, 'Invoice to TDS Authority ' ||
8366 	                                      cur_rec.invoice_to_tds_authority_num ||
8367 					      '(' || cur_rec.invoice_to_tds_authority_id ||
8368 					      ') Was submitted for Approval.
8369 					      Holds count ' || ln_holds_count);
8370     	    END IF ;
8371           EXCEPTION
8372 	    WHEN OTHERS THEN
8373 	     retcode := 'E';
8374 	     errbuf := 'Error from jai_ap_tds_generation_pkg.approve_tds_invoices-> :
8375 	                           during call to batch_approval for TDS invoice' || sqlerrm;
8376 	  END;
8377 
8378         End if;
8379 
8380         /* Invoice to Supplier */
8381         ln_holds_count1 := 0;
8382         lv_approval_status := null;
8383 
8384         If cur_rec.invoice_to_vendor_id is not null Then
8385 
8386 	OPEN c_jai_chk_tds_inv(cur_rec.invoice_to_vendor_id);
8387 	 FETCH c_jai_chk_tds_inv INTO ln_vendor_invoice_id,
8388 	                              ln_org_id,
8389 				       --Bug 6819855. Added by Lakshmi Gopalsami
8390 				      ln_sob_id;
8391 	CLOSE c_jai_chk_tds_inv;
8392 
8393 	mo_global.set_policy_context('S', ln_org_id);
8394 
8395         fnd_file.put_line(FND_FILE.LOG,' Supplier credit invoice id '
8396 	                               || cur_rec.invoice_to_vendor_id);
8397         /* Bug 6819855. Added by Lakshmi Gopalsami
8398 	   Commented the following code and added a call to function batch_approval
8399         ap_approval_pkg.approve
8400         (
8401           p_run_option             =>   null,
8402           p_invoice_batch_id       =>   null,
8403           p_begin_invoice_date     =>   null,
8404           p_end_invoice_date       =>   null,
8405           p_vendor_id              =>   null,
8406           p_pay_group              =>   null,
8407           p_invoice_id             =>   cur_rec.invoice_to_vendor_id,
8408           p_entered_by             =>   null,
8409           p_set_of_books_id        =>   null,
8410           p_trace_option           =>   null,
8411           p_conc_flag              =>      lv_conc_flag /*'N', /*Changed by nprashar for  bug # 6720018
8412           p_holds_count            =>   ln_holds_count,
8413           p_approval_status        =>   lv_approval_status,
8414           /* Bug  4943949. Added by Lakshmi Gopalsami
8415           p_funds_return_code         =>   lv_funds_ret_code,
8416           p_calling_sequence       =>   'jai_ap_tds_generation_pkg.approve_tds_invoices'
8417          ) ;
8418 	 */
8419 
8420 	  BEGIN
8421 	   IF ap_approval_pkg.batch_approval(
8422 	        p_run_option          => 'New',
8423 		p_sob_id              => ln_sob_id,
8424 		p_inv_start_date      => NULL,
8425 		p_inv_end_date        => NULL,
8426 		p_inv_batch_id        => NULL,
8427 		p_vendor_id           => NULL,
8428 		p_pay_group           => NULL,
8429 		p_invoice_id          => cur_rec.invoice_to_vendor_id,
8430 		p_entered_by          => NULL,
8431 		p_debug_switch        => 'N',
8432 		p_conc_request_id     => FND_GLOBAL.CONC_REQUEST_ID,
8433 		p_commit_size         => 1000,
8434 		p_org_id              => ln_org_id,
8435 		p_report_holds_count  => ln_holds_count1
8436 	       ) THEN
8437 
8438              Fnd_File.put_line(Fnd_File.LOG, 'Invoice to Supplier for TDS' ||
8439 	                                      cur_rec.invoice_to_vendor_num ||
8440 					      '(' || cur_rec.invoice_to_vendor_id ||
8441 					      ') Was submitted for Approval.
8442 					      Holds count ' || ln_holds_count1);
8443     	    END IF ;
8444           EXCEPTION
8445 	    WHEN OTHERS THEN
8446 	     retcode := 'E';
8447 	     errbuf := 'Error from jai_ap_tds_generation_pkg.approve_tds_invoices-> :
8448 	                           during call to batch_approval for TDS invoice' || sqlerrm;
8449 	  END;
8450 
8451 
8452        End if;
8453       end loop;
8454 
8455 
8456       <<exit_from_procedure>>
8457       jai_cmn_utils_pkg.WRITE_FND_LOG(G_LEVEL_PROCEDURE, G_MODULE_NAME||l_api_name||'.END', G_PKG_NAME || ': '||l_api_name||'()-');
8458       return;
8459 
8460     exception
8461       when others then
8462         retcode := 2;
8463         errbuf := 'Error from jai_ap_tds_generation_pkg.approve_tds_invoices : ' || sqlerrm;
8464     end approve_tds_invoices;
8465 
8466 /* ********************************* populate_tds_invoice_id  **************************************** */
8467 
8468   procedure populate_tds_invoice_id
8469   (
8470     p_invoice_id                        in                number,
8471     p_invoice_num                       in                varchar2,
8472     p_vendor_id                         in                number,
8473     p_vendor_site_id                    in                number,
8474     p_process_flag                      out     nocopy    varchar2,
8475     p_process_message                   out     nocopy    varchar2
8476   )
8477   is
8478 
8479     cursor c_check_inv_to_tds_authority (p_invoice_num varchar2, p_vendor_id number, p_vendor_site_id number) is
8480       select  threshold_trx_id,
8481               invoice_id
8482               --Added by Chong for bug#16414088 eTDS ER Start
8483               --------------------------------------------------
8484               ,tds_event
8485               ,DECODE(REGEXP_SUBSTR(invoice_to_tds_authority_num, '(WCT|TDS|ESSI)-\w+-\d+$',1,1,'i',1)
8486                                  ,'WCT', G_WCT_SECTION
8487                                  ,'ESSI',G_ESSI_SECTION
8488                                  , G_TDS_SECTION) section_type
8489               ,tds_section_code
8490               ,threshold_grp_id
8491               ,threshold_hdr_id
8492               --------------------------------------------------
8493               --Added by Chong for bug#16414088 eTDS ER End
8494       from    jai_ap_tds_thhold_trxs
8495       where   invoice_to_tds_authority_num = p_invoice_num
8496       and     tds_authority_vendor_id = p_vendor_id
8497       and     tds_authority_vendor_site_id = p_vendor_site_id
8498       and     invoice_to_tds_authority_id is null;
8499 
8500 
8501     cursor c_check_inv_to_vendor (p_invoice_num varchar2, p_vendor_id number, p_vendor_site_id number) is
8502       select  threshold_trx_id
8503       from    jai_ap_tds_thhold_trxs
8504       where   invoice_to_vendor_num = p_invoice_num
8505       and     vendor_id = p_vendor_id
8506       and     vendor_site_id = p_vendor_site_id
8507       and     invoice_to_vendor_id is null;
8508 
8509     r_check_inv_to_tds      c_check_inv_to_tds_authority%rowtype;     --Added by Chong for bug#16414088 eTDS ER
8510     ln_threshold_trx_id     jai_ap_tds_thhold_trxs.threshold_trx_id%type;
8511     ln_invoice_id           ap_invoices_all.invoice_id%type;
8512     l_api_name                   CONSTANT  VARCHAR2(50) := 'populate_tds_invoice_id()';
8513 
8514    begin
8515     jai_cmn_utils_pkg.WRITE_FND_LOG(G_LEVEL_PROCEDURE, G_MODULE_NAME||l_api_name||'.BEGIN', G_PKG_NAME || ': '||l_api_name||'()+');
8516     open  c_check_inv_to_tds_authority(p_invoice_num, p_vendor_id, p_vendor_site_id);
8517     --fetch c_check_inv_to_tds_authority into ln_threshold_trx_id, ln_invoice_id;  --Commented by Chong for bug#16414088 eTDS ER
8518     fetch c_check_inv_to_tds_authority into r_check_inv_to_tds;                     --Added by Chong for bug#16414088 eTDS ER
8519     close c_check_inv_to_tds_authority;
8520 
8521     --if ln_threshold_trx_id is not null then               --Commented by Chong for bug#16414088 eTDS ER
8522     if r_check_inv_to_tds.threshold_trx_id is not null then --Added by Chong for bug#16414088 eTDS ER
8523 
8524       /* Invoice being created is the invoice to TDS authority */
8525 
8526       update jai_ap_tds_thhold_trxs
8527       set    invoice_to_tds_authority_id = p_invoice_id
8528       where  threshold_trx_id = r_check_inv_to_tds.threshold_trx_id --ln_threshold_trx_id --Updated by Chong for bug#16414088 eTDS ER
8529       ;
8530 
8531       --Added by Chong for bug#16414088 eTDS ER Start
8532       ---------------------------------------------------------------------------------------
8533       --Hook code add here in authority branch
8534       SAVEPOINT Populdated_tds_invoice_id;
8535 
8536       BEGIN
8537       IF r_check_inv_to_tds.tds_event not in (G_SURCHARGE_ROLLBACK,G_SURCHARGE_CALCULATE) THEN
8538           jai_ap_tds_pop_rpst_pkg.populate_repository(
8539                 pn_source_invoice_id      => r_check_inv_to_tds.invoice_id
8540                ,pn_invoice_id             => p_invoice_id
8541                ,pv_event                  => r_check_inv_to_tds.tds_event
8542                ,pv_section_type           => r_check_inv_to_tds.section_type
8543                ,pv_section_code           => r_check_inv_to_tds.tds_section_code
8544                ,pn_threshold_grp_id       => r_check_inv_to_tds.threshold_grp_id
8545                ,pn_threshold_hdr_id       => r_check_inv_to_tds.threshold_hdr_id
8546                ,pn_threshold_type_id      => NULL
8547                ,pn_threshold_slab_id      => NULL
8548           );
8549       END IF;
8550        EXCEPTION
8551           WHEN OTHERS THEN
8552             jai_cmn_utils_pkg.WRITE_FND_LOG(G_LEVEL_ERROR, G_MODULE_NAME||l_api_name,
8553               'Failed populating TDS repository for TDS invoice: ' || p_invoice_id );
8554             ROLLBACK TO Populdated_tds_invoice_id;
8555        END;
8556       ---------------------------------------------------------------------------------------
8557       --Added by Chong for bug#16414088 eTDS ER End
8558 
8559     else
8560 
8561       /* Invoice being created is not the invoice to TDS authority */
8562       /*  check if it is the invoice to vendor for TDS */
8563       open  c_check_inv_to_vendor(p_invoice_num, p_vendor_id, p_vendor_site_id);
8564       fetch c_check_inv_to_vendor into ln_threshold_trx_id;
8565       close c_check_inv_to_vendor;
8566 
8567       if ln_threshold_trx_id is not null then
8568 
8569         /* Invoice being created is teh invoice to TDS authority */
8570         update jai_ap_tds_thhold_trxs
8571         set    invoice_to_vendor_id = p_invoice_id
8572         where  threshold_trx_id = ln_threshold_trx_id;
8573 
8574       end if; /* TDS invoice to vendor */
8575 
8576     end if; /* TDS invoice to TDS authority */
8577 
8578 
8579     <<exit_from_procedure>>
8580     jai_cmn_utils_pkg.WRITE_FND_LOG(G_LEVEL_PROCEDURE, G_MODULE_NAME||l_api_name||'.END', G_PKG_NAME || ': '||l_api_name||'()-');
8581     return;
8582 
8583   exception
8584     when others then
8585       p_process_flag := 'E';
8586       p_process_message := 'Error from jai_ap_tds_generation_pkg.populate_tds_invoice_id :' || sqlerrm;
8587   end populate_tds_invoice_id;
8588 
8589 /* ********************************* populate_tds_invoice_id  **************************************** */
8590 
8591 /* ********************************  insert_tds_thhold_trxs *******************************************  */
8592 	--for bug#4333449
8593   procedure insert_tds_thhold_trxs
8594   (
8595     p_invoice_id                        in                  number,
8596     p_tds_event                         in                  varchar2,
8597     p_tax_id                            in                  number     default null,
8598     p_tax_rate                          in                  number     default null,
8599     p_taxable_amount                    in                  number     default null,
8600     p_tax_amount                        in                  number     default null,
8601     p_tds_authority_vendor_id           in                  number     default null,
8602     p_tds_authority_vendor_site_id      in                  number     default null,
8603     p_invoice_tds_authority_num         in                  varchar2   default null,
8604     p_invoice_tds_authority_type        in                  varchar2   default null,
8605     p_invoice_tds_authority_curr        in                  varchar2   default null,
8606     p_invoice_tds_authority_amt         in                  number     default null,
8607     p_invoice_tds_authority_id          in                  number     default null,
8608     p_vendor_id                         in                  number     default null,
8609     p_vendor_site_id                    in                  number     default null,
8610     p_invoice_vendor_num                in                  varchar2   default null,
8611     p_invoice_vendor_type               in                  varchar2   default null,
8612     p_invoice_vendor_curr               in                  varchar2   default null,
8613     p_invoice_vendor_amt                in                  number     default null,
8614     p_invoice_vendor_id                 in                  number     default null,
8615     p_parent_inv_payment_priority       in                  number     default null,
8616     p_parent_inv_exchange_rate          in                  number     default null
8617   )
8618  is
8619     l_api_name                   CONSTANT  VARCHAR2(50) := 'insert_tds_thhold_trxs()';
8620  begin
8621     jai_cmn_utils_pkg.WRITE_FND_LOG(G_LEVEL_PROCEDURE, G_MODULE_NAME||l_api_name||'.BEGIN', G_PKG_NAME || ': '||l_api_name||'()+');
8622    fnd_file.put_line(FND_FILE.LOG, ' Insert -> insert_tds_thhold_trxs ');
8623 
8624    insert into jai_ap_tds_thhold_trxs
8625    (
8626      threshold_trx_id                         ,
8627      invoice_id                               ,
8628      tds_event                                ,
8629      tax_id                                   ,
8630      tax_rate                                 ,
8631      taxable_amount                           ,
8632      tax_amount                               ,
8633      tds_authority_vendor_id                  ,
8634      tds_authority_vendor_site_id             ,
8635      invoice_to_tds_authority_num             ,
8636      invoice_to_tds_authority_type            ,
8637      invoice_to_tds_authority_curr            ,
8638      invoice_to_tds_authority_amt             ,
8639      invoice_to_tds_authority_id              ,
8640      vendor_id                                ,
8641      vendor_site_id                           ,
8642      invoice_to_vendor_num                    ,
8643      invoice_to_vendor_type                   ,
8644      invoice_to_vendor_curr                   ,
8645      invoice_to_vendor_amt                    ,
8646      invoice_to_vendor_id                     ,
8647      parent_inv_payment_priority              ,
8648      parent_inv_exchange_rate                 ,
8649      created_by                               ,
8650      creation_date                            ,
8651      last_updated_by                          ,
8652      last_update_date                         ,
8653      last_update_login
8654    )
8655    values
8656    (
8657      jai_ap_tds_thhold_trxs_s.nextval         ,
8658      p_invoice_id                             ,
8659      p_tds_event                              ,
8660      p_tax_id                                 ,
8661      p_tax_rate                               ,
8662      p_taxable_amount                         ,
8663      p_tax_amount                             ,
8664      p_tds_authority_vendor_id                ,
8665      p_tds_authority_vendor_site_id           ,
8666      p_invoice_tds_authority_num              ,
8667      p_invoice_tds_authority_type             ,
8668      p_invoice_tds_authority_curr             ,
8669      p_invoice_tds_authority_amt              ,
8670      p_invoice_tds_authority_id               ,
8671      p_vendor_id                              ,
8672      p_vendor_site_id                         ,
8673      p_invoice_vendor_num                     ,
8674      p_invoice_vendor_type                    ,
8675      p_invoice_vendor_curr                    ,
8676      p_invoice_vendor_amt                     ,
8677      p_invoice_vendor_id                      ,
8678      p_parent_inv_payment_priority            ,
8679      p_parent_inv_exchange_rate               ,
8680      fnd_global.user_id                       ,
8681      sysdate                                  ,
8682      fnd_global.user_id                       ,
8683      sysdate                                  ,
8684      fnd_global.login_id
8685      );
8686 
8687     fnd_file.put_line(FND_FILE.LOG, ' Done Insert -> insert_tds_thhold_trxs ');
8688     jai_cmn_utils_pkg.WRITE_FND_LOG(G_LEVEL_PROCEDURE, G_MODULE_NAME||l_api_name||'.END', G_PKG_NAME || ': '||l_api_name||'()-');
8689   end insert_tds_thhold_trxs;
8690 
8691   /* ********************************  create_tds_after_holds_rel *******************************************  */
8692 
8693   -- Bug#5131075(4685754).  Added by Lakshmi Gopalsami
8694   -- Added for holds release
8695 
8696   Procedure create_tds_after_holds_release
8697   (
8698     errbuf                       out        nocopy    varchar2,
8699     retcode                      out        nocopy    varchar2,
8700     p_invoice_id                 IN  number,
8701     p_invoice_amount             IN  number,
8702     p_payment_status_flag        IN varchar2,
8703     p_invoice_type_lookup_code   IN varchar2,
8704     p_vendor_id                  IN  number,
8705     p_vendor_site_id             IN  number,
8706     p_accounting_date            IN DATE,
8707     p_invoice_currency_code      IN varchar2,
8708     p_exchange_rate              IN number,
8709     p_set_of_books_id            IN number,
8710     p_org_id                     IN number,
8711     p_call_from                  IN varchar2,
8712     p_process_flag               IN varchar2,
8713     p_process_message            IN varchar2,
8714     p_codepath                   IN varchar2,
8715     p_request_id                 IN number default null-- added, Harshita for Bug#5131075(5346558)
8716   ) IS
8717 
8718     lv_is_invoice_validated       varchar2(1);
8719     lv_invoice_validation_status  varchar2(25);
8720 
8721     lv_process_flag               varchar2(1);
8722     lv_process_message            varchar2(200);
8723     lv_codepath                   varchar2(2000);
8724 
8725     --Start addition by sanjikum for Bug#5131075(4722011)
8726     lv_new_transaction_si         VARCHAR2(1);
8727     lv_new_transaction_pp         VARCHAR2(1);
8728     lv_prepay_flag                VARCHAR2(1);
8729 
8730     -- added, Harshita for Bug#5131075(5346558)
8731     ln_req_status  BOOLEAN      ;
8732     lv_phase       VARCHAR2(80) ;
8733     lv_status      VARCHAR2(80) ;
8734     lv_dev_phase   VARCHAR2(80) ;
8735     lv_dev_status  VARCHAR2(80) ;
8736     lv_message     VARCHAR2(80) ;
8737 
8738     CURSOR c_check_prepayment_apply(p_invoice_distribution_id   NUMBER)
8739     IS
8740     SELECT  '1'
8741     FROM    jai_ap_tds_prepayments
8742     WHERE   invoice_distribution_id_prepay = p_invoice_distribution_id;
8743 
8744     CURSOR c_check_prepayment_unapply(p_invoice_distribution_id_pp  NUMBER)
8745     IS
8746     SELECT  '1'
8747     FROM    jai_ap_tds_prepayments
8748     WHERE   invoice_distribution_id_prepay = p_invoice_distribution_id_pp
8749     AND     unapply_flag = 'Y';
8750     --End addition by sanjikum for Bug#5131075(4722011)
8751 
8752     /*START, Added by Bgowrava for Bug#9214036*/
8753     CURSOR c_get_rnd_factor (p_org_id IN NUMBER, p_inv_date in date ) IS
8754         SELECT  nvl(tds_rounding_factor,0), tds_rounding_start_date
8755         FROM jai_ap_tds_years
8756         WHERE legal_entity_id  = p_org_id
8757         AND trunc (p_inv_date) between start_date and end_date ;
8758     /*END, Added by Bgowrava for Bug#9214036*/
8759 
8760     lv_debug char(1) :='N'; -- Harshita, changed debug to 'N' for 5367640
8761 
8762      -- Bug 5722028. Added by Lakshmi Gopalsami
8763       cursor get_creation_date is
8764       select creation_date
8765         from ap_invoices_all
8766        where invoice_id = p_invoice_id;
8767       ld_creation_date DATE;
8768   -- End for bug 5722028.
8769 
8770   Begin
8771 
8772      lv_codepath := p_codepath;
8773 
8774     /*START, Added by Bgowrava for Bug#9214036*/
8775     OPEN c_get_rnd_factor (p_org_id,p_accounting_date);
8776     FETCH c_get_rnd_factor into JAI_AP_TDS_GENERATION_pkg.gn_tds_rounding_factor, JAI_AP_TDS_GENERATION_pkg.gd_tds_rounding_effective_date;
8777     CLOSE c_get_rnd_factor ;
8778       /*END, Added by Bgowrava for Bug#9214036*/
8779 
8780      -- Harshita for Bug#5131075(5346558)
8781       BEGIN
8782        IF p_request_id is not null THEN
8783         ln_req_status :=  fnd_concurrent.wait_for_request
8784                          (request_id => p_request_id,
8785                           interval   => 1,
8786                           max_wait   => 0,
8787                           phase      => lv_phase,
8788                           status     => lv_status,
8789                           dev_phase  => lv_dev_phase,
8790                           dev_status => lv_dev_status,
8791                           message    => lv_message)   ;
8792 
8793          IF not ln_req_status THEN
8794            FND_FILE.put_line(FND_FILE.log, 'Phase : ' || lv_phase || 'Status : ' || lv_status || 'Dev Phase : ' || lv_dev_phase ||
8795             ' Dev Status : ' || lv_dev_status || ' Message : ' || lv_message );
8796            FND_FILE.put_line(FND_FILE.log, 'Status of Completion of previous Concurrent Create TDS Invoice After Holds Release - Request Id ' || p_request_id || ' ' || SQLERRM );
8797          END IF ;
8798 
8799        END IF ;
8800 
8801         EXCEPTION
8802           WHEN OTHERS THEN
8803             FND_FILE.put_line(FND_FILE.log, 'Phase : ' || lv_phase || 'Status : ' || lv_status || 'Dev Phase : ' || lv_dev_phase ||
8804             ' Dev Status : ' || lv_dev_status || ' Message : ' || lv_message );
8805            FND_FILE.put_line(FND_FILE.log, 'Status of Completion of previous Concurrent Create TDS Invoice After Holds Release - Request Id ' || p_request_id || ' ' || SQLERRM );
8806        END;
8807 
8808 
8809      lv_invoice_validation_status :=
8810        AP_INVOICES_UTILITY_PKG.get_approval_status(
8811             l_invoice_id                =>     p_invoice_id,
8812             l_invoice_amount            =>    p_invoice_amount,
8813             l_payment_status_flag       =>    p_payment_status_flag,
8814             l_invoice_type_lookup_code  =>    p_invoice_type_lookup_code);
8815 
8816     if lv_invoice_validation_status not in ('APPROVED', 'AVAILABLE', 'UNPAID') then
8817       lv_is_invoice_validated := 'N';
8818     Else
8819       lv_is_invoice_validated := 'Y';
8820     end if;
8821 
8822     if lv_debug='Y' then
8823       fnd_file.put_line(FND_FILE.LOG, ' value of validate'||lv_is_invoice_validated);
8824     end if ;
8825 
8826     if lv_is_invoice_validated = 'Y' then
8827 
8828     /*START, Added by Bgowrava for Bug#9214036*/
8829     OPEN get_creation_date;
8830         FETCH get_creation_date INTO ld_creation_date;
8831         CLOSE get_creation_date;
8832     /*END, Added by Bgowrava for Bug#9214036*/
8833 
8834       jai_ap_tds_generation_pkg.process_tds_at_inv_validate
8835         (
8836           p_invoice_id               =>     p_invoice_id,
8837           p_vendor_id                =>    p_vendor_id,
8838           p_vendor_site_id           =>     p_vendor_site_id,
8839           p_accounting_date          =>     p_accounting_date,
8840           p_invoice_currency_code    =>     p_invoice_currency_code,
8841           p_exchange_rate            =>     p_exchange_rate,
8842           p_set_of_books_id          =>     p_set_of_books_id,
8843           p_org_id                   =>     p_org_id,
8844           p_call_from                =>     p_call_from,
8845           p_creation_date            =>     ld_creation_date, -- Bug 5722028. Added by csahoo
8846           p_process_flag             =>     lv_process_flag,
8847           p_process_message          =>  lv_process_message,
8848           p_codepath                 =>     lv_codepath
8849         );
8850 
8851         --Moved this from below to here by Sanjikum for Bug#5131075(4722011)
8852       if   nvl(lv_process_flag, 'N') = 'E' then
8853         fnd_file.put_line(FND_FILE.LOG, ' Error in the concurrent program '|| lv_process_message);
8854         goto exit_from_procedure;
8855       END IF;
8856 
8857       --Start Addition by Sanjikum for Bug#5131075(4722011)
8858       FOR i IN(SELECT a.invoice_id,
8859                         a.amount,
8860                         a.invoice_distribution_id,
8861                         a.parent_reversal_id,
8862                         a.prepay_distribution_id,
8863                         a.accounting_date,
8864                         a.org_id,
8865                         a.last_updated_by,
8866                         a.last_update_date,
8867                         a.created_by,
8868                         a.creation_date,
8869                         b.vendor_id,
8870                         b.vendor_site_id,
8871                         b.invoice_currency_code,
8872                         b.exchange_rate,
8873                         b.set_of_books_id
8874                 FROM    ap_invoice_distributions_all a,
8875                         ap_invoices_all b
8876                 WHERE   a.invoice_id = b.invoice_id
8877                 AND     b.invoice_id = p_invoice_id
8878                 AND     a.line_type_lookup_code = 'PREPAY'
8879                 AND     b.source <> 'TDS'
8880                 AND     b.cancelled_date is null
8881                 AND     invoice_type_lookup_code NOT IN ('CREDIT', 'DEBIT'))
8882       LOOP
8883 
8884         lv_prepay_flag := NULL;
8885 
8886         --Apply Scenario
8887         IF NVL(i.amount,0) < 0 THEN
8888 
8889           OPEN c_check_prepayment_apply(i.invoice_distribution_id);
8890           FETCH c_check_prepayment_apply INTO lv_prepay_flag;
8891           CLOSE c_check_prepayment_apply;
8892 
8893         --Unapply Scenario
8894         ELSIF NVL(i.amount,0) > 0 THEN
8895 
8896           OPEN c_check_prepayment_unapply(i.parent_reversal_id);
8897           FETCH c_check_prepayment_unapply INTO lv_prepay_flag;
8898           CLOSE c_check_prepayment_unapply;
8899 
8900         END IF;
8901 
8902         --should be run, only if prepayment application/unapplication is not already processed
8903         IF lv_prepay_flag IS NULL THEN
8904 
8905 
8906           jai_ap_tds_tax_defaultation.check_old_transaction
8907           (
8908           p_invoice_id                    =>    i.invoice_id,
8909           p_new_transaction               =>    lv_new_transaction_si
8910           );
8911 
8912           --Check for Pprepayment
8913           jai_ap_tds_tax_defaultation.check_old_transaction
8914           (
8915           p_invoice_distribution_id      =>    i.prepay_distribution_id,
8916           p_new_transaction               =>   lv_new_transaction_pp
8917           );
8918 
8919           if lv_new_transaction_si = 'Y' and lv_new_transaction_pp = 'Y' then
8920 
8921             lv_codepath := null;
8922 
8923             jai_ap_tds_prepayments_pkg.process_prepayment
8924             (
8925                             p_event                          =>     'INSERT',         --Added for Bug 8431516
8926               p_invoice_id                     =>     i.invoice_id,
8927               p_invoice_distribution_id        =>     i.invoice_distribution_id,
8928               p_prepay_distribution_id         =>     i.prepay_distribution_id,
8929               p_parent_reversal_id             =>     i.parent_reversal_id,
8930               p_prepay_amount                  =>     i.amount,
8931               p_vendor_id                      =>     i.vendor_id,
8932               p_vendor_site_id                 =>     i.vendor_site_id,
8933               p_accounting_date                =>     i.accounting_date,
8934               p_invoice_currency_code          =>     i.invoice_currency_code,
8935               p_exchange_rate                  =>     i.exchange_rate,
8936               p_set_of_books_id                =>     i.set_of_books_id,
8937               p_org_id                         =>     i.org_id,
8938               p_creation_date                  =>     i.creation_date, -- Bug 5722028
8939               p_process_flag                   =>     lv_process_flag,
8940               p_process_message                =>     lv_process_message,
8941               p_codepath                       =>     lv_codepath
8942             );
8943 
8944             if   nvl(lv_process_flag, 'N') = 'E' then
8945               raise_application_error(-20007,
8946               'Error - procedure jai_ap_tds_generation_pkg.create_tds_after_holds_release : ' || lv_process_message);
8947             end if;
8948 
8949           else
8950             --Invoke the old regime functionality
8951             jai_ap_tds_prepayments_pkg.process_old_transaction
8952             (
8953               p_invoice_id                     =>     i.invoice_id,
8954               p_invoice_distribution_id        =>     i.invoice_distribution_id,
8955               p_prepay_distribution_id         =>     i.prepay_distribution_id,
8956               p_amount                         =>     i.amount,
8957               p_last_updated_by                =>     i.last_updated_by,
8958               p_last_update_date               =>     i.last_update_date,
8959               p_created_by                     =>     i.created_by,
8960               p_creation_date                  =>     i.creation_date,
8961               p_org_id                         =>     i.org_id,
8962               p_process_flag                   =>     lv_process_flag,
8963               p_process_message                =>     lv_process_message
8964             );
8965 
8966             if   nvl(lv_process_flag, 'N') = 'E' then
8967               raise_application_error(-20008,
8968               'Error - procedure jai_ap_tds_generation_pkg.create_tds_after_holds_release : ' || lv_process_message);
8969             end if;
8970           end if; --Transactions in new regime
8971 
8972         END IF;
8973 
8974       END LOOP;
8975 
8976       << exit_from_procedure >>
8977 
8978       NULL;
8979 
8980       --End Addition by Sanjikum for Bug#5131075(4722011)
8981 
8982       Else
8983         fnd_file.put_line(FND_FILE.LOG,' Not generating the TDS invoice
8984                                     as the parent invoice is not yet validated');
8985         retcode := 1;
8986       End if; /* lv_is_invoice_validated = 'Y' */
8987 
8988   End create_tds_after_holds_release;
8989   -- End for bug#5131075(4685754)
8990 
8991   /* ********************************  create_tds_after_holds_rel *******************************************  */
8992 
8993   --new procedure created by sanjikum for bug#5131075(4718907)
8994   --This procedure gives the current threshold slab
8995   /* ----------------------------------------------------------------------------
8996    Procedure Name : get_tds_threshold_slab
8997 
8998    Created By    : sanjikum
8999    Created Date  : 19-dec-2011
9000    Bug           : #5131075(4718907)
9001 
9002    CHANGE HISTORY:
9003    -------------------------------------------------------------------------------
9004    S.No      Date         Author and Details
9005    Update by Chong.Lei 2012-02-06
9006               : get threshold slab info.
9007                    If p_effective_invoice_amt is null, will get amount from JAI_AP_TDS_THHOLD_GRPS
9008                    If p_effective_invoice_amt is not null, will use given amount
9009   ---------------------------------------------------------------------------- */
9010   PROCEDURE get_tds_threshold_slab(p_prepay_distribution_id IN NUMBER,
9011                                    p_invoice_id             IN NUMBER,
9012                                    p_threshold_grp_id       IN OUT NOCOPY NUMBER,
9013                                    p_threshold_hdr_id       IN OUT NOCOPY NUMBER,
9014                                    p_effective_invoice_amt  IN NUMBER DEFAULT null,
9015                                    p_threshold_slab_id      OUT NOCOPY NUMBER,
9016                                    p_threshold_type         OUT NOCOPY VARCHAR2,
9017                                    p_process_flag           OUT NOCOPY VARCHAR2,
9018                                    p_process_message        OUT NOCOPY VARCHAR2,
9019                                    p_codepath               IN OUT NOCOPY VARCHAR2) IS
9020     /*Get Natural account by CCID  --->*/
9021     CURSOR cur_get_invoice_info IS
9022     SELECT set_of_books_id
9023           ,legal_entity_id
9024       FROM ap_invoices_all
9025        WHERE invoice_id = p_invoice_id;
9026     /*Get distribution id by section code and*/
9027     CURSOR c_distribution_id(p_invoice_id NUMBER,
9028                              p_section_type  VARCHAR2,
9029                              p_section_code  VARCHAR2
9030                              ) IS
9031       SELECT invoice_distribution_id
9032         FROM jai_ap_tds_inv_taxes
9033        WHERE invoice_id = p_invoice_id
9034          AND NVL(section_type, default_type) = p_section_type
9035          AND NVL(actual_section_code, default_section_code) = p_section_code
9036          AND invoice_distribution_id <> 1
9037     ORDER BY invoice_distribution_id ASC;
9038     --Get CCID by distribution id
9039 /*    CURSOR c_CCID(p_invoice_distribution_id NUMBER
9040                  ) IS
9041       SELECT dist_code_combination_id
9042         FROM ap_invoice_distributions_all
9043        WHERE invoice_distribution_id = p_invoice_distribution_id;
9044 */
9045     CURSOR c_get_threshold_grp_id(p_prepay_distribution_id NUMBER) IS
9046       SELECT threshold_grp_id
9047         FROM jai_ap_tds_inv_taxes
9048        WHERE invoice_distribution_id = p_prepay_distribution_id
9049          AND section_type = 'TDS_SECTION';
9050 
9051     CURSOR c_get_threshold_grp_dtl(p_threshold_grp_id NUMBER) IS
9052       SELECT *
9053         FROM jai_ap_tds_thhold_grps
9054        WHERE threshold_grp_id = p_threshold_grp_id;
9055 
9056     CURSOR c_get_threshold_hdr(p_vendor_id    NUMBER,
9057                                p_org_tan_num  VARCHAR2,
9058                                p_pan_num      VARCHAR2,
9059                                p_section_type VARCHAR2,
9060                                p_section_code VARCHAR2) IS
9061       SELECT threshold_hdr_id
9062         FROM jai_ap_tds_th_vsite_v
9063        WHERE vendor_id = p_vendor_id
9064          AND tan_no = p_org_tan_num
9065          AND pan_no = p_pan_num
9066          AND section_type = p_section_type
9067          AND section_code = p_section_code;
9068 
9069     /*Get multiple_rate_flg by Hdr_id*/
9070     CURSOR c_multiple_rate_setup(p_threshold_hdr_id NUMBER) IS
9071       SELECT NVL(multiple_rate_setup, 'N')
9072         FROM jai_ap_tds_thhold_hdrs
9073        WHERE threshold_hdr_id = p_threshold_hdr_id;
9074 
9075   /*Get slab by natrual account and threshold_hdr_id*/
9076     CURSOR c_get_tds_thhold_slabs_byNt(p_threshold_hdr_id NUMBER,
9077                                      p_natural_account_value   VARCHAR2,
9078                                      p_threshold_type   VARCHAR2,
9079                                      p_amount           NUMBER) IS
9080     SELECT jatts.threshold_slab_id,
9081            jatts.threshold_type_id,
9082            jatts.from_amount,
9083            jatts.to_amount,
9084            jatts.tax_rate
9085       FROM jai_ap_tds_thhold_slabs jatts
9086           ,jai_ap_tds_thhold_account jatta
9087           ,jai_ap_tds_thhold_types jattt
9088      WHERE jatts.threshold_hdr_id = jatta.threshold_hdr_id
9089        AND jatts.threshold_type_id = jatta.threshold_type_id
9090        AND jattt.threshold_type_id = jatts.threshold_type_id
9091        AND jattt.threshold_hdr_id = jatts.threshold_hdr_id
9092        AND jattt.threshold_type = p_threshold_type
9093        AND sysdate >= jattt.from_date
9094        AND NVL(jattt.to_date, sysdate) >= sysdate
9095        AND jatts.threshold_hdr_id = p_threshold_hdr_id
9096        AND jatta.natural_account_value = p_natural_account_value
9097        AND jatts.from_amount <= p_amount
9098        AND NVL(to_amount, p_amount) >= p_amount
9099        ORDER BY from_amount asc;
9100 
9101     CURSOR c_jai_ap_tds_thhold_slabs(p_threshold_hdr_id NUMBER,
9102                                      p_threshold_type   VARCHAR2,
9103                                      p_amount           NUMBER) IS
9104       SELECT threshold_slab_id,
9105              threshold_type_id,
9106              from_amount,
9107              to_amount,
9108              tax_rate
9109         FROM jai_ap_tds_thhold_slabs
9110        WHERE threshold_hdr_id = p_threshold_hdr_id
9111          AND threshold_type_id in
9112   --         (SELECT  threshold_type_id      --Commented by Chong for bug#15939571 20121212
9113              --Added by Chong for bug#15939571 20130313 Start
9114              ------------------------------------------------
9115              (SELECT FIRST_VALUE(threshold_type_id)
9116                      OVER (ORDER BY NVL(DEFAULT_TYPE,'N') DESC ,threshold_type_id ASC)
9117              ------------------------------------------------
9118              --Added by Chong for bug#15939571 20130313 End
9119                 FROM jai_ap_tds_thhold_types
9120                WHERE threshold_hdr_id = p_threshold_hdr_id
9121                  AND threshold_type = p_threshold_type
9122                  AND trunc(sysdate) between from_date and
9123                      nvl(to_date, sysdate + 1))
9124          AND from_amount <= p_amount
9125          AND NVL(to_amount, p_amount) >= p_amount
9126        ORDER BY from_amount asc;
9127 
9128     r_get_threshold_grp_dtl     c_get_threshold_grp_dtl%ROWTYPE;
9129     ln_effective_invoice_amt    NUMBER;
9130     r_jai_ap_tds_thhold_slabs   c_jai_ap_tds_thhold_slabs%ROWTYPE;
9131     r_get_tds_thhold_slabs_byNt c_get_tds_thhold_slabs_byNt%ROWTYPE;
9132     lv_threshold_type           jai_ap_tds_thhold_types.threshold_type%TYPE;
9133     lv_multiple_rate_setup      jai_ap_tds_thhold_hdrs.multiple_rate_setup%TYPE;
9134     lv_invoice_distribution_id  jai_ap_tds_inv_taxes.invoice_distribution_id%TYPE;
9135     lv_set_of_book_id           NUMBER;
9136     lv_legal_entity_id          NUMBER;
9137     lv_natural_account_segment  VARCHAR2(100);
9138     lv_natural_account          jai_ap_tds_thhold_account.natural_account_value%TYPE;
9139     r_CCID                      NUMBER;
9140 	lv_proc_name                VARCHAR2 (100) := 'get_tds_threshold_slab';
9141     ln_proc_level             NUMBER         := FND_LOG.level_procedure;
9142 	ln_dbg_level              NUMBER         := FND_LOG.g_current_runtime_level;
9143     l_api_name                   CONSTANT  VARCHAR2(50) := 'get_tds_threshold_slab()';
9144 
9145   BEGIN
9146     jai_cmn_utils_pkg.WRITE_FND_LOG(G_LEVEL_PROCEDURE, G_MODULE_NAME||l_api_name||'.BEGIN', G_PKG_NAME || ': '||l_api_name||'()+');
9147 
9148     IF p_threshold_grp_id IS NULL THEN
9149       OPEN c_get_threshold_grp_id(p_prepay_distribution_id);
9150       FETCH c_get_threshold_grp_id
9151         INTO p_threshold_grp_id;
9152       CLOSE c_get_threshold_grp_id;
9153     END IF;
9154 
9155     OPEN c_get_threshold_grp_dtl(p_threshold_grp_id);
9156     FETCH c_get_threshold_grp_dtl
9157       INTO r_get_threshold_grp_dtl;
9158     CLOSE c_get_threshold_grp_dtl;
9159 
9160     IF p_threshold_hdr_id IS NULL THEN
9161       OPEN c_get_threshold_hdr(r_get_threshold_grp_dtl.vendor_id,
9162                                r_get_threshold_grp_dtl.org_tan_num,
9163                                r_get_threshold_grp_dtl.vendor_pan_num,
9164                                r_get_threshold_grp_dtl.section_type,
9165                                r_get_threshold_grp_dtl.section_code);
9166       FETCH c_get_threshold_hdr
9167         INTO p_threshold_hdr_id;
9168       CLOSE c_get_threshold_hdr;
9169     END IF;
9170 
9171 
9172     IF p_effective_invoice_amt IS NULL THEN
9173       --If p_effective_invoice_amt is null, will get amount from JAI_AP_TDS_THHOLD_GRPS
9174       ln_effective_invoice_amt := r_get_threshold_grp_dtl.total_invoice_amount -
9175                                 r_get_threshold_grp_dtl.total_invoice_cancel_amount -
9176                                 r_get_threshold_grp_dtl.total_invoice_apply_amount +
9177                                 r_get_threshold_grp_dtl.total_invoice_unapply_amount;
9178     ELSE
9179       --If p_effective_invoice_amt is not null, will use given amount
9180       ln_effective_invoice_amt := p_effective_invoice_amt;
9181     END IF;
9182 
9183     --Get mutilple_rate_setup
9184     OPEN c_multiple_rate_setup(p_threshold_hdr_id);
9185     FETCH c_multiple_rate_setup
9186       INTO lv_multiple_rate_setup;
9187     CLOSE c_multiple_rate_setup;
9188 
9189     lv_threshold_type := 'CUMULATIVE';
9190 
9191     IF lv_multiple_rate_setup = 'N' THEN
9192       /*Multiple_rate_setup OFF*/
9193 
9194       --check if the current amount falls in the cumulative threshold
9195       OPEN c_jai_ap_tds_thhold_slabs(p_threshold_hdr_id,
9196                                      lv_threshold_type,
9197                                      ln_effective_invoice_amt);
9198       FETCH c_jai_ap_tds_thhold_slabs
9199         INTO r_jai_ap_tds_thhold_slabs;
9200       CLOSE c_jai_ap_tds_thhold_slabs;
9201 
9202     /* Commented by Chong.lei for (It's not correct to get single slab for cumulative amount) 2012/01/16
9203       IF r_jai_ap_tds_thhold_slabs.threshold_slab_id IS NULL THEN
9204 
9205         lv_threshold_type := 'SINGLE';
9206 
9207         --check if the current amount falls in the single threshold
9208         OPEN c_jai_ap_tds_thhold_slabs(p_threshold_hdr_id,
9209                                        lv_threshold_type,
9210                                        99999999999999);
9211         FETCH c_jai_ap_tds_thhold_slabs
9212           INTO r_jai_ap_tds_thhold_slabs;
9213         CLOSE c_jai_ap_tds_thhold_slabs;
9214       END IF;
9215     */
9216 
9217       p_threshold_slab_id := r_jai_ap_tds_thhold_slabs.threshold_slab_id;
9218       p_threshold_type    := lv_threshold_type;
9219 
9220     ELSE
9221       /*Multiple_rate_setup ON*/
9222       OPEN c_distribution_id(p_invoice_id
9223                             ,r_get_threshold_grp_dtl.section_type
9224                             ,r_get_threshold_grp_dtl.section_code
9225                             );
9226       FETCH c_distribution_id INTO lv_invoice_distribution_id;
9227       CLOSE c_distribution_id;
9228 
9229 /*      OPEN c_CCID(lv_invoice_distribution_id);
9230       FETCH c_CCID INTO r_CCID;
9231       CLOSE c_CCID;*/
9232       get_CCID(lv_invoice_distribution_id,r_CCID);
9233 
9234       OPEN cur_get_invoice_info;
9235       FETCH cur_get_invoice_info
9236        INTO lv_set_of_book_id
9237            ,lv_legal_entity_id;
9238       CLOSE cur_get_invoice_info;
9239 
9240 		  lv_natural_account_segment := jai_ap_utils_pkg.get_natural_account(lv_set_of_book_id,lv_legal_entity_id);
9241       lv_natural_account :=  jai_ap_utils_pkg.GET_NATURAL_ACCOUNT_VALUE(r_CCID
9242                                                                        ,lv_natural_account_segment);
9243       --Get slab info by natrual account and threshold_hdr_id
9244       OPEN c_get_tds_thhold_slabs_byNt(p_threshold_hdr_id
9245                                       ,lv_natural_account
9246                                       ,lv_threshold_type
9247                                       ,ln_effective_invoice_amt);
9248       FETCH c_get_tds_thhold_slabs_byNt INTO r_get_tds_thhold_slabs_byNt;
9249       CLOSE c_get_tds_thhold_slabs_byNt;
9250 
9251       p_threshold_slab_id := r_get_tds_thhold_slabs_byNt.threshold_slab_id;
9252       p_threshold_type    := r_get_tds_thhold_slabs_byNt.threshold_type_id;
9253 
9254       --Added by Chong for bug#16414088 eTDS ER Start
9255       ----------------------------------------------------------------------
9256       --Hook code add here after all cancellation logic processed
9257       IF p_threshold_slab_id IS NULL THEN
9258 
9259         OPEN c_jai_ap_tds_thhold_slabs(p_threshold_hdr_id,
9260                                        lv_threshold_type,
9261                                        ln_effective_invoice_amt);
9262         FETCH c_jai_ap_tds_thhold_slabs  INTO r_jai_ap_tds_thhold_slabs;
9263         CLOSE c_jai_ap_tds_thhold_slabs;
9264         p_threshold_slab_id := r_jai_ap_tds_thhold_slabs.threshold_slab_id;
9265         p_threshold_type    := r_get_tds_thhold_slabs_byNt.threshold_type_id;
9266       END IF; --n_threshold_trx_id IS NULL
9267       ----------------------------------------------------------------------
9268       --Added by Chong for bug#16414088 eTDS ER End
9269 
9270 	END IF;
9271 		--Fnd_File.put_line(Fnd_File.LOG, 'p_threshold_slab_id:[' || p_threshold_slab_id || ']');
9272 		--Fnd_File.put_line(Fnd_File.LOG, 'p_threshold_type:[' || p_threshold_type || ']');
9273 		--Fnd_File.put_line(Fnd_File.LOG, '**** END of procedure jai_ap_dtc_cancellation_pkg.get_tds_threshold_slab ****');
9274 		IF ( ln_proc_level >= ln_dbg_level)
9275 		THEN
9276 			FND_LOG.STRING ( ln_proc_level
9277 				   , GV_MODULE_PREFIX ||'.'|| lv_proc_name
9278 				   , 'p_threshold_slab_id:[' || p_threshold_slab_id || ']'
9279 				   );
9280 		END IF; --( ln_proc_level >= ln_dbg_level)
9281 		IF ( ln_proc_level >= ln_dbg_level)
9282 		THEN
9283 			FND_LOG.STRING ( ln_proc_level
9284 				   , GV_MODULE_PREFIX ||'.'|| lv_proc_name
9285 				   , 'p_threshold_type:[' || p_threshold_type || ']'
9286 				   );
9287 		END IF; --( ln_proc_level >= ln_dbg_level)
9288     jai_cmn_utils_pkg.WRITE_FND_LOG(G_LEVEL_PROCEDURE, G_MODULE_NAME||l_api_name||'.END', G_PKG_NAME || ': '||l_api_name||'()-');
9289   EXCEPTION
9290     WHEN OTHERS THEN
9291       p_process_flag    := 'E';
9292       p_process_message := SUBSTR(SQLERRM, 1, 200);
9293   END get_tds_threshold_slab;
9294 
9295 
9296   --new procedure created by sanjikum for bug#5131075(4718907)
9297   --This procedure takes as input the old and new threshold and checks if any type of Threshold Rollback processing is required
9298 PROCEDURE process_threshold_rollback(
9299     p_invoice_id                	IN              	VARCHAR2,
9300     p_before_threshold_type     	IN              	VARCHAR2,
9301     p_after_threshold_type      	IN              	VARCHAR2,
9302     p_before_threshold_slab_id  	IN              	NUMBER,
9303     p_after_threshold_slab_id   	IN              	NUMBER,
9304     p_threshold_grp_id          	IN              	NUMBER,
9305     p_org_id                    	IN              	NUMBER,
9306     p_accounting_date           	IN              	DATE,
9307     p_invoice_distribution_id   	IN              	NUMBER DEFAULT NULL,
9308     p_prepay_distribution_id    	IN              	NUMBER DEFAULT NULL,
9309     p_called_from			            IN		VARCHAR2,
9310     p_process_flag              	OUT    	NOCOPY  VARCHAR2,
9311     p_process_message           	OUT   	NOCOPY  VARCHAR2,
9312     p_codepath                  	IN OUT	NOCOPY  VARCHAR2)
9313 IS
9314 
9315   CURSOR c_tds_tax(cn_invoice_distribution_id NUMBER) IS
9316   SELECT tax_category_id,
9317          section_type,
9318          actual_section_code
9319   FROM JAI_AP_TDS_INV_TAXES
9320   WHERE INVOICE_DISTRIBUTION_ID = cn_invoice_distribution_id
9321      AND ROWNUM = 1;
9322 
9323   cursor c_get_tds_section_info(cn_threshold_grp_id NUMBER) is
9324     select section_type
9325           ,section_code
9326     from   jai_ap_tds_thhold_grps
9327     where  threshold_grp_id = cn_threshold_grp_id;
9328   CURSOR c_get_tax_amount(cv_event VARCHAR2, cn_threshold_grp_id NUMBER) IS
9329   SELECT SUM(TAXABLE_AMOUNT), SUM(TAX_AMOUNT)
9330     FROM JAI_AP_TDS_THHOLD_TRXS
9331    WHERE TDS_EVENT LIKE cv_event
9332     AND TDS_ROLLBACKED IS NULL
9333     AND THRESHOLD_GRP_ID = cn_threshold_grp_id;
9334 
9335   CURSOR c_get_tax_amount_without_event(cn_threshold_grp_id NUMBER) IS
9336   SELECT SUM(taxable_amount)
9337         ,SUM(tax_amount)
9338     FROM
9339         (SELECT jattt.TAXABLE_AMOUNT taxable_amount
9340                ,jattt.TAX_AMOUNT     tax_amount
9341            FROM JAI_AP_TDS_THHOLD_TRXS jattt
9342           WHERE jattt.TDS_ROLLBACKED IS NULL
9343             AND jattt.TDS_EVENT NOT LIKE 'PREPAYMENT APPLICATION'
9344             AND jattt.TDS_EVENT NOT IN (G_SURCHARGE_ROLLBACK)  --Added by Chong.Lei for bug#13359892 at 20121008
9345             AND jattt.THRESHOLD_GRP_ID = cn_threshold_grp_id
9346             AND NOT EXISTS(
9347                 SELECT 1
9348                   FROM JAI_AP_TDS_INV_TAXES jatit
9349                  WHERE jattt.THRESHOLD_TRX_ID = jatit.THRESHOLD_TRX_ID
9350                    AND jatit.THRESHOLD_SLAB_ID_SINGLE IS NOT NULL
9351             )
9352          UNION ALL        --Added 'ALL'  by Chong.Lei for bug#13802244 at 20120308
9353          SELECT -SUM(TAXABLE_AMOUNT) taxable_amount,
9354                 -SUM(TAX_AMOUNT) tax_amount
9355            FROM JAI_AP_TDS_THHOLD_TRXS
9356           WHERE TDS_ROLLBACKED IS NULL
9357             AND TDS_EVENT LIKE 'PREPAYMENT APPLICATION'
9358             AND THRESHOLD_GRP_ID = cn_threshold_grp_id
9359         );
9360 
9361   CURSOR c_get_invoice_num(cn_invoice_id NUMBER) IS
9362   SELECT invoice_num
9363   FROM ap_invoices_all
9364   WHERE invoice_id = cn_invoice_id;
9365 
9366   CURSOR c_ap_invoices_all(p_invoice_id number) is
9367   SELECT invoice_id,
9368          cancelled_date,
9369          payment_status_flag,
9370          invoice_amount,
9371          set_of_books_id,
9372          invoice_num,
9373          org_id
9374     FROM ap_invoices_all
9375    Where invoice_id = p_invoice_id;
9376 
9377   CURSOR c_get_surcharge_trxs IS
9378   SELECT threshold_trx_id,
9379          threshold_grp_id,
9380          threshold_hdr_id,
9381          tax_category_id,
9382          tds_section_code,
9383          taxable_amount,
9384          tax_amount,
9385          invoice_to_tds_authority_id,
9386          invoice_to_vendor_id,
9387          tds_event,
9388          calc_tax_amount,
9389          invoice_id
9390     FROM JAI_AP_TDS_THHOLD_TRXS
9391    WHERE TDS_ROLLBACKED IS NULL
9392      AND TDS_EVENT LIKE 'SURCHARGE_CALCULATE'
9393      AND THRESHOLD_GRP_ID = p_threshold_grp_id
9394    ORDER BY threshold_trx_id;
9395 
9396   CURSOR get_dist_gl_date(cp_invoice_id IN ap_invoices_all.invoice_id%TYPE) IS
9397   SELECT accounting_date
9398         ,creation_date  --Added by Chong for Bug#13802244 2012/09/17
9399     FROM ap_invoice_distributions_all
9400    WHERE invoice_id = cp_invoice_id
9401      AND distribution_line_number = 1;
9402 
9403     /*Get Accounting Date from AP_INVOICE_LINES_ALL.
9404     This is fail safe if Distributions does not have accounting date*/
9405   CURSOR c_get_lines_acct_date(cp_invoice_id IN ap_invoices_all.invoice_id%TYPE) IS
9406   SELECT accounting_date
9407         ,creation_date  --Added by Chong for Bug#13802244 2012/09/17
9408     FROM ap_invoice_lines_all
9409    WHERE invoice_id = cp_invoice_id
9410      AND line_number = 1;
9411 
9412   --Added by Chong for Bug#13802244 2012/09/17 Start
9413   -----------------------------------------------------------------------------
9414   --Cursor to get rollbacked INVs which are not cancelled after threshold rollback
9415   CURSOR c_get_invoice_not_cancelled
9416   IS
9417   SELECT DISTINCT jattt.invoice_id
9418                  ,jattt.threshold_grp_id
9419                  ,jattt.threshold_hdr_id
9420                  ,jattt.tds_section_code
9421                  ,aia.vendor_id
9422                  ,aia.vendor_site_id
9423                  ,aia.invoice_currency_code
9424                  ,aia.exchange_rate
9425                  ,aia.set_of_books_id
9426                  ,aia.org_id
9427   FROM   jai_ap_tds_thhold_trxs jattt
9428         ,ap_invoices_all aia
9429   WHERE  aia.invoice_id = jattt.invoice_id
9430   AND    jattt.threshold_grp_id = p_threshold_grp_id
9431   AND    NVL(jattt.tds_rollbacked,'N') = 'Y'
9432   AND    tds_section_code is not null
9433   AND    aia.cancelled_date IS NULL
9434   AND NOT EXISTS(
9435       SELECT 1
9436       FROM   jai_ap_tds_inv_taxes jatit
9437       WHERE  jatit.invoice_id = jattt.invoice_id
9438       AND    threshold_slab_id_single IS NOT NULL
9439   )
9440   ;
9441   -----------------------------------------------------------------------------
9442   --Added by Chong for Bug#13802244 2012/09/17 End
9443 
9444   --Added by Chong for Bug#13359892 2012/09/27 Start
9445   -----------------------------------------------------------------------------
9446   CURSOR c_get_thrhd_hdr_id(cp_slab_id jai_ap_tds_thhold_slabs.threshold_slab_id%TYPE)
9447   IS
9448   SELECT threshold_hdr_id
9449   FROM   jai_ap_tds_thhold_slabs
9450   where  threshold_slab_id = cp_slab_id
9451   ;
9452 
9453   --Get one surcharge tax from this group
9454   --Assume there is only one surcharge tax in this tax category.
9455   CURSOR c_get_surcharge_tax_id(cp_threshold_grp_id NUMBER)
9456   IS
9457   SELECT jatit.actual_tax_id
9458   FROM   jai_ap_tds_inv_taxes jatit
9459   WHERE  jatit.threshold_grp_id = cp_threshold_grp_id
9460   AND    actual_tax_id IS NOT NULL
9461   AND    tax_type = 'TDS_SURCHARGE'
9462   ;
9463   -----------------------------------------------------------------------------
9464   --Added by Chong for Bug#13359892 2012/09/27 End
9465   ln_taxable_amount        NUMBER;
9466   ln_tax_amount            NUMBER;
9467   ln_tax_category_id       NUMBER;
9468   ln_threshold_trx_id      NUMBER;
9469   lv_tds_invoice_num       ap_invoices_all.invoice_num%TYPE;
9470   lv_cm_invoice_num        ap_invoices_all.invoice_num%TYPE;
9471   lv_section_type          JAI_AP_TDS_INV_TAXES.section_type%TYPE;
9472   lv_section_code          JAI_AP_TDS_INV_TAXES.actual_section_code%TYPE;
9473   lv_prepay_invoice_num    ap_invoices_all.invoice_num%TYPE;
9474   lv_prepay_invoice_id     NUMBER;
9475   ln_threshold_grp_audit_id       NUMBER;
9476   lv_codepath              jai_ap_tds_inv_taxes.codepath%TYPE;
9477   r_ap_invoices_all_au     c_ap_invoices_all%ROWTYPE;
9478   r_ap_invoices_all_cm     c_ap_invoices_all%ROWTYPE;
9479   lb_return_value          BOOLEAN;
9480   ld_accounting_date       DATE;
9481   ld_creation_date         DATE;  --Added by Chong for Bug#13802244 2012/09/17
9482   lv_open_period           ap_invoice_distributions_all.period_name%TYPE;
9483   ld_ret_accounting_date   DATE;
9484   lv_token                 VARCHAR2(4000);
9485   lv_invoice_to_tds_num    ap_invoices_all.invoice_num%type;
9486   lv_invoice_to_vendor_num ap_invoices_all.invoice_num%type;
9487   lv_tds_credit_memo_flag    varchar2(1);
9488   lv_tds_credit_memo_message varchar2(250);
9489   lv_process_flag            varchar2(1);
9490   lv_process_message         varchar2(250);
9491   lv_tds_invoice_flag        varchar2(1);
9492   lv_tds_invoice_message     varchar2(250);
9493   lv_tds_event               jai_ap_tds_thhold_trxs.tds_event%TYPE;
9494   ln_tax_id                  NUMBER;
9495 
9496   lv_out_message_name           varchar2(240);
9497   ln_out_invoice_amount         number;
9498   ln_out_base_amount            number;
9499   ln_out_tax_amount             number;
9500   ln_out_temp_cancelled_amount  number;
9501   ln_out_cancelled_by           number;
9502   ln_out_cancelled_amount       number;
9503   ld_out_cancelled_date         date;
9504   ld_out_last_update_date       date;
9505   ln_out_original_prepay_amount number;
9506   ln_out_pay_curr_inv_amount    number;
9507   ln_start_threshold_trx_id     NUMBER;
9508   ln_threshold_grp_id           NUMBER;
9509   ln_threshold_hdr_id           NUMBER;
9510   l_api_name                   CONSTANT  VARCHAR2(50) := 'process_threshold_rollback()';
9511 
9512 BEGIN
9513     jai_cmn_utils_pkg.WRITE_FND_LOG(G_LEVEL_PROCEDURE, G_MODULE_NAME||l_api_name||'.BEGIN', G_PKG_NAME || ': '||l_api_name||'()+');
9514   jai_cmn_utils_pkg.WRITE_FND_LOG(G_LEVEL_PROCEDURE, G_MODULE_NAME||l_api_name||'.Parameters', 'p_invoice_id: '||p_invoice_id);
9515   jai_cmn_utils_pkg.WRITE_FND_LOG(G_LEVEL_PROCEDURE, G_MODULE_NAME||l_api_name||'.Parameters', 'p_before_threshold_slab_id: '||p_before_threshold_slab_id);
9516   jai_cmn_utils_pkg.WRITE_FND_LOG(G_LEVEL_PROCEDURE, G_MODULE_NAME||l_api_name||'.Parameters', 'p_after_threshold_slab_id: '||p_after_threshold_slab_id);
9517   jai_cmn_utils_pkg.WRITE_FND_LOG(G_LEVEL_PROCEDURE, G_MODULE_NAME||l_api_name||'.Parameters', 'p_threshold_grp_id: '||p_threshold_grp_id);
9518   jai_cmn_utils_pkg.WRITE_FND_LOG(G_LEVEL_PROCEDURE, G_MODULE_NAME||l_api_name||'.Parameters', 'p_invoice_distribution_id: '||p_invoice_distribution_id);
9519   jai_cmn_utils_pkg.WRITE_FND_LOG(G_LEVEL_PROCEDURE, G_MODULE_NAME||l_api_name||'.Parameters', 'p_prepay_distribution_id: '||p_prepay_distribution_id);
9520   jai_cmn_utils_pkg.WRITE_FND_LOG(G_LEVEL_PROCEDURE, G_MODULE_NAME||l_api_name||'.Parameters', 'p_called_from: '||p_called_from);
9521 
9522 /*--Commented by Chong for bug#16414088 Derive section info by threshold group.
9523 	IF p_invoice_distribution_id IS NOT NULL THEN
9524       --when call from prepayment apply, distribution_id will not be null
9525       OPEN c_tds_tax(p_invoice_distribution_id);
9526       FETCH c_tds_tax INTO ln_tax_category_id,lv_section_type,lv_section_code;
9527       CLOSE c_tds_tax;
9528     ELSE
9529  */
9530   --when call from cancel, get section info from group
9531   OPEN c_get_tds_section_info(p_threshold_grp_id);
9532   fetch c_get_tds_section_info into lv_section_type,lv_section_code;
9533   close c_get_tds_section_info;
9534 
9535  --END IF;  --Commented by Chong for bug#16414088
9536 
9537   get_prepay_invoice_id(p_prepay_distribution_id,lv_prepay_invoice_id);
9538   OPEN c_get_invoice_num(lv_prepay_invoice_id);
9539   FETCH c_get_invoice_num INTO lv_prepay_invoice_num;
9540   CLOSE c_get_invoice_num;
9541 
9542   --Get threshold heaeder id by slab
9543   OPEN c_get_thrhd_hdr_id(NVL(p_before_threshold_slab_id, p_after_threshold_slab_id));
9544   FETCH c_get_thrhd_hdr_id into ln_threshold_hdr_id;
9545   CLOSE c_get_thrhd_hdr_id;
9546 
9547   IF p_before_threshold_slab_id is NOT NULL and p_after_threshold_slab_id IS NULL THEN
9548 
9549 
9550 
9551     lv_tds_event := 'THRESHOLD ROLLBACK( from slab id - '||p_before_threshold_slab_id||' to slab id - '||p_after_threshold_slab_id||')';
9552     jai_cmn_utils_pkg.WRITE_FND_LOG(G_LEVEL_STATEMENT, G_MODULE_NAME||l_api_name, 'Rollback TDS event: '||lv_tds_event);
9553 
9554     OPEN c_get_tax_amount_without_event(p_threshold_grp_id);
9555     FETCH c_get_tax_amount_without_event  INTO ln_taxable_amount, ln_tax_amount;
9556     CLOSE c_get_tax_amount_without_event;
9557 
9558     --Call jai_ap_tds_generation_pkg.generate_tds_invoices with LN_TAXABLE_AMOUNT, LN_TAX_AMOUNT
9559     jai_ap_dtc_generation_pkg.generate_rollback_dtc_invoices
9560                 ( pn_invoice_id              =>      p_invoice_id                                   ,
9561 --                  pn_invoice_distribution_id =>      p_invoice_distribution_id                      ,
9562 --                  pv_invoice_num_prepay_apply=>      lv_prepay_invoice_num                          ,
9563                   pn_taxable_amount          =>      ln_taxable_amount                              ,
9564                   pn_tax_amount              =>      ln_tax_amount                                  ,
9565                   pd_accounting_date         =>      p_accounting_date                              ,
9566                   pv_tds_event               =>      lv_tds_event                                   ,
9567                   pn_threshold_grp_id        =>      p_threshold_grp_id                             ,
9568                   pn_threshold_hdr_id        =>      ln_threshold_hdr_id,      --Added by Chong for bug#16414088 20130320
9569                   pv_section_type            =>      lv_section_type                                ,
9570                   pv_section_code            =>      lv_section_code                                ,
9571                   pv_tds_invoice_num         =>      lv_tds_invoice_num                             ,
9572                   pv_cm_invoice_num          =>      lv_cm_invoice_num                              ,
9573                   pn_threshold_trx_id        =>      ln_threshold_trx_id                            ,
9574                   pd_creation_date           =>      sysdate                                        ,
9575                   p_process_flag             =>      p_process_flag                                 ,
9576                   p_process_message          =>      p_process_message,
9577                   p_codepath                 =>      p_codepath
9578                 );
9579 
9580     if p_process_flag = 'E' then
9581 
9582       lv_codepath        := jai_general_pkg.plot_codepath(1.01, lv_codepath); /* 1.01*/
9583       lv_process_flag    := p_process_flag;
9584       lv_process_message := p_process_message;
9585       goto exit_from_procedure;
9586     end if;
9587     --Maintain Threshold Group (Update Tax Amount)
9588     ln_threshold_grp_id := p_threshold_grp_id;
9589 
9590     maintain_thhold_grps(p_threshold_grp_id       => ln_threshold_grp_id,
9591                          p_trx_tax_paid           => (-1 * ln_tax_amount),
9592                          p_tds_event              => lv_tds_event,
9593                          p_invoice_id             => p_invoice_id,
9594                          p_threshold_grp_audit_id => ln_threshold_grp_audit_id,
9595                          p_process_flag           => p_process_flag,
9596                          P_process_message        => P_process_message,
9597                          p_codepath               => lv_codepath);
9598     if p_process_flag = 'E' then
9599 
9600       lv_codepath        := jai_general_pkg.plot_codepath(1.02, lv_codepath); /* 1.02*/
9601       lv_process_flag    := p_process_flag;
9602       lv_process_message := p_process_message;
9603       goto exit_from_procedure;
9604     end if;
9605 
9606     update JAI_AP_TDS_THHOLD_TRXS jattt
9607          set jattt.TDS_ROLLBACKED = 'Y'
9608        where jattt.TDS_ROLLBACKED is NULL
9609          and  TDS_EVENT NOT IN (G_SURCHARGE_ROLLBACK)
9610          and jattt.THRESHOLD_GRP_ID = p_threshold_grp_id
9611          and not exists(
9612              select 1
9613              from   jai_ap_tds_inv_taxes in_inv
9614              where  in_inv.threshold_grp_id = p_threshold_grp_id
9615              and    in_inv.threshold_trx_id = jattt.threshold_trx_id
9616              and    in_inv.threshold_slab_id_single is not null
9617     );
9618 
9619     if p_process_flag = 'E' then
9620 
9621       lv_codepath        := jai_general_pkg.plot_codepath(1.03, lv_codepath); /* 1.03*/
9622       lv_process_flag    := p_process_flag;
9623       lv_process_message := p_process_message;
9624       goto exit_from_procedure;
9625     end if;
9626     --Ceate TDS invoices for Rollbacked single transactions
9627     FOR cur_rec IN c_get_invoice_not_cancelled LOOP
9628 
9629         /*Derivced the accounting_date of the original distribution
9630         * as this value is also getting passed for Threshold adjustments if the
9631         * TDS invoice is already paid/cancelled.
9632         */
9633         OPEN get_dist_gl_date(cur_rec.invoice_id);
9634         FETCH get_dist_gl_date
9635          INTO ld_accounting_date, ld_creation_date;
9636         CLOSE get_dist_gl_date;
9637 
9638         /*Fetch Accouting Date from AP_INVOICE_LINES_ALL if Distributions are not saved yet*/
9639         IF (ld_accounting_date IS NULL) THEN
9640           OPEN c_get_lines_acct_date(cur_rec.invoice_id);
9641           FETCH c_get_lines_acct_date
9642            INTO ld_accounting_date, ld_creation_date;
9643           CLOSE c_get_lines_acct_date;
9644         END IF;
9645 
9646         -- Call defaultation procedure to get single slab if beach single
9647         -- Calculate tax amount update jai_ap_tds_inv_taxes table, call generation procedure to create single TDS invoice.
9648         process_dtc_at_inv_validate
9649         ( p_invoice_id            => cur_rec.invoice_id
9650          ,p_vendor_id             => cur_rec.vendor_id
9651          ,p_vendor_site_id        => cur_rec.vendor_site_id
9652          ,p_accounting_date       => ld_accounting_date
9653          ,p_invoice_currency_code => cur_rec.invoice_currency_code
9654          ,p_exchange_rate         => cur_rec.exchange_rate
9655          ,p_set_of_books_id       => cur_rec.set_of_books_id
9656          ,p_org_id                => cur_rec.org_id
9657          ,p_call_from             => G_CALL_FROM_ROLLBACK
9658          ,p_creation_date         => ld_creation_date
9659          ,p_process_flag          => p_process_flag
9660          ,p_process_message       => p_process_message
9661          ,p_codepath              => p_codepath
9662         );
9663 
9664         IF p_process_flag = 'E' THEN
9665           p_codepath        := jai_general_pkg.plot_codepath(1.04, p_codepath); /* 1.04*/
9666           GOTO exit_from_procedure;
9667         END IF;
9668     END LOOP;
9669 
9670   ELSIF p_before_threshold_slab_id is NOT NULL and p_after_threshold_slab_id IS NOT NULL
9671     AND p_before_threshold_slab_id <> p_after_threshold_slab_id THEN
9672 
9673   --Check if the Tax Category Attached to p_before_threshold_slab_id has Surcharge Taxes and p_after_threshold_slab_id does not have Surcharge taxes
9674 
9675     IF p_called_from = 'PREPAY' THEN
9676 
9677       jai_cmn_utils_pkg.WRITE_FND_LOG(G_LEVEL_STATEMENT, G_MODULE_NAME||l_api_name, 'Rollback TDS event: '||lv_tds_event);
9678 
9679       OPEN c_get_tax_amount(G_SURCHARGE_CALCULATE,p_threshold_grp_id);
9680       FETCH c_get_tax_amount  INTO ln_taxable_amount, ln_tax_amount;
9681       CLOSE c_get_tax_amount;
9682       /*
9683       Call jai_ap_tds_generation_pkg.generate_tds_invoices with LN_TAXABLE_AMOUNT, LN_TAX_AMOUNT
9684       Note: Create Surcharge Rollback TDS Invoice with TDS Event as SURCHARGE_ROLLBACK???
9685       */
9686       /*  --Commented by Chong for surcharge rollback issue 2012/10/10
9687       jai_ap_dtc_generation_pkg.generate_dtc_invoices
9688               (
9689                 pn_invoice_id              =>      p_invoice_id                                   ,
9690                 pn_invoice_distribution_id =>      p_invoice_distribution_id                      ,
9691                 pv_invoice_num_prepay_apply=>      lv_prepay_invoice_num                          ,
9692                 pn_taxable_amount          =>      ln_taxable_amount                              ,
9693                 pn_tax_amount              =>      ln_tax_amount                                  ,
9694                 pd_accounting_date         =>      p_accounting_date                              ,
9695                 pv_tds_event               =>      'SURCHARGE_ROLLBACK'                       ,
9696                 pn_threshold_grp_id        =>      null                                           ,
9697                 pn_tax_category_id         =>      ln_tax_category_id                             ,
9698                 pv_section_type            =>      lv_section_type                                ,
9699                 pv_section_code            =>      lv_section_code                                ,
9700                 pv_tds_invoice_num         =>      lv_tds_invoice_num                             ,
9701                 pv_cm_invoice_num          =>      lv_cm_invoice_num                              ,
9702                 pn_threshold_trx_id        =>      ln_threshold_trx_id                       ,
9703                 pd_creation_date           =>      SYSDATE                                        ,
9704                 p_process_flag             =>      p_process_flag                                 ,
9705                 p_process_message          =>      p_process_message
9706               );
9707       */
9708       --Added by Chong for surcharge rollback issue 2012/10/10 start
9709       -----------------------------------------------------------------------
9710 
9711       --Get one surcharge tax from this given group
9712       --Assume there is only one surcharge tax in this tax category.
9713       OPEN c_get_surcharge_tax_id(p_threshold_grp_id);
9714       FETCH c_get_surcharge_tax_id into ln_tax_id;
9715       CLOSE c_get_surcharge_tax_id;
9716 
9717       jai_ap_dtc_generation_pkg.generate_tds_invoices(
9718          pn_invoice_id              =>     p_invoice_id
9719         ,pn_threshold_hdr_id        =>     ln_threshold_hdr_id
9720         ,pn_taxable_amount          =>     ln_taxable_amount
9721         ,pn_tax_amount              =>     ln_tax_amount
9722         ,pn_tax_id                  =>     ln_tax_id
9723         ,pv_section_code            =>      lv_section_code   --Added by Chong for bug#16048702
9724         ,pd_accounting_date         =>     p_accounting_date
9725         ,pv_tds_event               =>     G_SURCHARGE_ROLLBACK
9726         ,pn_threshold_grp_id        =>     p_threshold_grp_id
9727         ,pv_tds_invoice_num         =>     lv_tds_invoice_num
9728         ,pv_cm_invoice_num          =>     lv_cm_invoice_num
9729         ,pn_threshold_trx_id        =>     ln_threshold_trx_id
9730         ,pd_creation_date           =>     sysdate
9731         ,pn_calc_tax_amount         =>     0
9732         ,p_process_flag             =>     p_process_flag
9733         ,p_process_message          =>     p_process_message
9734       );
9735       -----------------------------------------------------------------------
9736       --Added by Chong for surcharge rollback issue 2012/10/10 end
9737 
9738       update JAI_AP_TDS_THHOLD_TRXS jattt
9739            set jattt.TDS_ROLLBACKED = 'Y'
9740          where jattt.TDS_ROLLBACKED is NULL
9741            and  TDS_EVENT LIKE G_SURCHARGE_CALCULATE
9742            and jattt.THRESHOLD_GRP_ID = p_threshold_grp_id
9743            and not exists(
9744                select 1
9745                from   jai_ap_tds_inv_taxes in_inv
9746                where  in_inv.threshold_grp_id = p_threshold_grp_id
9747                and    in_inv.threshold_trx_id = jattt.threshold_trx_id
9748                and    in_inv.threshold_slab_id_single is not null
9749       );
9750 
9751       --Maintain Threshold Group (Update Tax Amount)
9752       ln_threshold_grp_id := p_threshold_grp_id;
9753 
9754       maintain_thhold_grps(p_threshold_grp_id       => ln_threshold_grp_id,
9755                            p_trx_tax_paid           => (-1 * ln_tax_amount),
9756                            p_tds_event              => 'SURCHARGE_ROLLBACK',
9757                            p_invoice_id             => p_invoice_id,
9758                            p_threshold_grp_audit_id => ln_threshold_grp_audit_id,
9759                            p_process_flag           => p_process_flag,
9760                            P_process_message        => P_process_message,
9761                            p_codepath               => lv_codepath);
9762 
9763     ELSIF p_called_from = 'CANCEL' THEN
9764 
9765 
9766       --Fetch the Surcharge Invoice from JAI_AP_TDS_THHOLD_TRXS
9767       FOR cur_rec IN c_get_surcharge_trxs
9768       LOOP
9769         r_ap_invoices_all_au := NULL;
9770         r_ap_invoices_all_cm := NULL;
9771         /* Get the details of the Invoice to TDS authority invoice*/
9772         OPEN c_ap_invoices_all(cur_rec.invoice_to_tds_authority_id);
9773         FETCH c_ap_invoices_all
9774          INTO r_ap_invoices_all_au;
9775         CLOSE c_ap_invoices_all;
9776         /* Get the details of the Invoice to CM invoice*/
9777         OPEN c_ap_invoices_all(cur_rec.invoice_to_vendor_id);
9778         FETCH c_ap_invoices_all
9779          INTO r_ap_invoices_all_cm;
9780         CLOSE c_ap_invoices_all;
9781 
9782         /*Derivced the accounting_date of the original distribution
9783         * as this value is also getting passed for Threshold adjustments if the
9784         * TDS invoice is already paid/cancelled.
9785         */
9786         OPEN get_dist_gl_date(r_ap_invoices_all_au.invoice_id);
9787         FETCH get_dist_gl_date
9788          INTO ld_accounting_date, ld_creation_date;  --Added creation_date by Chong for Bug#13802244 2012/09/17
9789         CLOSE get_dist_gl_date;
9790 
9791         /*Fetch Accouting Date from AP_INVOICE_LINES_ALL if Distributions are not saved yet*/
9792         IF (ld_accounting_date IS NULL) THEN
9793           OPEN c_get_lines_acct_date(r_ap_invoices_all_au.invoice_id);
9794           FETCH c_get_lines_acct_date
9795            INTO ld_accounting_date, ld_creation_date;  --Added creation_date by Chong for Bug#13802244 2012/09/17
9796           CLOSE c_get_lines_acct_date;
9797         END IF;
9798 
9799         /* Check if the TDS invoice is paid, no processing is required if it is already paid. */
9800         IF r_ap_invoices_all_au.payment_status_flag <> 'N' THEN
9801 
9802           /*lv_tds_invoice_flag        := 'X';
9803           lv_tds_invoice_message     := 'Invoice to TDS Authority is already paid.';
9804           lv_tds_credit_memo_flag    := 'X';
9805           lv_tds_credit_memo_message := 'No processing as Invoice to TDS Authority  is already paid';
9806           goto Continue_with_next_record;*/
9807           APP_EXCEPTION.RAISE_EXCEPTION(EXCEPTION_TYPE => 'APP',
9808                                         EXCEPTION_CODE => NULL,
9809                                         EXCEPTION_TEXT => 'Invoice to TDS Authority is already paid.');
9810         END IF;
9811 
9812         /*  Check if the invoice to TDS authority is already canccelled,
9813         if yes, no need to do the cancel processing of the invoice */
9814         lv_codepath := jai_general_pkg.plot_codepath(5, lv_codepath); /* 5 */
9815         if r_ap_invoices_all_au.cancelled_date is not null then
9816           lv_codepath            := jai_general_pkg.plot_codepath(6,lv_codepath); /* 6 */
9817           lv_tds_invoice_flag    := 'X';
9818           lv_tds_invoice_message := ' Invoice to TDS Authority is already Cancelled.';
9819           goto credit_memo_processing;
9820         end if;
9821 
9822         /* Control comes here only when the Invoice to TDS Authority  is not paid or not cancelled, need to cancel it */
9823         lb_return_value               := null;
9824         lv_out_message_name           := null;
9825         ln_out_invoice_amount         := null;
9826         ln_out_base_amount            := null;
9827         ln_out_tax_amount             := null;
9828         ln_out_temp_cancelled_amount  := null;
9829         ln_out_cancelled_by           := null;
9830         ln_out_cancelled_amount       := null;
9831         ld_out_cancelled_date         := null;
9832         ld_out_last_update_date       := null;
9833         ln_out_original_prepay_amount := null;
9834         ln_out_pay_curr_inv_amount    := null;
9835         lv_token                      := null;
9836 
9837         lv_codepath := jai_general_pkg.plot_codepath(7, lv_codepath); /* 7 */
9838 
9839         /* Fetch the accounting date of TDS invoice distribution
9840         | so that the same will be passed for reversal line which will get
9841         | created for cancellation.
9842         */
9843         --Check if the given date is in current open period
9844         lv_open_period := ap_utilities_pkg.get_current_gl_date(P_Date   => ld_accounting_date,
9845                                                                P_Org_Id => r_ap_invoices_all_au.org_id);
9846         if lv_open_period is null then
9847 
9848           lv_codepath := jai_general_pkg.plot_codepath(1.1, lv_codepath); /* 1.1 */
9849 
9850           ap_utilities_pkg.get_open_gl_date(p_date        => ld_accounting_date, /* In date */
9851                                             p_period_name => lv_open_period, /* out Period */
9852                                             p_gl_date     => ld_accounting_date, /* out date */
9853                                             P_Org_Id      => r_ap_invoices_all_au.org_id);
9854 
9855           if lv_open_period is null then
9856             lv_codepath        := jai_general_pkg.plot_codepath(1.2,lv_codepath); /* 1.2 */
9857             lv_process_flag    := 'E';
9858             lv_process_message := 'No open accounting Period after : ' || ld_accounting_date;
9859             goto exit_from_procedure;
9860           end if;
9861           ld_accounting_date := ld_ret_accounting_date;
9862 
9863         end if; /* lv_open_period is null */
9864         ld_ret_accounting_date := NULL;
9865 
9866         mo_global.set_policy_context('S', r_ap_invoices_all_au.org_id);
9867 
9868         lb_return_value := ap_cancel_pkg.ap_cancel_single_invoice(P_invoice_id        => cur_rec.invoice_to_tds_authority_id,
9869                                                                   P_last_updated_by   => fnd_global.user_id,
9870                                                                   P_last_update_login => fnd_global.login_id,
9871                                                                   P_accounting_date => ld_accounting_date,
9872                                                                   P_message_name   => lv_out_message_name,
9873                                                                   P_invoice_amount => ln_out_invoice_amount,
9874                                                                   P_base_amount    => ln_out_base_amount,
9875                                                                   --P_tax_amount                   =>    ln_out_tax_amount                        ,
9876                                                                   P_temp_cancelled_amount      => ln_out_temp_cancelled_amount,
9877                                                                   P_cancelled_by               => ln_out_cancelled_by,
9878                                                                   P_cancelled_amount           => ln_out_cancelled_amount,
9879                                                                   P_cancelled_date             => ld_out_cancelled_date,
9880                                                                   P_last_update_date           => ld_out_last_update_date,
9881                                                                   P_original_prepayment_amount => ln_out_original_prepay_amount,
9882                                                                   --P_check_id                     =>    null                                     ,
9883                                                                   P_pay_curr_invoice_amount => ln_out_pay_curr_inv_amount,
9884                                                                   P_Token                   => lv_token,
9885                                                                   P_calling_sequence        => 'India Localization - TDS thrreshold rollback');
9886 
9887         lv_codepath := jai_general_pkg.plot_codepath(8, lv_codepath); /* 8 */
9888 
9889         /*Check whether any value is returned in lv_token.
9890         IF it is not null display the error  message. */
9891 
9892         IF nvl(lv_token, 'A') <> 'A' Then
9893           APP_EXCEPTION.RAISE_EXCEPTION(EXCEPTION_TYPE => 'APP',
9894                                         EXCEPTION_CODE => NULL,
9895                                         EXCEPTION_TEXT => lv_token);
9896         End if;
9897 
9898         update ap_invoices_all
9899            set invoice_amount = ln_out_invoice_amount,
9900                base_amount    = ln_out_base_amount,
9901                temp_cancelled_amount      = ln_out_temp_cancelled_amount,
9902                cancelled_by               = ln_out_cancelled_by,
9903                cancelled_amount           = ln_out_cancelled_amount,
9904                cancelled_date             = ld_out_cancelled_date,
9905                last_update_date           = ld_out_last_update_date,
9906                original_prepayment_amount = ln_out_original_prepay_amount,
9907                pay_curr_invoice_amount    = ln_out_pay_curr_inv_amount
9908          where invoice_id = cur_rec.invoice_to_tds_authority_id;
9909 
9910         /*What if ap_cancel_pkg.ap_cancel_single_invoice is not there ?? */
9911         lv_tds_invoice_flag    := 'Y';
9912         lv_tds_invoice_message := 'Invoice to TDS Authority is Cancelled ';
9913 
9914         lv_codepath := jai_general_pkg.plot_codepath(9, lv_codepath); /* 9 */
9915 
9916 
9917         <<credit_memo_processing>>
9918         /*Derivced the accounting_date of the original distribution
9919         * as this value is also getting passed for Threshold adjustments if the
9920         * TDS CM invoice is already paid/cancelled.
9921         */
9922         OPEN get_dist_gl_date(r_ap_invoices_all_cm.invoice_id);
9923         FETCH get_dist_gl_date
9924           INTO ld_accounting_date, ld_creation_date;  --Added creation_date by Chong for Bug#13802244 2012/09/17
9925         CLOSE get_dist_gl_date;
9926 
9927         /*Fetch Accouting Date from AP_INVOICE_LINES_ALL if Distributions are not saved yet*/
9928         if (ld_accounting_date is NULL) then
9929           OPEN c_get_lines_acct_date(r_ap_invoices_all_cm.invoice_id);
9930           FETCH c_get_lines_acct_date
9931             INTO ld_accounting_date, ld_creation_date;  --Added creation_date by Chong for Bug#13802244 2012/09/17
9932           CLOSE c_get_lines_acct_date;
9933         end if;
9934 
9935         /*  Check if the Credit memo to the supplier for TDS already canccelled,
9936         if yes, no need to cancel it again here  */
9937 
9938         if r_ap_invoices_all_cm.cancelled_date is not null then
9939           lv_codepath                := jai_general_pkg.plot_codepath(10,
9940                                                                       lv_codepath); /* 10 */
9941           lv_tds_credit_memo_flag    := 'X';
9942           lv_tds_credit_memo_message := 'Credit memo to the supplier for TDS is already Cancelled.';
9943           goto Continue_with_next_record;
9944         end if;
9945 
9946         /*Check if the Credit memo to the supplier for TDS is paid,
9947         if yes a separate invoice needs to be generated, or else the same credit memo can be cancelled */
9948         IF r_ap_invoices_all_cm.payment_status_flag = 'N' THEN
9949           lv_codepath := jai_general_pkg.plot_codepath(11, lv_codepath); /* 11 */
9950           /* Credit memo not paid, can cancel the same */
9951           lv_tds_credit_memo_flag    := 'Y';
9952           lv_tds_credit_memo_message := 'Cancelling Credit memo to the supplier for TDS as it is not paid ';
9953 
9954           lb_return_value               := null;
9955           lv_out_message_name           := null;
9956           ln_out_invoice_amount         := null;
9957           ln_out_base_amount            := null;
9958           ln_out_tax_amount             := null;
9959           ln_out_temp_cancelled_amount  := null;
9960           ln_out_cancelled_by           := null;
9961           ln_out_cancelled_amount       := null;
9962           ld_out_cancelled_date         := null;
9963           ld_out_last_update_date       := null;
9964           ln_out_original_prepay_amount := null;
9965           ln_out_pay_curr_inv_amount    := null;
9966           lv_token                      := NULL;
9967 
9968           lv_codepath := jai_general_pkg.plot_codepath(12, lv_codepath); /* 12 */
9969 
9970           /*Fetch the accounting date of TDS invoice distribution
9971           | so that the same will be passed for reversal line which will get
9972           | created for cancellation.
9973           */
9974           --Check if the given date is in current open period
9975           lv_open_period := ap_utilities_pkg.get_current_gl_date(P_Date   => ld_accounting_date,
9976                                                                  P_Org_Id => r_ap_invoices_all_cm.org_id);
9977           if lv_open_period is null then
9978 
9979             lv_codepath := jai_general_pkg.plot_codepath(1.1, lv_codepath); /* 1.1 */
9980 
9981             ap_utilities_pkg.get_open_gl_date(p_date        => ld_accounting_date, /* In date */
9982                                               p_period_name => lv_open_period, /* out Period */
9983                                               p_gl_date     => ld_accounting_date, /* out date */
9984                                               P_Org_Id      => r_ap_invoices_all_cm.org_id);
9985 
9986             if lv_open_period is null then
9987               lv_codepath        := jai_general_pkg.plot_codepath(1.2,
9988                                                                   lv_codepath); /* 1.2 */
9989               lv_process_flag    := 'E';
9990               lv_process_message := 'No open accounting Period after : ' ||
9991                                     ld_accounting_date;
9992               goto exit_from_procedure;
9993             end if;
9994             ld_accounting_date := ld_ret_accounting_date;
9995           end if; /* lv_open_period is null */
9996           ld_ret_accounting_date := NULL;
9997 
9998           mo_global.set_policy_context('S', r_ap_invoices_all_cm.org_id);
9999 
10000           lb_return_value := ap_cancel_pkg.ap_cancel_single_invoice(P_invoice_id        => r_ap_invoices_all_cm.invoice_id,
10001                                                                     P_last_updated_by   => fnd_global.user_id,
10002                                                                     P_last_update_login => fnd_global.login_id,
10003                                                                     P_accounting_date => ld_accounting_date,
10004                                                                     P_message_name   => lv_out_message_name,
10005                                                                     P_invoice_amount => ln_out_invoice_amount,
10006                                                                     P_base_amount    => ln_out_base_amount,
10007                                                                     --P_tax_amount                   =>    ln_out_tax_amount                        ,
10008                                                                     P_temp_cancelled_amount      => ln_out_temp_cancelled_amount,
10009                                                                     P_cancelled_by               => ln_out_cancelled_by,
10010                                                                     P_cancelled_amount           => ln_out_cancelled_amount,
10011                                                                     P_cancelled_date             => ld_out_cancelled_date,
10012                                                                     P_last_update_date           => ld_out_last_update_date,
10013                                                                     P_original_prepayment_amount => ln_out_original_prepay_amount,
10014                                                                     --P_check_id                     =>    null                                     ,
10015                                                                     P_pay_curr_invoice_amount => ln_out_pay_curr_inv_amount,
10016                                                                     P_token                   => lv_token,
10017                                                                     P_calling_sequence        => 'India Localization - TDS thrreshold rollback');
10018 
10019           lv_codepath := jai_general_pkg.plot_codepath(13, lv_codepath); /* 13 */
10020 
10021           IF nvl(lv_token, 'A') <> 'A' Then
10022             APP_EXCEPTION.RAISE_EXCEPTION(EXCEPTION_TYPE => 'APP',
10023                                           EXCEPTION_CODE => NULL,
10024                                           EXCEPTION_TEXT => lv_token);
10025           End if;
10026 
10027           update ap_invoices_all
10028              set invoice_amount = ln_out_invoice_amount,
10029                  base_amount    = ln_out_base_amount,
10030                  temp_cancelled_amount      = ln_out_temp_cancelled_amount,
10031                  cancelled_by               = ln_out_cancelled_by,
10032                  cancelled_amount           = ln_out_cancelled_amount,
10033                  cancelled_date             = ld_out_cancelled_date,
10034                  last_update_date           = ld_out_last_update_date,
10035                  original_prepayment_amount = ln_out_original_prepay_amount,
10036                  pay_curr_invoice_amount    = ln_out_pay_curr_inv_amount
10037            where invoice_id = cur_rec.invoice_to_vendor_id;
10038 
10039         ELSE
10040           /* Credit memo has already been paid, have to generate a new invoice to nagate the effect */
10041           lv_codepath              := jai_general_pkg.plot_codepath(14,
10042                                                                     lv_codepath); /* 14 */
10043           ln_threshold_trx_id      := 0;
10044           lv_invoice_to_tds_num    := null;
10045           lv_invoice_to_vendor_num := null;
10046 
10047           jai_ap_dtc_generation_pkg.generate_dtc_invoices(pn_invoice_id                => cur_rec.invoice_id,
10048                                                           pv_invoice_num_to_vendor_can => r_ap_invoices_all_cm.invoice_num,
10049                                                           pn_taxable_amount            => cur_rec.taxable_amount,
10050                                                           pn_tax_amount                => cur_rec.tax_amount,
10051                                                           pn_tax_category_id           => cur_rec.tax_category_id,
10052                                                           pv_section_type              => lv_section_type, -- 'TDS_SECTION_TYPE'
10053                                                           pv_section_code              => cur_rec.tds_section_code,
10054                                                           pd_accounting_date           => ld_accounting_date,
10055                                                           pv_tds_event                 => 'INVOICE CANCEL',
10056                                                           pn_threshold_grp_id          => cur_rec.threshold_grp_id,
10057                                                           pv_tds_invoice_num           => lv_invoice_to_tds_num,
10058                                                           pv_cm_invoice_num            => lv_invoice_to_vendor_num,
10059                                                           pn_threshold_trx_id          => ln_threshold_trx_id,
10060                                                           p_process_flag               => lv_tds_credit_memo_flag,
10061                                                           p_process_message            => lv_tds_credit_memo_message,
10062                                                           pd_creation_Date             => sysdate,
10063                                                           pn_calc_tax_amount           => 0);
10064 
10065           if lv_tds_credit_memo_flag = 'E' then
10066             lv_codepath := jai_general_pkg.plot_codepath(15, lv_codepath); /* 15 */
10067             goto Continue_with_next_record;
10068           end if;
10069 
10070           lv_tds_credit_memo_flag    := 'Y';
10071           lv_tds_credit_memo_message := 'Generated Standard invoice to suppliet : ' || lv_invoice_to_vendor_num;
10072           lv_codepath                := jai_general_pkg.plot_codepath(16,lv_codepath); /* 16 */
10073 
10074           if ln_start_threshold_trx_id is null then
10075             ln_start_threshold_trx_id := ln_threshold_trx_id;
10076           end if;
10077 
10078           lv_codepath := jai_general_pkg.plot_codepath(17, lv_codepath); /* 17 */
10079 
10080         END IF; /* Credit memo to the supplier paid / not paid */
10081 
10082         /* Control comes here when either the credit memo for the tds authority is cancelled or a
10083         compensating standard invoice has been made */
10084 
10085         ln_threshold_grp_id := cur_rec.threshold_grp_id;
10086         maintain_thhold_grps(p_threshold_grp_id       => ln_threshold_grp_id,
10087                              p_trx_tax_paid           => (-1 * cur_rec.tax_amount),
10088                              p_tds_event              => 'INVOICE CANCEL',
10089                              p_invoice_id             => p_invoice_id,
10090                              p_threshold_grp_audit_id => ln_threshold_grp_audit_id,
10091                              p_process_flag           => lv_process_flag,
10092                              P_process_message        => lv_process_message,
10093                              p_codepath               => lv_codepath);
10094 
10095         <<Continue_with_next_record>>
10096         NULL;
10097       END LOOP;
10098 
10099       update JAI_AP_TDS_THHOLD_TRXS jattt
10100            set jattt.TDS_ROLLBACKED = 'Y'
10101          where jattt.TDS_ROLLBACKED is NULL
10102            and  TDS_EVENT LIKE 'SURCHARGE_CALCULATE'
10103            and jattt.THRESHOLD_GRP_ID = p_threshold_grp_id
10104            and not exists(
10105                select 1
10106                from   jai_ap_tds_inv_taxes in_inv
10107                where  in_inv.threshold_grp_id = p_threshold_grp_id
10108                and    in_inv.threshold_trx_id = jattt.threshold_trx_id
10109                and    in_inv.threshold_slab_id_single is not null
10110       );
10111 
10112     END IF;
10113 
10114     --Added by Chong for Bug#13359892 2012/09/27 Start
10115     -----------------------------------------------------------------------------
10116     --**Create RTN for transactions which in surcharge tax slab
10117 
10118     --Get surcharge taxable amount for surcharge RTN invoice
10119     SELECT SUM(jattt.TAXABLE_AMOUNT) INTO ln_taxable_amount
10120     FROM JAI_AP_TDS_THHOLD_TRXS jattt
10121     WHERE jattt.tds_event NOT in (G_SURCHARGE_CALCULATE)
10122     AND   jattt.tds_rollbacked IS NULL
10123     AND   jattt.threshold_grp_id = p_threshold_grp_id
10124     AND EXISTS(
10125           SELECT 1
10126           FROM   JAI_AP_TDS_INV_TAXES jatit
10127                 ,jai_cmn_taxes_all    jcta
10128           WHERE  jatit.invoice_id = jattt.invoice_id
10129           AND    jcta.tax_id      = jatit.actual_tax_id
10130           AND    jcta.tax_type = 'TDS_SURCHARGE'
10131     )
10132     AND NOT EXISTS(
10133           SELECT 1
10134           FROM   AP_INVOICES_ALL aia
10135           WHERE  aia.invoice_id = jattt.invoice_id
10136           AND   aia.cancelled_date IS NOT NULL
10137     )
10138     ;
10139     --Get surcharge tax amount for surcharge RTN invoice
10140     SELECT SUM(aila.AMOUNT) INTO ln_tax_amount
10141     FROM AP_INVOICE_LINES_ALL  aila
10142     WHERE INVOICE_ID IN (
10143           SELECT NVL(jattt.invoice_to_tds_authority_id, jattt.invoice_to_vendor_id)
10144           FROM JAI_AP_TDS_THHOLD_TRXS jattt
10145               ,AP_INVOICES_ALL        aia
10146           WHERE jattt.invoice_id = aia.invoice_id
10147           AND   jattt.tds_event NOT in (G_SURCHARGE_CALCULATE)
10148           AND   aia.cancelled_date IS NULL
10149           AND   jattt.tds_rollbacked IS NULL
10150           AND   jattt.threshold_grp_id = p_threshold_grp_id
10151           AND EXISTS(
10152                 SELECT 1
10153                 FROM   JAI_AP_TDS_INV_TAXES jatit
10154                       ,jai_cmn_taxes_all    jcta
10155                 WHERE  jatit.invoice_id = jattt.invoice_id
10156                 AND    jcta.tax_id      = jatit.actual_tax_id
10157                 AND    jcta.tax_type = 'TDS_SURCHARGE'
10158           )
10159     )
10160     AND aila.DESCRIPTION LIKE '%/TDS_SURCHARGE/%'
10161     ;
10162 
10163     --Get threshold heaeder id by slab
10164     OPEN c_get_thrhd_hdr_id(p_after_threshold_slab_id);
10165     FETCH c_get_thrhd_hdr_id into ln_threshold_hdr_id;
10166     CLOSE c_get_thrhd_hdr_id;
10167 
10168     --Get one surcharge tax from this given group
10169     --Assume there is only one surcharge tax in this tax category.
10170     OPEN c_get_surcharge_tax_id(p_threshold_grp_id);
10171     FETCH c_get_surcharge_tax_id into ln_tax_id;
10172     CLOSE c_get_surcharge_tax_id;
10173 
10174 
10175     jai_ap_dtc_generation_pkg.generate_tds_invoices
10176     (
10177        pn_invoice_id              =>     p_invoice_id
10178       ,pn_threshold_hdr_id        =>     ln_threshold_hdr_id
10179       ,pn_taxable_amount          =>     ln_taxable_amount
10180       ,pn_tax_amount              =>     ln_tax_amount
10181       ,pn_tax_id                  =>     ln_tax_id
10182       ,pv_section_code            =>      lv_section_code   --Added by Chong for bug#16048702
10183       ,pd_accounting_date         =>     p_accounting_date
10184       ,pv_tds_event               =>     G_SURCHARGE_ROLLBACK
10185       ,pn_threshold_grp_id        =>     p_threshold_grp_id
10186       ,pv_tds_invoice_num         =>     lv_tds_invoice_num
10187       ,pv_cm_invoice_num          =>     lv_cm_invoice_num
10188       ,pn_threshold_trx_id        =>     ln_threshold_trx_id
10189       ,pd_creation_date           =>     sysdate
10190       ,pn_calc_tax_amount         =>     0
10191       ,p_process_flag             =>     p_process_flag
10192       ,p_process_message          =>     p_process_message
10193     );
10194 
10195     if p_process_flag = 'E' then
10196        goto exit_from_procedure;
10197     end if;
10198 
10199      /* Update the total tax amount for which invoice was raised */
10200     ln_threshold_grp_id:= p_threshold_grp_id;
10201      maintain_thhold_grps
10202     (
10203      p_threshold_grp_id             =>   ln_threshold_grp_id,
10204      p_trx_tax_paid                 =>   -( ln_tax_amount ),
10205      p_trx_thhold_change_tax_paid   =>   -( ln_tax_amount ),
10206      p_trx_threshold_slab_id        =>   p_after_threshold_slab_id,
10207      p_tds_event                    =>   G_SURCHARGE_ROLLBACK,
10208      p_invoice_id                   =>   p_invoice_id,
10209      p_threshold_grp_audit_id       =>   ln_threshold_grp_audit_id,
10210      p_creation_date                =>   sysdate,
10211      p_process_flag                 =>   p_process_flag,
10212      P_process_message              =>   P_process_message,
10213      p_codepath                     =>   lv_codepath
10214     );
10215     if p_process_flag = 'E' then
10216        goto exit_from_procedure;
10217     end if;
10218     -----------------------------------------------------------------------------
10219     --Added by Chong for Bug#13359892 2012/09/27 End
10220     --Added by Chong for bug#16414088 eTDS ER Start
10221     ----------------------------------------------------------------------
10222     --Hook code add here after call generate_tds_invoice for surcharge calculation invoice.
10223     jai_ap_tds_pop_rpst_pkg.Process_surcharge(
10224                                   pn_source_invoice_id => p_invoice_id
10225                                  ,pv_event             => G_SURCHARGE_ROLLBACK
10226                                  ,pn_taxable_amount    => NULL
10227                                  ,pn_tax_amount        => NULL
10228                                  ,pn_threshold_grp_id  => p_threshold_grp_id
10229                                  ,pn_surcharge_tax_id  => ln_tax_id
10230 
10231      );
10232     ----------------------------------------------------------------------
10233     --Added by Chong for bug#16414088 eTDS ER End
10234   END IF;
10235 
10236   IF ln_threshold_trx_id IS NOT NULL THEN
10237 
10238       /* rollback invoice have been generated, call the program for invoking import and approval */
10239       jai_ap_tds_generation_pkg.import_and_approve(p_invoice_id          => p_invoice_id,
10240                                                    p_start_thhold_trx_id => ln_threshold_trx_id,
10241                                                    p_tds_event           => 'THRESHOLD ROLLBACK',
10242                                                    p_process_flag        => p_process_flag,
10243                                                    p_process_message     => P_process_message);
10244   END IF;
10245 
10246   <<exit_from_procedure>>
10247   lv_codepath := jai_general_pkg.plot_codepath(100,lv_codepath,NULL,'END'); /* 100 */
10248     jai_cmn_utils_pkg.WRITE_FND_LOG(G_LEVEL_PROCEDURE, G_MODULE_NAME||l_api_name||'.END', G_PKG_NAME || ': '||l_api_name||'()-');
10249 
10250 /* IF lv_process_flag = 'E' THEN
10251     raise_application_error(-20012, lv_process_message);
10252   END IF;*/
10253 END process_threshold_rollback;
10254 PROCEDURE get_prepay_invoice_id
10255   (
10256     p_prepay_inv_dist_id  NUMBER,
10257     p_prepay_inv_id       OUT NOCOPY NUMBER
10258 
10259    )
10260   IS
10261     --PRAGMA AUTONOMOUS_TRANSACTION;  --commented by Cholei for ZX integration bug#14040855
10262   BEGIN
10263     BEGIN
10264       SELECT invoice_id
10265         INTO p_prepay_inv_id
10266         FROM ap_invoice_distributions_all
10267        WHERE invoice_distribution_id = p_prepay_inv_dist_id;
10268     EXCEPTION
10269       WHEN NO_DATA_FOUND THEN
10270         p_prepay_inv_id := null;
10271     END;
10272   END get_prepay_invoice_id;
10273   -- Bug 5722028. Added by csahoo
10274 --Added by Chong.Lei for DTC ER #13359892 on 20120212 begin
10275 procedure generate_rollback_dtc_invoices
10276   ( pn_invoice_id                         in                 number,
10277     pn_threshold_grp_id                   in                 number,
10278     pn_threshold_hdr_id                   in                 number   default null,
10279     pv_section_type                       in                 varchar2,
10280     pv_section_code                       in                 varchar2,
10281     pn_taxable_amount                     in                 number,
10282     pn_tax_amount                         in                 number,
10283     pd_accounting_date                    in                 date,
10284     pv_tds_event                          in                 varchar2,
10285     pv_tds_invoice_num                    out      nocopy    varchar2,
10286     pv_cm_invoice_num                     out      nocopy    varchar2,
10287     pn_threshold_trx_id                   out      nocopy    number,
10288     pd_creation_date                      in                 date,
10289     pn_calc_tax_amount                    in                 number default 0, /* Added for bug 12965614 */
10290     p_process_flag                        out      nocopy    varchar2,
10291     p_process_message                     out      nocopy    varchar2,
10292     p_codepath                            in out    nocopy    varchar2
10293   )
10294   is
10295 
10296   cursor c_ap_invoices_all(cp_invoice_id number) is
10297     select  invoice_num,
10298             invoice_id,
10299             vendor_id,
10300             vendor_site_id,
10301             invoice_currency_code,
10302             exchange_rate_type,
10303             exchange_date,
10304             terms_id,
10305             payment_method_lookup_code,
10306             pay_group_lookup_code,
10307             invoice_date,
10308             goods_received_date,
10309             invoice_received_date,
10310             org_id,
10311             nvl(exchange_rate, 1) exchange_rate,
10312             set_of_books_id,
10313             payment_method_code, -- Bug 7109056
10314             accts_pay_code_combination_id -- Bug 9759709
10315     from    ap_invoices_all
10316     where   invoice_id = cp_invoice_id;
10317 
10318   cursor c_po_vendor_sites_all(cp_vendor_id  number, cp_vendor_site_id number) is
10319     select  terms_id,
10320             --payment_method_lookup_code, --commented by Sanjikum for Bug#4482462
10321             pay_group_lookup_code
10322     from    po_vendor_sites_all
10323     where   vendor_id = cp_vendor_id
10324     and     vendor_site_id = cp_vendor_site_id;
10325 
10326   cursor c_po_vendors(cp_vendor_id  number) is
10327     select  terms_id,
10328             --payment_method_lookup_code, --commented by Sanjikum for Bug#4482462
10329             pay_group_lookup_code
10330     from    po_vendors
10331     where   vendor_id = cp_vendor_id;
10332 
10333   --Get tax info by tax_account_id
10334 --cursor c_ja_in_tax_codes (cn_tax_account jai_cmn_taxes_all.tax_account_id%type) is
10335   cursor c_ja_in_tax_codes (cn_tax_id jai_cmn_taxes_all.tax_id%type) is --Change to tax_id by Chong for bug#16414088 20130320
10336     select  jcta.section_code,
10337             jcta.vendor_id,
10338             jcta.vendor_site_id,
10339             jcta.tax_rate,
10340             jcta.tax_type,
10341             jcta.stform_type,
10342             jcta.tax_account_id,
10343             jcta.tax_id,   --Added tax_id by Chong for bug#16414088 20130320
10344             jcta.section_type
10345     from    jai_cmn_taxes_all      jcta
10346            ,jai_ap_tds_inv_taxes   jatit
10347            ,jai_ap_tds_thhold_trxs jattt
10348     where jatit.actual_tax_id = jcta.tax_id
10349     and   jatit.threshold_trx_id = jattt.threshold_trx_id
10350     and   jatit.threshold_grp_id = pn_threshold_grp_id
10351     and   jatit.threshold_slab_id_single is null
10352     and   jattt.tds_rollbacked is null
10353   --and   jcta.tax_account_id = cn_tax_account; --Change to tax_id by Chong for bug#16414088 20130320
10354     and   jcta.tax_id = cn_tax_id; --Change to tax_id by Chong for bug#16414088 20130320
10355 
10356   cursor c_gl_sets_of_books(cp_set_of_books_id  number) is
10357     select currency_code
10358     from   gl_sets_of_books
10359     where  set_of_books_id = cp_set_of_books_id;
10360 
10361   cursor c_get_ja_in_ap_inv_id is
10362     select to_char(JAI_AP_TDS_THHOLD_TRXS_S1.nextval)--to_char(JAI_AP_TDS_INVOICE_NUM_S.nextval)commented by  rchandan for bug#4487676
10363     from  dual;
10364 
10365   cursor c_ap_payment_schedules_all(p_invoice_id number) is
10366     select payment_priority
10367     from   ap_payment_schedules_all
10368     where  invoice_id = p_invoice_id;
10369 
10370   r_ap_invoices_all               c_ap_invoices_all%rowtype;
10371   r_ja_in_tax_codes               c_ja_in_tax_codes%rowtype;
10372   r_po_vendor_sites_all           c_po_vendor_sites_all%rowtype;
10373   r_po_vendors                    c_po_vendors%rowtype;
10374   r_gl_sets_of_books              c_gl_sets_of_books%rowtype;
10375   r_ap_payment_schedules_all      c_ap_payment_schedules_all%rowtype;
10376 
10377 
10378   lv_source                       varchar2(30); --File.Sql.35 Cbabu  := 'TDS';
10379 
10380   lv_invoice_to_tds_num           ap_invoices_all.invoice_num%type;
10381   lv_invoice_to_vendor_num        ap_invoices_all.invoice_num%type;
10382 
10383   lv_invoice_to_tds_type          ap_invoices_all.invoice_type_lookup_code%type;
10384   lv_invoice_to_vendor_type       ap_invoices_all.invoice_type_lookup_code%type;
10385 
10386   ln_invoice_to_tds_id            ap_invoices_all.invoice_id%type;
10387   ln_invoice_to_vendor_id         ap_invoices_all.invoice_id%type;
10388 
10389   ln_invoice_to_tds_line_id       ap_invoice_lines_interface.invoice_line_id%type;
10390   ln_invoice_to_vendor_line_id    ap_invoice_lines_interface.invoice_line_id%type;
10391 
10392   lv_invoice_to_tds_line_type     ap_invoice_distributions_all.line_type_lookup_code%type; --File.Sql.35 Cbabu  := 'ITEM';
10393   lv_invoice_to_vendor_line_type  ap_invoice_distributions_all.line_type_lookup_code%type; --File.Sql.35 Cbabu  := 'ITEM';
10394 
10395   ln_invoice_to_tds_amount        number;
10396   ln_invoice_to_vendor_amount     number;
10397 
10398   ln_exchange_rate                number;
10399   lv_this_procedure               varchar2(50); --File.Sql.35 Cbabu  := 'jaiap.generate_tds_invoice';
10400 
10401   ln_terms_id                     po_vendors.terms_id%type;
10402   -- lv_payment_method_lookup_code   po_vendors.payment_method_lookup_code%type; --commented by Sanjikum for Bug#4482462
10403   lv_pay_group_lookup_code        po_vendors.pay_group_lookup_code%type;
10404 
10405   lv_ja_in_ap_inv_id              varchar2(15);
10406   ld_accounting_date              date;
10407   lv_open_period                  ap_invoice_distributions_all.period_name%type;
10408   ln_tax_amount                   number;
10409 
10410   lv_invoice_num                  ap_invoices_all.invoice_num%type;
10411   lv_source_attribute             jai_ap_tds_invoices.source_attribute%TYPE ;   --rchandan for bug#4428980
10412 
10413   ln_invoice_amount               ap_invoices_all.invoice_amount%TYPE; --Added by Ramananda for Bug#4562801
10414 
10415    lv_group_id                     VARCHAR2(80); --Added by Sanjikum for Bug#5131075(4722011)
10416 
10417    /* Bug 5722028. Added by Lakshmi Gopalsami
10418    * Added following variables
10419    */
10420   ln_tds_rnded_amt      NUMBER;
10421   ln_tds_mod_value      NUMBER;
10422   ln_tds_rnding_factor  NUMBER;
10423 
10424   lv_section_name varchar2(10); --Added for Bug# 7410219
10425   pv_invoice_date   DATE;  --Added by Bgowrava for Bug#9186263
10426   ln_accts_pay_ccid NUMBER; -- Bug 9759709
10427 
10428   ln_count number;
10429   lv_stform_type  varchar2(30);
10430 
10431 
10432   ln_vendor_id      number;
10433   ln_vendor_site_id number;
10434   ln_tax_id_new     number;
10435 
10436   ln_vendor_inv_sum_amount number;
10437   ln_author_inv_sum_amount number;
10438   ln_amount_for_sub_au     number;
10439   ln_amount_for_sub_cm     number;
10440 
10441   --Get total amount of current group
10442   cursor get_total_amt
10443   is
10444   select nvl(sum(decode(jattt.tds_event,'PREPAYMENT APPLICATION',-jatit.tax_amount,jatit.tax_amount)),0)
10445   from  jai_ap_tds_inv_taxes jatit
10446        ,jai_ap_tds_thhold_trxs jattt
10447   where jatit.threshold_trx_id = jattt.threshold_trx_id
10448   and   jatit.threshold_grp_id = pn_threshold_grp_id
10449   and   jattt.tds_rollbacked is null
10450   and   jatit.threshold_slab_id_single is null;
10451 
10452   --get amount for a tax acount
10453   --cursor get_amt_for_tax_account(cn_tax_account jai_cmn_taxes_all.tax_account_id%type)
10454   cursor get_amt_for_tax_account(cn_tax_id jai_cmn_taxes_all.tax_id%type)--Change to tax_id by Chong for bug#16414088 20130320
10455   is
10456   select nvl(sum(decode(jattt.tds_event,'PREPAYMENT APPLICATION',-jatit.tax_amount,jatit.tax_amount)),0)
10457   from jai_ap_tds_inv_taxes   jatit
10458       ,jai_ap_tds_thhold_trxs jattt
10459       ,jai_cmn_taxes_all      jcta
10460   where jatit.threshold_trx_id = jattt.threshold_trx_id
10461   and   jatit.actual_tax_id = jcta.tax_id
10462   and   jatit.threshold_grp_id = pn_threshold_grp_id
10463   and   jatit.threshold_slab_id_single is null
10464   and   jattt.tds_rollbacked is null
10465   --and   jcta.tax_account_id = cn_tax_account
10466   and   jcta.tax_id = cn_tax_id
10467   ;
10468 
10469   ln_tax_amt_all      number;
10470 
10471   ln_amt_tax_code     number;
10472 
10473   ln_amt_for_each     number;
10474   ln_tax_amt_for_each number;
10475 
10476    ln_dbg_level   NUMBER         := FND_LOG.g_current_runtime_level;
10477    ln_proc_level  NUMBER         := FND_LOG.level_procedure;
10478    lv_proc_name   VARCHAR2 (100) := 'generate_rollback_dtc_invoices';
10479    l_api_name                   CONSTANT  VARCHAR2(50) := 'generate_rollback_dtc_invoices()';
10480 
10481 begin
10482 
10483   jai_cmn_utils_pkg.WRITE_FND_LOG(G_LEVEL_PROCEDURE, G_MODULE_NAME||l_api_name||'.BEGIN', G_PKG_NAME || ': '||l_api_name||'()+');
10484   lv_source                        := 'INDIA TDS'; /* --:= 'TDS'; --Ramanand for bug#4388958 */
10485   lv_invoice_to_tds_line_type     := 'ITEM';
10486   lv_invoice_to_vendor_line_type  := 'ITEM';
10487   lv_this_procedure               := 'jaiap.generate_dtc_invoice';
10488 
10489 
10490   if pn_threshold_grp_id is null then
10491     p_process_flag := 'X';
10492     p_process_message := 'When rollback threshold, pn_threshold_grp_id can''t be null ';
10493     goto exit_from_procedure;
10494   end if;
10495 
10496   /* Amount to be paid to TDS Authority should always be +ve */
10497   /* In case of prepayment application, this is still passed as +ve amount */
10498 
10499   /* Bug 4513458. added by Lakshmi Gopalsami
10500    * Removed the rounding and assigned the exact amount
10501    * and the rounding is handled at later point to
10502    * accommodate the currency code
10503   */
10504   --ln_tax_amount := round(pn_tax_amount, 2);
10505   ln_tax_amount := pn_tax_amount;
10506 
10507   /* Bug 4522507. Added by Lakshmi Gopalsami
10508      Checked whether round(ln_tax_amount) is less than
10509      zero instead of ln_tax_amount */
10510   if round(ln_tax_amount,2) <= 0 then
10511     p_process_flag := 'X';
10512     p_process_message := 'TDS amount must be greater than 0 ';
10513     goto exit_from_procedure;
10514   end if;
10515 
10516   open  c_ap_invoices_all(pn_invoice_id);
10517   fetch c_ap_invoices_all into r_ap_invoices_all;
10518   close c_ap_invoices_all;
10519 
10520 
10521   open  c_gl_sets_of_books(r_ap_invoices_all.set_of_books_id);
10522   fetch c_gl_sets_of_books into r_gl_sets_of_books;
10523   close c_gl_sets_of_books;
10524 
10525   /*Bug # 7410219 - Derive the Section Name*/
10526   if (pv_section_type = 'TDS_SECTION') then
10527      lv_section_name := 'TDS';
10528   elsif (pv_section_type = 'WCT_SECTION') then
10529      lv_section_name := 'WCT';
10530   elsif (pv_section_type = 'ESSI_SECTION') then
10531      lv_section_name := 'ESSI';
10532   end if;
10533   /*Bug # 7410219 - End*/
10534 
10535 
10536 
10537   /* Get the unique number to suffix the tds invoices with */
10538   open c_get_ja_in_ap_inv_id;
10539   fetch c_get_ja_in_ap_inv_id into lv_ja_in_ap_inv_id;
10540   close c_get_ja_in_ap_inv_id;
10541 
10542   lv_invoice_num := substr(r_ap_invoices_all.invoice_num, 1, 30);
10543 
10544  /*Only for threshold rollback*/
10545  if pv_tds_event like 'THRESHOLD ROLLBACK%' then
10546 
10547     lv_invoice_to_tds_type := 'CREDIT';
10548     lv_invoice_to_vendor_type := 'STANDARD';
10549     /*Bug 7410219 - Modified Invoice Number as per Section*/
10550     lv_invoice_to_tds_num     := lv_invoice_num ||'-RTN-'||lv_section_name||'-CM-'||lv_ja_in_ap_inv_id;
10551     lv_invoice_to_vendor_num  := lv_invoice_num ||'-RTN-'||lv_section_name||'-SI-'||lv_ja_in_ap_inv_id;
10552 
10553     ln_invoice_to_tds_amount :=  -1 * ln_tax_amount;
10554     ln_invoice_to_vendor_amount :=  ln_tax_amount;
10555 
10556   end if; /* TDS event type */
10557 
10558   pv_tds_invoice_num := lv_invoice_to_tds_num;
10559   pv_cm_invoice_num  := lv_invoice_to_vendor_num;
10560 
10561   /* Check if the given date is in current open period */
10562 
10563   /* Bug 4559756. Added by Lakshmi Gopalsami
10564      Added org_id to ap_utilities_pkg
10565   */
10566   lv_open_period:=  ap_utilities_pkg.get_current_gl_date
10567                                      (pd_accounting_date,
10568               r_ap_invoices_all.org_id
10569               );
10570 
10571   /* Bug 4559756. Added by Lakshmi Gopalsami
10572      Added org_id to ap_utilities_pkg
10573   */
10574 
10575   if lv_open_period is null then
10576 
10577     ap_utilities_pkg.get_open_gl_date
10578     (
10579       pd_accounting_date,
10580       lv_open_period,
10581       ld_accounting_date,
10582       r_ap_invoices_all.org_id
10583     );
10584 
10585     if lv_open_period is null then
10586       p_process_flag := 'E';
10587       p_process_message := 'No open accounting Period after : ' || pd_accounting_date ;
10588       goto exit_from_procedure;
10589     end if;
10590 
10591   else
10592     ld_accounting_date := pd_accounting_date;
10593   end if; /* ld_accounting_date */
10594 
10595 
10596   lv_group_id := to_char(pn_invoice_id);
10597   pv_invoice_date := r_ap_invoices_all.invoice_date;  --Added by Bgowrava for Bug#9186263
10598 
10599 
10600  -- ln_invoice_to_tds_amount := ROUND(ln_invoice_to_tds_amount,0);
10601  /* Bug 5722028. Added by csahoo
10602   * Rounded depending on the setup.
10603   */
10604   IF pv_tds_event NOT IN
10605     -- Bug 7280925. Commented by Lakshmi Gopalsami ('INVOICE CANCEL',
10606        ('PREPAYMENT UNAPPLICATION')
10607   THEN
10608    ln_invoice_to_tds_amount := ROUND(ln_invoice_to_tds_amount,jai_ap_dtc_generation_pkg.g_inr_currency_rounding);
10609     fnd_file.put_line(FND_FILE.LOG, ' Bug 7280925 - value before round '||ln_invoice_to_tds_amount);
10610     IF trunc(pd_creation_date) >= trunc(jai_ap_dtc_generation_pkg.gd_tds_rounding_effective_date)
10611           /* Bug 7280925. Added by Lakshmi Gopalsami
10612      * we should not round for WCT and ESSI. For those threshold_grp_id
10613      * will be null
10614      */
10615            and pn_threshold_grp_id is not null
10616     THEN
10617       ln_invoice_to_tds_amount := get_rnded_value(ln_invoice_to_tds_amount);
10618       IF ( ln_proc_level >= ln_dbg_level)
10619       THEN
10620 
10621              FND_LOG.STRING ( ln_proc_level
10622                             , GV_MODULE_PREFIX ||'.'|| lv_proc_name
10623                             , 'value after round per setup TDS auth inv' || ln_invoice_to_tds_amount
10624                             );
10625 
10626       END IF; --( ln_proc_level >= ln_dbg_level)  ;
10627       --fnd_file.put_line(FND_FILE.LOG, ' Bug 7280925 - value after round per setup TDS auth inv'||ln_invoice_to_tds_amount);
10628     END IF;
10629   END IF ; -- pv_tds_event  not in
10630   if lv_invoice_to_vendor_num is not null and lv_invoice_to_vendor_type is not null then
10631 
10632              IF pv_tds_event = 'PREPAYMENT UNAPPLICATION' THEN  --2
10633                IF r_ap_invoices_all.invoice_currency_code <> r_gl_sets_of_books.currency_code  THEN --3
10634                     ln_invoice_to_vendor_amount := round( ln_invoice_to_vendor_amount, g_inr_currency_rounding);
10635                     IF trunc(pd_creation_date) >= trunc(jai_ap_dtc_generation_pkg.gd_tds_rounding_effective_date) THEN
10636                         ln_invoice_to_vendor_amount := get_rnded_value(ln_invoice_to_vendor_amount);
10637                     END IF;
10638                     ln_invoice_to_vendor_amount := round( ln_invoice_to_vendor_amount / r_ap_invoices_all.exchange_rate, g_fcy_currency_rounding);
10639                END IF;  --3
10640 
10641             ELSE --2
10642 
10643                if r_ap_invoices_all.invoice_currency_code <> r_gl_sets_of_books.currency_code  then
10644                   /*START, Bgowrava for Bug#8995604 , Adding below IF statement to round the INR TDS CM invoice to
10645                   the TDS rounding factor before converting it to a foreign currency CM*/
10646                     ln_invoice_to_vendor_amount := round( ln_invoice_to_vendor_amount, g_inr_currency_rounding);
10647                     IF trunc(pd_creation_date) >= trunc(jai_ap_dtc_generation_pkg.gd_tds_rounding_effective_date)
10648                          and pn_threshold_grp_id is not null THEN
10649 
10650                          ln_invoice_to_vendor_amount := get_rnded_value(ln_invoice_to_vendor_amount);
10651                     END IF;
10652                     /*END, Bgowrava for Bug#8995604 */
10653                     ln_invoice_to_vendor_amount := round( ln_invoice_to_vendor_amount / r_ap_invoices_all.exchange_rate, g_fcy_currency_rounding);
10654                ELSE
10655                     ln_invoice_to_vendor_amount := round( ln_invoice_to_vendor_amount, g_inr_currency_rounding);
10656                     /*START, Bgowrava for Bug#8995604 , Adding below IF statement to round the INR TDS CM invoice to   the TDS rounding factor*/
10657                     IF trunc(pd_creation_date) >= trunc(jai_ap_dtc_generation_pkg.gd_tds_rounding_effective_date)
10658                         and pn_threshold_grp_id is not null THEN
10659 
10660                         ln_invoice_to_vendor_amount := get_rnded_value(ln_invoice_to_vendor_amount);
10661                     END IF;
10662                     /*END, Bgowrava for Bug#8995604 */
10663 
10664                END IF; --2
10665             END IF;
10666             IF ( ln_proc_level >= ln_dbg_level)
10667             THEN
10668 
10669                    FND_LOG.STRING ( ln_proc_level
10670                                   , GV_MODULE_PREFIX ||'.'|| lv_proc_name
10671                                   , 'value before round ' || ln_invoice_to_vendor_amount
10672                                   );
10673 
10674             END IF;
10675 
10676               if upper(r_ap_invoices_all.exchange_rate_type) = 'USER' then
10677                 ln_exchange_rate := r_ap_invoices_all.exchange_rate;
10678             else
10679                 ln_exchange_rate := null;
10680             end if;
10681 
10682             IF ( ln_proc_level >= ln_dbg_level)
10683             THEN
10684 
10685                    FND_LOG.STRING ( ln_proc_level
10686                                   , GV_MODULE_PREFIX ||'.'|| lv_proc_name
10687                                   , ' CALL utils for inserting interface lines' || ''
10688                                   );
10689 
10690             END IF; --( ln_proc_level >= ln_dbg_level)  ;
10691             --fnd_file.put_line(FND_FILE.LOG, ' CALL utils for inserting interface lines');
10692 
10693             /*Bug 9759709 - Liability Account for the Credit Note must be fetched from the Standard Invoice
10694             If it is not present, then it needs to be defaulted from Vendor Site Setup. Passing NULL to
10695             parameter p_accts_pay_ccid in jai_ap_utils_pkg.insert_ap_inv_interface would cause it to default
10696             from setup*/
10697             if (r_ap_invoices_all.accts_pay_code_combination_id is not NULL) then
10698                ln_accts_pay_ccid := r_ap_invoices_all.accts_pay_code_combination_id;
10699             else
10700                ln_accts_pay_ccid := NULL;
10701             end if;
10702     end if;
10703     /**Create tds invoice for authority*/
10704     ln_count := 0;
10705 
10706     ln_author_inv_sum_amount := 0;
10707     ln_vendor_inv_sum_amount := 0;
10708     ln_amount_for_sub_au     := 0;
10709     ln_amount_for_sub_cm     := 0;
10710     --Get total amount(without rounding amount) from inv_taxes table
10711     open get_total_amt;
10712     fetch get_total_amt into ln_tax_amt_all;
10713     close get_total_amt;
10714 
10715     for rec_tax in (
10716         --select distinct jcta.tax_account_id
10717         select distinct jcta.tax_id        --Change to tax_id by Chong for bug#16414088 20130320
10718         from   jai_ap_tds_inv_taxes   jatit
10719               ,jai_ap_tds_thhold_trxs jattt
10720               ,jai_cmn_taxes_all      jcta
10721         where jattt.threshold_trx_id = jatit.threshold_trx_id
10722         and   jatit.actual_tax_id = jcta.tax_id
10723         and   jattt.tds_rollbacked is null
10724         and   jattt.threshold_grp_id = pn_threshold_grp_id
10725         and   jatit.threshold_slab_id_single is null
10726      )
10727      loop
10728          ln_count := ln_count + 1;
10729 
10730 
10731          if lv_invoice_to_tds_num is not null and lv_invoice_to_tds_type is not null and NVL(ln_invoice_to_tds_amount,0) <> 0 then
10732 
10733                /*There is only one authority verdor for each TDS group. Get any one from this group*/
10734              --open  c_ja_in_tax_codes(rec_tax.tax_account_id);
10735                open  c_ja_in_tax_codes(rec_tax.tax_id); --Change to tax_id by Chong for bug#16414088 20130320
10736                fetch c_ja_in_tax_codes into r_ja_in_tax_codes;
10737                close c_ja_in_tax_codes;
10738 
10739                if(ln_count = 1)then
10740 
10741                    ln_vendor_id      := r_ja_in_tax_codes.vendor_id;
10742                    ln_vendor_site_id := r_ja_in_tax_codes.vendor_site_id;
10743 
10744                    lv_stform_type := r_ja_in_tax_codes.stform_type;
10745 
10746                    open c_po_vendors(r_ja_in_tax_codes.vendor_id);
10747                    fetch c_po_vendors into r_po_vendors;
10748                    close c_po_vendors;
10749 
10750 
10751                    open  c_po_vendor_sites_all(r_ja_in_tax_codes.vendor_id, r_ja_in_tax_codes.vendor_site_id);
10752                    fetch c_po_vendor_sites_all into r_po_vendor_sites_all;
10753                    close c_po_vendor_sites_all;
10754 
10755 
10756                    ln_terms_id := r_po_vendor_sites_all.terms_id;
10757                    lv_pay_group_lookup_code      := r_po_vendor_sites_all.pay_group_lookup_code;
10758 
10759 
10760                    if ((ln_terms_id is null) or (lv_pay_group_lookup_code is null))then
10761 
10762                        ln_terms_id                   := r_po_vendors.terms_id;
10763                        lv_pay_group_lookup_code      := r_po_vendors.pay_group_lookup_code;
10764 
10765                    end if;
10766 
10767 
10768                       jai_ap_utils_pkg.insert_ap_inv_interface
10769                       (
10770                         p_jai_source                        => lv_this_procedure,
10771                         p_invoice_id                        => ln_invoice_to_tds_id,
10772                         p_invoice_num                       => lv_invoice_to_tds_num,
10773                         p_invoice_type_lookup_code          => lv_invoice_to_tds_type,
10774                         p_invoice_date                      => ld_accounting_date,  --Bug 10020606 - Replaced Base Supplier Invoice Date with GL Date
10775                         p_gl_date                           => ld_accounting_date, --Added by Bgowrava for Bug#9186263
10776                         p_vendor_id                         => ln_vendor_id,
10777                         p_vendor_site_id                    => ln_vendor_site_id,
10778                         p_invoice_amount                    => ln_invoice_to_tds_amount,
10779                         p_invoice_currency_code             => r_gl_sets_of_books.currency_code,
10780                         p_exchange_rate                     => null,
10781                         p_exchange_rate_type                => null,
10782                         p_exchange_date                     => null,
10783                         p_terms_id                          => ln_terms_id,
10784                         p_description                       => lv_invoice_to_tds_num,
10785                         p_last_update_date                  => sysdate,
10786                         p_last_updated_by                   => fnd_global.user_id,
10787                         p_last_update_login                 => fnd_global.login_id,
10788                         p_creation_date                     => sysdate,
10789                         p_created_by                        => fnd_global.user_id,
10790                         p_source                            => lv_source,
10791                         p_voucher_num                       => lv_invoice_to_tds_num,
10792                         p_pay_group_lookup_code             => lv_pay_group_lookup_code,
10793                         p_org_id                            => r_ap_invoices_all.org_id,
10794                         p_attribute_category                => 'India Original Invoice for TDS',
10795                         p_group_id                          => lv_group_id,
10796 			p_Calc_Tax_During_Import_Flag       => 'Y'   --Added by Qiong for AP Open Interface
10797                       );
10798               end if;
10799               /* Line Interface */
10800             --open get_amt_for_tax_account(rec_tax.tax_account_id);
10801               open get_amt_for_tax_account(rec_tax.tax_id);  --Change to tax_id by Chong for bug#16414088 20130320
10802               fetch get_amt_for_tax_account into ln_amt_tax_code;
10803               close get_amt_for_tax_account;
10804 
10805               ln_tax_amt_for_each := round(ln_invoice_to_tds_amount * ln_amt_tax_code/ln_tax_amt_all,g_inr_currency_rounding);
10806 
10807               jai_ap_utils_pkg.insert_ap_inv_lines_interface
10808               (
10809                 p_jai_source                        => lv_this_procedure,
10810                 p_invoice_id                        => ln_invoice_to_tds_id,
10811                 p_invoice_line_id                   => ln_invoice_to_tds_line_id,
10812                 p_line_number                       => ln_count,
10813                 p_line_type_lookup_code             => lv_invoice_to_tds_line_type,
10814                 p_amount                            => ln_tax_amt_for_each,
10815                 p_accounting_date                   => ld_accounting_date,
10816               --p_description                       => lv_invoice_to_tds_num ||'/'||pv_section_type||'/'||pv_section_code||'/'||rec_tax.tax_account_id,
10817                 p_description                       => lv_invoice_to_tds_num  ||'/'||pv_section_type||'/'||pv_section_code||'/'||r_ja_in_tax_codes.tax_type||'/'||r_ja_in_tax_codes.tax_id||'/'||r_ja_in_tax_codes.tax_rate,
10818                 p_dist_code_combination_id          => r_ja_in_tax_codes.tax_account_id, --rec_tax.tax_account_id, --Change by Chong for bug#16414088 20130320
10819                 p_last_update_date                  => sysdate,
10820                 p_last_updated_by                   => fnd_global.user_id,
10821                 p_last_update_login                 => fnd_global.login_id,
10822                 p_creation_date                     => sysdate,
10823                 p_created_by                        => fnd_global.user_id
10824               );
10825 
10826               --ln_author_inv_sum_amount := ln_author_inv_sum_amount + ln_tax_amt_for_each;
10827               if (ln_count <> 1) then
10828                 ln_amount_for_sub_au := ln_amount_for_sub_au + ln_tax_amt_for_each;
10829               end if;
10830          end if; /* Invoice to TDS authority */
10831 
10832 
10833            /**Create tds invoice for vendor*/
10834          if lv_invoice_to_vendor_num is not null and lv_invoice_to_vendor_type is not null then
10835 
10836             IF ( ln_proc_level >= ln_dbg_level)
10837             THEN
10838 
10839                    FND_LOG.STRING ( ln_proc_level
10840                                   , GV_MODULE_PREFIX ||'.'|| lv_proc_name
10841                                   , 'value before round ' || ln_invoice_to_vendor_amount
10842                                   );
10843 
10844             END IF; --( ln_proc_level >= ln_dbg_level)  ;
10845             --fnd_file.put_line(FND_FILE.LOG, ' Bug 7280925 - value before round '||ln_invoice_to_vendor_amount);
10846 
10847             IF ( ln_proc_level >= ln_dbg_level)
10848             THEN
10849 
10850                    FND_LOG.STRING ( ln_proc_level
10851                                   , GV_MODULE_PREFIX ||'.'|| lv_proc_name
10852                                   , ' CALL utils for inserting interface lines' || ''
10853                                   );
10854 
10855             END IF; --( ln_proc_level >= ln_dbg_level)  ;
10856             --fnd_file.put_line(FND_FILE.LOG, ' CALL utils for inserting interface lines');
10857 
10858             IF NVL(ln_invoice_to_vendor_amount,0) <> 0 THEN
10859 
10860             /*Bug 9759709 - Liability Account for the Credit Note must be fetched from the Standard Invoice
10861             If it is not present, then it needs to be defaulted from Vendor Site Setup. Passing NULL to
10862             parameter p_accts_pay_ccid in jai_ap_utils_pkg.insert_ap_inv_interface would cause it to default
10863             from setup*/
10864                 /*there will be only one liability Account in one threshold group*/
10865                 if (r_ap_invoices_all.accts_pay_code_combination_id is not NULL) then
10866                    ln_accts_pay_ccid := r_ap_invoices_all.accts_pay_code_combination_id;
10867                 else
10868                    ln_accts_pay_ccid := NULL;
10869                 end if;
10870                       /* Invoices Interface */
10871                   if(ln_count = 1)then
10872                       jai_ap_utils_pkg.insert_ap_inv_interface
10873                       (
10874                         p_jai_source                        => lv_this_procedure,
10875                         p_invoice_id                        => ln_invoice_to_vendor_id,
10876                         p_invoice_num                       => lv_invoice_to_vendor_num,
10877                         p_invoice_type_lookup_code          => lv_invoice_to_vendor_type,
10878                         p_invoice_date                      => pv_invoice_date,--r_ap_invoices_all.invoice_date,  --Modified to ld_accounting_date for Bug#9186263
10879                         p_gl_date                           => ld_accounting_date,
10880                         p_vendor_id                         => r_ap_invoices_all.vendor_id,
10881                         p_vendor_site_id                    => r_ap_invoices_all.vendor_site_id,
10882                         p_invoice_amount                    => ln_invoice_to_vendor_amount,
10883                         p_invoice_currency_code             => r_ap_invoices_all.invoice_currency_code,
10884                         p_exchange_rate                     => NULL,    --ln_exchange_rate,
10885                         p_exchange_rate_type                => r_ap_invoices_all.exchange_rate_type,
10886                         p_exchange_date                     => r_ap_invoices_all.exchange_date,
10887                         p_terms_id                          => r_ap_invoices_all.terms_id,
10888                         p_description                       => lv_invoice_to_vendor_num,
10889                         p_last_update_date                  => sysdate,
10890                         p_last_updated_by                   => fnd_global.user_id,
10891                         p_last_update_login                 => fnd_global.login_id,
10892                         p_creation_date                     => sysdate,
10893                         p_created_by                        => fnd_global.user_id,
10894                         p_source                            => lv_source,
10895                         p_voucher_num                       => lv_invoice_to_vendor_num,
10896                         p_payment_method_code               => r_ap_invoices_all.payment_method_code,
10897                         p_pay_group_lookup_code             => r_ap_invoices_all.pay_group_lookup_code,
10898                         p_goods_received_date               => r_ap_invoices_all.goods_received_date,
10899                         p_invoice_received_date             => r_ap_invoices_all.invoice_received_date,
10900                         p_org_id                            => r_ap_invoices_all.org_id,
10901                         p_attribute_category                => 'India Original Invoice for TDS',
10902                         p_group_id                          => lv_group_id,
10903                         p_accts_pay_ccid                    => ln_accts_pay_ccid,
10904 			p_Calc_Tax_During_Import_Flag       => 'Y'   --Added by Qiong for AP Open Interface
10905                       );
10906                     end if;
10907 
10908                 /* Lines Interface */
10909                 ln_amt_for_each := round(ln_invoice_to_vendor_amount * ln_amt_tax_code/ln_tax_amt_all,g_inr_currency_rounding);
10910 
10911 
10912                 jai_ap_utils_pkg.insert_ap_inv_lines_interface
10913                 (
10914                   p_jai_source                        => lv_this_procedure,
10915                   p_invoice_id                        => ln_invoice_to_vendor_id,
10916                   p_invoice_line_id                   => ln_invoice_to_vendor_line_id,
10917                   p_line_number                       => ln_count,
10918                   p_line_type_lookup_code             => lv_invoice_to_vendor_line_type,
10919                   p_amount                            => ln_amt_for_each,
10920                   p_accounting_date                   => ld_accounting_date,
10921                 --p_description                       => lv_invoice_to_vendor_num ||'/'||pv_section_type||'/'||pv_section_code||'/'||rec_tax.tax_account_id,
10922                   p_description                       => lv_invoice_to_vendor_num ||'/'||pv_section_type||'/'||pv_section_code||'/'||r_ja_in_tax_codes.tax_type||'/'||r_ja_in_tax_codes.tax_id||'/'||r_ja_in_tax_codes.tax_rate,
10923                   p_dist_code_combination_id          => r_ja_in_tax_codes.tax_account_id, --rec_tax.tax_account_id, --Change by Chong for bug#16414088 20130320
10924                   p_last_update_date                  => sysdate,
10925                   p_last_updated_by                   => fnd_global.user_id,
10926                   p_last_update_login                 => fnd_global.login_id,
10927                   p_creation_date                     => sysdate,
10928                   p_created_by                        => fnd_global.user_id
10929                 );
10930                 --ln_vendor_inv_sum_amount := ln_vendor_inv_sum_amount  + ln_amt_for_each;
10931 
10932                 if (ln_count <> 1) then
10933                   ln_amount_for_sub_cm := ln_amount_for_sub_cm + ln_amt_for_each;
10934                 end if;
10935             END IF;
10936 
10937 
10938          end if; /* Invoice to Supplier */
10939 
10940 
10941      end loop;
10942 
10943      if lv_invoice_to_tds_num is not null and lv_invoice_to_tds_type is not null and NVL(ln_invoice_to_tds_amount,0) <> 0 then
10944 
10945         update ap_invoice_lines_interface
10946         set    amount = round(ln_invoice_to_tds_amount - ln_amount_for_sub_au , g_inr_currency_rounding)
10947         where  invoice_id = ln_invoice_to_tds_id
10948         and    line_number = 1;
10949      end if;
10950      if lv_invoice_to_vendor_num is not null and lv_invoice_to_vendor_type is not null and NVL(ln_invoice_to_vendor_amount,0) <> 0  then
10951 
10952         update ap_invoice_lines_interface
10953         set    amount = round(ln_invoice_to_vendor_amount - ln_amount_for_sub_cm , g_inr_currency_rounding)
10954         where  invoice_id = ln_invoice_to_vendor_id
10955         and    line_number = 1;
10956 
10957      end if;
10958 
10959 
10960     /* Store the parent invoices payment priority as this is to be used in the credit memo generated for the supplier */
10961     open  c_ap_payment_schedules_all(r_ap_invoices_all.invoice_id);
10962     fetch c_ap_payment_schedules_all  into r_ap_payment_schedules_all;
10963     close c_ap_payment_schedules_all;
10964 
10965 
10966     /* Bug 5751783
10967      * Moved the assignment of ln_invoice_amount outside IF as this is used
10968      * in the insert to jai_ap_tds_thhold_trxs. This has to be derived irrespective
10969      * of the tds event.
10970      */
10971 
10972     --Fnd_File.put_line(Fnd_File.LOG,  'pn_taxable_amount '||pn_taxable_amount);
10973     /*IF pn_taxable_amount IS NOT NULL THEN
10974        ln_invoice_amount :=  pn_taxable_amount;
10975     ELSE*/ /*Commented the above if condition for bug 13070779 */
10976 --       ln_invoice_amount := pn_tax_amount * ( 100 / r_ja_in_tax_codes.tax_rate);
10977    -- END IF;
10978     --fnd_file.put_line(FND_FILE.LOG, ' invoice amount'|| ln_invoice_amount);
10979     IF ( ln_proc_level >= ln_dbg_level)
10980     THEN
10981 
10982            FND_LOG.STRING ( ln_proc_level
10983                           , GV_MODULE_PREFIX ||'.'|| lv_proc_name
10984                           , 'pn_taxable_amount ' || pn_taxable_amount
10985                           );
10986            FND_LOG.STRING ( ln_proc_level
10987                           , GV_MODULE_PREFIX ||'.'|| lv_proc_name
10988                           , 'ln_vendor_inv_sum_amount ' || ln_vendor_inv_sum_amount
10989                           );
10990     END IF; --( ln_proc_level >= ln_dbg_level)  ;
10991 
10992 
10993     -- Bug 5722028. Added by csahoo
10994   ln_tds_rnding_factor := 0;
10995   ln_tds_rnded_amt := pn_tax_amount;
10996   /* Added the below if condition for bug 12965614 */
10997   IF pv_tds_event = 'PREPAYMENT UNAPPLICATION' THEN  --2
10998         IF r_ap_invoices_all.invoice_currency_code <>  r_gl_sets_of_books.currency_code THEN  --3
10999        ln_tds_rnded_amt := ROUND(pn_calc_tax_amount , jai_ap_dtc_generation_pkg.g_inr_currency_rounding);
11000        IF (trunc(pd_creation_date) >= trunc(jai_ap_dtc_generation_pkg.gd_tds_rounding_effective_date)) THEN  --4
11001               ln_tds_rnding_factor := jai_ap_dtc_generation_pkg.gn_tds_rounding_factor;
11002               ln_tds_rnded_amt := get_rnded_value(ln_tds_rnded_amt);
11003             END IF; --4
11004        ln_tds_rnded_amt := ROUND(pn_calc_tax_amount / r_ap_invoices_all.exchange_rate, g_fcy_currency_rounding);
11005 
11006       END IF; --3
11007        ELSE --2
11008   /*IF pv_tds_event NOT IN
11009      -- Bug 7280925. commented by Lakshmi Gopalsami ('INVOICE CANCEL',
11010       ('PREPAYMENT UNAPPLICATION') THEN */
11011        IF r_ap_invoices_all.invoice_currency_code = r_gl_sets_of_books.currency_code THEN
11012       ln_tds_rnded_amt := ROUND(pn_tax_amount , jai_ap_dtc_generation_pkg.g_inr_currency_rounding);
11013       --moved this if-endif block from below to here for bug#8995604
11014      ELSE
11015      ln_tds_rnded_amt := ROUND(pn_tax_amount , jai_ap_dtc_generation_pkg.g_inr_currency_rounding);
11016         IF (trunc(pd_creation_date) >=
11017        trunc(jai_ap_dtc_generation_pkg.gd_tds_rounding_effective_date)
11018            /* Bug 7280925. Added by Lakshmi Gopalsami
11019       * we should not round for WCT and ESSI. For those threshold_grp_id
11020       * will be null
11021       */
11022             and pn_threshold_grp_id is not null )
11023       THEN
11024      ln_tds_rnding_factor := jai_ap_dtc_generation_pkg.gn_tds_rounding_factor;
11025      ln_tds_rnded_amt := get_rnded_value(ln_tds_rnded_amt);
11026           --fnd_file.put_line(FND_FILE.LOG, ' Bug 7280925 - value after round before insert into trxs'||ln_tds_rnded_amt);
11027       END IF;
11028       ln_tds_rnded_amt := ROUND(pn_tax_amount / r_ap_invoices_all.exchange_rate, g_fcy_currency_rounding);
11029      END IF ;
11030            --fnd_file.put_line(FND_FILE.LOG, ' Bug 7280925 - value before round '||ln_tds_rnded_amt);
11031 
11032   END IF;
11033      -- End for bug 5722028.
11034 
11035     insert into jai_ap_tds_thhold_trxs
11036     (
11037       threshold_trx_id                               ,
11038       invoice_id                                     ,
11039       invoice_line_number                            ,
11040       invoice_distribution_id                        ,
11041       threshold_grp_id                               ,
11042       threshold_hdr_id                               ,
11043       tds_event                                      ,
11044       tax_category_id                                ,
11045       taxable_amount                                 ,
11046       tax_amount                                     ,
11047       tds_authority_vendor_id                        ,
11048       tds_authority_vendor_site_id                   ,
11049       invoice_to_tds_authority_num                   ,
11050       invoice_to_tds_authority_type                  ,
11051       invoice_to_tds_authority_curr                  ,
11052       invoice_to_tds_authority_amt                   ,
11053       vendor_id                                      ,
11054       vendor_site_id                                 ,
11055       invoice_to_vendor_num                          ,
11056       invoice_to_vendor_type                         ,
11057       invoice_to_vendor_curr                         ,
11058       invoice_to_vendor_amt                          ,
11059       parent_inv_payment_priority                    ,
11060       parent_inv_exchange_rate                       ,
11061       created_by                                     ,
11062       creation_date                                  ,
11063       last_updated_by                                ,
11064       last_update_date                               ,
11065       last_update_login                               ,
11066       calc_tax_amount                                , /*Bug 5751783*/
11067       tds_rounding_factor,
11068       TDS_SECTION_CODE
11069     )
11070     values
11071     (
11072       jai_ap_tds_thhold_trxs_s.nextval               ,
11073       pn_invoice_id                                  ,
11074       NULL                                           ,
11075       NULL                                           ,
11076       pn_threshold_grp_id                            ,
11077       --NULL                                           ,
11078       pn_threshold_hdr_id,  --Added by Chong for bug#16414088 20130320
11079       pv_tds_event                                   ,
11080       NULL                             ,
11081       pn_taxable_amount,--ln_invoice_amount  --UPdate by Zhiwei Hou on 20120111                                ,
11082       ln_tds_rnded_amt,  --Bug 5722028. Added by csahoo
11083       ln_vendor_id                    ,
11084       ln_vendor_site_id               ,
11085       lv_invoice_to_tds_num                          ,
11086       lv_invoice_to_tds_type                         ,
11087       r_gl_sets_of_books.currency_code               ,
11088       ln_invoice_to_tds_amount                       ,
11089       r_ap_invoices_all.vendor_id                    ,
11090       r_ap_invoices_all.vendor_site_id               ,
11091       lv_invoice_to_vendor_num                       ,
11092       lv_invoice_to_vendor_type                      ,
11093       r_ap_invoices_all.invoice_currency_code        ,
11094       ln_invoice_to_vendor_amount                    ,
11095       r_ap_payment_schedules_all.payment_priority    ,
11096       r_ap_invoices_all.exchange_rate                ,
11097       fnd_global.user_id                             ,
11098       sysdate                                        ,
11099       fnd_global.user_id                             ,
11100       sysdate                                        ,
11101       fnd_global.login_id                         ,
11102       decode ( pv_tds_event, 'PREPAYMENT UNAPPLICATION', pn_calc_tax_amount, pn_tax_amount), /*Added decode condition for bug 12965614 */ /*Bug 5751783*/
11103       ln_tds_rnding_factor,
11104       pv_section_code
11105     )
11106     returning threshold_trx_id into pn_threshold_trx_id;
11107 
11108     <<exit_from_procedure>>
11109     jai_cmn_utils_pkg.WRITE_FND_LOG(G_LEVEL_PROCEDURE, G_MODULE_NAME||l_api_name||'.END', G_PKG_NAME || ': '||l_api_name||'()-');
11110       return;
11111 
11112     exception
11113       when others then
11114         p_process_flag := 'E';
11115         p_process_message := 'Error from jai_ap_dtc_generation_pkg.generate_rollback_dtc_invoices :' || sqlerrm;
11116 
11117   end generate_rollback_dtc_invoices;
11118 
11119 
11120 --Added by Chong.Lei for DTC ER #13359892 on 20120212 end
11121 	  FUNCTION get_rnded_value (p_tax_amount in number)
11122 	  RETURN NUMBER AS
11123 	   ln_tmp_tax_amt number ;
11124 	   ln_tds_mod_value number ;
11125 	   ln_tds_sign number;
11126 	  BEGIN
11127 	   ln_tds_sign := sign(p_tax_amount);
11128 	   ln_tmp_tax_amt := abs(p_tax_amount);
11129 
11130     IF jai_ap_dtc_generation_pkg.gn_tds_rounding_factor = -1 then
11131 	    ln_tds_mod_value := 0;
11132 	    ln_tds_mod_value := MOD(ROUND(ln_tmp_tax_amt,
11133 	                                   g_inr_currency_rounding),10);
11134 	    IF ln_tds_mod_value >= 5 THEN
11135 	      ln_tmp_tax_amt := ln_tmp_tax_amt + (10-ln_tds_mod_value);
11136 	    ELSE -- < 5
11137 	      ln_tmp_tax_amt := ln_tmp_tax_amt - ln_tds_mod_value;
11138 	    END IF ;
11139 	  END IF ; -- jai_ap_tds_generation_pkg.gn_tds_rounding_factor = -1
11140 	  return (ln_tmp_tax_amt* ln_tds_sign );
11141 	  END get_rnded_value;
11142   -- End for bug 5722028.
11143 
11144 
11145 END jai_ap_dtc_generation_pkg;