DBA Data[Home] [Help]

PACKAGE BODY: APPS.IBY_TRANSACTIONCC_PKG

Source


1 PACKAGE BODY iby_transactioncc_pkg AS
2 /*$Header: ibytxccb.pls 120.99.12020000.3 2012/10/04 16:42:44 dhati ship $*/
3 
4   --
5   -- Declare global variables
6   --
7   G_CURRENT_RUNTIME_LEVEL      CONSTANT NUMBER       := FND_LOG.G_CURRENT_RUNTIME_LEVEL;
8 G_LEVEL_STATEMENT            CONSTANT NUMBER       := FND_LOG.LEVEL_STATEMENT;
9   G_PKG_NAME CONSTANT VARCHAR2(30) := 'IBY_TRANSACTIONCC_PKG';
10   G_DEBUG_MODULE CONSTANT VARCHAR2(100) := 'iby.plsql.IBY_TRANSACTIONCC_PKG';
11 
12   --
13   -- USE: Validates the current open batch for the given (payee,bep,bep key)
14   --      combination.  This involves making sure: 1) the batch contains
15   --      at least one trxn, 2) a payee security key is present if the
16   --      batch contains encrypted trxns, 3) the batch contains trxns of
17   --      only a single currency
18   --
19   PROCEDURE validate_open_batch
20   (
21   p_bep_id           IN     iby_trxn_summaries_all.bepid%TYPE,
22   p_mbatch_id        IN     iby_batches_all.mbatchid%TYPE,
23   p_sec_key_on       IN     VARCHAR2,
24   x_trxn_count       OUT NOCOPY iby_batches_all.numtrxns%TYPE,
25   x_batch_currency   OUT NOCOPY iby_batches_all.currencynamecode%TYPE
26   )
27   IS
28     l_sec_trxn_count     NUMBER;
29     l_batch_currency     iby_trxn_summaries_all.currencynamecode%TYPE;
30 
31     l_call_string        VARCHAR2(1000);
32     l_call_params        JTF_VARCHAR2_TABLE_200 := JTF_VARCHAR2_TABLE_200();
33     l_return_status      VARCHAR2(10);
34     l_msg_count          NUMBER;
35     l_msg_data           VARCHAR2(5000);
36 
37     CURSOR c_currencycodes(ci_mbatch_id IN iby_batches_all.mbatchid%TYPE)
38     IS
39       SELECT ts.currencynamecode
40         FROM iby_batches_all ba, iby_trxn_summaries_all ts
41         WHERE (ba.mbatchid = ci_mbatch_id)
42           AND (ba.payeeid = ts.payeeid)
43           AND (ba.batchid = ts.batchid)
44         GROUP BY ts.currencynamecode;
45 
46     CURSOR c_valsets(ci_bep_id iby_trxn_summaries_all.bepid%TYPE)
47     IS
48       SELECT validation_code_package, validation_code_entry_point
49       FROM iby_validation_sets_b vs, iby_fndcpt_sys_cc_pf_b pf,
50         iby_val_assignments va
51       WHERE (vs.validation_code_language = 'PLSQL')
52         AND (vs.validation_level_code = 'INSTRUCTION' )
53         AND (pf.payment_system_id = ci_bep_id)
54         AND (pf.settlement_format_code = va.assignment_entity_id)
55         AND (va.val_assignment_entity_type = 'FORMAT')
56         AND (va.validation_set_code = vs.validation_set_code)
57         AND (NVL(va.inactive_date,SYSDATE-100) < SYSDATE);
58 
59   BEGIN
60 
61     IF (c_currencycodes%ISOPEN) THEN
62       CLOSE c_currencycodes;
63     END IF;
64 
65     --
66     -- first check if any encrypted trxns exist in the batch;
67     -- if so, then the security key must be present for the batch
68     -- close to continue
69     --
70     SELECT COUNT(transactionid)
71       INTO l_sec_trxn_count
72       FROM iby_batches_all ba, iby_trxn_summaries_all ts
73       WHERE (ba.mbatchid = p_mbatch_id)
74         AND (ba.payeeid = ts.payeeid)
75         AND (ba.batchid = ts.batchid)
76         AND (NOT sub_key_id IS NULL);
77 
78      IF ( (l_sec_trxn_count>0) AND
79           (p_sec_key_on<>iby_utility_pvt.C_API_YES) ) THEN
80        raise_application_error(-20000,'IBY_10002',FALSE);
81      END IF;
82 
83      IF ( G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
84 	     print_debuginfo('validate_ob', 'p_mbatch_id = ' || p_mbatch_id);
85 
86      END IF;
87     SELECT COUNT(transactionid)
88       INTO x_trxn_count
89       FROM iby_batches_all ba, iby_trxn_summaries_all ts
90       WHERE (ba.mbatchid = p_mbatch_id)
91         AND (ba.payeeid = ts.payeeid)
92         AND (ba.batchid = ts.batchid);
93      --
94      -- batch cannot be empty
95      --
96      IF (x_trxn_count<1) THEN
97        raise_application_error(-20000,'IBY_50314',FALSE);
98      END IF;
99 /* Multiple currencies may be allowed in the same batch*/
100 --     OPEN c_currencycodes(p_mbatch_id);
101 
102 --     FETCH c_currencycodes INTO x_batch_currency;
103 --     FETCH c_currencycodes INTO l_batch_currency;
104      --
105      -- 2nd successful fetch indicates multiple currencies are in the batch
106      --
107 --     IF (NOT c_currencycodes%NOTFOUND) THEN
108 --       CLOSE c_currencycodes;
109 --       raise_application_error(-20000,'IBY_20213',FALSE);
110 --     ELSE
111 --       CLOSE c_currencycodes;
112 --     END IF;
113 
114      -- perform payment format specific validations
115      --
116      l_call_params.extend(6);
117      l_call_params(1) := '1';
118      l_call_params(2) := '''' || FND_API.G_TRUE || '''';
119      l_call_params(3) := TO_CHAR(p_mbatch_id);
120      l_call_params(4) := '';
121      l_call_params(5) := '';
122      l_call_params(6) := '';
123 
124      FOR cp IN c_valsets(p_bep_id) LOOP
125        l_call_string :=
126          iby_utility_pvt.get_call_exec(cp.validation_code_package,
127                                        cp.validation_code_entry_point,
128                                        l_call_params);
129        EXECUTE IMMEDIATE l_call_string USING
130          OUT l_return_status,
131          OUT l_msg_count,
132          OUT l_msg_data;
133 
134        IF (l_return_status <> FND_API.G_RET_STS_SUCCESS) THEN
135           raise_application_error(-20000,
136             'IBY_20220#ERRMSG=' || fnd_msg_pub.get(p_msg_index => 1,p_encoded => FND_API.G_FALSE),
137             FALSE);
138        END IF;
139      END LOOP;
140 
141   END validate_open_batch;
142 
143   PROCEDURE prepare_instr_data
144   (p_commit   IN  VARCHAR2,
145    p_sys_key  IN  iby_security_pkg.DES3_KEY_TYPE,
146    p_instrnum IN  iby_trxn_summaries_all.instrnumber%TYPE,
147    p_instrtype IN  iby_trxn_summaries_all.instrtype%TYPE,
148    x_instrnum OUT NOCOPY iby_trxn_summaries_all.instrnumber%TYPE,
149    x_instr_subtype OUT NOCOPY iby_trxn_summaries_all.instrsubtype%TYPE,
150    x_instr_hash    OUT NOCOPY iby_trxn_summaries_all.instrnum_hash%TYPE,
151    x_range_id OUT NOCOPY iby_trxn_summaries_all.instrnum_sec_segment_id%TYPE,
152    x_instr_len OUT NOCOPY iby_trxn_summaries_all.instrnum_length%TYPE,
153    x_segment_id OUT NOCOPY iby_trxn_summaries_all.instrnum_sec_segment_id%TYPE
154   )
155   IS
156   BEGIN
157     IBY_SECURITY_PKG.prepare_instr_data
158       (p_commit,
159        p_sys_key,
160        p_instrnum,
161        p_instrtype,
162        x_instrnum,
163        x_instr_subtype,
164        x_instr_hash,
165        x_range_id,
166        x_instr_len,
167        x_segment_id);
168   END prepare_instr_data;
169 
170   --
171   -- USE: inserts transactional extensibility data
172   --
173   PROCEDURE insert_extensibility
174   (
175   p_trxnmid           IN     iby_trxn_summaries_all.trxnmid%TYPE,
176   p_commit            IN     VARCHAR2,
177   p_extend_names      IN     JTF_VARCHAR2_TABLE_100,
178   p_extend_vals       IN     JTF_VARCHAR2_TABLE_200
179   )
180   IS
181   BEGIN
182 
183     IF (p_extend_names IS NULL) THEN
184       RETURN;
185     END IF;
186 
187 
188     FOR i IN p_extend_names.FIRST..p_extend_names.LAST LOOP
189       INSERT INTO iby_trxn_extensibility
190       (trxn_extend_id,trxnmid,extend_name,extend_value,created_by,
191        creation_date,last_updated_by,last_update_date,last_update_login,
192        object_version_number)
193       VALUES
194       (iby_trxn_extensibility_s.NEXTVAL,
195        p_trxnmid,p_extend_names(i),p_extend_vals(i),
196        fnd_global.user_id,sysdate,fnd_global.user_id,sysdate,
197        fnd_global.login_id,1);
198     END LOOP;
199 
200     IF (p_commit = 'Y') THEN
201       COMMIT;
202     END IF;
203   END insert_extensibility;
204 
205   /* Inserts a new row into the IBY_TRXN_SUMMARIES_ALL table.  This method  */
206   /* would be called every time a MIPP authorize operation is performed. */
207 
208 PROCEDURE insert_auth_txn
209 	(
210 	 ecapp_id_in         IN     iby_trxn_summaries_all.ecappid%TYPE,
211          req_type_in         IN     iby_trxn_summaries_all.ReqType%TYPE,
212          order_id_in         IN     iby_transactions_v.order_id%TYPE,
213          merchant_id_in      IN     iby_transactions_v.merchant_id%TYPE,
214          vendor_id_in        IN     iby_transactions_v.vendor_id%TYPE,
215          vendor_key_in       IN     iby_transactions_v.bepkey%TYPE,
216          amount_in           IN     iby_transactions_v.amount%TYPE,
217          currency_in         IN     iby_transactions_v.currency%TYPE,
218          status_in           IN     iby_transactions_v.status%TYPE,
219          time_in             IN     iby_transactions_v.time%TYPE,
220          payment_name_in     IN     iby_transactions_v.payment_name%TYPE,
221 	 payment_type_in     IN	    iby_transactions_v.payment_type%TYPE,
222          trxn_type_in        IN     iby_transactions_v.trxn_type%TYPE,
223 	 authcode_in         IN     iby_transactions_v.authcode%TYPE,
224 	 referencecode_in    IN     iby_transactions_v.referencecode%TYPE,
225          AVScode_in          IN     iby_transactions_v.AVScode%TYPE,
226          acquirer_in         IN     iby_transactions_v.acquirer%TYPE,
227          Auxmsg_in           IN     iby_transactions_v.Auxmsg%TYPE,
228          vendor_code_in      IN     iby_transactions_v.vendor_code%TYPE,
229          vendor_message_in   IN     iby_transactions_v.vendor_message%TYPE,
230          error_location_in   IN     iby_transactions_v.error_location%TYPE,
231          trace_number_in     IN	    iby_transactions_v.TraceNumber%TYPE,
232 	 org_id_in           IN     iby_trxn_summaries_all.org_id%type,
233          billeracct_in       IN     iby_tangible.acctno%type,
234          refinfo_in          IN     iby_tangible.refinfo%type,
235          memo_in             IN     iby_tangible.memo%type,
236          order_medium_in     IN     iby_tangible.order_medium%TYPE,
237          eft_auth_method_in  IN     iby_tangible.eft_auth_method%TYPE,
238 	 payerinstrid_in     IN	    iby_trxn_summaries_all.payerinstrid%type,
239 	 instrnum_in	     IN     iby_trxn_summaries_all.instrnumber%type,
240 	 payerid_in          IN     iby_trxn_summaries_all.payerid%type,
241 	 instrtype_in        IN     iby_trxn_summaries_all.instrType%type,
242          cvv2result_in       IN     iby_trxn_core.CVV2Result%type,
243          master_key_in       IN     iby_security_pkg.DES3_KEY_TYPE,
244          subkey_seed_in      IN     RAW,
245          trxnref_in          IN     iby_trxn_summaries_all.trxnref%TYPE,
246          dateofvoiceauth_in  IN     iby_trxn_core.date_of_voice_authorization%TYPE,
247          instr_expirydate_in IN     iby_trxn_core.instr_expirydate%TYPE,
248          instr_sec_val_in    IN     VARCHAR2,
249          card_subtype_in     IN     iby_trxn_core.card_subtype_code%TYPE,
250          card_data_level_in  IN     iby_trxn_core.card_data_level%TYPE,
251          instr_owner_name_in    IN  iby_trxn_core.instr_owner_name%TYPE,
252          instr_address_line1_in IN  iby_trxn_core.instr_owner_address_line1%TYPE,
253          instr_address_line2_in IN  iby_trxn_core.instr_owner_address_line2%TYPE,
254          instr_address_line3_in IN  iby_trxn_core.instr_owner_address_line3%TYPE,
255          instr_city_in       IN     iby_trxn_core.instr_owner_city%TYPE,
256          instr_state_in      IN     iby_trxn_core.instr_owner_state_province%TYPE,
257          instr_country_in    IN     iby_trxn_core.instr_owner_country%TYPE,
258          instr_postalcode_in IN     iby_trxn_core.instr_owner_postalcode%TYPE,
259          instr_phonenumber_in IN    iby_trxn_core.instr_owner_phone%TYPE,
260          instr_email_in      IN     iby_trxn_core.instr_owner_email%TYPE,
261          pos_reader_cap_in   IN     iby_trxn_core.pos_reader_capability_code%TYPE,
262          pos_entry_method_in IN     iby_trxn_core.pos_entry_method_code%TYPE,
263          pos_card_id_method_in IN   iby_trxn_core.pos_id_method_code%TYPE,
264          pos_auth_source_in  IN     iby_trxn_core.pos_auth_source_code%TYPE,
265          reader_data_in      IN     iby_trxn_core.reader_data%TYPE,
266          extend_names_in     IN     JTF_VARCHAR2_TABLE_100,
267          extend_vals_in      IN     JTF_VARCHAR2_TABLE_200,
268          debit_network_code_in IN   iby_trxn_core.debit_network_code%TYPE,
269          surcharge_amount_in  IN    iby_trxn_core.surcharge_amount%TYPE,
270          proc_tracenumber_in  IN    iby_trxn_core.proc_tracenumber%TYPE,
271          transaction_id_out  OUT NOCOPY iby_trxn_summaries_all.TransactionID%TYPE,
272          transaction_mid_out OUT NOCOPY iby_trxn_summaries_all.trxnmid%TYPE,
273          org_type_in         IN      iby_trxn_summaries_all.org_type%TYPE,
274          payment_channel_code_in  IN iby_trxn_summaries_all.payment_channel_code%TYPE,
275          factored_flag_in         IN iby_trxn_summaries_all.factored_flag%TYPE,
276          process_profile_code_in     IN iby_trxn_summaries_all.process_profile_code%TYPE,
277 	 sub_key_id_in       IN     iby_trxn_summaries_all.sub_key_id%TYPE,
278 	 voiceAuthFlag_in    IN     iby_trxn_core.voiceauthflag%TYPE,
279 	 reauth_trxnid_in    IN     iby_trxn_summaries_all.TransactionID%TYPE
280 )
281   IS
282 
283     l_num_trxns      NUMBER	     := 0;
284     l_trxn_mid	     NUMBER;
285     l_transaction_id NUMBER;
286     l_tmid iby_trxn_summaries_all.mtangibleid%type;
287     l_mpayeeid iby_payee.mpayeeid%type;
288 
289     l_return_status    VARCHAR2(1);
290     l_msg_count        NUMBER;
291     l_msg_data         VARCHAR2(200);
292     l_checksum_valid   BOOLEAN := FALSE;  -- whether the card number is valid.
293 
294     l_cc_type          VARCHAR2(80);
295     lx_cc_hash         iby_trxn_summaries_all.instrnum_hash%TYPE;
296     lx_range_id        iby_cc_issuer_ranges.cc_issuer_range_id%TYPE;
297     lx_instr_len       iby_trxn_summaries_all.instrnum_length%TYPE;
298     lx_segment_id      iby_trxn_summaries_all.instrnum_sec_segment_id%TYPE;
299     l_old_segment_id   iby_trxn_summaries_all.instrnum_sec_segment_id%TYPE;
300 
301     l_instrnum         iby_trxn_summaries_all.instrnumber%type;
302     l_expirydate       iby_trxn_core.instr_expirydate%type;
303 
304     l_pos_txn          iby_trxn_core.pos_trxn_flag%TYPE;
305     l_payer_party_id   iby_trxn_summaries_all.payer_party_id%type;
306 
307     l_voiceauth_flag   iby_trxn_core.voiceauthflag%type;
308     l_sub_key_id       iby_trxn_summaries_all.sub_key_id%TYPE;
309 
310     -- variables for CHNAME and EXPDATE encryption
311     l_chname_sec_segment_id iby_security_segments.sec_segment_id%TYPE;
312     l_expdate_sec_segment_id iby_security_segments.sec_segment_id%TYPE;
313     l_masked_chname     VARCHAR2(100) := NULL;
314   --  l_encrypted_date_format VARCHAR2(20);
315     l_encrypted         VARCHAR2(1) := 'N';
316 
317  BEGIN
318 
319      l_num_trxns := getNumPendingTrxns(merchant_id_in,order_id_in,req_type_in);
320 
321      prepare_instr_data
322      (FND_API.G_FALSE,master_key_in,instrnum_in,instrType_in,l_instrnum,
323       l_cc_type,lx_cc_hash,lx_range_id,lx_instr_len,lx_segment_id);
324 
325 
326      --
327      -- NOTE: for all subsequent data encryptions, make sure that the
328      --       parameter to increment the subkey is set to 'N' so that
329      --       all encrypted data for the trxn uses the same key!!
330      --       else data will NOT DECRYPT CORRECTLY!!
331      --
332      l_expirydate := instr_expirydate_in;
333 
334 
335 
336      -- PABP Fixes
337      -- card holder name and instrument expiry are also considered to be
338      -- sensitive. We need to encrypt those before inserting/updating the
339      -- record in IBY_TRXN_CORE
340 
341      IF ((IBY_CREDITCARD_PKG.Get_CC_Encrypt_Mode() <>
342           IBY_SECURITY_PKG.G_ENCRYPT_MODE_NONE)
343 	--  AND ( IBY_CREDITCARD_PKG.Other_CC_Attribs_Encrypted = 'Y')
344 	)
345      THEN
346       l_chname_sec_segment_id :=
347                  IBY_SECURITY_PKG.encrypt_field_vals(instr_owner_name_in,
348 		                                     master_key_in,
349 						     null,
350 						     'N'
351 						     );
352       l_expdate_sec_segment_id :=
353                  IBY_SECURITY_PKG.encrypt_date_field(l_expirydate,
354 		                                     master_key_in,
355 						     null,
356 						     'N'
357 						     );
358 
359       l_masked_chname :=
360                 IBY_SECURITY_PKG.Mask_Data(instr_owner_name_in,
361 		                           IBY_SECURITY_PKG.G_MASK_ALL,
362 				           0,
363 					   'X'
364 					   );
365       l_encrypted := 'Y';
366       l_expirydate := NULL;
367      ELSE
368       l_masked_chname := instr_owner_name_in;
369       l_encrypted := 'N';
370 
371      END IF;
372 
373      IF ((pos_reader_cap_in IS NULL)
374          AND (pos_entry_method_in IS NULL)
375          AND (pos_card_id_method_in IS NULL)
376          AND (pos_auth_source_in IS NULL)
377          AND (reader_data_in IS NULL)
378         )
379      THEN
380        l_pos_txn := 'N';
381      ELSE
382        l_pos_txn := 'Y';
383      END IF;
384 
385      IF (l_num_trxns = 0)    THEN
386      	 -- new auth request, insert into table
387       	SELECT iby_trxnsumm_mid_s.NEXTVAL
388 	INTO l_trxn_mid
389 	FROM dual;
390 
391   -- get the payer_party_id if exists
392  begin
393    if(payerid_in is not NULL) then
394        l_payer_party_id :=to_number(payerid_in);
395        end if;
396   exception
397     when others then
398    select card_owner_id
399    into l_payer_party_id
400    from iby_creditcard
401    where instrid=payerinstrid_in;
402   end;
403 
404 	IF(reauth_trxnid_in > 0)THEN
405 	  l_transaction_id := reauth_trxnid_in;
406 	ELSE
407 	  l_transaction_id := getTID(merchant_id_in, order_id_in);
408 	END IF;
409 
410 	transaction_id_out := l_transaction_id;
411         transaction_mid_out := l_trxn_mid;
412 
413 	iby_accppmtmthd_pkg.getMPayeeId(merchant_id_in, l_mpayeeid);
414 
415        --Create an entry in iby_tangible table
416        iby_bill_pkg.createBill(order_id_in,amount_in,currency_in,
417 		   billeracct_in,refinfo_in, memo_in,
418                    order_medium_in, eft_auth_method_in, l_tmid);
419 --test_debug('subkeyid passed as: '|| sub_key_id_in);
420        INSERT INTO iby_trxn_summaries_all
421 	(TrxnMID, TransactionID,TrxntypeID, ReqType, ReqDate,
422 	 Amount,CurrencyNameCode, UpdateDate,Status, PaymentMethodName,
423 	 TangibleID,MPayeeID, PayeeID,BEPID,bepKey,mtangibleid,
424 	 BEPCode,BEPMessage,Errorlocation,ecappid,org_id,
425 	 payerinstrid, instrnumber, payerid, instrType,
426 
427 	 last_update_date,last_updated_by,creation_date, created_by,
428          last_update_login,object_version_number,instrsubtype,trxnref,
429          org_type, payment_channel_code, factored_flag,
430          cc_issuer_range_id, instrnum_hash, instrnum_length,
431          instrnum_sec_segment_id, payer_party_id, process_profile_code,
432          salt_version,needsupdt,sub_key_id)
433        VALUES (l_trxn_mid, l_transaction_id, trxn_type_in, req_type_in,
434                sysdate,
435 	       amount_in, currency_in, time_in, status_in, payment_type_in,
436 	       order_id_in, l_mpayeeid, merchant_id_in, vendor_id_in,
437 	       vendor_key_in, l_tmid, vendor_code_in, vendor_message_in,
438 	       error_location_in, ecapp_id_in, org_id_in,
439                payerinstrid_in, l_instrnum, payerid_in, instrType_in,
440 	       sysdate, fnd_global.user_id, sysdate, fnd_global.user_id,
441                fnd_global.login_id, 1, l_cc_type, trxnref_in,
442                org_type_in, payment_channel_code_in, factored_flag_in,
443                lx_range_id, lx_cc_hash, lx_instr_len, lx_segment_id,
444                l_payer_party_id, process_profile_code_in,
445                iby_security_pkg.get_salt_version,'Y',sub_key_id_in);
446 
447 
448       /*
449        * Fix for bug 5190504:
450        *
451        * Set the voice auth flag in iby_trxn_core to 'Y'
452        * in case, the voice auth date is not null.
453        */
454    --   IF (dateofvoiceauth_in IS NOT NULL) THEN
455    --       l_voiceauth_flag := 'Y';
456    --   ELSE
457    --       l_voiceauth_flag := 'N';
458    --   END IF;
459 
460        /*
461         * The above logic will not set the voiceAuthFlag if the
462 	* voice auth date is NULL.
463 	* The voiceAuthFlag is now received by this API as an
464 	* input parameter.
465 	*/
466 	l_voiceauth_flag := voiceAuthFlag_in;
467 
468       INSERT INTO iby_trxn_core (
469         TrxnMID, AuthCode, date_of_voice_authorization, voiceauthflag,
470         ReferenceCode, TraceNumber,AVSCode, CVV2Result, Acquirer,
471 	Auxmsg, InstrName,
472         Instr_Expirydate, expiry_sec_segment_id,
473 	Card_Subtype_Code, Card_Data_Level,
474         Instr_Owner_Name, chname_sec_segment_id, encrypted,
475 	Instr_Owner_Address_Line1, Instr_Owner_Address_Line2,
476         Instr_Owner_Address_Line3, Instr_Owner_City, Instr_Owner_State_Province,
477         Instr_Owner_Country, Instr_Owner_PostalCode, Instr_Owner_Phone,
478         Instr_Owner_Email,
479         POS_Reader_Capability_Code, POS_Entry_Method_Code,
480         POS_Id_Method_Code, POS_Auth_Source_Code, Reader_Data, POS_Trxn_Flag,
481 debit_network_code, surcharge_amount, proc_tracenumber,
482         last_update_date, last_updated_by,
483         creation_date, created_by, last_update_login, object_version_number
484         ) VALUES (
485         l_trxn_mid, authcode_in, dateofvoiceauth_in, l_voiceauth_flag,
486         referencecode_in, trace_number_in, AVScode_in, cvv2result_in,
487         acquirer_in, Auxmsg_in, payment_name_in,
488         l_expirydate, l_expdate_sec_segment_id,
489 	card_subtype_in, card_data_level_in,
490         l_masked_chname, l_chname_sec_segment_id, l_encrypted,
491         instr_address_line1_in, instr_address_line2_in, instr_address_line3_in,
492         instr_city_in, instr_state_in, instr_country_in, instr_postalcode_in,
493         instr_phonenumber_in, instr_email_in,
494         pos_reader_cap_in, pos_entry_method_in, pos_card_id_method_in,
495         pos_auth_source_in, reader_data_in, l_pos_txn,debit_network_code_in, surcharge_amount_in, proc_tracenumber_in,
496         sysdate,fnd_global.user_id,
497         sysdate,fnd_global.user_id,fnd_global.login_id,1
498         );
499 
500         -- probably a superflous call since the first insert is
501         -- to log the transaction before it is sent to the payment system
502         insert_extensibility(l_trxn_mid,'N',extend_names_in,extend_vals_in);
503 
504 	--test_debug('insertion complete..');
505 
506     ELSE
507 	--(l_num_trxns = 1)
508       -- One previous PENDING transaction, so update previous row
509        SELECT TrxnMID, TransactionID, Mtangibleid, instrnum_sec_segment_id, sub_key_id
510        INTO l_trxn_mid, transaction_id_out, l_tmid, l_old_segment_id, l_sub_key_id
511        FROM iby_trxn_summaries_all
512        WHERE (TangibleID = order_id_in)
513        AND (UPPER(ReqType) = UPPER(req_type_in))
514        AND (PayeeID = merchant_id_in)
515        AND (status IN (11,9));
516 
517        transaction_mid_out := l_trxn_mid;
518 
519        --Re-use the previous subkey for a retry case
520  --      sub_key_id_in := l_sub_key_id;
521 
522     -- Update iby_tangible table
523       iby_bill_pkg.modBill(l_tmid,order_id_in,amount_in,currency_in,
524 			   billeracct_in,refinfo_in,memo_in,
525                            order_medium_in, eft_auth_method_in);
526 
527 
528       UPDATE iby_trxn_summaries_all
529 	 SET BEPID = vendor_id_in,
530 	     bepKey = vendor_key_in,
531 	     Amount = amount_in,
532 		-- amount, bepid is updated as the request can come in
533 		-- from another online
534 	     TrxntypeID = trxn_type_in,
535 	     CurrencyNameCode = currency_in,
536 	     UpdateDate = time_in,
537 	     Status = status_in,
538 	     ErrorLocation = error_location_in,
539 	     BEPCode = vendor_code_in,
540 	     BEPMessage = vendor_message_in,
541              instrType = instrType,
542 
543 		-- we don't update payerinstrid and org_id here
544 		-- as it may overwrite previous payerinstrid, org_id
545 		-- (from offline scheduling)
546 		-- in case this request comes in from scheduler
547 
548 		-- could be a problem if this request comes in from
549 		-- another online, w/ a different payment instrment
550 		-- for a previous failed trxn, regardless, the
551 		--'instrnumber' will always be correct
552 
553 		--org_id = org_id_in,
554  		--payerinstrid = payerinstrid_in,
555                 -- same for org_type
556 
557              PaymentMethodName = NVL(payment_type_in,PaymentMethodName),
558 	     instrnumber = l_instrnum,
559              instrnum_hash = lx_cc_hash,
560              instrnum_length = lx_instr_len,
561              cc_issuer_range_id = lx_range_id,
562              instrnum_sec_segment_id = lx_segment_id,
563              trxnref = trxnref_in,
564 	     last_update_date = sysdate,
565 	     last_updated_by = fnd_global.user_id,
566 	     creation_date = sysdate,
567 	     created_by = fnd_global.user_id,
568 	     object_version_number = object_version_number + 1,
569              payment_channel_code = payment_channel_code_in,
570              factored_flag = factored_flag_in
571        WHERE TrxnMID = l_trxn_mid;
572 
573       DELETE iby_security_segments WHERE sec_segment_id = l_old_segment_id;
574 
575       UPDATE iby_trxn_core
576 	 SET AuthCode = authcode_in,
577              date_of_voice_authorization = dateofvoiceauth_in,
578            --voiceauthflag = DECODE(dateofvoiceauth_in, NULL, 'N', 'Y'),
579 	     voiceauthflag = voiceAuthFlag_in,
580 	     AvsCode = AVScode_in,
581              CVV2Result = cvv2result_in,
582 	     ReferenceCode = referencecode_in,
583 	     Acquirer = acquirer_in,
584 	     Auxmsg = Auxmsg_in,
585 	     TraceNumber = trace_number_in,
586              InstrName = NVL(payment_name_in,InstrName),
587 	     encrypted = l_encrypted,
588              Instr_Expirydate = l_expirydate,
589 	     expiry_sec_segment_id = l_expdate_sec_segment_id,
590 	     Card_Subtype_Code = card_subtype_in,
591              Card_Data_Level = card_data_level_in,
592              Instr_Owner_Name = l_masked_chname,
593 	     chname_sec_segment_id = l_chname_sec_segment_id,
594              Instr_Owner_Address_Line1 = instr_address_line1_in,
595              Instr_Owner_Address_Line2 = instr_address_line2_in,
596              Instr_Owner_Address_Line3 = instr_address_line3_in,
597              Instr_Owner_City = instr_city_in,
598              Instr_Owner_State_Province = instr_state_in,
599              Instr_Owner_Country = instr_country_in,
600              Instr_Owner_PostalCode = instr_postalcode_in,
601              Instr_Owner_Phone = instr_phonenumber_in,
602              Instr_Owner_Email = instr_email_in,
603              POS_Reader_Capability_Code = pos_reader_cap_in,
604              POS_Entry_Method_Code = pos_entry_method_in,
605              POS_Id_Method_Code = pos_card_id_method_in,
606              POS_Auth_Source_Code = pos_auth_source_in,
607              Reader_Data = reader_data_in,
608              POS_Trxn_Flag = l_pos_txn,
609              debit_network_code = debit_network_code_in,
610              surcharge_amount  = surcharge_amount_in,
611              proc_tracenumber = proc_tracenumber_in,
612 	     last_update_date = sysdate,
613 	     last_updated_by = fnd_global.user_id,
614 	     creation_date = sysdate,
615 	     created_by = fnd_global.user_id,
616 	     object_version_number = object_version_number + 1
617        WHERE TrxnMID = l_trxn_mid;
618 
619        insert_extensibility(l_trxn_mid,'N',extend_names_in,extend_vals_in);
620     END IF;
621 
622     COMMIT;
623   END insert_auth_txn;
624 
625   PROCEDURE insert_rev_result
626              ( trxnmid_in            IN     iby_trxn_summaries_all.trxnmid%TYPE,
627                trxnid_in             IN     iby_trxn_summaries_all.transactionid%TYPE,
628                status_in             IN     iby_trxn_summaries_all.status%TYPE,
629                trxntype_in           IN     iby_trxn_summaries_all.trxntypeid%TYPE,
630                revised_amt_in        IN     iby_trxn_summaries_all.amount%TYPE,
631                referencecode_in      IN     iby_transactions_v.referencecode%TYPE DEFAULT NULL,
632                AVScode_in            IN     iby_transactions_v.AVScode%TYPE DEFAULT NULL,
633                acquirer_in           IN     iby_transactions_v.acquirer%TYPE DEFAULT NULL,
634                Auxmsg_in             IN     iby_transactions_v.Auxmsg%TYPE DEFAULT NULL,
635                cvv2result_in         IN     iby_trxn_core.CVV2Result%type,
636                bepcode_in            IN     iby_trxn_summaries_all.bepcode%TYPE,
637                bepmessage_in         IN     iby_trxn_summaries_all.bepmessage%TYPE,
638                error_loc_in          IN     iby_trxn_summaries_all.errorlocation%TYPE,
639                tracenumber_in        IN     iby_trxn_core.tracenumber%TYPE,
640                authcode_in           IN     iby_trxn_core.authcode%TYPE,
641                extend_names_in       IN     JTF_VARCHAR2_TABLE_100,
642                extend_vals_in        IN     JTF_VARCHAR2_TABLE_200
643              )
644 IS
645     l_dbg_mod VARCHAR2(100) := 'IBY_TRANSACTIONCC_PKG' || '.insert_rev_result';
646     l_old_auth_trxnmid   NUMBER;
647     l_new_auth_trxnmid   NUMBER;
648     l_cursor_empty     BOOLEAN;
649 
650     CURSOR c_auth (ci_transactionid iby_trxn_summaries_all.transactionid%TYPE)
651     IS
652       SELECT trxnmid FROM iby_trxn_summaries_all
653       WHERE transactionid = ci_transactionid
654 	AND reqtype = 'ORAPMTREQ'
655 	AND trxntypeid = 2
656 	AND status = 0;
657 
658     --
659     -- Used for partial reversal.
660     -- Cursor fetches the new/updated extensibility data from reversal response.
661     -- In case a any extensibility attribute is missing(not echoed back) in the
662     -- reversal response then this attribute value is defaulted to that fetched
663     -- in the original authorization.
664     --
665     CURSOR c_extend (ci_trxnmid_old iby_trxn_summaries_all.trxnmid%TYPE,
666                      ci_trxnmid_new iby_trxn_summaries_all.trxnmid%TYPE)
667     IS
668       SELECT old_ext.extend_name extend_name,
669              nvl(new_ext.EXTEND_VALUE, old_ext.extend_value) extend_value
670       FROM IBY_TRXN_EXTENSIBILITY OLD_EXT,
671            IBY_TRXN_EXTENSIBILITY NEW_EXT
672       WHERE OLD_EXT.TRXNMID=ci_trxnmid_old
673         AND NEW_EXT.TRXNMID(+)=ci_trxnmid_new
674         and old_ext.extend_name=new_ext.extend_name(+);
675 
676   BEGIN
677     iby_debug_pub.add('Enter',IBY_DEBUG_PUB.G_LEVEL_PROCEDURE,l_dbg_mod);
678     UPDATE iby_trxn_summaries_all
679     SET status = status_in,
680 	bepcode = bepcode_in,
681 	bepmessage = bepmessage_in,
682 	UpdateDate = SYSDATE,
683 	errorlocation = error_loc_in,
684 	Last_Update_Date = sysdate,
685 	Last_Updated_by = fnd_global.user_id,
686 	Object_Version_Number = object_version_number + 1
687     WHERE trxnmid = trxnmid_in
688       AND reqtype = 'ORAPMTREVERSE'
689       AND trxntypeid = trxntype_in;
690 
691     IF (status_in = 0) THEN
692       iby_debug_pub.add('Reversal Successful.',IBY_DEBUG_PUB.G_LEVEL_INFO,l_dbg_mod);
693 
694       IF (c_auth%ISOPEN) THEN
695 	CLOSE c_auth;
696       END IF;
697 
698       OPEN c_auth(trxnid_in);
699       FETCH c_auth INTO l_old_auth_trxnmid;
700 	l_cursor_empty := c_auth%NOTFOUND;
701       CLOSE c_auth;
702 
703       UPDATE iby_trxn_summaries_all
704       SET status = trxntype_in,
705 	  Last_Update_Date = sysdate,
706 	  Last_Updated_by = fnd_global.user_id,
707 	  Object_Version_Number = object_version_number + 1
708       WHERE trxnmid = l_old_auth_trxnmid;
709 
710       UPDATE iby_trxn_core
711       SET authcode = authcode_in,
712 	  ReferenceCode = referencecode_in,
713 	  AVSCode = AVScode_in,
714 	  CVV2Result = cvv2result_in,
715 	  Acquirer = acquirer_in,
716 	  Auxmsg = Auxmsg_in,
717 	  Last_Update_Date = sysdate,
718 	  Last_Updated_by = fnd_global.user_id,
719 	  Object_Version_Number = object_version_number + 1
720       WHERE trxnmid = trxnmid_in;
721       iby_debug_pub.add('Inserting extensibility data for reversal record.',IBY_DEBUG_PUB.G_LEVEL_INFO,l_dbg_mod);
722       insert_extensibility(trxnmid_in,'N',extend_names_in,extend_vals_in);
723       IF (trxntype_in = 23) THEN --Partial Reversal
724 	iby_debug_pub.add('Partial reversal. Cloning auth record.',IBY_DEBUG_PUB.G_LEVEL_INFO,l_dbg_mod);
725 
726 	SELECT iby_trxnsumm_mid_s.NEXTVAL
727 	INTO l_new_auth_trxnmid
728 	FROM dual;
729 
730 	INSERT INTO iby_trxn_summaries_all
731 	(TrxnMID, TransactionID,TrxntypeID, ReqType, ReqDate,
732 	 Amount,CurrencyNameCode, UpdateDate,Status, PaymentMethodName,
733 	 TangibleID,MPayeeID, PayeeID,BEPID,bepKey,mtangibleid,
734 	 BEPCode,BEPMessage,Errorlocation,ecappid,org_id,
735 	 payerinstrid, instrnumber, payerid, instrType,
736 	 last_update_date,last_updated_by,creation_date, created_by,
737 	 last_update_login,object_version_number,instrsubtype,trxnref,
738 	 org_type, payment_channel_code, factored_flag,
739 	 cc_issuer_range_id, instrnum_hash, instrnum_length,
740 	 instrnum_sec_segment_id, payer_party_id, process_profile_code,
741 	 salt_version,needsupdt,sub_key_id,initiator_extension_id)
742 	 (SELECT l_new_auth_trxnmid, TransactionID, TrxntypeID, ReqType,ReqDate,
743 	       revised_amt_in, CurrencyNameCode, UpdateDate, 0, PaymentMethodName,
744 	       TangibleID, MPayeeID, PayeeID, BEPID,bepKey, mtangibleid,
745 	       BEPCode, BEPMessage,Errorlocation,ecappid, org_id,
746 	       payerinstrid, instrnumber, payerid, instrType,
747 	       sysdate, fnd_global.user_id, sysdate, fnd_global.user_id,
748 	       fnd_global.login_id, 1, instrsubtype, trxnref,
749 	       org_type, payment_channel_code, factored_flag,
750 	       cc_issuer_range_id, instrnum_hash, instrnum_length,
751 	       instrnum_sec_segment_id, payer_party_id, process_profile_code,
752 	       salt_version,needsupdt,sub_key_id,initiator_extension_id
753 	 FROM iby_trxn_summaries_all
754 	 WHERE trxnmid = l_old_auth_trxnmid);
755 
756 	 INSERT INTO iby_trxn_core (
757 	 TrxnMID, AuthCode, date_of_voice_authorization, voiceauthflag,
758 	 ReferenceCode, TraceNumber,AVSCode, CVV2Result, Acquirer,
759 	 Auxmsg, InstrName,
760 	 Instr_Expirydate, expiry_sec_segment_id,
761 	 Card_Subtype_Code, Card_Data_Level,
762 	 Instr_Owner_Name, chname_sec_segment_id, encrypted,
763 	 Instr_Owner_Address_Line1, Instr_Owner_Address_Line2,
764 	 Instr_Owner_Address_Line3, Instr_Owner_City, Instr_Owner_State_Province,
765 	 Instr_Owner_Country, Instr_Owner_PostalCode, Instr_Owner_Phone,
766 	 Instr_Owner_Email,
767 	 POS_Reader_Capability_Code, POS_Entry_Method_Code,
768 	 POS_Id_Method_Code, POS_Auth_Source_Code, Reader_Data, POS_Trxn_Flag,
769 	 debit_network_code, surcharge_amount, proc_tracenumber,
770 	 last_update_date, last_updated_by,
771 	 creation_date, created_by, last_update_login, object_version_number)
772 	 (SELECT
773 	 l_new_auth_trxnmid, authcode_in, date_of_voice_authorization, voiceauthflag,
774 	 NVL(referencecode_in, ReferenceCode), TraceNumber, NVL(AVScode_in, AVSCode),
775 	 NVL(cvv2result_in, CVV2Result), NVL(acquirer_in, Acquirer),
776 	 NVL(Auxmsg, Auxmsg_in), InstrName,
777 	 Instr_Expirydate, expiry_sec_segment_id,
778 	 Card_Subtype_Code, Card_Data_Level,
779 	 Instr_Owner_Name, chname_sec_segment_id, encrypted,
780 	 Instr_Owner_Address_Line1, Instr_Owner_Address_Line2,
781 	 Instr_Owner_Address_Line3, Instr_Owner_City, Instr_Owner_State_Province,
782 	 Instr_Owner_Country, Instr_Owner_PostalCode, Instr_Owner_Phone,
783 	 Instr_Owner_Email,
784 	 POS_Reader_Capability_Code, POS_Entry_Method_Code,
785 	 POS_Id_Method_Code, POS_Auth_Source_Code, Reader_Data, POS_Trxn_Flag,
786 	 debit_network_code, surcharge_amount, proc_tracenumber,
787 	 sysdate,fnd_global.user_id,
788 	 sysdate,fnd_global.user_id,fnd_global.login_id,1
789 	 FROM iby_trxn_core
790 	 WHERE trxnmid = l_old_auth_trxnmid);
791 
792 	 --insert_extensibility(l_new_auth_trxnmid,'N',extend_names_in,extend_vals_in);
793 
794 	 --
795 	 -- Copy the extensibility data from the old authorization. Any updated
796 	 -- attribute obtained during reversal overrides the old values.
797 	 --
798 	 FOR extend_rec IN c_extend(l_old_auth_trxnmid,trxnmid_in) LOOP
799 	   INSERT INTO iby_trxn_extensibility
800            (trxn_extend_id,trxnmid,extend_name,extend_value,created_by,
801             creation_date,last_updated_by,last_update_date,last_update_login,
802             object_version_number)
803            VALUES
804            (iby_trxn_extensibility_s.NEXTVAL,
805             l_new_auth_trxnmid,extend_rec.extend_name,extend_rec.extend_value,
806             fnd_global.user_id,sysdate,fnd_global.user_id,sysdate,
807             fnd_global.login_id,1);
808 	 END LOOP;
809 
810       END IF;
811     END IF ;
812     COMMIT ;
813     iby_debug_pub.add('Exit',IBY_DEBUG_PUB.G_LEVEL_PROCEDURE,l_dbg_mod);
814   END insert_rev_result;
815 
816   /* Inserts a new row into the IBY_TRXN_SUMMARIES table.  This method	 */
817   /* would be called every time a capture, credit, return, or void */
818 
819   /* operation is performed.					       */
820 
821   PROCEDURE insert_other_txn
822        ( ecapp_id_in	     IN	    iby_trxn_summaries_all.ecappid%TYPE,
823 	 req_type_in	     IN     iby_trxn_summaries_all.ReqType%TYPE,
824 	 order_id_in	     IN     iby_transactions_v.order_id%TYPE,
825 	 merchant_id_in      IN     iby_transactions_v.merchant_id%TYPE,
826 	 vendor_id_in	     IN     iby_transactions_v.vendor_id%TYPE,
827 	 vendor_key_in	     IN     iby_transactions_v.bepkey%TYPE,
828 	 status_in	     IN     iby_transactions_v.status%TYPE,
829 	 time_in	     IN     iby_transactions_v.time%TYPE,
830 	 payment_type_in     IN     iby_transactions_v.payment_type%TYPE,
831 	 payment_name_in     IN     iby_transactions_v.payment_name%TYPE,
832 	 trxn_type_in	     IN	    iby_transactions_v.trxn_type%TYPE,
833 	 amount_in	     IN     iby_transactions_v.amount%TYPE,
834 	 currency_in	     IN     iby_transactions_v.currency%TYPE,
835 	 referencecode_in    IN     iby_transactions_v.referencecode%TYPE,
836 	 vendor_code_in      IN     iby_transactions_v.vendor_code%TYPE,
837 	 vendor_message_in   IN     iby_transactions_v.vendor_message%TYPE,
838 	 error_location_in   IN     iby_transactions_v.error_location%TYPE,
839 	 trace_number_in     IN     iby_transactions_v.TraceNumber%TYPE,
840 	 org_id_in           IN     iby_trxn_summaries_all.org_id%type,
841 	 billeracct_in	     IN     iby_tangible.acctno%type,
842 	 refinfo_in	     IN     iby_tangible.refinfo%type,
843 	 memo_in	     IN     iby_tangible.memo%type,
844          order_medium_in     IN     iby_tangible.order_medium%TYPE,
845          eft_auth_method_in  IN     iby_tangible.eft_auth_method%TYPE,
846 	 payerinstrid_in     IN	    iby_trxn_summaries_all.payerinstrid%type,
847 	 instrnum_in	     IN     iby_trxn_summaries_all.instrnumber%type,
848 	 payerid_in          IN     iby_trxn_summaries_all.payerid%type,
849          master_key_in       IN     iby_security_pkg.DES3_KEY_TYPE,
850          subkey_seed_in      IN     RAW,
851          trxnref_in          IN     iby_trxn_summaries_all.trxnref%TYPE,
852          instr_expirydate_in IN     iby_trxn_core.instr_expirydate%TYPE,
853          card_subtype_in     IN     iby_trxn_core.card_subtype_code%TYPE,
854          instr_owner_name_in    IN  iby_trxn_core.instr_owner_name%TYPE,
855          instr_address_line1_in IN  iby_trxn_core.instr_owner_address_line1%TYPE,
856          instr_address_line2_in IN  iby_trxn_core.instr_owner_address_line2%TYPE,
857          instr_address_line3_in IN  iby_trxn_core.instr_owner_address_line3%TYPE,
858          instr_city_in       IN     iby_trxn_core.instr_owner_city%TYPE,
859          instr_state_in      IN     iby_trxn_core.instr_owner_state_province%TYPE,
860          instr_country_in    IN     iby_trxn_core.instr_owner_country%TYPE,
861          instr_postalcode_in IN     iby_trxn_core.instr_owner_postalcode%TYPE,
862          instr_phonenumber_in IN    iby_trxn_core.instr_owner_phone%TYPE,
863          instr_email_in      IN     iby_trxn_core.instr_owner_email%TYPE,
864          extend_names_in     IN     JTF_VARCHAR2_TABLE_100,
865          extend_vals_in      IN     JTF_VARCHAR2_TABLE_200,
866 	 transaction_id_in_out	IN OUT NOCOPY iby_trxn_summaries_all.TransactionID%TYPE,
867          transaction_mid_out OUT NOCOPY iby_trxn_summaries_all.trxnmid%TYPE,
868          org_type_in         IN      iby_trxn_summaries_all.org_type%TYPE,
869          payment_channel_code_in  IN iby_trxn_summaries_all.payment_channel_code%TYPE,
870          factored_flag_in         IN iby_trxn_summaries_all.factored_flag%TYPE,
871 	 settlement_date_in       IN iby_trxn_summaries_all.settledate%TYPE,
872  	 settlement_due_date_in   IN iby_trxn_summaries_all.settlement_due_date%TYPE,
873          process_profile_code_in   IN iby_trxn_summaries_all.process_profile_code%TYPE,
874          instrtype_in              IN iby_trxn_summaries_all.instrtype%TYPE
875        )
876   IS
877 
878     l_num_trxns      NUMBER	     := 0;
879     l_trxn_mid	     NUMBER;
880     transaction_id NUMBER;
881     l_tmid iby_trxn_summaries_all.mtangibleid%type;
882     l_order_id iby_trxn_summaries_all.tangibleid%type;
883     l_mpayeeid iby_payee.mpayeeid%type;
884     l_org_id NUMBER;
885     l_target_trxn_type iby_trxn_summaries_all.trxntypeid%TYPE := -1;
886     l_instrtype iby_trxn_summaries_all.instrtype%type;
887     l_instrsubtype iby_trxn_summaries_all.instrsubtype%type;
888 
889     lx_cc_hash         iby_trxn_summaries_all.instrnum_hash%TYPE;
890     lx_range_id        iby_cc_issuer_ranges.cc_issuer_range_id%TYPE;
891     lx_instr_len       iby_trxn_summaries_all.instrnum_length%TYPE;
892     lx_segment_id      iby_trxn_summaries_all.instrnum_sec_segment_id%TYPE;
893     l_old_segment_id   iby_trxn_summaries_all.instrnum_sec_segment_id%TYPE;
894 
895     l_instrnum         iby_trxn_summaries_all.instrnumber%TYPE;
896     l_expirydate       iby_trxn_core.instr_expirydate%type;
897 
898     l_cursor_empty     BOOLEAN;
899     l_process_profile_code   iby_trxn_summaries_all.process_profile_code%TYPE;
900     l_payer_party_id   iby_trxn_summaries_all.payer_party_id%TYPE;
901     l_pmt_chnl_code     iby_trxn_summaries_all.payment_channel_code%TYPE;
902     l_module_name      CONSTANT VARCHAR2(200) := 'IBY_TRANSACTIONCC_PKG.insert_other_txn';
903     l_subtype          iby_trxn_summaries_all.instrsubtype%type;
904 
905     l_currency         iby_transactions_v.currency%TYPE;
906     l_payerid          iby_trxn_summaries_all.payerid%TYPE;
907     l_payerinstrid     iby_trxn_summaries_all.payerinstrid%TYPE;
908 
909     CURSOR c_followon_info(ci_trxnid iby_trxn_summaries_all.transactionid%TYPE)
910     IS
911 	SELECT mtangibleid, tangibleid, instrType, instrsubtype,
912 	       process_profile_code, payer_party_id, payment_channel_code,
913 	       currencynamecode, payerid, payerinstrid
914 	FROM iby_trxn_summaries_all
915 	WHERE (transactionid = ci_trxnid)
916 	-- ignore the reversal trxntypes
917 	AND   (trxntypeid NOT IN (22,23))
918         --
919 	-- only consider succeeded ones here
920 	-- b/c different mtangibleid may get created in case of failed
921 	-- auth
922 	--
923 	--  status 100 is equivalent to 0
924 	--
925 	AND (status IN (0,100))
926         --
927         -- sort by trxnmid as lowest value indicates the
928         -- first trxn for this order, which is most likely
929         -- to have all information
930         --
931         ORDER BY trxnmid ASC;
932 
933   BEGIN
934     IF ( G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
935 	    print_debuginfo(l_module_name, 'ENTER');
936     END IF;
937     l_instrsubtype := NULL;
938     l_num_trxns := getNumPendingTrxns(merchant_id_in, order_id_in,
939 					req_type_in);
940     IF ( G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
941 	    print_debuginfo(l_module_name, 'Number of trxns::'||l_num_trxns);
942 
943     END IF;
944     IF (c_followon_info%ISOPEN) THEN
945       CLOSE c_followon_info;
946     END IF;
947 
948     IF (l_num_trxns = 0)    THEN
949       IF ( G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
950 	      print_debuginfo(l_module_name, 'INSERTING TRANSACTION ROW');
951       END IF;
952       -- Insert transaction row
953       SELECT iby_trxnsumm_mid_s.NEXTVAL
954 	INTO l_trxn_mid
955 	FROM dual;
956 
957       transaction_mid_out := l_trxn_mid;
958 
959      -- For OraPmtCredit we need to
960 
961      -- 1) return transactionid
962      -- 2) Create an entry in iby_tangible table
963       IF UPPER(req_type_in) = 'ORAPMTCREDIT'
964       THEN
965 
966 	transaction_id := getTID(merchant_id_in, order_id_in);
967 
968 	transaction_id_in_out := transaction_id;
969 
970 	iby_bill_pkg.createBill(order_id_in,amount_in,currency_in,
971 			   billeracct_in,refinfo_in, memo_in,
972                            order_medium_in, eft_auth_method_in, l_tmid);
973 
974 	l_org_id := org_id_in;
975 	l_order_id := order_id_in;
976         --Bug# 8324289
977         --Setting Profile code and instrument type so that the credit
978         --transaction should get picked up by the settlement batch program.
979         l_process_profile_code:= process_profile_code_in;
980         l_instrtype:=instrtype_in;
981         --
982         -- NOTE: for all subsequent data encryptions, make sure that the
983         --       parameter to increment the subkey is set to 'N' so that
984         --       all encrypted data for the trxn uses the same key!!
985         --       else data will NOT DECRYPT CORRECTLY!!
986         --
987         l_expirydate := instr_expirydate_in;
988 
989       ELSE
990 	-- follow on trxns
991 	--tangible info should already exist, get them based on
992 	--transactionid
993         --
994         OPEN c_followon_info(transaction_id_in_out);
995         FETCH c_followon_info INTO l_tmid, l_order_id, l_instrtype, l_instrsubtype,
996 	        l_process_profile_code, l_payer_party_id, l_pmt_chnl_code,
997 		l_currency, l_payerid, l_payerinstrid;
998         l_cursor_empty := c_followon_info%NOTFOUND;
999         CLOSE c_followon_info;
1000         --
1001         -- not likely to occur, but making this assumption could lead to
1002         -- a tricky error later
1003         --
1004         IF (l_cursor_empty) THEN
1005           raise_application_error(-20000, 'IBY_20528#', FALSE);
1006         END IF;
1007 
1008 	l_org_id := getOrgId(transaction_id_in_out);
1009 
1010       END IF;
1011 
1012 	iby_accppmtmthd_pkg.getMPayeeId(merchant_id_in, l_mpayeeid);
1013 
1014 	--Bug# 9911423
1015 	--Deriving the instrument sub type from Credit card table, if in case
1016 	--the input parameter value is null
1017 
1018 	IF ( G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
1019 	      print_debuginfo(l_module_name, 'l_instrsubtype='||l_instrsubtype);
1020 	      print_debuginfo(l_module_name, 'payment_name_in='||payment_name_in);
1021 	      print_debuginfo(l_module_name, 'payerinstrid_in='||payerinstrid_in);
1022 	END IF;
1023 
1024 	--IF (l_instrsubtype is NULL) THEN
1025 	   --l_instrsubtype := payment_name_in;
1026 	--END IF;
1027       -- [lmallick] - instrument information isn't really required for a follow on operation
1028       -- like ORAPMTREVERSE. So, this piece of code need not be executed
1029       IF (UPPER(req_type_in) <> 'ORAPMTREVERSE') THEN
1030               l_currency := currency_in;
1031               l_payerid  := payerid_in;
1032               l_payerinstrid := payerinstrid_in;
1033 
1034 	      l_instrsubtype := NVL(l_instrsubtype,payment_name_in);
1035 
1036 	      --Bug# 11800457
1037 	      -- If payer instrid is null, it's not required to fetch
1038 	      -- the issuer code from credit cards table
1039 
1040 	      IF (l_instrsubtype is NULL) THEN
1041 		   --l_instrsubtype := payment_name_in;
1042 		   IF(payerinstrid_in IS NOT NULL) THEN
1043 			SELECT card_issuer_code INTO l_subtype FROM
1044 				iby_creditcard WHERE instrid = payerinstrid_in;
1045 		   END IF;
1046 	      END IF;
1047 
1048 	      IF ( G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
1049 		 print_debuginfo(l_module_name, 'l_instrsubtype:'|| l_instrsubtype);
1050 		 print_debuginfo(l_module_name, 'Sub Type from CC table:'|| l_subtype);
1051 	      END IF;
1052 
1053 	      prepare_instr_data
1054 	      (FND_API.G_FALSE,master_key_in,
1055 	       instrnum_in,l_instrtype,l_instrnum,l_instrsubtype,
1056 	       lx_cc_hash,lx_range_id,lx_instr_len,lx_segment_id);
1057 	      l_instrsubtype := NVL(l_instrsubtype,l_subtype);
1058        END IF ;
1059 
1060       IF ( G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
1061 	      print_debuginfo(l_module_name, 'payment channel code passed='||payment_channel_code_in);
1062 	      print_debuginfo(l_module_name, 'payment channel code passed='||payment_channel_code_in);
1063 	      print_debuginfo(l_module_name, 'settledate='||settlement_date_in);
1064 	      print_debuginfo(l_module_name, 'settlement_due_date='||settlement_due_date_in);
1065 
1066       END IF;
1067       INSERT INTO iby_trxn_summaries_all
1068 
1069 	(TrxnMID, TransactionID,TrxntypeID, ReqType, ReqDate,
1070 	 Amount,CurrencyNameCode, UpdateDate,Status, PaymentMethodName,
1071 	 TangibleID,MPayeeID, PayeeID,BEPID,bepKey, MtangibleId,
1072 	 BEPCode,BEPMessage,Errorlocation,ecappid,org_id,
1073 	 payerinstrid, instrnumber, payerid,
1074 	 last_update_date,last_updated_by,creation_date,created_by,
1075 	 last_update_login,object_version_number,instrType,instrsubtype,trxnref,         org_type, payment_channel_code, factored_flag,
1076          instrnum_hash, instrnum_length, cc_issuer_range_id,
1077          instrnum_sec_segment_id, payer_party_id, process_profile_code,
1078          salt_version,needsupdt, settledate, settlement_due_date)
1079       VALUES (l_trxn_mid, transaction_id_in_out, trxn_type_in,
1080 	      req_type_in, sysdate,
1081 	      amount_in, l_currency, time_in, status_in, payment_type_in,
1082 	      l_order_id, l_mpayeeid, merchant_id_in, vendor_id_in,
1083 	      vendor_key_in, l_tmid, vendor_code_in, vendor_message_in,
1084               error_location_in, ecapp_id_in, l_org_id,
1085               l_payerinstrid, l_instrnum, l_payerid,
1086 	      sysdate, fnd_global.user_id, sysdate, fnd_global.user_id,
1087               fnd_global.login_id, 1, l_instrtype, l_instrsubtype, trxnref_in,
1088               org_type_in, nvl(payment_channel_code_in, l_pmt_chnl_code), factored_flag_in,
1089               lx_cc_hash, lx_instr_len, lx_range_id, lx_segment_id,
1090               l_payer_party_id, l_process_profile_code,
1091               iby_security_pkg.get_salt_version,'Y', settlement_date_in, settlement_due_date_in
1092              );
1093 
1094       INSERT INTO iby_trxn_core
1095 	(TrxnMID, ReferenceCode, TraceNumber, InstrName,
1096          Instr_Expirydate, Card_Subtype_Code,
1097          Instr_Owner_Name, Instr_Owner_Address_Line1,
1098          Instr_Owner_Address_Line2, Instr_Owner_Address_Line3,
1099          Instr_Owner_City, Instr_Owner_State_Province, Instr_Owner_Country,
1100          Instr_Owner_PostalCode, Instr_Owner_Phone, Instr_Owner_Email,
1101 	 last_update_date,last_updated_by,creation_date,created_by,
1102 	 last_update_login,object_version_number)
1103       VALUES
1104          (l_trxn_mid, referencecode_in, trace_number_in, payment_name_in,
1105           l_expirydate, card_subtype_in,
1106           instr_owner_name_in, instr_address_line1_in, instr_address_line2_in,
1107           instr_address_line3_in, instr_city_in, instr_state_in,
1108           instr_country_in, instr_postalcode_in, instr_phonenumber_in,
1109           instr_email_in,
1110 	  sysdate,fnd_global.user_id,sysdate,fnd_global.user_id,
1111           fnd_global.login_id,1);
1112 
1113       insert_extensibility(l_trxn_mid,'N',extend_names_in,extend_vals_in);
1114 
1115 ELSIF (l_num_trxns = 1)    THEN
1116       -- One previous transaction, so update previous row
1117 
1118        SELECT TrxnMID,Mtangibleid,transactionid, instrnum_sec_segment_id
1119 	 INTO l_trxn_mid,l_tmid,transaction_id_in_out, l_old_segment_id
1120 	 FROM iby_trxn_summaries_all
1121 	WHERE TangibleID = order_id_in
1122 	  AND UPPER(ReqType) = UPPER(req_type_in)
1123 	  AND PayeeID = merchant_id_in
1124           AND Status IN (9,11);
1125 
1126         transaction_mid_out := l_trxn_mid;
1127 
1128 	IF (UPPER(req_type_in) = 'ORAPMTCREDIT') THEN
1129 	     --Update iby_tangible table
1130 	     iby_bill_pkg.modBill(l_tmid,order_id_in,amount_in,currency_in,
1131 				   billeracct_in,refinfo_in,memo_in,
1132                                    order_medium_in, eft_auth_method_in);
1133 
1134 		-- do not update 'payerinstrid, org_id' here, same reason
1135 		-- as shown in 'auth'
1136 
1137   l_expirydate := instr_expirydate_in;
1138         ELSE
1139 
1140           OPEN c_followon_info(transaction_id_in_out);
1141           FETCH c_followon_info INTO l_tmid, l_order_id, l_instrtype, l_instrsubtype,
1142 	                  l_process_profile_code, l_payer_party_id, l_pmt_chnl_code,
1143 			  l_currency, l_payerid, l_payerinstrid;
1144           l_cursor_empty := c_followon_info%NOTFOUND;
1145           CLOSE c_followon_info;
1146           IF (l_cursor_empty) THEN
1147             raise_application_error(-20000, 'IBY_20528#', FALSE);
1148           END IF;
1149 
1150  	END IF;
1151 -- Bug:14007884 - added paymentchannelcode.
1152 
1153       UPDATE iby_trxn_summaries_all
1154 	 SET BEPID = vendor_id_in,
1155 	     bepKey = vendor_key_in,
1156 	     Amount = amount_in,
1157 	     TrxntypeID = trxn_type_in,
1158 	     CurrencyNameCode = currency_in,
1159 	     UpdateDate = time_in,
1160 	     Status = status_in,
1161 	     ErrorLocation = error_location_in,
1162 	     BEPCode = vendor_code_in,
1163 	     BEPMessage = vendor_message_in,
1164              --payerinstrid = payerinstrid_in,
1165              PaymentMethodName = NVL(payment_type_in,PaymentMethodName),
1166              instrtype = NVL(l_instrtype,instrtype),
1167              instrsubtype = NVL(l_instrsubtype,instrsubtype),
1168              instrnumber = l_instrnum,
1169              instrnum_hash = lx_cc_hash,
1170              instrnum_length = lx_instr_len,
1171              cc_issuer_range_id = lx_range_id,
1172              instrnum_sec_segment_id = lx_segment_id,
1173              trxnref = trxnref_in,
1174 	     payment_channel_code = l_pmt_chnl_code,
1175 	     Last_Update_Date = sysdate,
1176 	     Last_Updated_by = fnd_global.user_id,
1177 	     Creation_Date = sysdate,
1178 	     Created_By = fnd_global.user_id,
1179 	     Object_Version_Number = object_version_number + 1
1180        WHERE TrxnMID = l_trxn_mid;
1181 
1182       DELETE iby_security_segments WHERE sec_segment_id = l_old_segment_id;
1183 
1184       UPDATE iby_trxn_core
1185 	 SET ReferenceCode = referencecode_in,
1186 	     TraceNumber = trace_number_in,
1187              InstrName = NVL(payment_name_in,InstrName),
1188              Instr_Expirydate = instr_expirydate_in,
1189              Card_Subtype_Code = card_subtype_in,
1190              Instr_Owner_Name = instr_owner_name_in,
1191              Instr_Owner_Address_Line1 = instr_address_line1_in,
1192              Instr_Owner_Address_Line2 = instr_address_line2_in,
1193              Instr_Owner_Address_Line3 = instr_address_line3_in,
1194              Instr_Owner_City = instr_city_in,
1195              Instr_Owner_State_Province = instr_state_in,
1196              Instr_Owner_Country = instr_country_in,
1197              Instr_Owner_PostalCode = instr_postalcode_in,
1198              Instr_Owner_Phone = instr_phonenumber_in,
1199              Instr_Owner_Email = instr_email_in,
1200 	     Last_Update_Date = sysdate,
1201 	     Last_Updated_by = fnd_global.user_id,
1202 	     Creation_Date = sysdate,
1203 	     Created_By = fnd_global.user_id,
1204 	     Object_Version_Number = object_version_number + 1
1205        WHERE TrxnMID = l_trxn_mid;
1206 
1207       insert_extensibility(l_trxn_mid,'N',extend_names_in,extend_vals_in);
1208 
1209     ELSE
1210       -- will never run into this block
1211       -- More than one previous transaction, which is an
1212       -- error
1213        	raise_application_error(-20000, 'IBY_20422#', FALSE);
1214       --raise_application_error(-20422, 'Multiple matching other transactions');
1215 
1216 
1217     END IF;
1218 
1219 
1220     -- for voids mark the target trxn as cancelled
1221     IF req_type_in='ORAPMTVOID' THEN
1222 
1223 	-- get the targe trxn type
1224 	--
1225 	IF trxn_type_in = 4 THEN
1226 	   -- auth only
1227 	   l_target_trxn_type := 2;
1228 
1229 	ELSIF trxn_type_in = 7 THEN
1230 	   -- auth capture
1231 	   l_target_trxn_type := 3;
1232 
1233 	ELSIF trxn_type_in = 13 THEN
1234 	   -- capture
1235 	   l_target_trxn_type := 8;
1236 
1237 	ELSIF trxn_type_in = 14 THEN
1238 	   -- mark capture
1239 	   l_target_trxn_type := 9;
1240 
1241 	ELSIF trxn_type_in = 17 THEN
1242 	   -- return
1243 	   l_target_trxn_type := 5;
1244 
1245 	ELSIF trxn_type_in = 18 THEN
1246 	   -- mark return
1247 	   l_target_trxn_type := 10;
1248 
1249 	ELSIF trxn_type_in = 19 THEN
1250 	   -- credit
1251 	   l_target_trxn_type := 11;
1252 
1253 	END IF;
1254 
1255 	UPDATE iby_trxn_summaries_all
1256 	SET
1257 	  -- CHANGE: UPDATE STATUS FOR VOIDED GATEWAY TRXNS
1258 	  --
1259 	  -- currently only change the status for processor
1260 	  -- batched trxns; in the future should probably
1261 	  -- update for gateway trxns as well
1262 	  --
1263 	  status=decode(status,100,114,status),
1264 	  last_update_date = sysdate,
1265    updatedate = sysdate,
1266 	  last_updated_by = fnd_global.user_id,
1267 	  object_version_number = object_version_number + 1
1268 	WHERE (transactionid=transaction_id_in_out) AND (trxntypeid=l_target_trxn_type);
1269     END IF;
1270 
1271     COMMIT;
1272 
1273 
1274   END insert_other_txn;
1275 
1276 
1277   /* Inserts a row into the iby_transaction table if auth, capture, */
1278   /* return, credit, and void timeout				   */
1279 
1280    PROCEDURE insert_timeout_txn
1281 	(req_type_in	     IN     iby_trxn_summaries_all.ReqType%TYPE,
1282 	 order_id_in	     IN     iby_transactions_v.order_id%TYPE,
1283 
1284 	 merchant_id_in      IN     iby_transactions_v.merchant_id%TYPE,
1285 	 vendor_id_in	     IN     iby_transactions_v.vendor_id%TYPE,
1286 	 vendor_key_in	     IN     iby_transactions_v.bepkey%TYPE,
1287 	 ecapp_id_in	  IN	 iby_trxn_summaries_all.ecappid%TYPE,
1288 	 time_in	    IN	   iby_transactions_v.time%TYPE,
1289 
1290 
1291 	 status_in	  IN	 iby_transactions_v.status%TYPE,
1292 	 org_id_in IN iby_trxn_summaries_all.org_id%type,
1293 	 amount_in	     IN     iby_tangible.amount%type,
1294 	 currency_in	     IN     iby_tangible.currencynamecode%type,
1295 	 billeracct_in	     IN     iby_tangible.acctno%type,
1296 	 refinfo_in	     IN     iby_tangible.refinfo%type,
1297 	 memo_in	     IN     iby_tangible.memo%type,
1298          order_medium_in     IN     iby_tangible.order_medium%TYPE,
1299          eft_auth_method_in  IN     iby_tangible.eft_auth_method%TYPE,
1300 	payerinstrid_in	IN	iby_trxn_summaries_all.payerinstrid%type,
1301 	instrnum_in	IN  iby_trxn_summaries_all.instrnumber%type,
1302 	payerid_in IN iby_trxn_summaries_all.payerid%type,
1303 	instrtype_in IN iby_trxn_summaries_all.instrType%type,
1304         master_key_in       IN     iby_security_pkg.DES3_KEY_TYPE,
1305         subkey_seed_in      IN     RAW,
1306         trxnref_in          IN     iby_trxn_summaries_all.trxnref%TYPE,
1307 	transaction_id_out  OUT NOCOPY iby_trxn_summaries_all.TransactionID%TYPE,
1308         transaction_mid_out OUT NOCOPY iby_trxn_summaries_all.trxnmid%TYPE,
1309         trxntypeid_in IN iby_trxn_summaries_all.trxntypeid%TYPE,
1310          org_type_in         IN      iby_trxn_summaries_all.org_type%TYPE,
1311          payment_channel_code_in  IN iby_trxn_summaries_all.payment_channel_code%TYPE,
1312          factored_flag_in         IN iby_trxn_summaries_all.factored_flag%TYPE,
1313 	 reauth_transaction_id    IN iby_trxn_summaries_all.TransactionID%TYPE
1314         )
1315 
1316    IS
1317 
1318     l_num_trxns      NUMBER	     := 0;
1319     l_trxn_mid	     NUMBER;
1320     transaction_id NUMBER;
1321     l_tmid iby_trxn_summaries_all.mtangibleid%type;
1322     l_order_id iby_trxn_summaries_all.tangibleid%type;
1323     l_mpayeeid iby_payee.mpayeeid%type;
1324     l_org_id NUMBER;
1325     l_instrsubtype iby_trxn_summaries_all.instrsubtype%type;
1326 
1327     l_return_status    VARCHAR2(1);
1328     l_msg_count        NUMBER;
1329     l_msg_data         VARCHAR2(200);
1330     l_checksum_valid   BOOLEAN := FALSE;  -- To check whether the card number is valid.
1331     l_cc_type        VARCHAR2(80);
1332 
1333     l_instrnum         iby_trxn_summaries_all.instrnumber%TYPE;
1334     l_subkey_id        iby_payee_subkeys.payee_subkey_id%TYPE;
1335 
1336   BEGIN
1337 
1338     -- Count number of previous PENDING transactions
1339 
1340      l_num_trxns := getNumPendingTrxns(merchant_id_in, order_id_in,
1341 					req_type_in);
1342 
1343     IF (l_num_trxns = 0)
1344     THEN
1345       -- Everything is fine, insert into table
1346       SELECT iby_trxnsumm_mid_s.NEXTVAL
1347 	INTO l_trxn_mid
1348 	FROM dual;
1349       IF(reauth_transaction_id > 0)THEN
1350 	transaction_id := reauth_transaction_id;
1351       ELSE
1352         transaction_id := getTID(merchant_id_in, order_id_in);
1353       END IF;
1354 
1355       transaction_id_out := transaction_id;
1356       transaction_mid_out := l_trxn_mid;
1357 
1358       iby_accppmtmthd_pkg.getMPayeeId(merchant_id_in, l_mpayeeid);
1359 
1360       -- Create an entry in iby_tangible table
1361       IF ((UPPER(req_type_in) = 'ORAPMTCREDIT') OR
1362 
1363 	  (UPPER(req_type_in) = 'ORAPMTREQ')) THEN
1364 	  iby_bill_pkg.createBill(order_id_in,amount_in,currency_in,
1365 		   	billeracct_in,refinfo_in, memo_in,
1366                         order_medium_in, eft_auth_method_in, l_tmid);
1367 
1368 	l_order_id := order_id_in;
1369 	l_org_id := org_id_in;
1370       ELSE
1371 	--tangible info should already exist, get them based on
1372 	--transactionid
1373 	SELECT DISTINCT mtangibleid, tangibleid
1374 	INTO l_tmid, l_order_id
1375 	FROM iby_trxn_summaries_all
1376 	WHERE transactionid = transaction_id_out
1377 	--
1378 	-- 100 is equivalent to 0
1379 	--
1380 	AND (status IN (0,100))
1381 	AND TRXNTYPEID NOT IN(22,23);
1382 
1383 	-- input org_id is null, check previous orgid
1384 	l_org_id := getOrgId(transaction_id_out);
1385       END IF;
1386 
1387       iby_cc_validate.ValidateCC(1.0,FND_API.G_FALSE,instrnum_in,SYSDATE(),l_return_status,l_msg_count,l_msg_data,l_checksum_valid,l_cc_type);
1388       IF (l_cc_type is NULL) THEN
1389         iby_cc_validate.ValidateCC(1.0,FND_API.G_FALSE,instrnum_in,SYSDATE(),l_return_status,l_msg_count,l_msg_data,l_checksum_valid,l_cc_type);
1390       END IF;
1391 /*
1392       prepare_instr_data(ecapp_id_in,merchant_id_in,master_key_in,
1393         instrnum_in,subkey_seed_in,FND_API.G_TRUE,l_instrnum,l_subkey_id);
1394 */
1395       INSERT INTO iby_trxn_summaries_all
1396 	(TrxnMID, TransactionID, ReqType, ReqDate,
1397 	 UpdateDate,Status, Amount, CurrencyNameCode,
1398 	 TangibleID,MPayeeID, PayeeID,BEPID,bepKey, ECAppID,org_id,mtangibleid,
1399 	payerinstrid, instrnumber, sub_key_id, payerid, instrType,
1400 	 last_update_date,last_updated_by,creation_date,created_by,
1401 	 last_update_login,object_version_number,instrsubtype,TrxnTypeID,trxnref,
1402          org_type, payment_channel_code, factored_flag,needsupdt)
1403       VALUES (l_trxn_mid, transaction_id_out, req_type_in, time_in,
1404 	      time_in, status_in, amount_in, currency_in,
1405 	      l_order_id, l_mpayeeid, merchant_id_in, vendor_id_in,
1406 		vendor_key_in, ecapp_id_in, l_org_id,l_tmid,
1407 		payerinstrid_in, l_instrnum, l_subkey_id, payerid_in, instrType_in,
1408 		sysdate,fnd_global.user_id,sysdate,fnd_global.user_id,
1409 		fnd_global.login_id,1,l_cc_type,trxntypeid_in,trxnref_in,
1410                 org_type_in, payment_channel_code_in, factored_flag_in,'Y');
1411 
1412 
1413       INSERT INTO iby_trxn_core
1414 	(TrxnMID,
1415 	 last_update_date,last_updated_by,creation_date,created_by,
1416 	 last_update_login,object_version_number)
1417       VALUES (l_trxn_mid,
1418 	 sysdate,fnd_global.user_id,sysdate,fnd_global.user_id,fnd_global.login_id,1);
1419 
1420 
1421     ELSIF (l_num_trxns = 1)    THEN
1422       -- One previous transaction, so update previous row
1423        SELECT TrxnMID, TransactionID, MtangibleId
1424 	 INTO l_trxn_mid, transaction_id_out, l_tmid
1425 
1426 	 FROM iby_trxn_summaries_all
1427 	WHERE TangibleID = order_id_in
1428 	  AND UPPER(ReqType) = UPPER(req_type_in)
1429 	  AND PayeeID = merchant_id_in
1430           AND Status IN (9,11);
1431 
1432       transaction_mid_out := l_trxn_mid;
1433 
1434       IF ((UPPER(req_type_in) = 'ORAPMTCREDIT') OR
1435 	  (UPPER(req_type_in) = 'ORAPMTREQ')) THEN
1436 	  -- Update iby_tangible table
1437  	iby_bill_pkg.modBill(l_tmid,order_id_in,amount_in,currency_in,
1438 			   billeracct_in,refinfo_in,memo_in,
1439                            order_medium_in, eft_auth_method_in);
1440 
1441       END IF;
1442 
1443       UPDATE iby_trxn_summaries_all
1444 	 SET UpdateDate = time_in,
1445 	     Status = status_in,
1446 	     BEPID = vendor_id_in,
1447 	     bepKey = vendor_key_in,
1448 	     ECAppID = ecapp_id_in,
1449 	-- not updating payerinstrid, org_id, org_type for the same reason
1450 		--payerinstrid = payerinstrid_in,
1451 		instrnumber = l_instrnum,
1452 		sub_key_id = l_subkey_id,
1453 		instrType = instrType_in,
1454              trxnref = trxnref_in,
1455 
1456 	     Last_Update_Date = sysdate,
1457 	     Last_Updated_by = fnd_global.user_id,
1458 	     Creation_Date = sysdate,
1459 	     Created_By = fnd_global.user_id,
1460 	     Object_Version_Number = object_version_number + 1,
1461              payment_channel_code = payment_channel_code_in,
1462              factored_flag = factored_flag_in
1463        WHERE TrxnMID = l_trxn_mid;
1464 
1465     ELSE
1466 
1467       -- will never run into this block
1468       -- More than one previous transaction, which is an
1469       -- error
1470        	raise_application_error(-20000, 'IBY_20422#', FALSE);
1471       --raise_application_error(-20422, 'Multiple matching timeout transactions');
1472 
1473     END IF;
1474 
1475     COMMIT;
1476 
1477   END insert_timeout_txn;
1478 
1479 
1480   /* Inserts a row about batch status into iby_batches_all.  This will */
1481   /* be called for link error, timeout error or other batch status   */
1482 
1483   PROCEDURE insert_batch_status
1484     (merch_batchid_in	 IN     iby_batches_all.batchid%TYPE,
1485      merchant_id_in	 IN     iby_batches_all.payeeid%TYPE,
1486      vendor_id_in        IN     iby_batches_all.bepid%TYPE,
1487      vendor_key_in       IN     iby_batches_all.bepkey%TYPE,
1488      pmt_type_in	 IN     iby_batches_all.paymentmethodname%TYPE,
1489      status_in		 IN     iby_batches_all.batchstatus%TYPE,
1490      time_in		 IN     iby_batches_all.batchclosedate%TYPE,
1491      viby_batchid_in	 IN     iby_batches_all.vpsbatchid%TYPE ,
1492      currency_in	 IN     iby_batches_all.currencynamecode%TYPE,
1493      numtrxns_in	 IN     iby_batches_all.NumTrxns%TYPE,
1494      batchstate_in	 IN     iby_batches_all.BatchStateid%TYPE,
1495      batchtotal_in	 IN     iby_batches_all.BatchTotal%TYPE,
1496      saleamount_in	 IN     iby_batches_all.BatchSales%TYPE,
1497      cramount_in	 IN     iby_batches_all.BatchCredit%TYPE,
1498      gwid_in		 IN     iby_batches_all.GWBatchID%TYPE,
1499      vendor_code_in	 IN     iby_batches_all.BEPcode%TYPE,
1500      vendor_message_in	 IN     iby_batches_all.BEPmessage%TYPE,
1501      error_location_in	 IN     iby_batches_all.errorlocation%TYPE,
1502      terminal_id_in	 IN     iby_batches_all.TerminalId%TYPE,
1503      acquirer_id_in	 IN     iby_batches_all.Acquirer%TYPE,
1504      org_id_in           IN     iby_trxn_summaries_all.org_id%TYPE,
1505      req_type_in         IN     iby_batches_all.reqtype%TYPE,
1506      sec_key_present_in  IN     VARCHAR2,
1507      mbatchid_out        OUT NOCOPY iby_batches_all.mbatchid%type
1508      )
1509   IS
1510 
1511     numrows NUMBER;
1512     l_mpayeeid iby_payee.mpayeeid%type;
1513     l_mbatchid iby_batches_all.mbatchid%type;
1514     l_beptype  iby_bepinfo.bep_type%TYPE;
1515     l_trxncount iby_batches_all.numtrxns%TYPE;
1516     l_batchcurr iby_batches_all.currencynamecode%TYPE;
1517     l_pinlessdebitcard  CONSTANT VARCHAR2(100) :='PINLESSDEBITCARD';
1518   BEGIN
1519 
1520    -- First check if a row already exists for this batch status
1521 
1522    SELECT COUNT(*)
1523    INTO numrows
1524    FROM iby_batches_all
1525    WHERE batchid = merch_batchid_in
1526      AND payeeid = merchant_id_in;
1527 
1528    -- insert batch status into iby_batches_all
1529 
1530   IF numrows = 0
1531 
1532   THEN
1533        --
1534        -- need to lock trxn summaries table to ensure that
1535        -- trxns which have not been validated do not sneak into
1536        -- the batch; gap between call to validate_open_batch
1537        -- and update of IBY_TRXN_SUMMARIES_ALL has been shown
1538        -- to be vulnerable to race conditions even under moderate
1539        -- concurrency loads
1540        --
1541        --LOCK TABLE iby_batches_all, iby_trxn_summaries_all IN EXCLUSIVE MODE;
1542 
1543        SELECT iby_batches_s.NEXTVAL
1544          INTO l_mbatchid
1545 	 FROM dual;
1546 
1547        mbatchid_out := l_mbatchid;
1548 
1549        l_batchcurr := currency_in;
1550        l_trxncount := numtrxns_in;
1551 
1552        SELECT NVL(bep_type,iby_bepinfo_pkg.C_BEPTYPE_GATEWAY)
1553          INTO l_beptype
1554          FROM iby_bepinfo
1555          WHERE (bepid=vendor_id_in);
1556 
1557        --
1558        -- if the bep is a processor, then we create a batch
1559        --
1560        IF ( (l_beptype = iby_bepinfo_pkg.C_BEPTYPE_PROCESSOR) AND
1561             ((req_type_in = iby_transactioncc_pkg.C_REQTYPE_BATCHCLOSE) OR
1562              (req_type_in = iby_transactioncc_pkg.C_REQTYPE_PDC_BATCHCLOSE)))
1563        THEN
1564 
1565          --
1566          -- associate all trxns in the current open batch
1567          -- with the bathc id of the batch close
1568          --
1569          UPDATE iby_trxn_summaries_all
1570           SET
1571             status = iby_transactioncc_pkg.C_STATUS_BATCH_PENDING,
1572             batchid = merch_batchid_in,
1573             mbatchid = l_mbatchid,
1574             last_update_date = sysdate,
1575             updatedate = sysdate,
1576             last_updated_by = fnd_global.user_id,
1577             object_version_number = object_version_number + 1
1578 	  WHERE (bepid = vendor_id_in)
1579 	    AND (bepkey = vendor_key_in)
1580 	    AND (payeeid = merchant_id_in)
1581 	    AND (status = iby_transactioncc_pkg.C_STATUS_OPEN_BATCHED)
1582 	    AND ((instrtype IN (iby_creditcard_pkg.C_INSTRTYPE_CCARD,
1583                            iby_creditcard_pkg.C_INSTRTYPE_PCARD)
1584 		AND
1585 	(req_type_in = iby_transactioncc_pkg.C_REQTYPE_BATCHCLOSE))
1586                  OR
1587 	(instrtype IN (l_pinlessdebitcard)
1588 		 AND
1589 	(req_type_in = iby_transactioncc_pkg.C_REQTYPE_PDC_BATCHCLOSE))
1590 	          OR
1591         instrtype IS NULL)
1592 	    AND (batchid IS NULL);
1593 
1594        END IF;
1595 
1596        iby_accppmtmthd_pkg.getMPayeeId(merchant_id_in, l_mpayeeid);
1597  -- Making Changes for bug:8363526
1598 -- Will insert value for settledate as SYSDATE.
1599    INSERT INTO iby_batches_all
1600      (MBATCHID, BATCHID, MPAYEEID, PAYEEID, BEPID, BEPKEY, PAYMENTMETHODNAME,
1601       BATCHSTATUS, BATCHCLOSEDATE, VPSBATCHID, CURRENCYNAMECODE,
1602       NUMTRXNS, BATCHSTATEID, BATCHTOTAL, BATCHSALES, BATCHCREDIT,
1603       GWBATCHID, BEPCODE, BEPMESSAGE, ERRORLOCATION,
1604 
1605       TerminalId, Acquirer,reqtype, reqdate,
1606       last_update_date,last_updated_by,creation_date,created_by,
1607 	last_update_login,  object_version_number,settledate)
1608    VALUES
1609      ( l_mbatchid, merch_batchid_in, l_mpayeeid, merchant_id_in, vendor_id_in,
1610       vendor_key_in, pmt_type_in, status_in, time_in, viby_batchid_in,
1611       '', 0, batchstate_in, batchtotal_in, saleamount_in,
1612       cramount_in, gwid_in, vendor_code_in, vendor_message_in,
1613       error_location_in, terminal_id_in, Acquirer_id_in,req_type_in, sysdate,
1614 	 sysdate,fnd_global.user_id,sysdate,fnd_global.user_id,fnd_global.login_id,1,sysdate);
1615 
1616       validate_open_batch(vendor_id_in, l_mbatchid, sec_key_present_in,
1617                           l_trxncount, l_batchcurr);
1618 
1619       UPDATE iby_batches_all
1620       SET CURRENCYNAMECODE = l_batchcurr,
1621           NUMTRXNS = l_trxncount
1622       WHERE mbatchid = l_mbatchid;
1623 
1624     ELSIF (numrows = 1)
1625     THEN
1626          l_trxncount := numtrxns_in;
1627          IF (l_trxncount<1) THEN
1628            l_trxncount := NULL;
1629          END IF;
1630       -- One previous transaction, so update previous row
1631       	 UPDATE iby_batches_all
1632 	 SET PAYMENTMETHODNAME = pmt_type_in,
1633 	     BATCHSTATUS = status_in,
1634 	     BATCHCLOSEDATE = time_in,
1635 	     CURRENCYNAMECODE = NVL(currency_in,CURRENCYNAMECODE),
1636 	     NUMTRXNS = NVL(l_trxncount,NUMTRXNS),
1637 	     BATCHSTATEID = batchstate_in,
1638 	     BATCHTOTAL = batchtotal_in,
1639 	     BATCHSALES = saleamount_in,
1640 	     BATCHCREDIT = cramount_in,
1641 	     GWBATCHID = gwid_in,
1642 	     BEPCODE = vendor_code_in,
1643 	     BEPMESSAGE = vendor_message_in,
1644 	     ERRORLOCATION = error_location_in,
1645 	     Last_Update_Date = sysdate,
1646 	     Last_Updated_by = fnd_global.user_id,
1647 
1648              -- Do not update creation timestamp
1649              -- when updating records: Bug 3128675
1650 	     --Creation_Date = sysdate,
1651 	     --Created_By = fnd_global.user_id,
1652 
1653 	     Object_Version_Number = Object_Version_Number + 1
1654 
1655        WHERE batchid = merch_batchid_in
1656 	 AND payeeid = merchant_id_in;
1657 
1658 	IF ((req_type_in = 'ORAPMTCLOSEBATCH') OR
1659             (req_type_in = 'ORAPMTPDCCLOSEBATCH') ) THEN
1660 		-- we don't update the following for querybatch
1661      	 	UPDATE iby_batches_all
1662 		     SET VPSBATCHID = viby_batchid_in,
1663 			reqtype = req_type_in,
1664 			reqdate = sysdate
1665        		WHERE batchid = merch_batchid_in
1666 	 		AND payeeid = merchant_id_in;
1667 	END IF;
1668 
1669         SELECT mbatchid
1670         INTO mbatchid_out
1671         FROM iby_batches_all
1672         WHERE batchid = merch_batchid_in
1673 	 AND payeeid = merchant_id_in;
1674 
1675    ELSE
1676       -- will never run into this block
1677       -- More than one pending transaction, which is an
1678       -- error
1679        	raise_application_error(-20000, 'IBY_20422#', FALSE);
1680   END IF;
1681 
1682   COMMIT;
1683 
1684   EXCEPTION
1685     WHEN OTHERS THEN
1686       ROLLBACK;
1687       --
1688       -- rethrow any internally generated exception
1689       --
1690       --raise_application_error(SQLCODE, SQLERRM, FALSE);
1691       RAISE;
1692   END insert_batch_status;
1693 
1694 /*--------------------------------------------------------------------
1695  | NAME:
1696  |     insert_batch_status_new
1697  |
1698  | PURPOSE:
1699  |
1700  |
1701  |
1702  | PARAMETERS:
1703  |     IN
1704  |
1705  |
1706  |     OUT
1707  |
1708  |
1709  | RETURNS:
1710  |
1711  | NOTES:
1712  |
1713  *---------------------------------------------------------------------*/
1714   PROCEDURE insert_batch_status_new
1715   (
1716   merch_batchid_in    IN     iby_batches_all.batchid%TYPE,
1717   profile_code_in     IN     iby_batches_all.process_profile_code%TYPE,
1718   merchant_id_in      IN     iby_batches_all.payeeid%TYPE,
1719   vendor_id_in        IN     iby_batches_all.bepid%TYPE,
1720   vendor_key_in       IN     iby_batches_all.bepkey%TYPE,
1721   pmt_type_in         IN     iby_batches_all.paymentmethodname%TYPE,
1722   status_in           IN     iby_batches_all.batchstatus%TYPE,
1723   time_in             IN     iby_batches_all.batchclosedate%TYPE,
1724   viby_batchid_in     IN     iby_batches_all.vpsbatchid%TYPE ,
1725   currency_in         IN     iby_batches_all.currencynamecode%TYPE,
1726   numtrxns_in         IN     iby_batches_all.NumTrxns%TYPE,
1727   batchstate_in	      IN     iby_batches_all.BatchStateid%TYPE,
1728   batchtotal_in	      IN     iby_batches_all.BatchTotal%TYPE,
1729   saleamount_in	      IN     iby_batches_all.BatchSales%TYPE,
1730   cramount_in	      IN     iby_batches_all.BatchCredit%TYPE,
1731   gwid_in             IN     iby_batches_all.GWBatchID%TYPE,
1732   vendor_code_in      IN     iby_batches_all.BEPcode%TYPE,
1733   vendor_message_in   IN     iby_batches_all.BEPmessage%TYPE,
1734   error_location_in   IN     iby_batches_all.errorlocation%TYPE,
1735   terminal_id_in      IN     iby_batches_all.TerminalId%TYPE,
1736   acquirer_id_in      IN     iby_batches_all.Acquirer%TYPE,
1737   org_id_in           IN     iby_trxn_summaries_all.org_id%TYPE,
1738   req_type_in         IN     iby_batches_all.reqtype%TYPE,
1739   sec_key_present_in  IN     VARCHAR2,
1740   acct_profile_in     IN     iby_batches_all.process_profile_code%TYPE,
1741   instr_type_in       IN     iby_batches_all.instrument_type%TYPE,
1742   br_disputed_flag_in IN     iby_batches_all.br_disputed_flag%TYPE,
1743   f_pmt_channel_in    IN     iby_trxn_summaries_all.
1744                                  payment_channel_code%TYPE,
1745   f_curr_in           IN     iby_trxn_summaries_all.
1746                                  currencynamecode%TYPE,
1747   f_settle_date       IN     iby_trxn_summaries_all.
1748                                  settledate%TYPE,
1749   f_due_date          IN     iby_trxn_summaries_all.
1750                                  settlement_due_date%TYPE,
1751   f_maturity_date     IN     iby_trxn_summaries_all.
1752                                  br_maturity_date%TYPE,
1753   f_instr_type        IN     iby_trxn_summaries_all.
1754                                  instrtype%TYPE,
1755   mbatch_ids_out      OUT    NOCOPY JTF_NUMBER_TABLE,
1756   batch_ids_out       OUT    NOCOPY JTF_VARCHAR2_TABLE_100
1757   )
1758   IS
1759 
1760   numrows NUMBER;
1761 
1762   l_mpayeeid  iby_payee.mpayeeid%type;
1763   l_mbatchid  iby_batches_all.mbatchid%type;
1764   l_beptype   iby_bepinfo.bep_type%TYPE;
1765   l_trxncount iby_batches_all.numtrxns%TYPE;
1766   l_batchcurr iby_batches_all.currencynamecode%TYPE;
1767 
1768   l_pinlessdebitcard  CONSTANT VARCHAR2(100) :='PINLESSDEBITCARD';
1769 
1770   l_batches_tab         batchAttrTabType;
1771   l_trxns_in_batch_tab  trxnsInBatchTabType;
1772   l_mbatch_ids_out      mBatchIdsTab;
1773 
1774   l_index               NUMBER;
1775 
1776   l_module_name         CONSTANT VARCHAR2(200) := G_PKG_NAME ||
1777                               '.insert_batch_status_new';
1778 
1779   /*
1780    * Cursor to pick up all existing mbatchids for
1781    * a given (batch id, payee id, profile code)
1782    * combination.
1783    */
1784   CURSOR c_mbatch_ids (batch_id   IBY_BATCHES_ALL.batchid%TYPE,
1785                        payee_id   IBY_BATCHES_ALL.payeeid%TYPE,
1786                        profile_cd IBY_BATCHES_ALL.process_profile_code%TYPE
1787                        )
1788   IS
1789   SELECT
1790       mbatchid
1791   FROM
1792       IBY_BATCHES_ALL
1793   WHERE
1794       batchid = batch_id                 AND
1795       payeeid = payee_id                 AND
1796       process_profile_code = profile_cd
1797   ;
1798 
1799  BEGIN
1800 
1801      IF ( G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
1802 	     print_debuginfo(l_module_name, 'ENTER');
1803 
1804      END IF;
1805      mbatch_ids_out := JTF_NUMBER_TABLE();
1806      batch_ids_out  := JTF_VARCHAR2_TABLE_100();
1807 
1808      /* First check if a row already exists for this batch status */
1809      SELECT
1810          COUNT(*)
1811      INTO
1812          numrows
1813      FROM
1814          IBY_BATCHES_ALL
1815      WHERE
1816          batchid = merch_batchid_in AND
1817          payeeid = merchant_id_in
1818      ;
1819 
1820      /*
1821       * If row does not exist, then insert batch status into iby_batches_all
1822       */
1823      IF numrows = 0 THEN
1824 
1825          IF ( G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
1826 	         print_debuginfo(l_module_name, 'num rows is zero');
1827 
1828          END IF;
1829          --
1830          -- need to lock trxn summaries table to ensure that
1831          -- trxns which have not been validated do not sneak into
1832          -- the batch; gap between call to validate_open_batch
1833          -- and update of IBY_TRXN_SUMMARIES_ALL has been shown
1834          -- to be vulnerable to race conditions even under moderate
1835          -- concurrency loads
1836          --
1837          --LOCK TABLE iby_batches_all, iby_trxn_summaries_all IN EXCLUSIVE MODE;
1838 
1839          --SELECT iby_batches_s.NEXTVAL
1840          --  INTO l_mbatchid
1841          --FROM dual;
1842 
1843          --mbatchid_out := l_mbatchid;
1844 
1845          l_batchcurr := currency_in;
1846          l_trxncount := numtrxns_in;
1847 
1848          SELECT
1849              NVL(bep_type,iby_bepinfo_pkg.C_BEPTYPE_GATEWAY)
1850          INTO
1851              l_beptype
1852          FROM
1853              IBY_BEPINFO
1854          WHERE
1855              (bepid=vendor_id_in)
1856          ;
1857 
1858          IF ( G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
1859 	         print_debuginfo(l_module_name, 'STEP 1');
1860 
1861          END IF;
1862          --
1863          -- if the bep is a processor, then we create a batch
1864          --
1865          IF (
1866              (l_beptype = iby_bepinfo_pkg.C_BEPTYPE_PROCESSOR) AND
1867              (
1868               (req_type_in = iby_transactioncc_pkg.C_REQTYPE_BATCHCLOSE) OR
1869               (req_type_in = iby_transactioncc_pkg.C_REQTYPE_PDC_BATCHCLOSE)
1870              )
1871             ) THEN
1872 
1873              IF ( G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
1874 	             print_debuginfo(l_module_name, 'Invoking grouping ..');
1875 
1876              END IF;
1877              /*
1878               * Group all the transactions for this profile into
1879               * batches as per the grouping attributes on the profile.
1880               */
1881              performTransactionGrouping(
1882                  profile_code_in,
1883                  instr_type_in,
1884                  req_type_in,
1885                  f_pmt_channel_in,
1886                  f_curr_in,
1887                  f_settle_date,
1888                  f_due_date,
1889                  f_maturity_date,
1890                  f_instr_type,
1891                  l_batches_tab,
1892                  l_trxns_in_batch_tab
1893                  );
1894 
1895              IF ( G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
1896 	             print_debuginfo(l_module_name, '# batches created: '
1897 	                 || l_batches_tab.COUNT);
1898 
1899 	             print_debuginfo(l_module_name, '# transactions processed: '
1900 	                 || l_trxns_in_batch_tab.COUNT);
1901 
1902              END IF;
1903              /*
1904               * After grouping it is possible that multiple batches were
1905               * created. Each batch will be a separate row in the
1906               * IBY_BATCHES_ALL table with a unique mbatchid.
1907               *
1908               * The user may have provided a batch id (batch prefix), we will
1909               * have to assign that batch id to each of the created batches.
1910               *
1911               * This batch id would be sent to the payment system. It therefore
1912               * has to be unique. Therefore, we add a suffix to the user
1913               * provided batch id to ensure that batches created after grouping
1914               * have a unique batch id.
1915               */
1916              IF (l_batches_tab.COUNT > 0) THEN
1917 
1918                  l_index := 1;
1919                  FOR k IN l_batches_tab.FIRST .. l_batches_tab.LAST LOOP
1920 
1921                      /*
1922                       * Assign a unique batch id to each batch.
1923                       */
1924                      l_batches_tab(k).batch_id :=
1925                          merch_batchid_in ||'_'|| l_index;
1926                      l_index := l_index + 1;
1927 
1928                  END LOOP;
1929 
1930              END IF;
1931 
1932              /*
1933               * After grouping, the transactions will be assigned a mbatch id.
1934               * Assign them a batch id as well (based on the batch id
1935               * corresponding to each mbatch id).
1936               */
1937              IF (l_trxns_in_batch_tab.COUNT > 0) THEN
1938 
1939                  FOR m IN l_trxns_in_batch_tab.FIRST ..
1940                      l_trxns_in_batch_tab.LAST LOOP
1941 
1942                      FOR k IN l_batches_tab.FIRST .. l_batches_tab.LAST LOOP
1943 
1944                          /*
1945                           * Find the mbatch id in the batches array
1946                           * corresponding to the mbatchid of this transaction.
1947                           */
1948                          IF (l_trxns_in_batch_tab(m).mbatch_id =
1949                              l_batches_tab(k).mbatch_id) THEN
1950 
1951                              /*
1952                               * Assign the batch id from the batches array
1953                               * to this transaction.
1954                               */
1955                              l_trxns_in_batch_tab(m).batch_id :=
1956                                  l_batches_tab(k).batch_id;
1957 
1958                          END IF;
1959 
1960                      END LOOP;
1961 
1962                  END LOOP;
1963 
1964              END IF;
1965 
1966              /*
1967               * BEP and vendor related params.
1968               */
1969              IF ( G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
1970 	             print_debuginfo(l_module_name, 'vendor_id_in: '
1971 	                 || vendor_id_in);
1972 	             print_debuginfo(l_module_name, 'vendor_key_in: '
1973 	                 || vendor_key_in);
1974 	             print_debuginfo(l_module_name, 'merchant_id_in: '
1975 	                 || merchant_id_in);
1976 	             print_debuginfo(l_module_name, 'req_type_in: '
1977 	                 || req_type_in);
1978 
1979              END IF;
1980              --
1981              -- associate all trxns in the current open batch
1982              -- with the batch id of the batch close
1983              --
1984              IF (l_trxns_in_batch_tab.COUNT <> 0) THEN
1985 
1986                  FOR i IN l_trxns_in_batch_tab.FIRST ..
1987                      l_trxns_in_batch_tab.LAST LOOP
1988 
1989                      /*
1990                       * This SQL statement has been replaced by
1991                       * the SQL update statement (below). It is kept
1992                       * here for documentation purposes.
1993                       */
1994                      /*------------------------------------------
1995                      UPDATE
1996                          IBY_TRXN_SUMMARIES_ALL
1997                      SET
1998                          status = iby_transactioncc_pkg.C_STATUS_BATCH_PENDING,
1999                          batchid = merch_batchid_in
2000                                      || '_' || i,
2001                          mbatchid = l_trxns_in_batch_tab(i).mbatch_id,
2002                          last_update_date = sysdate,
2003                          updatedate = sysdate,
2004                          last_updated_by = fnd_global.user_id,
2005                          object_version_number = object_version_number + 1
2006                      WHERE
2007                          (bepid = vendor_id_in)     AND
2008                          (bepkey = vendor_key_in)   AND
2009                          (payeeid = merchant_id_in) AND
2010                          (status = iby_transactioncc_pkg.C_STATUS_OPEN_BATCHED)i
2011                          AND
2012                          (
2013                            (instrtype IN
2014                                (iby_creditcard_pkg.C_INSTRTYPE_CCARD,
2015                                 iby_creditcard_pkg.C_INSTRTYPE_PCARD) AND
2016                            (req_type_in =
2017                                iby_transactioncc_pkg.C_REQTYPE_BATCHCLOSE))
2018                            OR
2019                            (instrtype IN (l_pinlessdebitcard) AND
2020                            (req_type_in = iby_transactioncc_pkg.
2021                                               C_REQTYPE_PDC_BATCHCLOSE)
2022                            )
2023                            OR
2024                            instrtype IS NULL
2025                          )
2026                          AND
2027                          (batchid IS NULL);
2028                      -------------------------------------------*/
2029 
2030                      IF ( G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
2031 	                     print_debuginfo(l_module_name, 'Going to update '
2032 	                         || 'transaction ' || l_trxns_in_batch_tab(i).trxn_id);
2033 
2034                      END IF;
2035                      UPDATE
2036                          IBY_TRXN_SUMMARIES_ALL
2037                      SET
2038                          status                = iby_transactioncc_pkg.
2039                                                      C_STATUS_BATCH_PENDING,
2040                          batchid               = l_trxns_in_batch_tab(i).
2041                                                      batch_id,
2042                          mbatchid              = l_trxns_in_batch_tab(i).
2043                                                      mbatch_id,
2044                          last_update_date      = sysdate,
2045                          updatedate            = sysdate,
2046                          last_updated_by       = fnd_global.user_id,
2047                          object_version_number = object_version_number + 1
2048                      WHERE
2049                          transactionid = l_trxns_in_batch_tab(i).trxn_id AND
2050                          status = iby_transactioncc_pkg.C_STATUS_OPEN_BATCHED
2051                          ;
2052 
2053                      IF ( G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
2054 	                     print_debuginfo(l_module_name, 'Finished updating '
2055 	                         || 'transaction'
2056 	                         || l_trxns_in_batch_tab(i).trxn_id
2057 	                         );
2058 
2059                      END IF;
2060                  END LOOP;
2061 
2062              END IF; -- if trxn count <> 0
2063 
2064          END IF; -- if bep type = PROCESSOR
2065 
2066          iby_accppmtmthd_pkg.getMPayeeId(merchant_id_in, l_mpayeeid);
2067 
2068          IF (l_batches_tab.COUNT <> 0) THEN
2069 
2070              FOR i IN l_batches_tab.FIRST .. l_batches_tab.LAST LOOP
2071 		 IF ( G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
2072 	                 print_debuginfo(l_module_name, 'Going to insert batch for mbatchid'
2073 	                     || l_batches_tab(i).mbatch_id);
2074 
2075                  END IF;
2076 
2077                  INSERT INTO
2078                      iby_batches_all
2079                  (
2080                  MBATCHID,
2081                  BATCHID,
2082                  MPAYEEID,
2083                  PAYEEID,
2084                  BEPID,
2085                  BEPKEY,
2086                  PAYMENTMETHODNAME,
2087                  BATCHSTATUS,
2088                  BATCHCLOSEDATE,
2089                  VPSBATCHID,
2090                  CURRENCYNAMECODE,
2091                  NUMTRXNS,
2092                  BATCHSTATEID,
2093                  BATCHTOTAL,
2094                  BATCHSALES,
2095                  BATCHCREDIT,
2096                  GWBATCHID,
2097                  BEPCODE,
2098                  BEPMESSAGE,
2099                  ERRORLOCATION,
2100                  TERMINALID,
2101                  ACQUIRER,
2102                  REQTYPE,
2103                  REQDATE,
2104                  PROCESS_PROFILE_CODE,
2105                  INSTRUMENT_TYPE,
2106                  BR_DISPUTED_FLAG,
2107                  LAST_UPDATE_DATE,
2108                  LAST_UPDATED_BY,
2109                  CREATION_DATE,
2110                  CREATED_BY,
2111                  LAST_UPDATE_LOGIN,
2112                  OBJECT_VERSION_NUMBER,
2113                  PAYEEINSTRID,
2114                  LEGAL_ENTITY_ID,
2115                  ORG_ID,
2116                  ORG_TYPE,
2117                  SETTLEDATE
2118                  )
2119                  VALUES
2120                  (
2121                  l_batches_tab(i).mbatch_id,
2122                  merch_batchid_in || '_' || i,
2123                  l_mpayeeid,
2124                  merchant_id_in,
2125                  vendor_id_in,
2126                  l_batches_tab(i).bep_key,
2127                  pmt_type_in,
2128                  status_in,
2129                  time_in,
2130                  viby_batchid_in,
2131                  l_batches_tab(i).curr_code,
2132                  0,
2133                  batchstate_in,
2134                  batchtotal_in,
2135                  saleamount_in,
2136                  cramount_in,
2137                  gwid_in,
2138                  vendor_code_in,
2139                  vendor_message_in,
2140                  error_location_in,
2141                  terminal_id_in,
2142                  Acquirer_id_in,
2143                  req_type_in,
2144                  sysdate,
2145                  l_batches_tab(i).profile_code,
2146                  instr_type_in,
2147                  br_disputed_flag_in,
2148                  sysdate,
2149                  fnd_global.user_id,
2150                  sysdate,
2151                  fnd_global.user_id,
2152                  fnd_global.login_id,
2153                  1,
2154                  l_batches_tab(i).int_bank_acct_id,
2155                  l_batches_tab(i).le_id,
2156                  l_batches_tab(i).org_id,
2157                  l_batches_tab(i).org_type,
2158                  l_batches_tab(i).settle_date
2159                  );
2160 
2161                  IF ( G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
2162 	                 print_debuginfo(l_module_name, 'finished insert '
2163 	                     || 'for batch id '
2164 	                     || l_batches_tab(i).mbatch_id
2165 	                     );
2166 
2167                  END IF;
2168                  validate_open_batch(
2169                      vendor_id_in,
2170                      l_batches_tab(i).mbatch_id,
2171                      sec_key_present_in,
2172                      l_trxncount,
2173                      l_batchcurr);
2174 
2175                  UPDATE
2176                      IBY_BATCHES_ALL
2177                  SET
2178                      currencynamecode = l_batchcurr,
2179                      numtrxns = l_trxncount
2180                  WHERE
2181                      mbatchid = l_batches_tab(i).mbatch_id
2182                  ;
2183 
2184                  /*
2185                   * Store the created mbatchids in the output param
2186                   * to return to the caller.
2187                   */
2188                  mbatch_ids_out.EXTEND;
2189                  mbatch_ids_out(i) := l_batches_tab(i).mbatch_id;
2190 
2191                  /*
2192                   * Store the created batchids in the output param
2193                   * to return to the caller.
2194                   */
2195                  batch_ids_out.EXTEND;
2196                  batch_ids_out(i) := l_batches_tab(i).batch_id;
2197 
2198              END LOOP;
2199 
2200          END IF; -- if l_batches_tab.COUNT <> 0
2201 
2202      ELSIF (numrows = 1) THEN
2203 
2204          l_trxncount := numtrxns_in;
2205 
2206          IF (l_trxncount<1) THEN
2207             l_trxncount := NULL;
2208          END IF;
2209 
2210          /* One previous transaction, so update previous row */
2211          UPDATE
2212              IBY_BATCHES_ALL
2213          SET
2214              PAYMENTMETHODNAME = pmt_type_in,
2215              BATCHSTATUS = status_in,
2216              BATCHCLOSEDATE = time_in,
2217              CURRENCYNAMECODE = NVL(currency_in,CURRENCYNAMECODE),
2218              NUMTRXNS = NVL(l_trxncount,NUMTRXNS),
2219              BATCHSTATEID = batchstate_in,
2220              BATCHTOTAL = batchtotal_in,
2221              BATCHSALES = saleamount_in,
2222              BATCHCREDIT = cramount_in,
2223              GWBATCHID = gwid_in,
2224              BEPCODE = vendor_code_in,
2225              BEPMESSAGE = vendor_message_in,
2226              ERRORLOCATION = error_location_in,
2227              LAST_UPDATE_DATE = sysdate,
2228              LAST_UPDATED_BY = fnd_global.user_id,
2229 
2230              -- Do not update creation timestamp
2231              -- when updating records: Bug 3128675
2232 	     --CREATION_DATE = sysdate,
2233 	     --CREATED_BY = fnd_global.user_id,
2234 
2235              OBJECT_VERSION_NUMBER = OBJECT_VERSION_NUMBER + 1
2236          WHERE
2237              batchid = merch_batchid_in AND
2238              payeeid = merchant_id_in
2239          ;
2240 
2241 	 IF ((req_type_in = 'ORAPMTCLOSEBATCH') OR
2242              (req_type_in = 'ORAPMTPDCCLOSEBATCH') ) THEN
2243 
2244              -- we don't update the following for querybatch
2245              UPDATE
2246                  iby_batches_all
2247              SET
2248                  VPSBATCHID = viby_batchid_in,
2249                  reqtype = req_type_in,
2250                  reqdate = sysdate
2251              WHERE
2252                  batchid = merch_batchid_in  AND
2253                  payeeid = merchant_id_in;
2254 
2255          END IF;
2256 
2257          --SELECT mbatchid
2258          --INTO mbatchid_out
2259          --FROM iby_batches_all
2260          --WHERE batchid = merch_batchid_in
2261          --AND payeeid = merchant_id_in;
2262 
2263          /*
2264           * Pick up all mbatchids for the given (batch id, merchant id,
2265           * account profile) combination.
2266           *
2267           * Since this is a retry, and retry is only applicable to a
2268           * specific batch, we should be getting only one mbatchid.
2269           */
2270          OPEN  c_mbatch_ids (merch_batchid_in, merchant_id_in, profile_code_in);
2271          FETCH c_mbatch_ids BULK COLLECT INTO l_mbatch_ids_out;
2272          CLOSE c_mbatch_ids;
2273 
2274          IF (l_mbatch_ids_out.COUNT <> 0) THEN
2275 
2276              FOR i IN l_mbatch_ids_out.FIRST .. l_mbatch_ids_out.LAST LOOP
2277 
2278                  /*
2279                   * In the retry scenario, the user will provide
2280                   * the batch id to retry explicitly. So in the
2281                   * retry case, we will returning only one batch id
2282                   * and one mbatch id.
2283                   */
2284 
2285                  mbatch_ids_out.EXTEND;
2286                  mbatch_ids_out(i) := l_mbatch_ids_out(i);
2287 
2288                  batch_ids_out.EXTEND;
2289                  batch_ids_out(i)  := merch_batchid_in;
2290 
2291              END LOOP;
2292 
2293          END IF;
2294 
2295      ELSE
2296 
2297          -- will never run into this block
2298          -- More than one pending transaction, which is an
2299          -- error
2300          raise_application_error(-20000, 'IBY_20422#', FALSE);
2301 
2302      END IF;
2303 
2304      IF ( G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
2305 	     print_debuginfo(l_module_name, 'mbatchids out count: '
2306 	       || mbatch_ids_out.COUNT);
2307 
2308      END IF;
2309      COMMIT;
2310 
2311  EXCEPTION
2312 
2313      WHEN OTHERS THEN
2314          ROLLBACK;
2315          --
2316          -- rethrow any internally generated exception
2317          --
2318          --raise_application_error(SQLCODE, SQLERRM, FALSE);
2319          RAISE;
2320 
2321  END insert_batch_status_new;
2322 
2323 
2324 /*--------------------------------------------------------------------
2325  | NAME:
2326  |     insert_batch_status_new
2327  |
2328  | PURPOSE:
2329  |     This is an Overloaded API of the previous one. This one
2330  |     takes an Array of Account FC profiles instead of a single on.
2331  |     This virtually means that we are accepting multiple bep keys in the API.
2332  |     THis will turn on the feature where we will have multiple divisions per
2333  |     Settlement Batch file.
2334  |
2335  | PARAMETERS:
2336  |     IN
2337  |
2338  |
2339  |     OUT
2340  |
2341  |
2342  | RETURNS:
2343  |
2344  | NOTES:
2345  |
2346  *---------------------------------------------------------------------*/
2347   PROCEDURE insert_batch_status_new
2348   (
2349   merch_batchid_in    IN     iby_batches_all.batchid%TYPE,
2350   profile_code_array  IN     JTF_VARCHAR2_TABLE_100,
2351   merchant_id_in      IN     iby_batches_all.payeeid%TYPE,
2352   vendor_id_in        IN     iby_batches_all.bepid%TYPE,
2353   vendor_key_in       IN     iby_batches_all.bepkey%TYPE,
2354   pmt_type_in         IN     iby_batches_all.paymentmethodname%TYPE,
2355   status_in           IN     iby_batches_all.batchstatus%TYPE,
2356   time_in             IN     iby_batches_all.batchclosedate%TYPE,
2357   viby_batchid_in     IN     iby_batches_all.vpsbatchid%TYPE ,
2358   currency_in         IN     iby_batches_all.currencynamecode%TYPE,
2359   numtrxns_in         IN     iby_batches_all.NumTrxns%TYPE,
2360   batchstate_in	      IN     iby_batches_all.BatchStateid%TYPE,
2361   batchtotal_in	      IN     iby_batches_all.BatchTotal%TYPE,
2362   saleamount_in	      IN     iby_batches_all.BatchSales%TYPE,
2363   cramount_in	      IN     iby_batches_all.BatchCredit%TYPE,
2364   gwid_in             IN     iby_batches_all.GWBatchID%TYPE,
2365   vendor_code_in      IN     iby_batches_all.BEPcode%TYPE,
2366   vendor_message_in   IN     iby_batches_all.BEPmessage%TYPE,
2367   error_location_in   IN     iby_batches_all.errorlocation%TYPE,
2368   terminal_id_in      IN     iby_batches_all.TerminalId%TYPE,
2369   acquirer_id_in      IN     iby_batches_all.Acquirer%TYPE,
2370   org_id_in           IN     iby_trxn_summaries_all.org_id%TYPE,
2371   req_type_in         IN     iby_batches_all.reqtype%TYPE,
2372   sec_key_present_in  IN     VARCHAR2,
2373   acct_profile_in     IN     iby_batches_all.process_profile_code%TYPE,
2374   instr_type_in       IN     iby_batches_all.instrument_type%TYPE,
2375   br_disputed_flag_in IN     iby_batches_all.br_disputed_flag%TYPE,
2376   f_pmt_channel_in    IN     iby_trxn_summaries_all.
2377                                  payment_channel_code%TYPE,
2378   f_curr_in           IN     iby_trxn_summaries_all.
2379                                  currencynamecode%TYPE,
2380   f_settle_date       IN     iby_trxn_summaries_all.
2381                                  settledate%TYPE,
2382   f_due_date          IN     iby_trxn_summaries_all.
2383                                  settlement_due_date%TYPE,
2384   f_maturity_date     IN     iby_trxn_summaries_all.
2385                                  br_maturity_date%TYPE,
2386   f_instr_type        IN     iby_trxn_summaries_all.
2387                                  instrtype%TYPE,
2388   mbatch_ids_out      OUT    NOCOPY JTF_NUMBER_TABLE,
2389   batch_ids_out       OUT    NOCOPY JTF_VARCHAR2_TABLE_100
2390   )
2391   IS
2392 
2393   numrows NUMBER;
2394 
2395   l_mpayeeid  iby_payee.mpayeeid%type;
2396   l_mbatchid  iby_batches_all.mbatchid%type;
2397   l_beptype   iby_bepinfo.bep_type%TYPE;
2398   l_trxncount iby_batches_all.numtrxns%TYPE;
2399   l_batchcurr iby_batches_all.currencynamecode%TYPE;
2400 --  profile_code_in   iby_batches_all.process_profile_code%TYPE;
2401   numProfiles NUMBER;
2402   strProfCodes VARCHAR2(4000);
2403 
2404   l_pinlessdebitcard  CONSTANT VARCHAR2(100) :='PINLESSDEBITCARD';
2405 
2406   l_batches_tab         batchAttrTabType;
2407   l_trxns_in_batch_tab  trxnsInBatchTabType;
2408   l_mbatch_ids_out      mBatchIdsTab;
2409 
2410   l_index               NUMBER;
2411 
2412   l_cursor_stmt         VARCHAR2(1000);
2413   TYPE dyn_batches      IS REF CURSOR;
2414   l_batch_cursor        dyn_batches;
2415 
2416   l_module_name         CONSTANT VARCHAR2(200) := G_PKG_NAME ||
2417                               '.insert_batch_status_new';
2418 
2419   /*
2420    * Cursor to pick up all existing mbatchids for
2421    * a given (batch id, payee id, profile code)
2422    * combination.
2423    */
2424 --  CURSOR c_mbatch_ids (batch_id   IBY_BATCHES_ALL.batchid%TYPE,
2425 --                       payee_id   IBY_BATCHES_ALL.payeeid%TYPE,
2426 --                       strProfiles VARCHAR2
2427 --                       )
2428 --  IS
2429 --  SELECT
2430 --      mbatchid
2431 --  FROM
2432 --      IBY_BATCHES_ALL
2433 --  WHERE
2434 --      batchid = batch_id                 AND
2435 --      payeeid = payee_id                 AND
2436 --      process_profile_code IN (strProfiles)
2437  -- ;
2438 
2439  BEGIN
2440 
2441      IF ( G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
2442 	     print_debuginfo(l_module_name, 'ENTER: overloaded API.');
2443 
2444      END IF;
2445      mbatch_ids_out := JTF_NUMBER_TABLE();
2446      batch_ids_out  := JTF_VARCHAR2_TABLE_100();
2447 
2448      /* Form a comma separated string for the profile codes */
2449      numProfiles := profile_code_array.count;
2450      FOR i IN 1..(numProfiles-1) LOOP
2451         strProfCodes := strProfCodes||''''||profile_code_array(i)||''',';
2452      END LOOP;
2453      /* Append the last profile code without comma at the end */
2454      strProfCodes := strProfCodes||''''||profile_code_array(numProfiles)||'''';
2455      IF ( G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
2456 	     print_debuginfo(l_module_name, 'Comma Separated string of profile codes: '|| strProfCodes);
2457 
2458      END IF;
2459      /*
2460       * Form the dynamic reference cursor to pick up
2461       * all existing mbatchids for a given (batchid,payeeid and
2462       * a string of profile codes)
2463       */
2464      l_cursor_stmt := ' SELECT mbatchid FROM                             '||
2465                       ' IBY_BATCHES_ALL WHERE                            '||
2466 		      ' batchid = '''||merch_batchid_in||''' AND         '||
2467 		      ' payeeid = '''||merchant_id_in||''' AND           '||
2468 		      ' process_profile_code IN ('||strProfCodes||')     '
2469 		      ;
2470 
2471 
2472      /* First check if a row already exists for this batch status */
2473      SELECT
2474          COUNT(*)
2475      INTO
2476          numrows
2477      FROM
2478          IBY_BATCHES_ALL
2479      WHERE
2480          batchid = merch_batchid_in AND
2481          payeeid = merchant_id_in
2482      ;
2483 
2484      /*
2485       * If row does not exist, then insert batch status into iby_batches_all
2486       */
2487      IF numrows = 0 THEN
2488 
2489          IF ( G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
2490 	         print_debuginfo(l_module_name, 'num rows is zero');
2491 
2492          END IF;
2493          --
2494          -- need to lock trxn summaries table to ensure that
2495          -- trxns which have not been validated do not sneak into
2496          -- the batch; gap between call to validate_open_batch
2497          -- and update of IBY_TRXN_SUMMARIES_ALL has been shown
2498          -- to be vulnerable to race conditions even under moderate
2499          -- concurrency loads
2500          --
2501          --LOCK TABLE iby_batches_all, iby_trxn_summaries_all IN EXCLUSIVE MODE;
2502 
2503          --SELECT iby_batches_s.NEXTVAL
2504          --  INTO l_mbatchid
2505          --FROM dual;
2506 
2507          --mbatchid_out := l_mbatchid;
2508 
2509          l_batchcurr := currency_in;-- should be made NULL
2510          l_trxncount := numtrxns_in;
2511 
2512          SELECT
2513              NVL(bep_type,iby_bepinfo_pkg.C_BEPTYPE_GATEWAY)
2514          INTO
2515              l_beptype
2516          FROM
2517              IBY_BEPINFO
2518          WHERE
2519              (bepid=vendor_id_in)
2520          ;
2521 
2522          IF ( G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
2523 	         print_debuginfo(l_module_name, 'STEP 1');
2524 
2525          END IF;
2526          --
2527          -- if the bep is a processor, then we create a batch
2528          --
2529          IF (
2530              (l_beptype = iby_bepinfo_pkg.C_BEPTYPE_PROCESSOR) AND
2531              (
2532               (req_type_in = iby_transactioncc_pkg.C_REQTYPE_BATCHCLOSE) OR
2533               (req_type_in = iby_transactioncc_pkg.C_REQTYPE_PDC_BATCHCLOSE)
2534              )
2535             ) THEN
2536 
2537              IF ( G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
2538 	             print_debuginfo(l_module_name, 'Invoking grouping ..');
2539 
2540              END IF;
2541              /*
2542               * Group all the transactions for this profile into
2543               * batches as per the grouping attributes on the profile.
2544               */
2545              performTransactionGrouping(
2546                  profile_code_array,
2547                  instr_type_in,
2548                  req_type_in,
2549                  f_pmt_channel_in,
2550                  f_curr_in,
2551                  f_settle_date,
2552                  f_due_date,
2553                  f_maturity_date,
2554                  f_instr_type,
2555 		 merch_batchid_in,
2556                  l_batches_tab,
2557                  l_trxns_in_batch_tab
2558                  );
2559 
2560              IF ( G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
2561 	             print_debuginfo(l_module_name, '# batches created: '
2562 	                 || l_batches_tab.COUNT);
2563 
2564 	             print_debuginfo(l_module_name, '# transactions processed: '
2565 	                 || l_trxns_in_batch_tab.COUNT);
2566 
2567              END IF;
2568              /*
2569               * After grouping it is possible that multiple batches were
2570               * created. Each batch will be a separate row in the
2571               * IBY_BATCHES_ALL table with a unique mbatchid.
2572               *
2573               * The user may have provided a batch id (batch prefix), we will
2574               * have to assign that batch id to each of the created batches.
2575               *
2576               * This batch id would be sent to the payment system. It therefore
2577               * has to be unique. Therefore, we add a suffix to the user
2578               * provided batch id to ensure that batches created after grouping
2579               * have a unique batch id.
2580               */
2581              --IF (l_batches_tab.COUNT > 0) THEN
2582 
2583                  --l_index := 1;
2584                  --FOR k IN l_batches_tab.FIRST .. l_batches_tab.LAST LOOP
2585 
2586                      /*
2587                       * Assign a unique batch id to each batch.
2588                       */
2589                      --l_batches_tab(k).batch_id :=
2590                          --merch_batchid_in ||'_'|| l_index;
2591                      --l_index := l_index + 1;
2592 
2593                  --END LOOP;
2594 
2595              --END IF;
2596 
2597              /*
2598               * After grouping, the transactions will be assigned a mbatch id.
2599               * Assign them a batch id as well (based on the batch id
2600               * corresponding to each mbatch id).
2601               */
2602              /*IF (l_trxns_in_batch_tab.COUNT > 0) THEN
2603 
2604                  FOR m IN l_trxns_in_batch_tab.FIRST ..
2605                      l_trxns_in_batch_tab.LAST LOOP
2606 
2607                      FOR k IN l_batches_tab.FIRST .. l_batches_tab.LAST LOOP
2608 
2609 
2610                          IF (l_trxns_in_batch_tab(m).mbatch_id =
2611                              l_batches_tab(k).mbatch_id) THEN
2612 
2613 
2614                              l_trxns_in_batch_tab(m).batch_id :=
2615                                  l_batches_tab(k).batch_id;
2616 
2617                          END IF;
2618 
2619                      END LOOP;
2620 
2621                  END LOOP;
2622 
2623              END IF;*/
2624 
2625              /*
2626               * BEP and vendor related params.
2627               */
2628              IF ( G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
2629 	             print_debuginfo(l_module_name, 'vendor_id_in: '
2630 	                 || vendor_id_in);
2631              END IF;
2632              /* need to change since mulitiple keys could be present here*/
2633              IF ( G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
2634 	             print_debuginfo(l_module_name, 'vendor_key_in: '
2635 	                 || vendor_key_in);
2636 	             print_debuginfo(l_module_name, 'merchant_id_in: '
2637 	                 || merchant_id_in);
2638 	             print_debuginfo(l_module_name, 'req_type_in: '
2639 	                 || req_type_in);
2640 
2641              END IF;
2642              --
2643              -- associate all trxns in the current open batch
2644              -- with the batch id of the batch close
2645              --
2646              --IF (l_trxns_in_batch_tab.COUNT <> 0) THEN
2647 
2648                  --FOR i IN l_trxns_in_batch_tab.FIRST ..
2649                      --l_trxns_in_batch_tab.LAST LOOP
2650 
2651                      /*
2652                       * This SQL statement has been replaced by
2653                       * the SQL update statement (below). It is kept
2654                       * here for documentation purposes.
2655                       */
2656                      /*------------------------------------------
2657                      UPDATE
2658                          IBY_TRXN_SUMMARIES_ALL
2659                      SET
2660                          status = iby_transactioncc_pkg.C_STATUS_BATCH_PENDING,
2661                          batchid = merch_batchid_in
2662                                      || '_' || i,
2663                          mbatchid = l_trxns_in_batch_tab(i).mbatch_id,
2664                          last_update_date = sysdate,
2665                          updatedate = sysdate,
2666                          last_updated_by = fnd_global.user_id,
2667                          object_version_number = object_version_number + 1
2668                      WHERE
2669                          (bepid = vendor_id_in)     AND
2670                          (bepkey = vendor_key_in)   AND
2671                          (payeeid = merchant_id_in) AND
2672                          (status = iby_transactioncc_pkg.C_STATUS_OPEN_BATCHED)i
2673                          AND
2674                          (
2675                            (instrtype IN
2676                                (iby_creditcard_pkg.C_INSTRTYPE_CCARD,
2677                                 iby_creditcard_pkg.C_INSTRTYPE_PCARD) AND
2678                            (req_type_in =
2679                                iby_transactioncc_pkg.C_REQTYPE_BATCHCLOSE))
2680                            OR
2681                            (instrtype IN (l_pinlessdebitcard) AND
2682                            (req_type_in = iby_transactioncc_pkg.
2683                                               C_REQTYPE_PDC_BATCHCLOSE)
2684                            )
2685                            OR
2686                            instrtype IS NULL
2687                          )
2688                          AND
2689                          (batchid IS NULL);
2690                      -------------------------------------------*/
2691 
2692                      --IF ( G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
2693 	                     --print_debuginfo(l_module_name, 'Going to update '
2694 	                         --|| 'transaction ' || l_trxns_in_batch_tab(i).trxn_id);
2695 
2696                      --END IF;
2697 
2698                      /*UPDATE
2699                          IBY_TRXN_SUMMARIES_ALL
2700                      SET
2701                          status                = iby_transactioncc_pkg.
2702                                                      C_STATUS_BATCH_PENDING,
2703                          batchid               = l_trxns_in_batch_tab(i).
2704                                                      batch_id,
2705                          mbatchid              = l_trxns_in_batch_tab(i).
2706                                                      mbatch_id,
2707                          last_update_date      = sysdate,
2708                          updatedate            = sysdate,
2709                          last_updated_by       = fnd_global.user_id,
2710                          object_version_number = object_version_number + 1
2711                      WHERE
2712                          transactionid = l_trxns_in_batch_tab(i).trxn_id AND
2713                          status = iby_transactioncc_pkg.C_STATUS_OPEN_BATCHED
2714                          ;*/
2715 
2716                      /*IF ( G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
2717 	                     print_debuginfo(l_module_name, 'Finished updating '
2718 	                         || 'transaction'
2719 	                         || l_trxns_in_batch_tab(i).trxn_id
2720 	                         );
2721 
2722                      END IF;*/
2723                  --END LOOP;
2724 
2725              --END IF; -- if trxn count <> 0
2726 
2727          END IF; -- if bep type = PROCESSOR
2728 
2729          iby_accppmtmthd_pkg.getMPayeeId(merchant_id_in, l_mpayeeid);
2730 
2731          IF (l_batches_tab.COUNT <> 0) THEN
2732 
2733              FOR i IN l_batches_tab.FIRST .. l_batches_tab.LAST LOOP
2734 
2735                  --Bug# 9313298
2736 		 --Assign the batch_id to the batches tab
2737 		 l_batches_tab(i).batch_id:=  merch_batchid_in || '_' || i;
2738 
2739 		 IF ( G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
2740 	                 print_debuginfo(l_module_name, 'Going to insert batch for mbatchid'
2741 	                     || l_batches_tab(i).mbatch_id);
2742 			 print_debuginfo(l_module_name, 'Going to insert batch for batchid'
2743 	                     || l_batches_tab(i).batch_id);
2744 
2745                  END IF;
2746 
2747                  INSERT INTO
2748                      iby_batches_all
2749                  (
2750                  MBATCHID,
2751                  BATCHID,
2752                  MPAYEEID,
2753                  PAYEEID,
2754                  BEPID,
2755                  BEPKEY,
2756                  PAYMENTMETHODNAME,
2757                  BATCHSTATUS,
2758                  BATCHCLOSEDATE,
2759                  VPSBATCHID,
2760                  CURRENCYNAMECODE,
2761                  NUMTRXNS,
2762                  BATCHSTATEID,
2763                  BATCHTOTAL,
2764                  BATCHSALES,
2765                  BATCHCREDIT,
2766                  GWBATCHID,
2767                  BEPCODE,
2768                  BEPMESSAGE,
2769                  ERRORLOCATION,
2770                  TERMINALID,
2771                  ACQUIRER,
2772                  REQTYPE,
2773                  REQDATE,
2774                  PROCESS_PROFILE_CODE,
2775                  INSTRUMENT_TYPE,
2776                  BR_DISPUTED_FLAG,
2777                  LAST_UPDATE_DATE,
2778                  LAST_UPDATED_BY,
2779                  CREATION_DATE,
2780                  CREATED_BY,
2781                  LAST_UPDATE_LOGIN,
2782                  OBJECT_VERSION_NUMBER,
2783                  PAYEEINSTRID,
2784                  LEGAL_ENTITY_ID,
2785                  ORG_ID,
2786                  ORG_TYPE,
2787                  SETTLEDATE
2788                  )
2789                  VALUES
2790                  (
2791                  l_batches_tab(i).mbatch_id,
2792                  merch_batchid_in || '_' || i,
2793                  l_mpayeeid,
2794                  merchant_id_in,
2795                  vendor_id_in,
2796                  l_batches_tab(i).bep_key,-- should be made NULL
2797                  pmt_type_in,
2798                  status_in,
2799                  time_in,
2800                  viby_batchid_in,
2801                  l_batches_tab(i).curr_code,-- should be made NULL
2802                  0,
2803                  batchstate_in,
2804                  batchtotal_in,
2805                  saleamount_in,
2806                  cramount_in,
2807                  gwid_in,
2808                  vendor_code_in,
2809                  vendor_message_in,
2810                  error_location_in,
2811                  terminal_id_in,
2812                  Acquirer_id_in,
2813                  req_type_in,
2814                  sysdate,
2815                 -- l_batches_tab(i).profile_code,-- should be made NULL
2816 		 profile_code_array(1),
2817                  instr_type_in,
2818                  br_disputed_flag_in,
2819                  sysdate,
2820                  fnd_global.user_id,
2821                  sysdate,
2822                  fnd_global.user_id,
2823                  fnd_global.login_id,
2824                  1,
2825                  l_batches_tab(i).int_bank_acct_id,
2826                  l_batches_tab(i).le_id,
2827                  l_batches_tab(i).org_id,
2828                  l_batches_tab(i).org_type,
2829                  l_batches_tab(i).settle_date
2830                  );
2831 
2832                  IF ( G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
2833 	                 print_debuginfo(l_module_name, 'finished insert '
2834 	                     || 'for mbatch id '
2835 	                     || l_batches_tab(i).mbatch_id
2836 	                     );
2837 
2838                  END IF;
2839                  validate_open_batch(
2840                      vendor_id_in,
2841                      l_batches_tab(i).mbatch_id,
2842                      sec_key_present_in,
2843                      l_trxncount,
2844                      l_batchcurr);
2845 
2846                  UPDATE
2847                      IBY_BATCHES_ALL
2848                  SET
2849                      currencynamecode = l_batchcurr,-- should be made NULL
2850                      numtrxns = l_trxncount
2851                  WHERE
2852                      mbatchid = l_batches_tab(i).mbatch_id
2853                  ;
2854 
2855                  /*
2856                   * Store the created mbatchids in the output param
2857                   * to return to the caller.
2858                   */
2859                  mbatch_ids_out.EXTEND;
2860                  mbatch_ids_out(i) := l_batches_tab(i).mbatch_id;
2861 
2862                  /*
2863                   * Store the created batchids in the output param
2864                   * to return to the caller.
2865                   */
2866                  batch_ids_out.EXTEND;
2867 		 --print_debuginfo(l_module_name, 'l_batches_tab(i).batch_id:'|| l_batches_tab(i).batch_id);
2868                  batch_ids_out(i) := l_batches_tab(i).batch_id;
2869 		 IF ( G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
2870 			print_debuginfo(l_module_name, 'batch_ids_out:'|| batch_ids_out(i));
2871 			print_debuginfo(l_module_name, 'mbatch_ids_out:'|| mbatch_ids_out(i));
2872 		 END IF;
2873 
2874              END LOOP;
2875 
2876          END IF; -- if l_batches_tab.COUNT <> 0
2877 
2878      ELSIF (numrows = 1) THEN
2879 
2880          l_trxncount := numtrxns_in;
2881 
2882          IF (l_trxncount<1) THEN
2883             l_trxncount := NULL;
2884          END IF;
2885 
2886          /* One previous transaction, so update previous row */
2887          UPDATE
2888              IBY_BATCHES_ALL
2889          SET
2890              PAYMENTMETHODNAME = pmt_type_in,
2891              BATCHSTATUS = status_in,
2892              BATCHCLOSEDATE = time_in,
2893              CURRENCYNAMECODE = NVL(currency_in,CURRENCYNAMECODE),-- should be made NULL
2894              NUMTRXNS = NVL(l_trxncount,NUMTRXNS),
2895              BATCHSTATEID = batchstate_in,
2896              BATCHTOTAL = batchtotal_in,
2897              BATCHSALES = saleamount_in,
2898              BATCHCREDIT = cramount_in,
2899              GWBATCHID = gwid_in,
2900              BEPCODE = vendor_code_in,
2901              BEPMESSAGE = vendor_message_in,
2902              ERRORLOCATION = error_location_in,
2903              LAST_UPDATE_DATE = sysdate,
2904              LAST_UPDATED_BY = fnd_global.user_id,
2905 
2906              -- Do not update creation timestamp
2907              -- when updating records: Bug 3128675
2908 	     --CREATION_DATE = sysdate,
2909 	     --CREATED_BY = fnd_global.user_id,
2910 
2911              OBJECT_VERSION_NUMBER = OBJECT_VERSION_NUMBER + 1
2912          WHERE
2913              batchid = merch_batchid_in AND
2914              payeeid = merchant_id_in
2915          ;
2916 
2917 	 IF ((req_type_in = 'ORAPMTCLOSEBATCH') OR
2918              (req_type_in = 'ORAPMTPDCCLOSEBATCH') ) THEN
2919 
2920              -- we don't update the following for querybatch
2921              UPDATE
2922                  iby_batches_all
2923              SET
2924                  VPSBATCHID = viby_batchid_in,
2925                  reqtype = req_type_in,
2926                  reqdate = sysdate
2927              WHERE
2928                  batchid = merch_batchid_in  AND
2929                  payeeid = merchant_id_in;
2930 
2931          END IF;
2932 
2933          --SELECT mbatchid
2934          --INTO mbatchid_out
2935          --FROM iby_batches_all
2936          --WHERE batchid = merch_batchid_in
2937          --AND payeeid = merchant_id_in;
2938 
2939          /*
2940           * Pick up all mbatchids for the given (batch id, merchant id,
2941           * account profile) combination.
2942           *
2943           * Since this is a retry, and retry is only applicable to a
2944           * specific batch, we should be getting only one mbatchid.
2945           */
2946   --       OPEN  c_mbatch_ids (merch_batchid_in, merchant_id_in, strProfCodes);
2947   --       FETCH c_mbatch_ids BULK COLLECT INTO l_mbatch_ids_out;
2948   --       CLOSE c_mbatch_ids;
2949 
2950            OPEN l_batch_cursor FOR l_cursor_stmt;
2951 	   FETCH l_batch_cursor BULK COLLECT INTO l_mbatch_ids_out;
2952 	   CLOSE l_batch_cursor;
2953 
2954          IF (l_mbatch_ids_out.COUNT <> 0) THEN
2955 
2956              FOR i IN l_mbatch_ids_out.FIRST .. l_mbatch_ids_out.LAST LOOP
2957 
2958                  /*
2959                   * In the retry scenario, the user will provide
2960                   * the batch id to retry explicitly. So in the
2961                   * retry case, we will returning only one batch id
2962                   * and one mbatch id.
2963                   */
2964 
2965                  mbatch_ids_out.EXTEND;
2966                  mbatch_ids_out(i) := l_mbatch_ids_out(i);
2967 
2968                  batch_ids_out.EXTEND;
2969                  batch_ids_out(i)  := merch_batchid_in;
2970 
2971              END LOOP;
2972 
2973          END IF;
2974 
2975      ELSE
2976 
2977          -- will never run into this block
2978          -- More than one pending transaction, which is an
2979          -- error
2980          raise_application_error(-20000, 'IBY_20422#', FALSE);
2981 
2982      END IF;
2983 
2984      IF ( G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
2985 	     print_debuginfo(l_module_name, 'mbatchids out count: '
2986 	       || mbatch_ids_out.COUNT);
2987 	     print_debuginfo(l_module_name, 'batchids out count: '
2988 	       || batch_ids_out.COUNT);
2989 
2990      END IF;
2991      COMMIT;
2992 
2993  EXCEPTION
2994 
2995      WHEN OTHERS THEN
2996          ROLLBACK;
2997          --
2998          -- rethrow any internally generated exception
2999          --
3000          --raise_application_error(SQLCODE, SQLERRM, FALSE);
3001          RAISE;
3002 
3003  END insert_batch_status_new;
3004 
3005 
3006 
3007 /*--------------------------------------------------------------------
3008  | NAME:
3009  |     performTransactionGrouping
3010  |
3011  | PURPOSE:
3012  |
3013  |
3014  |
3015  | PARAMETERS:
3016  |     IN
3017  |
3018  |
3019  |     OUT
3020  |
3021  |
3022  | RETURNS:
3023  |
3024  | NOTES:
3025  |
3026  *---------------------------------------------------------------------*/
3027  PROCEDURE performTransactionGrouping(
3028      p_profile_code       IN IBY_FNDCPT_USER_CC_PF_B.
3029                                  user_cc_profile_code%TYPE,
3030      instr_type           IN IBY_TRXN_SUMMARIES_ALL.
3031                                  instrtype%TYPE,
3032      req_type             IN IBY_BATCHES_ALL.
3033                                  reqtype%TYPE,
3034      f_pmt_channel_in     IN IBY_TRXN_SUMMARIES_ALL.
3035                                  payment_channel_code%TYPE,
3036      f_curr_in            IN IBY_TRXN_SUMMARIES_ALL.
3037                                  currencynamecode%TYPE,
3038      f_settle_date        IN IBY_TRXN_SUMMARIES_ALL.
3039                                  settledate%TYPE,
3040      f_due_date           IN IBY_TRXN_SUMMARIES_ALL.
3041                                  settlement_due_date%TYPE,
3042      f_maturity_date      IN IBY_TRXN_SUMMARIES_ALL.
3043                                  br_maturity_date%TYPE,
3044      f_instr_type         IN IBY_TRXN_SUMMARIES_ALL.
3045                                  instrtype%TYPE,
3046      x_batchTab           IN OUT NOCOPY IBY_TRANSACTIONCC_PKG.
3047                                             batchAttrTabType,
3048      x_trxnsInBatchTab    IN OUT NOCOPY IBY_TRANSACTIONCC_PKG.
3049                                             trxnsInBatchTabType
3050      )
3051  IS
3052  l_module_name           CONSTANT VARCHAR2(200) := G_PKG_NAME ||
3053                                                   '.performTransactionGrouping';
3054 
3055  l_sql_str               VARCHAR2(5000);
3056  l_cursor_stmt           VARCHAR2(8000);
3057 
3058  l_first_record          VARCHAR2(1)   := 'Y';
3059 
3060  /* user defined grouping rule flags */
3061  l_org_flag              VARCHAR2(1)   := 'N';
3062  l_le_flag               VARCHAR2(1)   := 'N';
3063  l_int_bnk_flag          VARCHAR2(1)   := 'N';
3064  l_curr_flag             VARCHAR2(1)   := 'N';
3065  l_settle_date_flag      VARCHAR2(1)   := 'N';
3066 
3067  /* user defined limits */
3068  l_max_trxn_limit        NUMBER(15)    := 0;
3069  l_fx_rate_type          VARCHAR2(255) := '';
3070  l_fx_curr_code          VARCHAR2(10)  := '';
3071  l_max_amount_limit      NUMBER(15)    := 0;
3072 
3073  /*
3074   * NOTE:
3075   *
3076   * IBY_BATCHES_ALL.batchid  = user generated batch id
3077   * IBY_BATCHES_ALL.mbatchid = system generated batch id
3078   *
3079   * If batch close is invoked by the user, the batchid will
3080   * be a user defined string (should be unique).
3081   *
3082   * If batch close is invoked by the scheduler, the batch is
3083   * be a sequence number (iby_batchid_s.nextval).
3084   *
3085   * mbatchid will always be a sequence number (iby_batchid_s.nextval).
3086   *
3087   * In the new architecture, multiple mbatchids can be generated
3088   * for a single batchid (based on user defined grouping rules).
3089   */
3090  l_mbatch_id             IBY_BATCHES_ALL.mbatchid%TYPE;
3091  l_batch_total           NUMBER(15)    := 0;
3092  l_trxns_in_batch_count  NUMBER(15)    := 0;
3093 
3094  l_trx_fx_amount         NUMBER(15)    := 0;
3095 
3096  /*
3097   * Used to substitute null values in date comparisons.
3098   * It is assumed that not document payable would ever
3099   * have a year 1100 date.
3100   */
3101  l_impossible_date       DATE := TO_DATE('01/01/1100 10:25:55',
3102                                      'MM/DD/YYYY HH24:MI:SS');
3103 
3104  /*
3105   * These two are related data structures. Each row in batchAttrTabType
3106   * PLSQL table is used in inserting a row into the IBY_BATCHES_ALL
3107   * table.
3108   *
3109   * A separate data structure is needed to keep track of the transactions
3110   * that are part of a batch. This information is tracked in the
3111   * trxnsInBatchTabType table. The rows in trxnsInBatchTabType are
3112   * used to update the rows in IBY_TRXN_SUMMARIES_ALL table with
3113   * batch ids.
3114   *
3115   *            l_batchTab                        l_trxnsInBatchTab
3116   *       (insert into IBY_BATCHES_ALL)   (update IBY_TRXN_SUMMARIES_ALL)
3117   * /-------------------------------------\       /------------\
3118   * |MBatch |Profile|..|Curr   |Org    |..|       |MBatch |Trx |
3119   * |Id     |Code   |..|Code   |Id     |..|       |Id     |Id  |
3120   * |       |       |..|       |       |..|       |       |    |
3121   * |-------------------------------------|       |------------|
3122   * |   4000|     10|  |    USD|    204|  |       |   4000| 501|
3123   * |       |       |  |       |       |  |       |   4000| 504|
3124   * |       |       |  |       |       |  |       |   4000| 505|
3125   * |-------|-------|--|-------|-------|--|       |-------|----|
3126   * |   4001|     11|  |    -- |    342|  |       |   4001| 502|
3127   * |       |       |  |       |       |  |       |   4001| 509|
3128   * |       |       |  |       |       |  |       |   4001| 511|
3129   * |       |       |  |       |       |  |       |   4001| 523|
3130   * |       |       |  |       |       |  |       |     : |  : |
3131   * |-------|-------|--|-------|-------|--|       |-------|----|
3132   * |    :  |     : |  |    :  |     : |  |       |     : |  : |
3133   * \_______|_______|__|_______|_______|__/       \_______|____/
3134   *
3135   */
3136 
3137  l_batchRec          IBY_TRANSACTIONCC_PKG.batchAttrRecType;
3138  l_trxnsInBatchTab   IBY_TRANSACTIONCC_PKG.trxnsInBatchTabType;
3139 
3140  l_trxnsInBatchRec   IBY_TRANSACTIONCC_PKG.trxnsInBatchRecType;
3141  l_batchTab          IBY_TRANSACTIONCC_PKG.batchAttrTabType;
3142 
3143  l_trxnGrpCriTab     IBY_TRANSACTIONCC_PKG.trxnGroupCriteriaTabType;
3144 
3145  l_pinlessdebitcard  CONSTANT VARCHAR2(100) :='PINLESSDEBITCARD';
3146  l_bankaccount       CONSTANT VARCHAR2(100) :='BANKACCOUNT';
3147 
3148  /* previous transaction attributes */
3149  prev_trxn_id                iby_trxn_summaries_all.transactionid%TYPE;
3150  prev_trxn_currency          iby_trxn_summaries_all.currencynamecode%TYPE;
3151  prev_trxn_amount            iby_trxn_summaries_all.amount%TYPE;
3152  prev_int_bank_acct_id       iby_trxn_summaries_all.payeeinstrid%TYPE;
3153  prev_org_id                 iby_trxn_summaries_all.org_id%TYPE;
3154  prev_org_type               iby_trxn_summaries_all.org_type%TYPE;
3155  prev_settle_date            iby_trxn_summaries_all.settledate%TYPE;
3156  prev_le_id                  iby_trxn_summaries_all.legal_entity_id%TYPE;
3157  prev_bep_key                iby_trxn_summaries_all.bepkey%TYPE;
3158  prev_profile_cd             iby_trxn_summaries_all.process_profile_code%TYPE;
3159 
3160  /* current transaction attributes */
3161  curr_trxn_id                iby_trxn_summaries_all.transactionid%TYPE;
3162  curr_trxn_currency          iby_trxn_summaries_all.currencynamecode%TYPE;
3163  curr_trxn_amount            iby_trxn_summaries_all.amount%TYPE;
3164  curr_int_bank_acct_id       iby_trxn_summaries_all.payeeinstrid%TYPE;
3165  curr_org_id                 iby_trxn_summaries_all.org_id%TYPE;
3166  curr_org_type               iby_trxn_summaries_all.org_type%TYPE;
3167  curr_settle_date            iby_trxn_summaries_all.settledate%TYPE;
3168  curr_le_id                  iby_trxn_summaries_all.legal_entity_id%TYPE;
3169  curr_bep_key                iby_trxn_summaries_all.bepkey%TYPE;
3170  curr_profile_cd             iby_trxn_summaries_all.process_profile_code%TYPE;
3171  l_user_pf_table_name        VARCHAR2(100);
3172  l_sys_pf_table_name         VARCHAR2(100);
3173  l_user_pf_column_name       VARCHAR2(100);
3174  l_sys_pf_column_name        VARCHAR2(100);
3175 
3176  l_numeric_char_mask         VARCHAR2(100);
3177 
3178  TYPE dyn_transactions       IS REF CURSOR;
3179  l_trxn_cursor               dyn_transactions;
3180 
3181  /*
3182   * This cursor up will pick up all valid transactions for
3183   * the specified payment profile. The select statement will
3184   * order the transactions based on grouping criteria.
3185   *
3186   * Important Note:
3187   *
3188   * Always ensure that there is a corresponding order by
3189   * clause for each grouping criterion that you wish to use.
3190   * This is required in order to create minimum possible
3191   * batches from a given set of transactions.
3192   *
3193   * Note 2: The sample sql is not right as the base table for
3194   * process profile is different
3195   * the dynamic sql is changed according to that
3196   */
3197  CURSOR c_transactions (
3198             p_profile_code VARCHAR2,
3199             p_instr_type   VARCHAR2,
3200             p_req_type     VARCHAR2
3201             )
3202  IS
3203  SELECT
3204      txn.transactionid,
3205      txn.process_profile_code,
3206      txn.bepkey,
3207      txn.org_id,
3208      txn.org_type,
3209      txn.currencynamecode,
3210      txn.amount,
3211      txn.legal_entity_id,
3212      txn.payeeinstrid,
3213      txn.settledate,
3214      sys_prof.group_by_org,
3215      sys_prof.group_by_legal_entity,
3216      sys_prof.group_by_int_bank_account,
3217      sys_prof.group_by_settlement_curr,
3218      sys_prof.group_by_settlement_date,
3219      sys_prof.limit_by_amt_curr,
3220      sys_prof.limit_by_exch_rate_type,
3221      sys_prof.limit_by_total_amt,
3222      sys_prof.limit_by_settlement_num
3223  FROM
3224      IBY_TRXN_SUMMARIES_ALL  txn,
3225      IBY_FNDCPT_USER_CC_PF_B user_prof,
3226      IBY_FNDCPT_SYS_CC_PF_B  sys_prof
3227  WHERE
3228      user_prof.user_cc_profile_code = p_profile_code               AND
3229      txn.process_profile_code     = user_prof.user_cc_profile_code AND
3230      sys_prof.sys_cc_profile_code = user_prof.sys_cc_profile_code  AND
3231      txn.status = iby_transactioncc_pkg.C_STATUS_OPEN_BATCHED      AND
3232      (
3233          /*
3234           * This clause will pick up credit card / purchase card
3235           * transactions.
3236           */
3237          (
3238              p_instr_type IN
3239              (
3240                  iby_creditcard_pkg.C_INSTRTYPE_CCARD,
3241                  iby_creditcard_pkg.C_INSTRTYPE_PCARD
3242              )
3243              AND
3244              (
3245                  txn.reqtype IN
3246                  (
3247                  iby_transactioncc_pkg.C_REQTYPE_BATCHCLOSE,
3248                  iby_transactioncc_pkg.C_REQTYPE_CAPTURE,
3249                  iby_transactioncc_pkg.C_REQTYPE_CREDIT,
3250                  iby_transactioncc_pkg.C_REQTYPE_RETURN
3251                  )
3252              )
3253              AND
3254              (
3255                  txn.instrtype IN
3256                  (
3257                  iby_creditcard_pkg.C_INSTRTYPE_CCARD,
3258                  iby_creditcard_pkg.C_INSTRTYPE_PCARD
3259                  )
3260              )
3261          )
3262 
3263          /*
3264           * This clause will pick up pinless debit card
3265           * transactions.
3266           */
3267          OR
3268          (
3269              p_instr_type IN
3270              (
3271                  l_pinlessdebitcard
3272              )
3273              AND
3274              (
3275                  txn.reqtype IN
3276                  (
3277                  iby_transactioncc_pkg.C_REQTYPE_PDC_BATCHCLOSE,
3278                  iby_transactioncc_pkg.C_REQTYPE_REQUEST
3279                  )
3280              )
3281              AND
3282              (
3283                  txn.instrtype IN
3284                  (
3285                  l_pinlessdebitcard
3286                  )
3287              )
3288          )
3289 
3290          /*
3291           * This clause will pick up bank account transactions
3292           * transactions.
3293           */
3294          OR
3295          (
3296              p_instr_type IN
3297              (
3298                  l_bankaccount
3299              )
3300              AND
3301              (
3302                  txn.reqtype IN
3303                  (
3304                  iby_transactioncc_pkg.C_REQTYPE_EFT_BATCHCLOSE,
3305                  iby_transactioncc_pkg.C_REQTYPE_BATCHREQ
3306                  )
3307              )
3308              AND
3309              (
3310                  txn.instrtype IN
3311                  (
3312                  l_bankaccount
3313                  )
3314              )
3315 
3316              /*
3317               * Fix for bug 5442922:
3318               *
3319               * For bank account instruments, the auth / verify
3320               * transaction will have trantypeid 20; The
3321               * capture transaction will have trxntypeid 100.
3322               *
3323               * Since we are picking up only capture transactions
3324               * here, explicitly specify the trxntypeid in the
3325               * WHERE clause. Otherwise, auths are also picked
3326               * up and put into the batch.
3327               */
3328              AND
3329              (
3330                  /*
3331                   * This trxn type 100 maps to
3332                   * IBY_FNDCPT_TRXN_PUB.BA_CAPTURE_TRXNTYPE
3333                   */
3334                  txn.trxntypeid = 100
3335              )
3336          )
3337 
3338          /*
3339           * This clause will pick up any transaction which does not
3340           * have an instrument type. This looks dangerous to me but
3341           * kept for backward compatibility - Ramesh
3342           */
3343          OR
3344          (
3345              txn.instrtype IS NULL
3346          )
3347      )                                                             AND
3348      txn.batchid IS NULL                                           AND
3349      /*
3350       *  Fix for bug 5632947:
3351       *
3352       *  Join with CE_SECURITY_PROFILES_V for MOAC compliance.
3353       */
3354      ((txn.org_id IS NULL) OR
3355      ((txn.org_id IS NOT NULL) AND
3356      (txn.org_id, txn.org_type) IN
3357          (SELECT
3358               ce.organization_id,
3359               ce.organization_type
3360           FROM
3361               ce_security_profiles_v ce
3362          )))
3363  ORDER BY
3364      txn.process_profile_code,   --
3365      txn.bepkey,                 -- Ensure that the
3366      txn.org_id,                 -- grouping rules below
3367      txn.org_type,               -- follow this same
3368      txn.legal_entity_id,        -- order (necessary
3369      txn.payeeinstrid,           -- for creating minimum
3370      txn.currencynamecode,       -- number of batches)
3371      txn.settledate              --
3372  ;
3373 
3374 
3375  BEGIN
3376 
3377      IF ( G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
3378 	     print_debuginfo(l_module_name, 'ENTER');
3379 
3380 	     print_debuginfo(l_module_name, 'Payment Profile Cd: '||
3381 	         p_profile_code);
3382 	     print_debuginfo(l_module_name, 'Instrument Type: '   ||
3383 	         instr_type);
3384 	     print_debuginfo(l_module_name, 'Request Type: '      ||
3385 	         req_type);
3386 
3387      END IF;
3388      /*
3389       * Filter params.
3390       */
3391      IF ( G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
3392 	     print_debuginfo(l_module_name, 'f_pmt_channel_in: '
3393 	         || f_pmt_channel_in);
3394 	     print_debuginfo(l_module_name, 'f_curr_in: '
3395 	         || f_curr_in);
3396 	     print_debuginfo(l_module_name, 'f_settle_date: '
3397 	         || f_settle_date);
3398 	     print_debuginfo(l_module_name, 'f_due_date: '
3399 	         || f_due_date);
3400 	     print_debuginfo(l_module_name, 'f_maturity_date: '
3401 	         || f_maturity_date);
3402 	     print_debuginfo(l_module_name, 'f_instr_type: '
3403 	         || f_instr_type);
3404 
3405      END IF;
3406      /*
3407       * Fix for bug 5407120:
3408       *
3409       * Before we do anything, alter the session to set the numeric
3410       * character mask. This is because of XML publisher limitation -
3411       * it cannot handle numbers like '230,56' which is the European
3412       * representation of '230.56'.
3413       *
3414       * Therefore, we explicitly set the numeric character mask at the
3415       * beginning of this routine and revert back to the default
3416       * setting at the end of this method.
3417       */
3418      BEGIN
3419 
3420          SELECT
3421              value
3422          INTO
3423              l_numeric_char_mask
3424          FROM
3425              V$NLS_PARAMETERS
3426          WHERE
3427              parameter='NLS_NUMERIC_CHARACTERS'
3428          ;
3429 
3430          IF ( G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
3431 	         print_debuginfo(l_module_name, 'Current numeric char mask: '
3432 	             || l_numeric_char_mask
3433 	             );
3434 
3435          END IF;
3436      EXCEPTION
3437          WHEN OTHERS THEN
3438              IF ( G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
3439 	             print_debuginfo(l_module_name, 'Non-Fatal: Exception occured '
3440 	                 || 'when attempting to retrieve numeric character mask.'
3441 	                 );
3442 
3443 	             print_debuginfo(l_module_name, 'SQL code: '   || SQLCODE);
3444 	             print_debuginfo(l_module_name, 'SQL err msg: '|| SQLERRM);
3445              END IF;
3446      END;
3447 
3448      /*
3449       * Now alter the session, to force the NLS numeric character
3450       * decimal indicator to be a '.'.
3451       */
3452      BEGIN
3453 
3454          EXECUTE IMMEDIATE
3455              'ALTER SESSION SET NLS_NUMERIC_CHARACTERS = ".,"'
3456              ;
3457 
3458      EXCEPTION
3459          WHEN OTHERS THEN
3460              IF ( G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
3461 	             print_debuginfo(l_module_name, 'Non-Fatal: Exception occured '
3462 	                 || 'when attempting to later session to set '
3463 	                 || 'numeric character mask.'
3464 	                 );
3465 
3466 	             print_debuginfo(l_module_name, 'SQL code: '   || SQLCODE);
3467 	             print_debuginfo(l_module_name, 'SQL err msg: '|| SQLERRM);
3468              END IF;
3469      END;
3470 
3471      /*
3472       * Dynamically form SQL string to limit the rows that
3473       * are picked up for the batch close operation.
3474       *
3475       * Use the supplied filter parameters to form the SQL
3476       * string.
3477       */
3478      IF (f_pmt_channel_in IS NOT NULL) THEN
3479      l_sql_str:= l_sql_str||'AND nvl(payment_channel_code'''||f_pmt_channel_in||''') = '
3480                           || '''' || f_pmt_channel_in || '''';
3481      END IF;
3482 
3483      IF (f_curr_in IS NOT NULL) THEN
3484          l_sql_str := l_sql_str || ' AND currencynamecode = '
3485                           || '''' || f_curr_in || '''';
3486      END IF;
3487 
3488      IF (f_settle_date IS NOT NULL) THEN
3489          l_sql_str := l_sql_str || ' AND nvl(settledate,'''||f_settle_date||''') <= '
3490                           || '''' || f_settle_date || '''';
3491      END IF;
3492 
3493      IF (f_due_date IS NOT NULL) THEN
3494          l_sql_str := l_sql_str || ' AND settlement_due_date <= '
3495                           || '''' || f_due_date || '''';
3496      END IF;
3497 
3498      IF (f_maturity_date IS NOT NULL) THEN
3499          l_sql_str := l_sql_str || ' AND br_maturity_date <= '
3500                           || '''' || f_maturity_date || '''';
3501      END IF;
3502 
3503      IF (f_instr_type IS NOT NULL) THEN
3504          l_sql_str := l_sql_str || ' AND nvl(instrtype,'''||f_instr_type||''') = '
3505                           || '''' || f_instr_type || '''';
3506      END IF;
3507 
3508      IF ( G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
3509 	     print_debuginfo(l_module_name, 'Dynamic SQL snippet: '
3510 	         || l_sql_str);
3511 
3512      END IF;
3513     /* determine the process profile table and column */
3514 
3515      l_user_pf_table_name :='IBY_FNDCPT_USER_CC_PF_B';
3516      l_sys_pf_table_name  :='IBY_FNDCPT_SYS_CC_PF_B';
3517      l_user_pf_column_name :='USER_CC_PROFILE_CODE';
3518      l_sys_pf_column_name :='SYS_CC_PROFILE_CODE';
3519   IF (instr_type IS NOT NULL) THEN
3520        if(instr_type =l_bankaccount) THEN
3521                     l_user_pf_table_name :='IBY_FNDCPT_USER_EFT_PF_B';
3522                     l_sys_pf_table_name  :='IBY_FNDCPT_SYS_EFT_PF_B';
3523                     l_user_pf_column_name :='USER_EFT_PROFILE_CODE';
3524                     l_sys_pf_column_name :='SYS_EFT_PROFILE_CODE';
3525        ELSIF  (instr_type =l_pinlessdebitcard) THEN
3526                     l_user_pf_table_name :='IBY_FNDCPT_USER_DC_PF_B';
3527                     l_sys_pf_table_name  :='IBY_FNDCPT_SYS_DC_PF_B';
3528                     l_user_pf_column_name :='USER_DC_PROFILE_CODE';
3529                     l_sys_pf_column_name :='SYS_DC_PROFILE_CODE';
3530        END IF;
3531 
3532    END IF;
3533      /*
3534       * The cursor below is the same as the cursor c_transactions
3535       * defined at the beginning of this method.
3536       *
3537       * We cannot directly use c_transactions because we need to use
3538       * the provided filter params to form a dynamic where clause.
3539       *
3540       * For this reason, this cursor has been made into a dynamic cursor.
3541       * c_transactions is kept for documentation / debugging purposes
3542       * but is not used.
3543       */
3544      l_cursor_stmt :=
3545      'SELECT '
3546          || 'txn.transactionid,                  '
3547          || 'txn.process_profile_code,           '
3548          || 'txn.bepkey,                         '
3549          || 'txn.org_id,                         '
3550          || 'txn.org_type,                       '
3551          || 'txn.currencynamecode,               '
3552          || 'txn.amount,                         '
3553          || 'txn.legal_entity_id,                '
3554          || 'txn.payeeinstrid,                   '
3555          || 'txn.settledate,                     '
3556          || 'sys_prof.group_by_org,              '
3557          || 'sys_prof.group_by_legal_entity,     '
3558          || 'sys_prof.group_by_int_bank_account, '
3559          || 'sys_prof.group_by_settlement_curr,  '
3560          || 'sys_prof.group_by_settlement_date,  '
3561          || 'sys_prof.limit_by_amt_curr,         '
3562          || 'sys_prof.limit_by_exch_rate_type,   '
3563          || 'sys_prof.limit_by_total_amt,        '
3564          || 'sys_prof.limit_by_settlement_num    '
3565      || 'FROM  '
3566          || 'IBY_TRXN_SUMMARIES_ALL  txn,        '
3567          || l_user_pf_table_name || '  user_prof,  '
3568          ||  l_sys_pf_table_name || '  sys_prof    '
3569      || 'WHERE '
3570          || 'user_prof.'||l_user_pf_column_name||'  = :profile_code     AND '
3571          || 'txn.process_profile_code     = user_prof.'||l_user_pf_column_name||'  AND '
3572          || 'sys_prof.' ||l_sys_pf_column_name||'   = user_prof. '||l_sys_pf_column_name || ' AND '
3573          || 'txn.status = :open_batch                                      AND '
3574          || '( '
3575              /*
3576               * This clause will pick up credit card / purchase card
3577               * transactions.
3578               */
3579              || '( '
3580                 || ':A IN (:C1, :C2) AND (txn.reqtype IN (:T1A, :T1B, :T1C, :T1D)) AND '
3581                 || '(txn.instrtype IN (:C3, :C4)) '
3582              || ') '
3583 
3584              /*
3585               * This clause will pick up pinless debit card
3586               * transactions.
3587               */
3588              || 'OR '
3589              || '( '
3590                  || ':C IN (:P1) AND (txn.reqtype IN (:T2A, :T2B)) AND '
3591                  || '(txn.instrtype IN (:P2)) '
3592              || ') '
3593 
3594              /*
3595               * This clause will pick up bank account transactions
3596               * transactions.
3597               */
3598 
3599              || 'OR '
3600              || '( '
3601                  || ':E IN (:B1) AND (txn.reqtype IN (:T3A, :T3B, :T3C)) AND '
3602                  || '(txn.instrtype IN (:B2)) '
3603 
3604 
3605                  /*
3606                   * Fix for bug 5442922:
3607                   *
3608                   * For bank account instruments, the auth / verify
3609                   * transaction will have trantypeid 20; The
3610                   * capture transaction will have trxntypeid 100.
3611                   *
3612                   * Since we are picking up only capture transactions
3613                   * here, explicitly specify the trxntypeid in the
3614                   * WHERE clause. Otherwise, auths are also picked
3615                   * up and put into the batch.
3616                   */
3617                  || 'AND '
3618                  || '( '
3619                      /*
3620                       * This trxn type 100 maps to
3621                       * IBY_FNDCPT_TRXN_PUB.BA_CAPTURE_TRXNTYPE
3622                       */
3623                      || 'txn.trxntypeid = 100 '
3624                  || ') '
3625 
3626              || ') '
3627 
3628              /*
3629               * This clause will pick up any transaction which does not
3630               * have an instrument type. This looks dangerous to me but
3631               * kept for backward compatibility - Ramesh
3632               */
3633              || 'OR '
3634              || '( '
3635                  || 'txn.instrtype IS NULL '
3636              || ') '
3637          || ')                                                             AND '
3638          || 'txn.batchid IS NULL                                           AND '
3639          /*
3640           *  Fix for bug 5632947:
3641           *
3642           *  Join with CE_SECURITY_PROFILES_V for MOAC compliance.
3643           */
3644          || '((txn.org_id IS NULL) OR '
3645          || '((txn.org_id IS NOT NULL) AND '
3646          || '(txn.org_id, txn.org_type) IN '
3647          || '    (SELECT '
3648          || '         ce.organization_id, '
3649          || '         ce.organization_type '
3650          || '     FROM  '
3651          || '         ce_security_profiles_v ce '
3652          || '    ))) '
3653          || NVL (l_sql_str, 'AND 1=1 ')
3654      || 'ORDER BY '
3655          || 'txn.process_profile_code, '  --
3656          || 'txn.bepkey,               '  -- Ensure that the
3657          || 'txn.org_id,               '  -- grouping rules below
3658          || 'txn.org_type,             '  -- follow this same
3659          || 'txn.legal_entity_id,      '  -- order (necessary
3660          || 'txn.payeeinstrid,         '  -- for creating minimum
3661          || 'txn.currencynamecode,     '  -- number of batches)
3662          || 'txn.settledate            '  --
3663      ;
3664 
3665      OPEN l_trxn_cursor FOR
3666          l_cursor_stmt
3667      USING
3668          p_profile_code,                                 /* profile_code */
3669          iby_transactioncc_pkg.C_STATUS_OPEN_BATCHED,    /* open_batch */
3670          instr_type,                                     /* A */
3671          iby_creditcard_pkg.C_INSTRTYPE_CCARD,           /* C1 */
3672          iby_creditcard_pkg.C_INSTRTYPE_PCARD,           /* C2 */
3673          iby_transactioncc_pkg.C_REQTYPE_BATCHCLOSE,     /* T1A */
3674          iby_transactioncc_pkg.C_REQTYPE_CAPTURE,        /* T1B */
3675          iby_transactioncc_pkg.C_REQTYPE_CREDIT,         /* T1C */
3676          iby_transactioncc_pkg.C_REQTYPE_RETURN,         /* T1D */
3677          iby_creditcard_pkg.C_INSTRTYPE_CCARD,           /* C3 */
3678          iby_creditcard_pkg.C_INSTRTYPE_PCARD,           /* C4 */
3679          instr_type,                                     /* C */
3680          l_pinlessdebitcard,                             /* P1 */
3681          iby_transactioncc_pkg.C_REQTYPE_PDC_BATCHCLOSE, /* T2A */
3682          iby_transactioncc_pkg.C_REQTYPE_REQUEST,        /* T2B */
3683          l_pinlessdebitcard,                             /* P2 */
3684          instr_type,                                     /* E */
3685          l_bankaccount,                                  /* B1 */
3686          iby_transactioncc_pkg.C_REQTYPE_EFT_BATCHCLOSE, /* T3A */
3687          iby_transactioncc_pkg.C_REQTYPE_BATCHREQ,       /* T3B */
3688          iby_transactioncc_pkg.C_REQTYPE_REQUEST,        /* T3C */
3689          l_bankaccount                                   /* B2 */
3690          ;
3691      FETCH l_trxn_cursor BULK COLLECT INTO l_trxnGrpCriTab;
3692      CLOSE l_trxn_cursor;
3693 
3694      /*
3695       * Exit if no documents were found.
3696       */
3697      IF (l_trxnGrpCriTab.COUNT = 0) THEN
3698          IF ( G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
3699 	         print_debuginfo(l_module_name, 'No transactions were '
3700 	             || 'retrieved from DB for profile '
3701 	             || p_profile_code
3702 	             || '. Exiting transaction grouping ..');
3703 
3704 	         print_debuginfo(l_module_name, 'EXIT');
3705          END IF;
3706          RETURN;
3707      ELSE
3708          IF ( G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
3709 	         print_debuginfo(l_module_name, '# valid transactions '
3710 	             || 'retrieved from DB for profile '
3711 	             || p_profile_code
3712 	             || ' = '
3713 	             || l_trxnGrpCriTab.COUNT);
3714          END IF;
3715      END IF;
3716 
3717      /*
3718       * Loop through all the fetched documents, grouping them
3719       * into payments.
3720       */
3721      FOR i in l_trxnGrpCriTab.FIRST .. l_trxnGrpCriTab.LAST LOOP
3722 
3723          curr_trxn_id           := l_trxnGrpCriTab(i).trxn_id;
3724          curr_profile_cd        := l_trxnGrpCriTab(i).process_profile_code;
3725          curr_int_bank_acct_id  := l_trxnGrpCriTab(i).int_bank_acct_id;
3726          curr_bep_key           := l_trxnGrpCriTab(i).bep_key;
3727          curr_org_id            := l_trxnGrpCriTab(i).org_id;
3728          curr_org_type          := l_trxnGrpCriTab(i).org_type;
3729          curr_trxn_currency     := l_trxnGrpCriTab(i).curr_code;
3730          curr_trxn_amount       := l_trxnGrpCriTab(i).amount;
3731          curr_le_id             := l_trxnGrpCriTab(i).legal_entity_id;
3732          curr_settle_date       := l_trxnGrpCriTab(i).settle_date;
3733 
3734          l_org_flag             := l_trxnGrpCriTab(i).group_by_org;
3735          l_le_flag              := l_trxnGrpCriTab(i).group_by_le;
3736          l_int_bnk_flag         := l_trxnGrpCriTab(i).group_by_int_bank_acct;
3737          l_curr_flag            := l_trxnGrpCriTab(i).group_by_curr;
3738          l_settle_date_flag     := l_trxnGrpCriTab(i).group_by_settle_date;
3739 
3740          l_max_trxn_limit       := l_trxnGrpCriTab(i).num_trxns_limit;
3741 
3742          l_fx_rate_type         := l_trxnGrpCriTab(i).fx_rate_type;
3743          l_fx_curr_code         := l_trxnGrpCriTab(i).max_amt_curr;
3744          l_max_amount_limit     := l_trxnGrpCriTab(i).max_amt_limit;
3745 
3746          /*
3747           * Log all the fetched document fields
3748           */
3749          IF ( G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
3750 	         print_debuginfo(l_module_name,
3751 	             'Fetched data for transaction:' || curr_trxn_id
3752 	             || ', internal bank account: ' || curr_int_bank_acct_id
3753 	             || ', profile: '               || curr_profile_cd
3754 	             || ', bep key: '               || curr_bep_key
3755 	             || ', org: '                   || curr_org_id
3756 	             || ', org type: '              || curr_org_type
3757 	             || ', le:  '                   || curr_le_id
3758 	             || ', currency: '              || curr_trxn_currency
3759 	             || ', amount: '                || curr_trxn_amount
3760 	             || ', settle date: '           || curr_settle_date
3761 	             );
3762 
3763 	         print_debuginfo(l_module_name,
3764 	             'Fetched data for transaction:' || curr_trxn_id
3765 	             || ', org flag: '               || l_org_flag
3766 	             || ', le flag: '                || l_le_flag
3767 	             || ', int bank acct flag: '     || l_int_bnk_flag
3768 	             || ', currency flag: '          || l_curr_flag
3769 	             || ', settle date flag: '       || l_settle_date_flag
3770 	             || ', max trxns limit: '        || l_max_trxn_limit
3771 	             || ', max amount limit: '       || l_max_amount_limit
3772 	             || ', exch rate: '              || l_fx_rate_type
3773 	             || ', exch currency: '          || l_fx_curr_code
3774 	             );
3775 
3776          END IF;
3777          IF (l_first_record = 'Y') THEN
3778              prev_trxn_id              := curr_trxn_id;
3779              prev_int_bank_acct_id     := curr_int_bank_acct_id;
3780              prev_profile_cd           := curr_profile_cd;
3781              prev_org_id               := curr_org_id;
3782              prev_org_type             := curr_org_type;
3783              prev_le_id                := curr_le_id;
3784              prev_bep_key              := curr_bep_key;
3785              prev_trxn_currency        := curr_trxn_currency;
3786              prev_trxn_amount          := curr_trxn_amount;
3787              prev_settle_date          := curr_settle_date;
3788          END IF;
3789 
3790          /*
3791           * We have just fetched a new transaction for this profile.
3792           * We will either insert this transaction into a new batch or
3793           * we will be inserting this transaction into the currently running
3794           * batch.
3795           *
3796           * In either case, we need to insert this trxn into a batch.
3797           * So pre-populate the batch record with attributes of
3798           * this document. This is because the batch takes on the
3799           * attributes of its constituent transactions.
3800           *
3801           * Note: For user defined grouping rules, we will
3802           * have to populate the batch attributes only if
3803           * the user has turned on grouping by that attribute.
3804           */
3805 
3806          /* Only pre-fill hardcoded grouping rule attributes */
3807          l_batchRec.profile_code       := curr_profile_cd;
3808          l_batchRec.bep_key            := curr_bep_key;
3809 
3810          /*
3811           * Pre-fill grouping rule attributes for user defined
3812           * grouping rules (that are enabled by the user).
3813           *
3814           * It is necessary to pre-fill user defined grouping
3815           * attributes before the grouping rules are triggered
3816           * because we don't know which user defined grouping rules
3817           * are going to get triggered first, and once a rule is
3818           * triggered all rules below it are skipped. So it is too
3819           * late to populate grouping attributes within the grouping
3820           * rule itself.
3821           */
3822          IF (l_org_flag = 'Y') THEN
3823              l_batchRec.org_id   := curr_org_id;
3824              l_batchRec.org_type := curr_org_type;
3825          END IF;
3826 
3827          IF (l_le_flag = 'Y') THEN
3828              l_batchRec.le_id := curr_le_id;
3829          END IF;
3830 
3831          IF (l_int_bnk_flag = 'Y') THEN
3832              l_batchRec.int_bank_acct_id := curr_int_bank_acct_id;
3833          END IF;
3834 
3835          IF (l_curr_flag = 'Y') THEN
3836              l_batchRec.curr_code := curr_trxn_currency;
3837          END IF;
3838 
3839          IF (l_settle_date_flag = 'Y') THEN
3840              l_batchRec.settle_date := curr_settle_date;
3841          END IF;
3842 
3843          /*
3844           * Pre-fill the document record with the details
3845           * of the current document.
3846           */
3847          l_trxnsInBatchRec.trxn_id := curr_trxn_id;
3848 
3849          /*-- HARDCODED GROUPING RULES START HERE --*/
3850 
3851          /*
3852           * Grouping Step 1: Payment Profile Code
3853           */
3854          IF (prev_profile_cd <> curr_profile_cd) THEN
3855 
3856              IF ( G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
3857 	             print_debuginfo(l_module_name, 'Grouping by payment '
3858 	                 || 'profile triggered for transaction '
3859 	                 || curr_trxn_id);
3860 
3861              END IF;
3862              insertTrxnIntoBatch(l_batchRec, l_batchTab,
3863                  true, l_mbatch_id, l_trxnsInBatchTab,
3864                  l_trxnsInBatchRec, l_trxns_in_batch_count);
3865 
3866              GOTO label_finish_iteration;
3867 
3868          END IF;
3869 
3870          /*
3871           * Grouping Step 2: Payment System Account (Bep Key)
3872           */
3873          IF (prev_bep_key <> curr_bep_key) THEN
3874 
3875              IF ( G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
3876 	             print_debuginfo(l_module_name, 'Grouping by payment '
3877 	                 || 'system account triggered for transaction '
3878 	                 || curr_trxn_id);
3879 
3880              END IF;
3881              insertTrxnIntoBatch(l_batchRec, l_batchTab,
3882                  true, l_mbatch_id, l_trxnsInBatchTab,
3883                  l_trxnsInBatchRec, l_trxns_in_batch_count);
3884 
3885              GOTO label_finish_iteration;
3886 
3887          END IF;
3888 
3889          /*-- USER DEFINED GROUPING RULES START HERE --*/
3890 
3891          /*
3892           * Grouping Step 3: Organization ID And Organization Type
3893           */
3894          IF (l_org_flag = 'Y') THEN
3895 
3896              IF (prev_org_id <> curr_org_id)     OR
3897                 (NVL(prev_org_type, 0) <> NVL(curr_org_type, 0)) THEN
3898 
3899                  IF ( G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
3900 	                 print_debuginfo(l_module_name, 'Grouping by organization '
3901 	                     || 'id/type triggered for transaction '
3902 	                     || curr_trxn_id);
3903 
3904                  END IF;
3905                  insertTrxnIntoBatch(l_batchRec, l_batchTab,
3906                      true, l_mbatch_id, l_trxnsInBatchTab,
3907                      l_trxnsInBatchRec, l_trxns_in_batch_count);
3908 
3909                  GOTO label_finish_iteration;
3910 
3911              END IF;
3912 
3913          END IF;
3914 
3915          /*
3916           * Grouping Step 3: Legal Entity ID
3917           */
3918          IF (l_le_flag = 'Y') THEN
3919 
3920              IF (prev_le_id <> curr_le_id) THEN
3921 
3922                  IF ( G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
3923 	                 print_debuginfo(l_module_name, 'Grouping by legal '
3924 	                     || 'entity triggered for transaction '
3925 	                     || curr_trxn_id);
3926 
3927                  END IF;
3928                  insertTrxnIntoBatch(l_batchRec, l_batchTab,
3929                      true, l_mbatch_id, l_trxnsInBatchTab,
3930                      l_trxnsInBatchRec, l_trxns_in_batch_count);
3931 
3932                  GOTO label_finish_iteration;
3933 
3934              END IF;
3935 
3936          END IF;
3937 
3938          /*
3939           * Grouping Step 4: Internal Bank Account ID
3940           */
3941          IF (l_int_bnk_flag = 'Y') THEN
3942 
3943              IF (prev_int_bank_acct_id <> curr_int_bank_acct_id) THEN
3944 
3945                  IF ( G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
3946 	                 print_debuginfo(l_module_name, 'Grouping by internal bank '
3947 	                     || 'account triggered for transaction '
3948 	                     || curr_trxn_id);
3949 
3950                  END IF;
3951                  insertTrxnIntoBatch(l_batchRec, l_batchTab,
3952                      true, l_mbatch_id, l_trxnsInBatchTab,
3953                      l_trxnsInBatchRec, l_trxns_in_batch_count);
3954 
3955                  GOTO label_finish_iteration;
3956 
3957              END IF;
3958 
3959          END IF;
3960 
3961          /*
3962           * Grouping Step 5: Settlement Currency
3963           */
3964          IF (l_curr_flag = 'Y') THEN
3965 
3966              IF (prev_trxn_currency <> curr_trxn_currency) THEN
3967 
3968                  IF ( G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
3969 	                 print_debuginfo(l_module_name, 'Grouping by settlement '
3970 	                     || 'currency triggered for transaction '
3971 	                     || curr_trxn_id);
3972 
3973                  END IF;
3974                  insertTrxnIntoBatch(l_batchRec, l_batchTab,
3975                      true, l_mbatch_id, l_trxnsInBatchTab,
3976                      l_trxnsInBatchRec, l_trxns_in_batch_count);
3977 
3978                  GOTO label_finish_iteration;
3979 
3980              END IF;
3981 
3982          END IF;
3983 
3984          /*
3985           * Grouping Step 6: Settlement Date
3986           */
3987          IF (l_settle_date_flag = 'Y') THEN
3988 
3989              IF (prev_settle_date <> curr_settle_date) THEN
3990 
3991                  IF ( G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
3992 	                 print_debuginfo(l_module_name, 'Grouping by settlement '
3993 	                     || 'date triggered for transaction '
3994 	                     || curr_trxn_id);
3995 
3996                  END IF;
3997                  insertTrxnIntoBatch(l_batchRec, l_batchTab,
3998                      true, l_mbatch_id, l_trxnsInBatchTab,
3999                      l_trxnsInBatchRec, l_trxns_in_batch_count);
4000 
4001                  GOTO label_finish_iteration;
4002 
4003              END IF;
4004 
4005          END IF;
4006 
4007          /*
4008           * Grouping Step 7: Max Transactions Per Batch
4009           */
4010          IF (l_max_trxn_limit IS NOT NULL) THEN
4011 
4012              IF (l_trxns_in_batch_count = l_max_trxn_limit) THEN
4013 
4014                  IF ( G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
4015 	                 print_debuginfo(l_module_name, 'Grouping by '
4016 	                     || 'max trxns per batch triggered for transaction '
4017 	                     || curr_trxn_id);
4018 
4019                  END IF;
4020                  insertTrxnIntoBatch(l_batchRec, l_batchTab,
4021                      true, l_mbatch_id, l_trxnsInBatchTab,
4022                      l_trxnsInBatchRec, l_trxns_in_batch_count);
4023 
4024                  GOTO label_finish_iteration;
4025 
4026              END IF;
4027 
4028          END IF;
4029 
4030          /*
4031           * Grouping Step 8: Max Amount Per Batch
4032           */
4033          IF (l_max_amount_limit IS NOT NULL) THEN
4034 
4035              IF (l_batch_total + l_trx_fx_amount > l_max_amount_limit) THEN
4036 
4037                  IF ( G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
4038 	                 print_debuginfo(l_module_name, 'Grouping by '
4039 	                     || 'max batch amount triggered by transaction '
4040 	                     || curr_trxn_id);
4041 
4042                  END IF;
4043                  insertTrxnIntoBatch(l_batchRec, l_batchTab,
4044                      true, l_mbatch_id, l_trxnsInBatchTab,
4045                      l_trxnsInBatchRec, l_trxns_in_batch_count);
4046 
4047                  GOTO label_finish_iteration;
4048 
4049              END IF;
4050 
4051          END IF;
4052 
4053          /*
4054           * End Of Grouping:
4055           * If a transaction reaches here, it means that this transaction
4056           * is similar to the previous transaction as far a grouping
4057           * criteria is concerned.
4058           *
4059           * Add this transaction to the currently running batch.
4060           */
4061          IF ( G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
4062 	         print_debuginfo(l_module_name, 'No grouping rules '
4063 	             || 'were triggered for transaction '
4064 	             || curr_trxn_id);
4065 
4066          END IF;
4067          insertTrxnIntoBatch(l_batchRec, l_batchTab,
4068              false, l_mbatch_id, l_trxnsInBatchTab,
4069              l_trxnsInBatchRec, l_trxns_in_batch_count);
4070 
4071 
4072          <<label_finish_iteration>>
4073 
4074          /*
4075           * Lastly, before going into the next iteration
4076           * of the loop copy all the current grouping criteria
4077           * into 'prev' fields so that we can compare these
4078           * fields with the next record.
4079           *
4080           * No need to copy the current values into the previous ones for
4081           * the first record because we have already done it at the beginning.
4082           */
4083          IF (l_first_record <> 'Y') THEN
4084              prev_trxn_id           := curr_trxn_id;
4085              prev_profile_cd        := curr_profile_cd;
4086              prev_int_bank_acct_id  := curr_int_bank_acct_id;
4087              prev_bep_key           := curr_bep_key;
4088              prev_org_id            := curr_org_id;
4089              prev_org_type          := curr_org_type;
4090              prev_trxn_currency     := curr_trxn_currency;
4091              prev_trxn_amount       := curr_trxn_amount;
4092              prev_le_id             := curr_le_id;
4093              prev_settle_date       := curr_settle_date;
4094          END IF;
4095 
4096          /*
4097           *  Remember to reset the first record flag before going
4098           *  into the next iteration.
4099           */
4100          IF (l_first_record = 'Y') THEN
4101              l_first_record := 'N';
4102          END IF;
4103 
4104          IF ( G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
4105 	         print_debuginfo(l_module_name, '+----------------------------------+');
4106 
4107          END IF;
4108      END LOOP;
4109 
4110      IF ( G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
4111 	     print_debuginfo(l_module_name, 'Created '
4112 	         || l_batchTab.COUNT   || ' batch(s) from '
4113 	         || l_trxnsInBatchTab.COUNT || ' transaction(s) for profile '
4114 	         || p_profile_code || '.');
4115 
4116      END IF;
4117      /*
4118       * Finally, return the batches created by grouping to the caller.
4119       */
4120      x_batchTab        := l_batchTab;
4121      x_trxnsInBatchTab := l_trxnsInBatchTab;
4122 
4123 
4124      /*
4125       * Fix for bug 5407120:
4126       *
4127       * Revert back thenumeric character mask to its original
4128       * setting. See begininning of this methods for comments
4129       * regarding this issue.
4130       *
4131       */
4132      BEGIN
4133 
4134          IF (l_numeric_char_mask IS NOT NULL) THEN
4135 
4136              EXECUTE IMMEDIATE
4137                  'ALTER SESSION SET NLS_NUMERIC_CHARACTERS = '
4138                     || '"'
4139                     || l_numeric_char_mask
4140                     || '"'
4141                  ;
4142 
4143              IF ( G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
4144 	             print_debuginfo(l_module_name, 'Reverted numeric char mask to: '
4145 	                 || l_numeric_char_mask
4146 	                 );
4147 
4148              END IF;
4149          END IF;
4150 
4151      EXCEPTION
4152          WHEN OTHERS THEN
4153              IF ( G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
4154 	             print_debuginfo(l_module_name, 'Non-Fatal: Exception occured '
4155 	                 || 'when attempting to revert numeric character mask.'
4156 	                 );
4157 
4158 	             print_debuginfo(l_module_name, 'SQL code: '   || SQLCODE);
4159 	             print_debuginfo(l_module_name, 'SQL err msg: '|| SQLERRM);
4160              END IF;
4161      END;
4162 
4163      IF ( G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
4164 	     print_debuginfo(l_module_name, 'EXIT');
4165 
4166      END IF;
4167  END performTransactionGrouping;
4168 
4169 
4170 /*--------------------------------------------------------------------
4171  | NAME:
4172  |     performTransactionGrouping
4173  |
4174  | PURPOSE:
4175  |     This is the Overloaded API for the earlier one. This will be invoked
4176  |     by the corresponding overloaded procedure insert_batch_ststus_new.
4177  |     This one also takes an array of User profile codes instead of one.
4178  |
4179  | PARAMETERS:
4180  |     IN
4181  |
4182  |
4183  |     OUT
4184  |
4185  |
4186  | RETURNS:
4187  |
4188  | NOTES:
4189  |
4190  *---------------------------------------------------------------------*/
4191  PROCEDURE performTransactionGrouping(
4192      profile_code_array   IN JTF_VARCHAR2_TABLE_100,
4193      instr_type           IN IBY_TRXN_SUMMARIES_ALL.
4194                                  instrtype%TYPE,
4195      req_type             IN IBY_BATCHES_ALL.
4196                                  reqtype%TYPE,
4197      f_pmt_channel_in     IN IBY_TRXN_SUMMARIES_ALL.
4198                                  payment_channel_code%TYPE,
4199      f_curr_in            IN IBY_TRXN_SUMMARIES_ALL.
4200                                  currencynamecode%TYPE,
4201      f_settle_date        IN IBY_TRXN_SUMMARIES_ALL.
4202                                  settledate%TYPE,
4203      f_due_date           IN IBY_TRXN_SUMMARIES_ALL.
4204                                  settlement_due_date%TYPE,
4205      f_maturity_date      IN IBY_TRXN_SUMMARIES_ALL.
4206                                  br_maturity_date%TYPE,
4207      f_instr_type         IN IBY_TRXN_SUMMARIES_ALL.
4208                                  instrtype%TYPE,
4209      merch_batchid_in     IN iby_batches_all.batchid%TYPE,
4210 
4211      x_batchTab           IN OUT NOCOPY IBY_TRANSACTIONCC_PKG.
4212                                             batchAttrTabType,
4213      x_trxnsInBatchTab    IN OUT NOCOPY IBY_TRANSACTIONCC_PKG.
4214                                             trxnsInBatchTabType
4215      )
4216  IS
4217  l_module_name           CONSTANT VARCHAR2(200) := G_PKG_NAME ||
4218                                                   '.performTransactionGrouping';
4219 
4220  l_sql_str               VARCHAR2(5000);
4221  l_cursor_stmt           VARCHAR2(8000);
4222 
4223  l_first_record          VARCHAR2(1)   := 'Y';
4224 
4225  /* user defined grouping rule flags */
4226  l_org_flag              VARCHAR2(1)   := 'N';
4227  l_le_flag               VARCHAR2(1)   := 'N';
4228  l_int_bnk_flag          VARCHAR2(1)   := 'N';
4229  l_curr_flag             VARCHAR2(1)   := 'N';
4230  l_settle_date_flag      VARCHAR2(1)   := 'N';
4231 
4232  /* user defined limits */
4233  l_max_trxn_limit        NUMBER(15)    := 0;
4234  l_fx_rate_type          VARCHAR2(255) := '';
4235  l_fx_curr_code          VARCHAR2(10)  := '';
4236  l_max_amount_limit      NUMBER(15)    := 0;
4237 
4238  /*
4239   * NOTE:
4240   *
4241   * IBY_BATCHES_ALL.batchid  = user generated batch id
4242   * IBY_BATCHES_ALL.mbatchid = system generated batch id
4243   *
4244   * If batch close is invoked by the user, the batchid will
4245   * be a user defined string (should be unique).
4246   *
4247   * If batch close is invoked by the scheduler, the batch is
4248   * be a sequence number (iby_batchid_s.nextval).
4249   *
4250   * mbatchid will always be a sequence number (iby_batchid_s.nextval).
4251   *
4252   * In the new architecture, multiple mbatchids can be generated
4253   * for a single batchid (based on user defined grouping rules).
4254   */
4255  l_mbatch_id             IBY_BATCHES_ALL.mbatchid%TYPE;
4256  l_batch_total           NUMBER(15)    := 0;
4257  l_trxns_in_batch_count  NUMBER(15)    := 0;
4258 
4259  l_trx_fx_amount         NUMBER(15)    := 0;
4260 
4261  /*
4262   * Used to substitute null values in date comparisons.
4263   * It is assumed that not document payable would ever
4264   * have a year 1100 date.
4265   */
4266  l_impossible_date       DATE := TO_DATE('01/01/1100 10:25:55',
4267                                      'MM/DD/YYYY HH24:MI:SS');
4268 
4269  /*
4270   * These two are related data structures. Each row in batchAttrTabType
4271   * PLSQL table is used in inserting a row into the IBY_BATCHES_ALL
4272   * table.
4273   *
4274   * A separate data structure is needed to keep track of the transactions
4275   * that are part of a batch. This information is tracked in the
4276   * trxnsInBatchTabType table. The rows in trxnsInBatchTabType are
4277   * used to update the rows in IBY_TRXN_SUMMARIES_ALL table with
4278   * batch ids.
4279   *
4280   *            l_batchTab                        l_trxnsInBatchTab
4281   *       (insert into IBY_BATCHES_ALL)   (update IBY_TRXN_SUMMARIES_ALL)
4282   * /-------------------------------------\       /------------\
4283   * |MBatch |Profile|..|Curr   |Org    |..|       |MBatch |Trx |
4284   * |Id     |Code   |..|Code   |Id     |..|       |Id     |Id  |
4285   * |       |       |..|       |       |..|       |       |    |
4286   * |-------------------------------------|       |------------|
4287   * |   4000|     10|  |    USD|    204|  |       |   4000| 501|
4288   * |       |       |  |       |       |  |       |   4000| 504|
4289   * |       |       |  |       |       |  |       |   4000| 505|
4290   * |-------|-------|--|-------|-------|--|       |-------|----|
4291   * |   4001|     11|  |    -- |    342|  |       |   4001| 502|
4292   * |       |       |  |       |       |  |       |   4001| 509|
4293   * |       |       |  |       |       |  |       |   4001| 511|
4294   * |       |       |  |       |       |  |       |   4001| 523|
4295   * |       |       |  |       |       |  |       |     : |  : |
4296   * |-------|-------|--|-------|-------|--|       |-------|----|
4297   * |    :  |     : |  |    :  |     : |  |       |     : |  : |
4298   * \_______|_______|__|_______|_______|__/       \_______|____/
4299   *
4300   */
4301 
4302  l_batchRec          IBY_TRANSACTIONCC_PKG.batchAttrRecType;
4303  l_trxnsInBatchTab   IBY_TRANSACTIONCC_PKG.trxnsInBatchTabType;
4304  emptyTrxnInsBatchTab IBY_TRANSACTIONCC_PKG.trxnsInBatchTabType;
4305 
4306  l_trxnsInBatchRec   IBY_TRANSACTIONCC_PKG.trxnsInBatchRecType;
4307  l_batchTab          IBY_TRANSACTIONCC_PKG.batchAttrTabType;
4308 
4309  l_trxnGrpCriTab     IBY_TRANSACTIONCC_PKG.trxnGroupCriteriaTabType;
4310  emptyGrpCriTab      IBY_TRANSACTIONCC_PKG.trxnGroupCriteriaTabType;
4311 
4312  l_pinlessdebitcard  CONSTANT VARCHAR2(100) :='PINLESSDEBITCARD';
4313  l_bankaccount       CONSTANT VARCHAR2(100) :='BANKACCOUNT';
4314 
4315  /* previous transaction attributes */
4316  prev_trxn_id                iby_trxn_summaries_all.transactionid%TYPE;
4317  prev_trxn_currency          iby_trxn_summaries_all.currencynamecode%TYPE;
4318  prev_trxn_amount            iby_trxn_summaries_all.amount%TYPE;
4319  prev_int_bank_acct_id       iby_trxn_summaries_all.payeeinstrid%TYPE;
4320  prev_org_id                 iby_trxn_summaries_all.org_id%TYPE;
4321  prev_org_type               iby_trxn_summaries_all.org_type%TYPE;
4322  prev_settle_date            iby_trxn_summaries_all.settledate%TYPE;
4323  prev_le_id                  iby_trxn_summaries_all.legal_entity_id%TYPE;
4324  prev_bep_key                iby_trxn_summaries_all.bepkey%TYPE;
4325  prev_profile_cd             iby_trxn_summaries_all.process_profile_code%TYPE;
4326 
4327  /* current transaction attributes */
4328  curr_trxn_id                iby_trxn_summaries_all.transactionid%TYPE;
4329  curr_trxn_currency          iby_trxn_summaries_all.currencynamecode%TYPE;
4330  curr_trxn_amount            iby_trxn_summaries_all.amount%TYPE;
4331  curr_int_bank_acct_id       iby_trxn_summaries_all.payeeinstrid%TYPE;
4332  curr_org_id                 iby_trxn_summaries_all.org_id%TYPE;
4333  curr_org_type               iby_trxn_summaries_all.org_type%TYPE;
4334  curr_settle_date            iby_trxn_summaries_all.settledate%TYPE;
4335  curr_le_id                  iby_trxn_summaries_all.legal_entity_id%TYPE;
4336  curr_bep_key                iby_trxn_summaries_all.bepkey%TYPE;
4337  curr_profile_cd             iby_trxn_summaries_all.process_profile_code%TYPE;
4338  l_user_pf_table_name        VARCHAR2(100);
4339  l_sys_pf_table_name         VARCHAR2(100);
4340  l_user_pf_column_name       VARCHAR2(100);
4341  l_sys_pf_column_name        VARCHAR2(100);
4342 
4343  l_numeric_char_mask         VARCHAR2(100);
4344 
4345  TYPE dyn_transactions       IS REF CURSOR;
4346  l_trxn_cursor               dyn_transactions;
4347 
4348  strProfCodes                VARCHAR2(4000);
4349  numProfiles                 NUMBER;
4350  recLimit                    NUMBER := 1000;
4351  l_index                     NUMBER;
4352 
4353  /*
4354   * This cursor up will pick up all valid transactions for
4355   * the specified payment profile. The select statement will
4356   * order the transactions based on grouping criteria.
4357   *
4358   * Important Note:
4359   *
4360   * Always ensure that there is a corresponding order by
4361   * clause for each grouping criterion that you wish to use.
4362   * This is required in order to create minimum possible
4363   * batches from a given set of transactions.
4364   *
4365   * Note 2: The sample sql is not right as the base table for
4366   * process profile is different
4367   * the dynamic sql is changed according to that
4368   */
4369  CURSOR c_transactions (
4370             strProfiles VARCHAR2,
4371             p_instr_type   VARCHAR2,
4372             p_req_type     VARCHAR2
4373             )
4374  IS
4375  SELECT
4376      txn.transactionid,
4377      txn.process_profile_code,
4378      txn.bepkey,
4379      txn.org_id,
4380      txn.org_type,
4381      txn.currencynamecode,
4382      txn.amount,
4383      txn.legal_entity_id,
4384      txn.payeeinstrid,
4385 	 --The grouping logic is modified, Now it will be grouped by settlement_due_date instead of settledate Bug# 13799238
4386      txn.settlement_due_date,
4387      sys_prof.group_by_org,
4388      sys_prof.group_by_legal_entity,
4389      sys_prof.group_by_int_bank_account,
4390      sys_prof.group_by_settlement_curr,
4391      sys_prof.group_by_settlement_date,
4392      sys_prof.limit_by_amt_curr,
4393      sys_prof.limit_by_exch_rate_type,
4394      sys_prof.limit_by_total_amt,
4395      sys_prof.limit_by_settlement_num
4396  FROM
4397      IBY_TRXN_SUMMARIES_ALL  txn,
4398      IBY_FNDCPT_USER_CC_PF_B user_prof,
4399      IBY_FNDCPT_SYS_CC_PF_B  sys_prof
4400  WHERE
4401      user_prof.user_cc_profile_code IN (strProfiles)               AND
4402      txn.process_profile_code     = user_prof.user_cc_profile_code AND
4403      sys_prof.sys_cc_profile_code = user_prof.sys_cc_profile_code  AND
4404      txn.status = iby_transactioncc_pkg.C_STATUS_OPEN_BATCHED      AND
4405      (
4406          /*
4407           * This clause will pick up credit card / purchase card
4408           * transactions.
4409           */
4410          (
4411              p_instr_type IN
4412              (
4413                  iby_creditcard_pkg.C_INSTRTYPE_CCARD,
4414                  iby_creditcard_pkg.C_INSTRTYPE_PCARD
4415              )
4416              AND
4417              (
4418                  txn.reqtype IN
4419                  (
4420                  iby_transactioncc_pkg.C_REQTYPE_BATCHCLOSE,
4421                  iby_transactioncc_pkg.C_REQTYPE_CAPTURE,
4422                  iby_transactioncc_pkg.C_REQTYPE_CREDIT,
4423                  iby_transactioncc_pkg.C_REQTYPE_RETURN
4424                  )
4425              )
4426              AND
4427              (
4428                  txn.instrtype IN
4429                  (
4430                  iby_creditcard_pkg.C_INSTRTYPE_CCARD,
4431                  iby_creditcard_pkg.C_INSTRTYPE_PCARD
4432                  )
4433              )
4434          )
4435 
4436          /*
4437           * This clause will pick up pinless debit card
4438           * transactions.
4439           */
4440          OR
4441          (
4442              p_instr_type IN
4443              (
4444                  l_pinlessdebitcard
4445              )
4446              AND
4447              (
4448                  txn.reqtype IN
4449                  (
4450                  iby_transactioncc_pkg.C_REQTYPE_PDC_BATCHCLOSE,
4451                  iby_transactioncc_pkg.C_REQTYPE_REQUEST
4452                  )
4453              )
4454              AND
4455              (
4456                  txn.instrtype IN
4457                  (
4458                  l_pinlessdebitcard
4459                  )
4460              )
4461          )
4462 
4463          /*
4464           * This clause will pick up bank account transactions
4465           * transactions.
4466           */
4467          OR
4468          (
4469              p_instr_type IN
4470              (
4471                  l_bankaccount
4472              )
4473              AND
4474              (
4475                  txn.reqtype IN
4476                  (
4477                  iby_transactioncc_pkg.C_REQTYPE_EFT_BATCHCLOSE,
4478                  iby_transactioncc_pkg.C_REQTYPE_BATCHREQ
4479                  )
4480              )
4481              AND
4482              (
4483                  txn.instrtype IN
4484                  (
4485                  l_bankaccount
4486                  )
4487              )
4488 
4489              /*
4490               * Fix for bug 5442922:
4491               *
4492               * For bank account instruments, the auth / verify
4493               * transaction will have trantypeid 20; The
4494               * capture transaction will have trxntypeid 100.
4495               *
4496               * Since we are picking up only capture transactions
4497               * here, explicitly specify the trxntypeid in the
4498               * WHERE clause. Otherwise, auths are also picked
4499               * up and put into the batch.
4500               */
4501              AND
4502              (
4503                  /*
4504                   * This trxn type 100 maps to
4505                   * IBY_FNDCPT_TRXN_PUB.BA_CAPTURE_TRXNTYPE
4506                   */
4507                  txn.trxntypeid = 100
4508              )
4509          )
4510 
4511          /*
4512           * This clause will pick up any transaction which does not
4513           * have an instrument type. This looks dangerous to me but
4514           * kept for backward compatibility - Ramesh
4515           */
4516          OR
4517          (
4518              txn.instrtype IS NULL
4519          )
4520      )                                                             AND
4521      txn.batchid IS NULL                                           AND
4522      /*
4523       *  Fix for bug 5632947:
4524       *
4525       *  Join with CE_SECURITY_PROFILES_V for MOAC compliance.
4526       */
4527      ((txn.org_id IS NULL) OR
4528      ((txn.org_id IS NOT NULL) AND
4529      (txn.org_id, txn.org_type) IN
4530          (SELECT
4531               ce.organization_id,
4532               ce.organization_type
4533           FROM
4534               ce_security_profiles_v ce
4535          )))
4536  ORDER BY
4537      txn.process_profile_code,   --
4538      txn.bepkey,                 -- Ensure that the
4539      txn.org_id,                 -- grouping rules below
4540      txn.org_type,               -- follow this same
4541      txn.legal_entity_id,        -- order (necessary
4542      txn.payeeinstrid,           -- for creating minimum
4543      txn.currencynamecode,       -- number of batches)
4544      txn.settlement_due_date              --
4545 	 --The grouping logic is modified, Now it will be grouped by settlement_due_date instead of settledate Bug# 13799238
4546  ;
4547 
4548 
4549  BEGIN
4550 
4551      IF ( G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
4552 	     print_debuginfo(l_module_name, 'ENTER: Overloaded API.');
4553 
4554      END IF;
4555    --  print_debuginfo(l_module_name, 'Payment Profile Cd: '||
4556    --      p_profile_code);
4557        IF ( G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
4558 	       print_debuginfo(l_module_name, 'Payment Profile Cd: '||
4559 	        strProfCodes);
4560 	     print_debuginfo(l_module_name, 'Instrument Type: '   ||
4561 	         instr_type);
4562 	     print_debuginfo(l_module_name, 'Request Type: '      ||
4563 	         req_type);
4564 
4565      END IF;
4566      /*
4567       * Filter params.
4568       */
4569 
4570     -- initailizing the sec context for org id for bug 12814095
4571     cep_standard.init_security;
4572      IF ( G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
4573 	     print_debuginfo(l_module_name, 'f_pmt_channel_in: '
4574 	         || f_pmt_channel_in);
4575 	     print_debuginfo(l_module_name, 'f_curr_in: '
4576 	         || f_curr_in);
4577 	     print_debuginfo(l_module_name, 'f_settle_date: '
4578 	         || f_settle_date);
4579 	     print_debuginfo(l_module_name, 'f_due_date: '
4580 	         || f_due_date);
4581 	     print_debuginfo(l_module_name, 'f_maturity_date: '
4582 	         || f_maturity_date);
4583 	     print_debuginfo(l_module_name, 'f_instr_type: '
4584 	         || f_instr_type);
4585 
4586      END IF;
4587      /*
4588       * Fix for bug 5407120:
4589       *
4590       * Before we do anything, alter the session to set the numeric
4591       * character mask. This is because of XML publisher limitation -
4592       * it cannot handle numbers like '230,56' which is the European
4593       * representation of '230.56'.
4594       *
4595       * Therefore, we explicitly set the numeric character mask at the
4596       * beginning of this routine and revert back to the default
4597       * setting at the end of this method.
4598       */
4599      BEGIN
4600 
4601          SELECT
4602              value
4603          INTO
4604              l_numeric_char_mask
4605          FROM
4606              V$NLS_PARAMETERS
4607          WHERE
4608              parameter='NLS_NUMERIC_CHARACTERS'
4609          ;
4610 
4611          IF ( G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
4612 	         print_debuginfo(l_module_name, 'Current numeric char mask: '
4613 	             || l_numeric_char_mask
4614 	             );
4615 
4616          END IF;
4617      EXCEPTION
4618          WHEN OTHERS THEN
4619              IF ( G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
4620 	             print_debuginfo(l_module_name, 'Non-Fatal: Exception occured '
4621 	                 || 'when attempting to retrieve numeric character mask.'
4622 	                 );
4623 
4624 	             print_debuginfo(l_module_name, 'SQL code: '   || SQLCODE);
4625 	             print_debuginfo(l_module_name, 'SQL err msg: '|| SQLERRM);
4626              END IF;
4627      END;
4628 
4629      /*
4630       * Now alter the session, to force the NLS numeric character
4631       * decimal indicator to be a '.'.
4632       */
4633      BEGIN
4634 
4635          EXECUTE IMMEDIATE
4636              'ALTER SESSION SET NLS_NUMERIC_CHARACTERS = ".,"'
4637              ;
4638 
4639      EXCEPTION
4640          WHEN OTHERS THEN
4641              IF ( G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
4642 	             print_debuginfo(l_module_name, 'Non-Fatal: Exception occured '
4643 	                 || 'when attempting to later session to set '
4644 	                 || 'numeric character mask.'
4645 	                 );
4646 
4647 	             print_debuginfo(l_module_name, 'SQL code: '   || SQLCODE);
4648 	             print_debuginfo(l_module_name, 'SQL err msg: '|| SQLERRM);
4649              END IF;
4650      END;
4651 
4652      /*
4653       * Dynamically form SQL string to limit the rows that
4654       * are picked up for the batch close operation.
4655       *
4656       * Use the supplied filter parameters to form the SQL
4657       * string.
4658       */
4659      IF (f_pmt_channel_in IS NOT NULL) THEN
4660          l_sql_str := l_sql_str || ' AND payment_channel_code = '
4661                           || '''' || f_pmt_channel_in || '''';
4662      END IF;
4663 
4664      IF (f_curr_in IS NOT NULL) THEN
4665          l_sql_str := l_sql_str || ' AND currencynamecode = '
4666                           || '''' || f_curr_in || '''';
4667      END IF;
4668 
4669      IF (f_settle_date IS NOT NULL) THEN
4670          l_sql_str := l_sql_str || ' AND settledate <= '
4671                           || '''' || f_settle_date || '''';
4672      END IF;
4673 
4674      IF (f_due_date IS NOT NULL) THEN
4675          l_sql_str := l_sql_str || ' AND settlement_due_date <= '
4676                           || '''' || f_due_date || '''';
4677      END IF;
4678 
4679      IF (f_maturity_date IS NOT NULL) THEN
4680          l_sql_str := l_sql_str || ' AND br_maturity_date <= '
4681                           || '''' || f_maturity_date || '''';
4682      END IF;
4683      -- Bug# 12825203
4684      -- Including Purchase cards, as CCARD AND PCARD are considered
4685      -- to be the same.
4686      IF (f_instr_type IS NOT NULL) THEN
4687         IF(f_instr_type = iby_creditcard_pkg.C_INSTRTYPE_CCARD) THEN
4688          l_sql_str := l_sql_str || ' AND instrtype IN ('
4689                           || '''' || f_instr_type || ''''
4690 			  ||', '''|| iby_creditcard_pkg.C_INSTRTYPE_PCARD|| ''')';
4691 	ELSE
4692          l_sql_str := l_sql_str || ' AND instrtype = '
4693                           || '''' || f_instr_type || '''';
4694 	END IF;
4695      END IF;
4696 
4697      IF ( G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
4698 	     print_debuginfo(l_module_name, 'Dynamic SQL snippet: '
4699 	         || l_sql_str);
4700 
4701      END IF;
4702     /* determine the process profile table and column */
4703 
4704      l_user_pf_table_name :='IBY_FNDCPT_USER_CC_PF_B';
4705      l_sys_pf_table_name  :='IBY_FNDCPT_SYS_CC_PF_B';
4706      l_user_pf_column_name :='USER_CC_PROFILE_CODE';
4707      l_sys_pf_column_name :='SYS_CC_PROFILE_CODE';
4708   IF (instr_type IS NOT NULL) THEN
4709        if(instr_type =l_bankaccount) THEN
4710                     l_user_pf_table_name :='IBY_FNDCPT_USER_EFT_PF_B';
4711                     l_sys_pf_table_name  :='IBY_FNDCPT_SYS_EFT_PF_B';
4712                     l_user_pf_column_name :='USER_EFT_PROFILE_CODE';
4713                     l_sys_pf_column_name :='SYS_EFT_PROFILE_CODE';
4714        ELSIF  (instr_type =l_pinlessdebitcard) THEN
4715                     l_user_pf_table_name :='IBY_FNDCPT_USER_DC_PF_B';
4716                     l_sys_pf_table_name  :='IBY_FNDCPT_SYS_DC_PF_B';
4717                     l_user_pf_column_name :='USER_DC_PROFILE_CODE';
4718                     l_sys_pf_column_name :='SYS_DC_PROFILE_CODE';
4719        END IF;
4720 
4721    END IF;
4722 
4723      /* Form a comma separated string for the profile codes */
4724      numProfiles := profile_code_array.count;
4725      FOR i IN 1..(numProfiles-1) LOOP
4726         strProfCodes := strProfCodes||''''||profile_code_array(i)||''',';
4727      END LOOP;
4728      /* Append the last profile code without comma at the end */
4729      strProfCodes := strProfCodes||''''||profile_code_array(numProfiles)||'''';
4730 
4731      /*
4732       * The cursor below is the same as the cursor c_transactions
4733       * defined at the beginning of this method.
4734       *
4735       * We cannot directly use c_transactions because we need to use
4736       * the provided filter params to form a dynamic where clause.
4737       *
4738       * For this reason, this cursor has been made into a dynamic cursor.
4739       * c_transactions is kept for documentation / debugging purposes
4740       * but is not used.
4741       */
4742      l_cursor_stmt :=
4743      'SELECT '
4744          || 'txn.transactionid,                  '
4745          || 'txn.process_profile_code,           '
4746          || 'txn.bepkey,                         '
4747          || 'txn.org_id,                         '
4748          || 'txn.org_type,                       '
4749          || 'txn.currencynamecode,               '
4750          || 'txn.amount,                         '
4751          || 'txn.legal_entity_id,                '
4752          || 'txn.payeeinstrid,                   '
4753 		 ----The grouping logic is modified, Now it will be grouped by settlement_due_date instead of settledate Bug# 13799238
4754          || 'txn.settlement_due_date,            '
4755          || 'sys_prof.group_by_org,              '
4756          || 'sys_prof.group_by_legal_entity,     '
4757          || 'sys_prof.group_by_int_bank_account, '
4758          || 'sys_prof.group_by_settlement_curr,  '
4759          || 'sys_prof.group_by_settlement_date,  '
4760          || 'sys_prof.limit_by_amt_curr,         '
4761          || 'sys_prof.limit_by_exch_rate_type,   '
4762          || 'sys_prof.limit_by_total_amt,        '
4763          || 'sys_prof.limit_by_settlement_num    '
4764      || 'FROM  '
4765          || 'IBY_TRXN_SUMMARIES_ALL  txn,        '
4766          || l_user_pf_table_name || '  user_prof,  '
4767          ||  l_sys_pf_table_name || '  sys_prof    '
4768      || 'WHERE '
4769          || 'user_prof.'||l_user_pf_column_name||'  IN ('||strProfCodes||')     AND '
4770          || 'txn.process_profile_code     = user_prof.'||l_user_pf_column_name||'  AND '
4771          || 'sys_prof.' ||l_sys_pf_column_name||'   = user_prof. '||l_sys_pf_column_name || ' AND '
4772          || 'txn.status = :open_batch                                      AND '
4773          || '( '
4774              /*
4775               * This clause will pick up credit card / purchase card
4776               * transactions.
4777               */
4778              || '( '
4779                 || ':A IN (:C1, :C2) AND (txn.reqtype IN (:T1A, :T1B, :T1C, :T1D, :T1E)) AND '
4780                 || '(txn.instrtype IN (:C3, :C4)) '
4781              || ') '
4782 
4783              /*
4784               * This clause will pick up pinless debit card
4785               * transactions.
4786               */
4787              || 'OR '
4788              || '( '
4789                  || ':C IN (:P1) AND (txn.reqtype IN (:T2A, :T2B)) AND '
4790                  || '(txn.instrtype IN (:P2)) '
4791              || ') '
4792 
4793              /*
4794               * This clause will pick up bank account transactions
4795               * transactions.
4796               */
4797 
4798              || 'OR '
4799              || '( '
4800                  || ':E IN (:B1) AND (txn.reqtype IN (:T3A, :T3B, :T3C)) AND '
4801                  || '(txn.instrtype IN (:B2)) '
4802 
4803 
4804                  /*
4805                   * Fix for bug 5442922:
4806                   *
4807                   * For bank account instruments, the auth / verify
4808                   * transaction will have trantypeid 20; The
4809                   * capture transaction will have trxntypeid 100.
4810                   *
4811                   * Since we are picking up only capture transactions
4812                   * here, explicitly specify the trxntypeid in the
4813                   * WHERE clause. Otherwise, auths are also picked
4814                   * up and put into the batch.
4815                   */
4816                  || 'AND '
4817                  || '( '
4818                      /*
4819                       * This trxn type 100 maps to
4820                       * IBY_FNDCPT_TRXN_PUB.BA_CAPTURE_TRXNTYPE
4821                       */
4822                      || 'txn.trxntypeid = 100 '
4823                  || ') '
4824 
4825              || ') '
4826 
4827              /*
4828               * This clause will pick up any transaction which does not
4829               * have an instrument type. This looks dangerous to me but
4830               * kept for backward compatibility - Ramesh
4831               */
4832              || 'OR '
4833              || '( '
4834                  || 'txn.instrtype IS NULL '
4835              || ') '
4836          || ')                                                             AND '
4837          || 'txn.batchid IS NULL                                           AND '
4838          /*
4839           *  Fix for bug 5632947:
4840           *
4841           *  Join with CE_SECURITY_PROFILES_V for MOAC compliance.
4842           */
4843          || '((txn.org_id IS NULL) OR '
4844          || '((txn.org_id IS NOT NULL) AND '
4845          || '(txn.org_id, txn.org_type) IN '
4846          || '    (SELECT '
4847          || '         ce.organization_id, '
4848          || '         ce.organization_type '
4849          || '     FROM  '
4850          || '         ce_security_profiles_v ce '
4851          || '    ))) '
4852          || NVL (l_sql_str, 'AND 1=1 ')
4853      || 'ORDER BY '
4854          || 'txn.process_profile_code, '  --
4855          || 'txn.bepkey,               '  -- Ensure that the
4856          || 'txn.org_id,               '  -- grouping rules below
4857          || 'txn.org_type,             '  -- follow this same
4858          || 'txn.legal_entity_id,      '  -- order (necessary
4859          || 'txn.payeeinstrid,         '  -- for creating minimum
4860          || 'txn.currencynamecode,     '  -- number of batches)
4861          || 'txn.settlement_due_date   '  --
4862 		 ----The grouping logic is modified, Now it will be grouped by settlement_due_date instead of settledate Bug# 13799238
4863      ;
4864 
4865      OPEN l_trxn_cursor FOR
4866          l_cursor_stmt
4867      USING
4868          -- comment out this one as we have already put this value in a comma separated string
4869          --p_profile_code,                                 /* profile_code */
4870          iby_transactioncc_pkg.C_STATUS_OPEN_BATCHED,    /* open_batch */
4871          instr_type,                                     /* A */
4872          iby_creditcard_pkg.C_INSTRTYPE_CCARD,           /* C1 */
4873          iby_creditcard_pkg.C_INSTRTYPE_PCARD,           /* C2 */
4874          iby_transactioncc_pkg.C_REQTYPE_BATCHCLOSE,     /* T1A */
4875          iby_transactioncc_pkg.C_REQTYPE_CAPTURE,        /* T1B */
4876          iby_transactioncc_pkg.C_REQTYPE_CREDIT,         /* T1C */
4877          iby_transactioncc_pkg.C_REQTYPE_RETURN,         /* T1D */
4878          iby_transactioncc_pkg.C_REQTYPE_REQUEST,         /* T1E */
4879          iby_creditcard_pkg.C_INSTRTYPE_CCARD,           /* C3 */
4880          iby_creditcard_pkg.C_INSTRTYPE_PCARD,           /* C4 */
4881          instr_type,                                     /* C */
4882          l_pinlessdebitcard,                             /* P1 */
4883          iby_transactioncc_pkg.C_REQTYPE_PDC_BATCHCLOSE, /* T2A */
4884          iby_transactioncc_pkg.C_REQTYPE_REQUEST,        /* T2B */
4885          l_pinlessdebitcard,                             /* P2 */
4886          instr_type,                                     /* E */
4887          l_bankaccount,                                  /* B1 */
4888          iby_transactioncc_pkg.C_REQTYPE_EFT_BATCHCLOSE, /* T3A */
4889          iby_transactioncc_pkg.C_REQTYPE_BATCHREQ,       /* T3B */
4890          iby_transactioncc_pkg.C_REQTYPE_REQUEST,        /* T3C */
4891          l_bankaccount                                   /* B2 */
4892          ;
4893     --Bug 8658052
4894     --Included fetch limit
4895      LOOP
4896      FETCH l_trxn_cursor BULK COLLECT INTO l_trxnGrpCriTab LIMIT recLimit;
4897 
4898      --CLOSE l_trxn_cursor;
4899 
4900      /*
4901       * Exit if no documents were found.
4902       */
4903      IF (l_trxnGrpCriTab.COUNT = 0) THEN
4904          IF ( G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
4905 	         print_debuginfo(l_module_name, 'No transactions were '
4906 	             || 'retrieved from DB for profile '
4907 	             || strProfCodes
4908 	             || '. Exiting transaction grouping ..');
4909 
4910 	         print_debuginfo(l_module_name, 'EXIT');
4911          END IF;
4912          RETURN;
4913      ELSE
4914          IF ( G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
4915 	         print_debuginfo(l_module_name, '# valid transactions '
4916 	             || 'retrieved from DB for profile '
4917 	             || strProfCodes
4918 	             || ' = '
4919 	             || l_trxnGrpCriTab.COUNT);
4920          END IF;
4921      END IF;
4922 
4923      /*
4924       * Loop through all the fetched documents, grouping them
4925       * into payments.
4926       */
4927      FOR i in l_trxnGrpCriTab.FIRST .. l_trxnGrpCriTab.LAST LOOP
4928 
4929          curr_trxn_id           := l_trxnGrpCriTab(i).trxn_id;
4930          curr_profile_cd        := l_trxnGrpCriTab(i).process_profile_code;
4931          curr_int_bank_acct_id  := l_trxnGrpCriTab(i).int_bank_acct_id;
4932          curr_bep_key           := l_trxnGrpCriTab(i).bep_key;
4933          curr_org_id            := l_trxnGrpCriTab(i).org_id;
4934          curr_org_type          := l_trxnGrpCriTab(i).org_type;
4935          curr_trxn_currency     := l_trxnGrpCriTab(i).curr_code;
4936          curr_trxn_amount       := l_trxnGrpCriTab(i).amount;
4937          curr_le_id             := l_trxnGrpCriTab(i).legal_entity_id;
4938          curr_settle_date       := l_trxnGrpCriTab(i).settle_date;
4939 
4940          l_org_flag             := l_trxnGrpCriTab(i).group_by_org;
4941          l_le_flag              := l_trxnGrpCriTab(i).group_by_le;
4942          l_int_bnk_flag         := l_trxnGrpCriTab(i).group_by_int_bank_acct;
4943          l_curr_flag            := l_trxnGrpCriTab(i).group_by_curr;
4944          l_settle_date_flag     := l_trxnGrpCriTab(i).group_by_settle_date;
4945 
4946          l_max_trxn_limit       := l_trxnGrpCriTab(i).num_trxns_limit;
4947 
4948          l_fx_rate_type         := l_trxnGrpCriTab(i).fx_rate_type;
4949          l_fx_curr_code         := l_trxnGrpCriTab(i).max_amt_curr;
4950          l_max_amount_limit     := l_trxnGrpCriTab(i).max_amt_limit;
4951 
4952          /*
4953           * Log all the fetched document fields
4954           */
4955          IF ( G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
4956 	         print_debuginfo(l_module_name,
4957 	             'Fetched data for transaction:' || curr_trxn_id
4958 	             || ', internal bank account: ' || curr_int_bank_acct_id
4959 	             || ', profile: '               || curr_profile_cd
4960 	             || ', bep key: '               || curr_bep_key
4961 	             || ', org: '                   || curr_org_id
4962 	             || ', org type: '              || curr_org_type
4963 	             || ', le:  '                   || curr_le_id
4964 	             || ', currency: '              || curr_trxn_currency
4965 	             || ', amount: '                || curr_trxn_amount
4966 	             || ', settle date: '           || curr_settle_date
4967 	             );
4968 
4969 	         print_debuginfo(l_module_name,
4970 	             'Fetched data for transaction:' || curr_trxn_id
4971 	             || ', org flag: '               || l_org_flag
4972 	             || ', le flag: '                || l_le_flag
4973 	             || ', int bank acct flag: '     || l_int_bnk_flag
4974 	             || ', currency flag: '          || l_curr_flag
4975 	             || ', settle date flag: '       || l_settle_date_flag
4976 	             || ', max trxns limit: '        || l_max_trxn_limit
4977 	             || ', max amount limit: '       || l_max_amount_limit
4978 	             || ', exch rate: '              || l_fx_rate_type
4979 	             || ', exch currency: '          || l_fx_curr_code
4980 	             );
4981 
4982          END IF;
4983          IF (l_first_record = 'Y') THEN
4984              prev_trxn_id              := curr_trxn_id;
4985              prev_int_bank_acct_id     := curr_int_bank_acct_id;
4986              prev_profile_cd           := curr_profile_cd;
4987              prev_org_id               := curr_org_id;
4988              prev_org_type             := curr_org_type;
4989              prev_le_id                := curr_le_id;
4990              prev_bep_key              := curr_bep_key;
4991              prev_trxn_currency        := curr_trxn_currency;
4992              prev_trxn_amount          := curr_trxn_amount;
4993              prev_settle_date          := curr_settle_date;
4994          END IF;
4995 
4996          /*
4997           * We have just fetched a new transaction for this profile.
4998           * We will either insert this transaction into a new batch or
4999           * we will be inserting this transaction into the currently running
5000           * batch.
5001           *
5002           * In either case, we need to insert this trxn into a batch.
5003           * So pre-populate the batch record with attributes of
5004           * this document. This is because the batch takes on the
5005           * attributes of its constituent transactions.
5006           *
5007           * Note: For user defined grouping rules, we will
5008           * have to populate the batch attributes only if
5009           * the user has turned on grouping by that attribute.
5010           */
5011 
5012          /* Only pre-fill hardcoded grouping rule attributes */
5013 	 /* Commenting out this one as, we no more have profile code and currency
5014 	    as hard coded grouping rules
5015 	 */
5016          --l_batchRec.profile_code       := curr_profile_cd;
5017          --l_batchRec.bep_key            := curr_bep_key;
5018 
5019          /*
5020           * Pre-fill grouping rule attributes for user defined
5021           * grouping rules (that are enabled by the user).
5022           *
5023           * It is necessary to pre-fill user defined grouping
5024           * attributes before the grouping rules are triggered
5025           * because we don't know which user defined grouping rules
5026           * are going to get triggered first, and once a rule is
5027           * triggered all rules below it are skipped. So it is too
5028           * late to populate grouping attributes within the grouping
5029           * rule itself.
5030           */
5031          IF (l_org_flag = 'Y') THEN
5032              l_batchRec.org_id   := curr_org_id;
5033              l_batchRec.org_type := curr_org_type;
5034          END IF;
5035 
5036          IF (l_le_flag = 'Y') THEN
5037              l_batchRec.le_id := curr_le_id;
5038          END IF;
5039 
5040          IF (l_int_bnk_flag = 'Y') THEN
5041              l_batchRec.int_bank_acct_id := curr_int_bank_acct_id;
5042          END IF;
5043 
5044          IF (l_curr_flag = 'Y') THEN
5045              l_batchRec.curr_code := curr_trxn_currency;
5046          END IF;
5047 
5048          IF (l_settle_date_flag = 'Y') THEN
5049              l_batchRec.settle_date := curr_settle_date;
5050          END IF;
5051 
5052          /*
5053           * Pre-fill the document record with the details
5054           * of the current document.
5055           */
5056          l_trxnsInBatchRec.trxn_id := curr_trxn_id;
5057 
5058          /*-- HARDCODED GROUPING RULES START HERE --*/
5059 	 /* Commenting out this one as, we no more have profile code and currency
5060 	    as hard coded grouping rules
5061 	 */
5062 
5063          /*
5064           * Grouping Step 1: Payment Profile Code
5065           */
5066     /*     IF (prev_profile_cd <> curr_profile_cd) THEN
5067 
5068              IF ( G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
5069 	             print_debuginfo(l_module_name, 'Grouping by payment '
5070 	                 || 'profile triggered for transaction '
5071 	                 || curr_trxn_id);
5072 
5073              END IF;
5074              insertTrxnIntoBatch(l_batchRec, l_batchTab,
5075                  true, l_mbatch_id, l_trxnsInBatchTab,
5076                  l_trxnsInBatchRec, l_trxns_in_batch_count);
5077 
5078              GOTO label_finish_iteration;
5079 
5080          END IF;
5081     */
5082 
5083          /*
5084           * Grouping Step 2: Payment System Account (Bep Key)
5085           */
5086     /*
5087          IF (prev_bep_key <> curr_bep_key) THEN
5088 
5089              IF ( G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
5090 	             print_debuginfo(l_module_name, 'Grouping by payment '
5091 	                 || 'system account triggered for transaction '
5092 	                 || curr_trxn_id);
5093 
5094              END IF;
5095              insertTrxnIntoBatch(l_batchRec, l_batchTab,
5096                  true, l_mbatch_id, l_trxnsInBatchTab,
5097                  l_trxnsInBatchRec, l_trxns_in_batch_count);
5098 
5099              GOTO label_finish_iteration;
5100 
5101          END IF;
5102     */
5103 
5104          /*-- USER DEFINED GROUPING RULES START HERE --*/
5105 
5106          /*
5107           * Grouping Step 3: Organization ID And Organization Type
5108           */
5109          IF (l_org_flag = 'Y') THEN
5110 
5111              IF (prev_org_id <> curr_org_id)     OR
5112                 (NVL(prev_org_type, 0) <> NVL(curr_org_type, 0)) THEN
5113 
5114                  IF ( G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
5115 	                 print_debuginfo(l_module_name, 'Grouping by organization '
5116 	                     || 'id/type triggered for transaction '
5117 	                     || curr_trxn_id);
5118 
5119                  END IF;
5120                  insertTrxnIntoBatch(l_batchRec, l_batchTab,
5121                      true, l_mbatch_id, l_trxnsInBatchTab,
5122                      l_trxnsInBatchRec, l_trxns_in_batch_count);
5123 
5124                  GOTO label_finish_iteration;
5125 
5126              END IF;
5127 
5128          END IF;
5129 
5130          /*
5131           * Grouping Step 3: Legal Entity ID
5132           */
5133          IF (l_le_flag = 'Y') THEN
5134 
5135              IF (prev_le_id <> curr_le_id) THEN
5136 
5137                  IF ( G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
5138 	                 print_debuginfo(l_module_name, 'Grouping by legal '
5139 	                     || 'entity triggered for transaction '
5140 	                     || curr_trxn_id);
5141 
5142                  END IF;
5143                  insertTrxnIntoBatch(l_batchRec, l_batchTab,
5144                      true, l_mbatch_id, l_trxnsInBatchTab,
5145                      l_trxnsInBatchRec, l_trxns_in_batch_count);
5146 
5147                  GOTO label_finish_iteration;
5148 
5149              END IF;
5150 
5151          END IF;
5152 
5153          /*
5154           * Grouping Step 4: Internal Bank Account ID
5155           */
5156          IF (l_int_bnk_flag = 'Y') THEN
5157 
5158              IF (prev_int_bank_acct_id <> curr_int_bank_acct_id) THEN
5159 
5160                  IF ( G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
5161 	                 print_debuginfo(l_module_name, 'Grouping by internal bank '
5162 	                     || 'account triggered for transaction '
5163 	                     || curr_trxn_id);
5164 
5165                  END IF;
5166                  insertTrxnIntoBatch(l_batchRec, l_batchTab,
5167                      true, l_mbatch_id, l_trxnsInBatchTab,
5168                      l_trxnsInBatchRec, l_trxns_in_batch_count);
5169 
5170                  GOTO label_finish_iteration;
5171 
5172              END IF;
5173 
5174          END IF;
5175 
5176          /*
5177           * Grouping Step 5: Settlement Currency
5178           */
5179          IF (l_curr_flag = 'Y') THEN
5180 
5181              IF (prev_trxn_currency <> curr_trxn_currency) THEN
5182 
5183                  IF ( G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
5184 	                 print_debuginfo(l_module_name, 'Grouping by settlement '
5185 	                     || 'currency triggered for transaction '
5186 	                     || curr_trxn_id);
5187 
5188                  END IF;
5189                  insertTrxnIntoBatch(l_batchRec, l_batchTab,
5190                      true, l_mbatch_id, l_trxnsInBatchTab,
5191                      l_trxnsInBatchRec, l_trxns_in_batch_count);
5192 
5193                  GOTO label_finish_iteration;
5194 
5195              END IF;
5196 
5197          END IF;
5198 
5199          /*
5200           * Grouping Step 6: Settlement Date
5201           */
5202          IF (l_settle_date_flag = 'Y') THEN
5203 
5204              IF (prev_settle_date <> curr_settle_date) THEN
5205 
5206                  IF ( G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
5207 	                 print_debuginfo(l_module_name, 'Grouping by settlement '
5208 	                     || 'date triggered for transaction '
5209 	                     || curr_trxn_id);
5210 
5211                  END IF;
5212                  insertTrxnIntoBatch(l_batchRec, l_batchTab,
5213                      true, l_mbatch_id, l_trxnsInBatchTab,
5214                      l_trxnsInBatchRec, l_trxns_in_batch_count);
5215 
5216                  GOTO label_finish_iteration;
5217 
5218              END IF;
5219 
5220          END IF;
5221 
5222          /*
5223           * Grouping Step 7: Max Transactions Per Batch
5224           */
5225          IF (l_max_trxn_limit IS NOT NULL) THEN
5226 
5227              IF (l_trxns_in_batch_count = l_max_trxn_limit) THEN
5228 
5229                  IF ( G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
5230 	                 print_debuginfo(l_module_name, 'Grouping by '
5231 	                     || 'max trxns per batch triggered for transaction '
5232 	                     || curr_trxn_id);
5233 
5234                  END IF;
5235                  insertTrxnIntoBatch(l_batchRec, l_batchTab,
5236                      true, l_mbatch_id, l_trxnsInBatchTab,
5237                      l_trxnsInBatchRec, l_trxns_in_batch_count);
5238 
5239                  GOTO label_finish_iteration;
5240 
5241              END IF;
5242 
5243          END IF;
5244 
5245          /*
5246           * Grouping Step 8: Max Amount Per Batch
5247           */
5248          IF (l_max_amount_limit IS NOT NULL) THEN
5249 
5250              IF (l_batch_total + l_trx_fx_amount > l_max_amount_limit) THEN
5251 
5252                  IF ( G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
5253 	                 print_debuginfo(l_module_name, 'Grouping by '
5254 	                     || 'max batch amount triggered by transaction '
5255 	                     || curr_trxn_id);
5256 
5257                  END IF;
5258                  insertTrxnIntoBatch(l_batchRec, l_batchTab,
5259                      true, l_mbatch_id, l_trxnsInBatchTab,
5260                      l_trxnsInBatchRec, l_trxns_in_batch_count);
5261 
5262                  GOTO label_finish_iteration;
5263 
5264              END IF;
5265 
5266          END IF;
5267 
5268          /*
5269           * End Of Grouping:
5270           * If a transaction reaches here, it means that this transaction
5271           * is similar to the previous transaction as far a grouping
5272           * criteria is concerned.
5273           *
5274           * Add this transaction to the currently running batch.
5275           */
5276          IF ( G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
5277 	         print_debuginfo(l_module_name, 'No grouping rules '
5278 	             || 'were triggered for transaction '
5279 	             || curr_trxn_id);
5280 
5281          END IF;
5282          insertTrxnIntoBatch(l_batchRec, l_batchTab,
5283              false, l_mbatch_id, l_trxnsInBatchTab,
5284              l_trxnsInBatchRec, l_trxns_in_batch_count);
5285 
5286 
5287          <<label_finish_iteration>>
5288 
5289          /*
5290           * Lastly, before going into the next iteration
5291           * of the loop copy all the current grouping criteria
5292           * into 'prev' fields so that we can compare these
5293           * fields with the next record.
5294           *
5295           * No need to copy the current values into the previous ones for
5296           * the first record because we have already done it at the beginning.
5297           */
5298          IF (l_first_record <> 'Y') THEN
5299              prev_trxn_id           := curr_trxn_id;
5300              prev_profile_cd        := curr_profile_cd;
5301              prev_int_bank_acct_id  := curr_int_bank_acct_id;
5302              prev_bep_key           := curr_bep_key;
5303              prev_org_id            := curr_org_id;
5304              prev_org_type          := curr_org_type;
5305              prev_trxn_currency     := curr_trxn_currency;
5306              prev_trxn_amount       := curr_trxn_amount;
5307              prev_le_id             := curr_le_id;
5308              prev_settle_date       := curr_settle_date;
5309          END IF;
5310 
5311          /*
5312           *  Remember to reset the first record flag before going
5313           *  into the next iteration.
5314           */
5315          IF (l_first_record = 'Y') THEN
5316              l_first_record := 'N';
5317          END IF;
5318 
5319          IF ( G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
5320 	         print_debuginfo(l_module_name, '+----------------------------------+');
5321 
5322          END IF;
5323 
5324 	 x_batchTab:= l_batchTab;
5325 	--x_trxnsInBatchTab(x_trxnsInBatchTab.COUNT+1):= l_trxnsInBatchTab(i);
5326 
5327 	print_debuginfo(l_module_name, 'l_batchTab.COUNT:'||
5328 			x_batchTab.COUNT);
5329 	print_debuginfo(l_module_name, 'l_trxnsInBatchTab.COUNT:'||
5330 			l_trxnsInBatchTab.COUNT);
5331 
5332      END LOOP;
5333 
5334      -- Moved logic from insert_batch_status_new
5335        IF (l_batchTab.COUNT > 0) THEN
5336 
5337                  l_index := 1;
5338                  FOR k IN l_batchTab.FIRST .. l_batchTab.LAST LOOP
5339 
5340                      /*
5341                       * Assign a unique batch id to each batch.
5342                       */
5343                      l_batchTab(k).batch_id :=
5344                          merch_batchid_in ||'_'|| l_index;
5345                      l_index := l_index + 1;
5346                  END LOOP;
5347 
5348         END IF;
5349 
5350         IF (l_trxnsInBatchTab.COUNT > 0) THEN
5351 
5352                  FOR m IN l_trxnsInBatchTab.FIRST ..
5353                      l_trxnsInBatchTab.LAST LOOP
5354 
5355                      FOR k IN l_batchTab.FIRST .. l_batchTab.LAST LOOP
5356 
5357                          /*
5358                           * Find the mbatch id in the batches array
5359                           * corresponding to the mbatchid of this transaction.
5360                           */
5361                          IF (l_trxnsInBatchTab(m).mbatch_id =
5362                              l_batchTab(k).mbatch_id) THEN
5363 
5364                              /*
5365                               * Assign the batch id from the batches array
5366                               * to this transaction.
5367                               */
5368                              l_trxnsInBatchTab(m).batch_id :=
5369                                  l_batchTab(k).batch_id;
5370 			     l_trxnsInBatchRec:= l_trxnsInBatchTab(m);
5371 			     -- Converting Table of records to record of tables
5372 			     trxnTab.transactionid(m):= l_trxnsInBatchRec.trxn_id;
5373                              trxnTab.mbatchid(m):= l_trxnsInBatchRec.mbatch_id;
5374 			     trxnTab.batchid(m):= l_trxnsInBatchRec.batch_id;
5375 
5376                          END IF;
5377 
5378                      END LOOP;
5379 
5380                  END LOOP;
5381 
5382         END IF;
5383 
5384 	-- Bulk Update
5385 	FORALL i in trxnTab.transactionid.FIRST .. trxnTab.transactionid.LAST
5386                      /* Bug 9958732 : Used INDEX hint to force the index */
5387 		     UPDATE /*+ INDEX(IBY_TRXN_SUMMARIES_ALL IBY_TRXN_SUMM_TRANS_ID_N1) */
5388                          IBY_TRXN_SUMMARIES_ALL
5389                      SET
5390                          status                = iby_transactioncc_pkg.
5391                                                      C_STATUS_BATCH_PENDING,
5392                          batchid               = trxnTab.batchid(i),
5393                          mbatchid              = trxnTab.mbatchid(i),
5394                          last_update_date      = sysdate,
5395                          updatedate            = sysdate,
5396                          last_updated_by       = fnd_global.user_id,
5397                          object_version_number = object_version_number + 1
5398                      WHERE
5399                          transactionid = trxnTab.transactionid(i) AND
5400                          status = iby_transactioncc_pkg.C_STATUS_OPEN_BATCHED
5401                          ;
5402        -- Bug# 8658052
5403        -- Freeing up the memory space. Assign an empty table
5404        l_trxnGrpCriTab:= emptyGrpCriTab;
5405        delete_trxnTable;
5406        l_trxnsInBatchTab:=emptyTrxnInsBatchTab;
5407        print_debuginfo(l_module_name, 'After freeing up memory space');
5408 
5409  END LOOP; -- Bulk fetch end loop
5410 
5411  CLOSE l_trxn_cursor;
5412 
5413      IF ( G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
5414 	     print_debuginfo(l_module_name, 'Created '
5415 	         || l_batchTab.COUNT   || ' batch(s) from '
5416 	         || l_trxnsInBatchTab.COUNT || ' transaction(s) for profile '
5417 	         || 'removed this value for the time being' || '.');
5418 	if(l_batchTab.COUNT > 0) THEN
5419 		print_debuginfo(l_module_name, 'l_batchTab.BATCHID:'|| l_batchTab(0).batch_id);
5420 		print_debuginfo(l_module_name, 'l_batchTab.MBATCHID:'|| l_batchTab(0).mbatch_id);
5421 	END IF;
5422      END IF;
5423      /*
5424       * Finally, return the batches created by grouping to the caller.
5425       */
5426      x_batchTab        := l_batchTab;
5427      x_trxnsInBatchTab := l_trxnsInBatchTab;
5428 
5429 
5430      /*
5431       * Fix for bug 5407120:
5432       *
5433       * Revert back thenumeric character mask to its original
5434       * setting. See begininning of this methods for comments
5435       * regarding this issue.
5436       *
5437       */
5438      BEGIN
5439 
5440          IF (l_numeric_char_mask IS NOT NULL) THEN
5441 
5442              EXECUTE IMMEDIATE
5443                  'ALTER SESSION SET NLS_NUMERIC_CHARACTERS = '
5444                     || '"'
5445                     || l_numeric_char_mask
5446                     || '"'
5447                  ;
5448 
5449              IF ( G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
5450 	             print_debuginfo(l_module_name, 'Reverted numeric char mask to: '
5451 	                 || l_numeric_char_mask
5452 	                 );
5453 
5454              END IF;
5455          END IF;
5456 
5457      EXCEPTION
5458          WHEN OTHERS THEN
5459              IF ( G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
5460 	             print_debuginfo(l_module_name, 'Non-Fatal: Exception occured '
5461 	                 || 'when attempting to revert numeric character mask.'
5462 	                 );
5463 
5464 	             print_debuginfo(l_module_name, 'SQL code: '   || SQLCODE);
5465 	             print_debuginfo(l_module_name, 'SQL err msg: '|| SQLERRM);
5466              END IF;
5467      END;
5468 
5469      IF ( G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
5470 	     print_debuginfo(l_module_name, 'EXIT');
5471 
5472      END IF;
5473  END performTransactionGrouping;
5474 
5475 
5476 /*--------------------------------------------------------------------
5477  | NAME:
5478  |     insertTrxnIntoBatch
5479  |
5480  | PURPOSE:
5481  |     Inserts a given transaction into a currently running batch
5482  |     or into a new batch as per given flag.
5483  |
5484  |     This method is called by every grouping rule to add
5485  |     a given transaction into a current batch/new batch.
5486  |
5487  | PARAMETERS:
5488  |     IN
5489  |
5490  |
5491  |     OUT
5492  |
5493  |
5494  | RETURNS:
5495  |
5496  | NOTES:
5497  |
5498  *---------------------------------------------------------------------*/
5499  PROCEDURE insertTrxnIntoBatch(
5500      x_batchRec            IN OUT NOCOPY batchAttrRecType,
5501      x_batchTab            IN OUT NOCOPY batchAttrTabType,
5502      p_newBatchFlag        IN            BOOLEAN,
5503      x_currentBatchId      IN OUT NOCOPY IBY_BATCHES_ALL.batchid%TYPE,
5504      x_trxnsInBatchTab     IN OUT NOCOPY trxnsInBatchTabType,
5505      x_trxnsInBatchRec     IN OUT NOCOPY trxnsInBatchRecType,
5506      x_trxnsInBatchCount   IN OUT NOCOPY NUMBER
5507      )
5508  IS
5509  l_module_name    CONSTANT VARCHAR2(200) := G_PKG_NAME ||
5510                                                 '.insertTrxnIntoBatch';
5511 
5512  BEGIN
5513 
5514      IF ( G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
5515 	     print_debuginfo(l_module_name, 'ENTER');
5516 
5517      END IF;
5518      /*
5519       * GROUPING LOGIC IS IN IF-ELSE BLOCK BELOW:
5520       *
5521       * Irrespective of whether this transaction is part of
5522       * an existing batch or whether it should be part
5523       * of a new batch, ensure that the PLSQL batches
5524       * table is updated with the details of this transaction
5525       * within this if-else block.
5526       *
5527       * We need to do this each time we enter this procedure
5528       * because this might well be the last transaction in
5529       * in the provided profile, and this procedure may
5530       * not be called again for this profile. So
5531       * the PLSQL batches table should always be up-to-date
5532       * when it exits this procedure.
5533       */
5534 
5535      IF (p_newBatchFlag = true) THEN
5536 
5537          /*
5538           * This is a new batch; Get an id for this batch
5539           */
5540          getNextBatchId(x_currentBatchId);
5541 
5542          /*
5543           * Create a new batch record using the incoming
5544           * transaction as a constituent, and insert this record
5545           * into the PLSQL batches table.
5546           */
5547          x_batchRec.mbatch_id        := x_currentBatchId;
5548          x_trxnsInBatchCount         := 1;
5549 
5550 	 x_batchRec.trxn_count   := x_trxnsInBatchCount;
5551 
5552 	 IF ( G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
5553 	         print_debuginfo(l_module_name, ' x_batchRec.trxn_count  ' || x_batchRec.trxn_count );
5554          END IF;
5555 
5556          x_batchTab(x_batchTab.COUNT + 1) := x_batchRec;
5557 
5558          IF ( G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
5559 	         print_debuginfo(l_module_name,' Inserted transaction : '
5560 	             || x_trxnsInBatchRec.trxn_id || ' into new batch: '
5561 	             || x_currentBatchId);
5562 
5563          END IF;
5564          /*
5565           * Assign the batch id of the new batch to this
5566           * trxn, and insert the trxn into the trxns array.
5567           */
5568          x_trxnsInBatchRec.mbatch_id := x_batchRec.mbatch_id;
5569          x_trxnsInBatchTab(x_trxnsInBatchTab.COUNT + 1) := x_trxnsInBatchRec;
5570 
5571      ELSE
5572 
5573          /*
5574           * This means we need to add the incoming transaction to
5575           * the current batch.
5576           */
5577 
5578          /*
5579           * First check special case: Payments PLSQL table is empty
5580           *
5581           * If the PLSQL table for batches is empty, we have to
5582           * initialize it by inserting a dummy record. This dummy
5583           * record will get overwritten below.
5584           */
5585          IF (x_batchTab.COUNT = 0) THEN
5586 
5587              getNextBatchId(x_currentBatchId);
5588 
5589              x_batchRec.mbatch_id := x_currentBatchId;
5590              x_trxnsInBatchCount := 0;
5591 
5592              /*
5593               * Insert the first record into the table. This
5594               * is a dummy record.
5595               */
5596              x_batchTab(x_batchTab.COUNT + 1) := x_batchRec;
5597 
5598              IF ( G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
5599 	             print_debuginfo(l_module_name, 'Created a new batch: '
5600 	                 || x_currentBatchId);
5601 
5602              END IF;
5603          END IF;
5604 
5605          /*
5606           * The incoming transaction should be part of the current batch.
5607           * So add the document amount to the current payment
5608           * record and increment the document count for the current
5609           * payment record.
5610           */
5611          x_batchRec.mbatch_id   := x_currentBatchId;
5612          x_trxnsInBatchCount    := x_trxnsInBatchCount + 1;
5613 
5614          --x_batchRec.payment_amount :=
5615          --    x_batchRec.payment_amount + x_trxnsInBatchRec.document_amount;
5616 
5617          /*
5618           * Overwrite the current batch record in the
5619           * PLSQL batches table with the updated record.
5620           */
5621          x_batchRec.trxn_count   := x_trxnsInBatchCount;
5622 
5623 	 IF ( G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
5624 	         print_debuginfo(l_module_name, ' x_batchRec.trxn_count  ' || x_batchRec.trxn_count );
5625          END IF;
5626 
5627          x_batchTab(x_batchTab.COUNT) := x_batchRec;
5628 
5629          IF ( G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
5630 	         print_debuginfo(l_module_name, 'Inserted transaction: '
5631 	             || x_trxnsInBatchRec.trxn_id || ' into existing batch: '
5632 	             || x_currentBatchId);
5633 
5634          END IF;
5635          /*
5636           * Assign the batch id of the current batch to this
5637           * transaction, and insert the trxn into the trxns array.
5638           */
5639          x_trxnsInBatchRec.mbatch_id := x_batchRec.mbatch_id;
5640          x_trxnsInBatchTab(x_trxnsInBatchTab.COUNT + 1) := x_trxnsInBatchRec;
5641 
5642      END IF;
5643 
5644      IF ( G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
5645 	     print_debuginfo(l_module_name, 'EXIT');
5646 
5647      END IF;
5648  END insertTrxnIntoBatch;
5649 
5650 /*--------------------------------------------------------------------
5651  | NAME:
5652  |     print_debuginfo
5653  |
5654  | PURPOSE:
5655  |     This procedure prints the debug message to the concurrent manager
5656  |     log file.
5657  |
5658  | PARAMETERS:
5659  |     IN
5660  |      p_debug_text - The debug message to be printed
5661  |
5662  |     OUT
5663  |
5664  |
5665  | RETURNS:
5666  |
5667  | NOTES:
5668  |
5669  *---------------------------------------------------------------------*/
5670  PROCEDURE print_debuginfo(
5671      p_module     IN VARCHAR2,
5672      p_debug_text IN VARCHAR2
5673      )
5674  IS
5675  PRAGMA AUTONOMOUS_TRANSACTION;
5676 
5677  BEGIN
5678 
5679      /*
5680       * If FND_GLOBAL.conc_request_id is -1, it implies that
5681       * this method has not been invoked via the concurrent
5682       * manager. In that case, write to apps log else write
5683       * to concurrent manager log file.
5684       */
5685      /*Remove this 2 lines after debugging*/
5686     -- INSERT INTO TEMP_IBY_LOGS VALUES (p_module || ': '
5687     --        || p_debug_text, sysdate);
5688     -- commit;
5689 
5690      IF (FND_GLOBAL.conc_request_id = -1) THEN
5691 
5692          /*
5693           * OPTION I:
5694           * Write debug text to the common application log file.
5695           */
5696          IBY_DEBUG_PUB.add(
5697              substr(RPAD(p_module,55) || ' : ' || p_debug_text, 0, 150),
5698              FND_LOG.G_CURRENT_RUNTIME_LEVEL,
5699              'iby.plsql.IBY_VALIDATIONSETS_PUB'
5700              );
5701 
5702          /*
5703           * OPTION II:
5704           * Write debug text to DBMS output file.
5705           */
5706          --DBMS_OUTPUT.PUT_LINE(substr(RPAD(p_module,40)||' : '||
5707          --    p_debug_text, 0, 150));
5708 
5709          /*
5710           * OPTION III:
5711           * Write debug text to temporary table.
5712           *
5713           * Use this script to create a debug table.
5714           * CREATE TABLE TEMP_IBY_LOGS(TEXT VARCHAR2(4000), TIME DATE);
5715           */
5716          /* uncomment these two lines for debugging */
5717          --INSERT INTO TEMP_IBY_LOGS VALUES (p_module || ': '
5718          --    || p_debug_text, sysdate);
5719 
5720          --COMMIT;
5721 
5722      ELSE
5723 
5724          /*
5725           * OPTION I:
5726           * Write debug text to the concurrent manager log file.
5727           */
5728          FND_FILE.PUT_LINE(FND_FILE.LOG, p_module || ': ' || p_debug_text);
5729 
5730          /*
5731           * OPTION II:
5732           * Write debug text to DBMS output file.
5733           */
5734          --DBMS_OUTPUT.PUT_LINE(substr(RPAD(p_module,40)||' : '||
5735          --    p_debug_text, 0, 150));
5736 
5737          /*
5738           * OPTION III:
5739           * Write debug text to temporary table.
5740           *
5741           * Use this script to create a debug table.
5742           * CREATE TABLE TEMP_IBY_LOGS(TEXT VARCHAR2(4000), TIME DATE);
5743           */
5744          /* uncomment these two lines for debugging */
5745          --INSERT INTO TEMP_IBY_LOGS VALUES (p_module || ': '
5746          --    || p_debug_text, sysdate);
5747 
5748          --COMMIT;
5749 
5750      END IF;
5751 
5752  END print_debuginfo;
5753 
5754 /*--------------------------------------------------------------------
5755  | NAME:
5756  |     getNextBatchId
5757  |
5758  | PURPOSE:
5759  |     Returns the next batch id from a sequence. These ids are
5760  |     used to uniquely number batches.
5761  |
5762  | PARAMETERS:
5763  |     IN
5764  |
5765  |
5766  |     OUT
5767  |
5768  |
5769  | RETURNS:
5770  |
5771  | NOTES:
5772  |
5773  *---------------------------------------------------------------------*/
5774  PROCEDURE getNextBatchId(
5775      x_batchID IN OUT NOCOPY IBY_BATCHES_ALL.batchid%TYPE
5776      )
5777  IS
5778 
5779  BEGIN
5780 
5781      SELECT IBY_BATCHID_S.NEXTVAL INTO x_batchID
5782          FROM DUAL;
5783 
5784  END getNextBatchId;
5785 
5786   -- Checks if a row already exists in transactions table
5787   -- based on the values passed.  This function is called by
5788   -- for query batch and query transaction operations to check
5789   -- before inserting a row.
5790 
5791   FUNCTION checkrows
5792 	(order_id_in  	     IN     iby_transactions_v.order_id%TYPE,
5793 	 merchant_id_in      IN     iby_transactions_v.merchant_id%TYPE,
5794 	 vendor_id_in	     IN     iby_transactions_v.vendor_id%TYPE,
5795 
5796 	 status_in	     IN     iby_transactions_v.status%TYPE,
5797 	 trxn_type_in	     IN     iby_transactions_v.trxn_type%TYPE)
5798    RETURN number
5799 
5800   IS
5801 
5802    	l_numrows	NUMBER := 0;
5803 	l_needupdate    boolean;
5804 	 l_tx1	     iby_transactions_v.trxn_type%TYPE;
5805 	 l_tx2	     iby_transactions_v.trxn_type%TYPE;
5806 
5807      CURSOR c_getNumTrxns(tx1 NUMBER,
5808              tx2 NUMBER DEFAULT NULL)
5809 	IS
5810            SELECT count(*)
5811            FROM iby_transactions_v
5812            WHERE order_Id = order_id_in
5813            AND merchant_id = merchant_id_in
5814 	   AND vendor_id = vendor_id_in
5815 	   AND status = status_in
5816 	   AND trxn_type = tx1;
5817            --AND trxn_type IN (tx1, tx2);
5818 	   --AND trxn_type IS NOT NULL;  -- add this for 'other operations' case
5819 
5820    BEGIN
5821 	IF (c_getNumTrxns%isopen) THEN
5822 		close c_getNumTrxns;
5823 	END IF;
5824 
5825 	-- no longer distinguish different trxntypeid returned by
5826 	-- Cybercash, considering 'closeBatch' effect
5827 	/*
5828 	IF (trxn_type_in = 8 or trxn_type_in = 9) THEN
5829 	   -- capture operations
5830 	   l_needupdate := true;
5831 	   open c_getNumTrxns(8, 9);
5832 
5833 	ELSIF (trxn_type_in = 5 or trxn_type_in = 10) THEN
5834 	   -- return operations
5835 	   l_needupdate := true;
5836 	   l_tx1 := 5;
5837 	   l_tx2 := 10;
5838 	   open c_getNumTrxns(5, 10);
5839 	ELSIF (trxn_type_in = 13 or trxn_type_in = 14) THEN
5840 		-- void capture
5841 	   l_needupdate := true;
5842 	   l_tx1 := 13;
5843 	   l_tx2 := 14;
5844 	   open c_getNumTrxns(13, 14);
5845 	ELSIF (trxn_type_in = 17 or trxn_type_in = 18) THEN
5846 		-- void return
5847 	   l_needupdate := true;
5848 	   l_tx1 := 17;
5849 	   l_tx2 := 18;
5850 	   open c_getNumTrxns(17, 18);
5851 	ELSE
5852 	   -- other operations
5853 	   l_needupdate := false;
5854 	   open c_getNumTrxns(trxn_type_in);
5855 	END IF;
5856 
5857 	*/
5858 
5859 	open c_getNumTrxns(trxn_type_in);
5860 
5861 	FETCH c_getNumTrxns INTO l_numrows;
5862 	/* IF (l_numrows > 0 AND l_needupdate) THEN
5863 	   UPDATE iby_trxn_summaries_all
5864 	   SET trxntypeid = trxn_type_in
5865            WHERE tangibleid = order_id_in
5866            AND payeeid = merchant_id_in
5867 	   AND bepid = vendor_id_in
5868 	   AND status = status_in
5869            AND trxntypeid IN (l_tx1, l_tx2);
5870 	END IF; */
5871 
5872 	CLOSE c_getNumTrxns;
5873 
5874    	RETURN l_numrows;
5875 
5876    END checkrows;
5877 
5878 
5879   /* Inserts the transaction record for the closebatch operation */
5880 
5881   PROCEDURE insert_batch_txn
5882     (ecapp_id_in	 IN	iby_trxn_summaries_all.ECAPPID%TYPE,
5883 
5884      order_id_in      IN     iby_transactions_v.order_id%TYPE,
5885      merchant_id_in   IN     iby_transactions_v.merchant_id%TYPE,
5886      merch_batchid_in	 IN	 iby_transactions_v.MerchBatchID%TYPE,
5887      vendor_id_in     IN     iby_transactions_v.vendor_id%TYPE,
5888      vendor_key_in    IN     iby_transactions_v.bepkey%TYPE,
5889      status_in		 IN	iby_transactions_v.status%TYPE,
5890      time_in		 IN	iby_transactions_v.time%TYPE,
5891      trxn_type_in	 IN	iby_transactions_v.trxn_type%TYPE,
5892      vendor_code_in	 IN	iby_transactions_v.vendor_code%TYPE,
5893      vendor_message_in	 IN	iby_transactions_v.vendor_message%TYPE,
5894      error_location_in	 IN	iby_transactions_v.error_location%TYPE,
5895 
5896      trace_number_in	    IN	  iby_transactions_v.TraceNumber%TYPE,
5897 	 org_id_in IN iby_trxn_summaries_all.org_id%type,
5898      transaction_id_out  OUT NOCOPY iby_trxn_summaries_all.TransactionID%TYPE)
5899 
5900   IS
5901 
5902     num_rows 	NUMBER;
5903     l_trxn_mid	     NUMBER;
5904     transaction_id NUMBER;
5905 
5906     l_mpayeeid iby_payee.mpayeeid%type;
5907     l_mbatchid iby_batches_all.mbatchid%type;
5908     l_mtangibleid iby_tangible.mtangibleid%type;
5909 
5910     l_prev_trxn_count number;
5911     l_reqtype iby_trxn_summaries_all.reqtype%type;
5912     l_instrtype iby_trxn_summaries_all.instrtype%type;
5913     l_instrsubtype iby_trxn_summaries_all.instrsubtype%type;
5914   BEGIN
5915 
5916   -- Update the existing row for this order id with merchant batch id
5917   -- Only the transaction types auth,authcapture,return,capture,markcapture
5918   -- and markreturn are taken into account.
5919 
5920   -- capture/markedcapture
5921   -- mark the authonly, authcapture, capture and Markcapture with the batchid
5922   IF (trxn_type_in = 8 OR trxn_type_in = 9)  THEN
5923 	l_reqtype := 'ORAPMTCAPTURE';
5924 	--dbms_output.put_line('position 1');
5925     getMBatchId(merch_batchid_in, merchant_id_in, l_mbatchid);
5926     UPDATE iby_trxn_summaries_all
5927     SET BatchID = merch_batchid_in,
5928     	MBatchID = l_mbatchid,
5929     last_update_date=sysdate,
5930     updatedate = sysdate,
5931     last_updated_by = fnd_global.user_id,
5932     creation_date = sysdate,
5933     created_by = fnd_global.user_id,
5934     object_version_number = object_version_number + 1
5935     WHERE TangibleID =	order_id_in
5936     AND PayeeID = merchant_id_in
5937     AND TrxntypeID IN (2, 3, 8,9)
5938     AND Status = 0;
5939 
5940   -- For return/credit transaction type, mark the return, MarkReturn
5941   --	transaction type  with batchid
5942   ELSIF (trxn_type_in = 5 OR trxn_type_in = 10) THEN
5943 	l_reqtype := 'ORAPMTRETURN';
5944 	--dbms_output.put_line('position 2');
5945     getMBatchId(merch_batchid_in, merchant_id_in, l_mbatchid);
5946 
5947     UPDATE iby_trxn_summaries_all
5948 
5949     SET BatchID = merch_batchid_in,
5950 	MBatchID = l_mbatchid,
5951     last_update_date=sysdate,
5952     updatedate = sysdate,
5953     last_updated_by = fnd_global.user_id,
5954     creation_date = sysdate,
5955     created_by = fnd_global.user_id,
5956     object_version_number = object_version_number + 1
5957     WHERE TangibleID =	order_id_in
5958     AND PayeeID = merchant_id_in
5959 	AND TrxntypeID IN (5, 10)
5960     AND Status = 0;
5961 
5962   END IF;
5963 
5964   num_rows := checkrows(order_id_in, merchant_id_in, vendor_id_in,
5965 			status_in, trxn_type_in);
5966 
5967   --dbms_output.put_line('position 3 ' || num_rows);
5968 
5969 
5970  IF num_rows = 0  THEN
5971   -- Now insert a new row for this transaction in the batch
5972   -- Get the transaction id first
5973       SELECT count(*)
5974       INTO l_prev_trxn_count
5975       FROM iby_trxn_summaries_all
5976       WHERE  tangibleid = order_id_in AND
5977 	     payeeid = merchant_id_in;
5978 
5979 	IF (l_prev_trxn_count = 0) THEN
5980 		-- this happens when previous trxn wasn't recorded in
5981 		-- payment server, e.g, Aalok/Jonathan's testing --jjwu
5982 		-- what about mtangibleid ???
5983 	  transaction_id_out := getTID(merchant_id_in, order_id_in);
5984 	  l_mtangibleid := -1;
5985 	ELSE
5986       	   SELECT DISTINCT transactionid, mtangibleid, instrtype, instrsubtype
5987       	   INTO transaction_id_out, l_mtangibleid, l_instrtype, l_instrsubtype
5988        	   FROM iby_trxn_summaries_all
5989            WHERE  tangibleid = order_id_in AND
5990 	        payeeid = merchant_id_in
5991 		AND status = 0;
5992 	END IF;
5993 
5994 	--dbms_output.put_line('position 4');
5995   -- Get the master transaction id for this record
5996 
5997      SELECT iby_trxnsumm_mid_s.NEXTVAL
5998 	INTO l_trxn_mid
5999 	FROM dual;
6000 
6001 	--dbms_output.put_line('position 5');
6002 
6003 	getMBatchId(merch_batchid_in, merchant_id_in, l_mbatchid);
6004 	iby_accppmtmthd_pkg.getMPayeeId(merchant_id_in, l_mpayeeid);
6005 
6006 
6007 	-- this insertion from close/query batch is problematic
6008 	-- 1) there is no corresponding entry in ibY_trxn_core table
6009 	-- 2) mtangible id might not be correct, there might not be
6010 	--    an entry in iby_tangible table
6011 	-- 3) currency, amount is missing
6012 	-- regardless, this should be a rare case, it exists because
6013 	-- 1) Cybercash doesn't return 'trxntypeid' for capture/return
6014 	--    accurately
6015 	-- 2) during testing, there are trxns submitted directly to bep
6016 	--    (not through iPayment)
6017 	-- 3) during testing, requests submitted to Cybercash regular
6018 	--    and Cybercash SSL are considered different, but during close
6019 	--    batch, they are mixed.
6020      INSERT INTO iby_trxn_summaries_all
6021 	(TrxnMID, TransactionID,TangibleID,MPayeeID, PayeeID,BEPID, bepKey,
6022 	 ECAppID,org_id, Status, UpdateDate,TrxnTypeID, MBatchID, BatchID,
6023 	 BEPCode,BEPMessage,Errorlocation,
6024 	ReqType, ReqDate, mtangibleid,
6025 	 last_update_date,last_updated_by,creation_date,created_by,
6026 
6027 	 last_update_login,object_version_number,instrType,instrsubtype,needsupdt)
6028       VALUES (l_trxn_mid,  transaction_id_out,
6029 	      order_id_in, l_mpayeeid, merchant_id_in, vendor_id_in,
6030 	       vendor_key_in, ecapp_id_in, org_id_in, status_in, time_in,
6031 		trxn_type_in, l_mbatchid, merch_batchid_in,
6032 	      vendor_code_in, vendor_message_in, error_location_in,
6033 		l_reqtype, sysdate, l_mtangibleid,
6034 	 	sysdate,fnd_global.user_id,sysdate,fnd_global.user_id,
6035 		fnd_global.login_id,1,l_instrtype,l_instrsubtype,'Y');
6036 	--dbms_output.put_line('position 6');
6037   ELSE
6038 
6039     -- retrieve existing tid out
6040     SELECT distinct(transactionid)
6041       INTO transaction_id_out
6042       FROM iby_trxn_summaries_all
6043       WHERE tangibleid = order_id_in
6044 	AND payeeid = merchant_id_in
6045 	AND bepid = vendor_id_in
6046 	AND trxntypeid = trxn_type_in
6047 	AND status = status_in;
6048 
6049   END IF;
6050 
6051   COMMIT;
6052   END insert_batch_txn;
6053 
6054 
6055  /* Inserts transaction record for transaction query operation */
6056 
6057   PROCEDURE insert_query_txn
6058     (transaction_id_in   IN     iby_trxn_summaries_all.TransactionID%TYPE,
6059      order_id_in         IN     iby_transactions_v.order_id%TYPE,
6060      merchant_id_in      IN     iby_transactions_v.merchant_id%TYPE,
6061      vendor_id_in        IN     iby_transactions_v.vendor_id%TYPE,
6062      vendor_key_in       IN     iby_transactions_v.bepkey%TYPE,
6063      status_in           IN     iby_transactions_v.status%TYPE,
6064      time_in             IN     iby_transactions_v.time%TYPE DEFAULT sysdate,
6065      trxn_type_in        IN     iby_transactions_v.trxn_type%TYPE,
6066      amount_in           IN     iby_transactions_v.amount%TYPE DEFAULT NULL,
6067      currency_in         IN     iby_transactions_v.currency%TYPE DEFAULT NULL,
6068      payment_name_in     IN     iby_transactions_v.payment_name%TYPE DEFAULT NULL,
6069      authcode_in         IN     iby_transactions_v.authcode%TYPE DEFAULT NULL,
6070      referencecode_in    IN     iby_transactions_v.referencecode%TYPE DEFAULT NULL,
6071      avscode_in          IN     iby_transactions_v.AVScode%TYPE DEFAULT NULL,
6072      acquirer_in         IN     iby_transactions_v.acquirer%TYPE DEFAULT NULL,
6073      auxmsg_in           IN     iby_transactions_v.Auxmsg%TYPE DEFAULT NULL,
6074      vendor_code_in      IN     iby_transactions_v.vendor_code%TYPE DEFAULT NULL,
6075      vendor_message_in   IN     iby_transactions_v.vendor_message%TYPE DEFAULT NULL,
6076      error_location_in   IN     iby_transactions_v.error_location%TYPE DEFAULT NULL,
6077      trace_number_in     IN     iby_transactions_v.TraceNumber%TYPE DEFAULT NULL,
6078      org_id_in           IN     iby_trxn_summaries_all.org_id%type DEFAULT NULL,
6079      ecappid_in          IN     iby_ecapp.ecappid%type,
6080      req_type_in         IN     iby_trxn_summaries_all.reqtype%type)
6081   IS
6082 
6083     num_rows	  NUMBER;
6084     l_trxn_mid	     NUMBER;
6085     l_mpayeeid iby_payee.mpayeeid%type;
6086    l_mtangibleid iby_trxn_summaries_all.mtangibleid%type;
6087 	l_cnt number;
6088     l_instrtype iby_trxn_summaries_all.instrtype%type;
6089     l_instrsubtype iby_trxn_summaries_all.instrsubtype%type;
6090    l_trxnref iby_trxn_summaries_all.trxnref%type;
6091 
6092     CURSOR c_trxnmid(
6093                     ci_trxnid iby_trxn_summaries_all.TransactionID%TYPE,
6094                     ci_merchid iby_trxn_summaries_all.PayeeId%TYPE,
6095                     --ci_trxntype iby_trxn_summaries_all.TrxnTypeId%TYPE,
6096                     ci_reqtype iby_trxn_summaries_all.ReqType%TYPE,
6097                     ci_status iby_trxn_summaries_all.Status%TYPE
6098                     )
6099     IS
6100       SELECT trxnmid
6101       FROM iby_trxn_summaries_all
6102       WHERE (status = ci_status)
6103       AND (payeeid = ci_merchid)
6104       AND (transactionid = ci_trxnid)
6105       AND (reqtype = ci_reqtype);
6106 
6107     CURSOR c_order_info
6108            (
6109            ci_orderid iby_transactions_v.order_id%TYPE,
6110            ci_merchid iby_transactions_v.merchant_id%TYPE
6111            )
6112     IS
6113       SELECT mtangibleid, instrtype, instrsubtype, trxnref
6114       FROM iby_trxn_summaries_all
6115       WHERE (tangibleid = ci_orderid)
6116       AND (payeeid = ci_merchid)
6117       AND (mtangibleid <> -1)
6118       ORDER BY reqdate DESC;
6119 
6120   BEGIN
6121 
6122   IF (c_trxnmid%ISOPEN) THEN
6123     CLOSE c_trxnmid;
6124   END IF;
6125 
6126   IF (c_order_info%ISOPEN) THEN
6127     CLOSE c_order_info;
6128   END IF;
6129 
6130   -- find any transitional trxns and update them
6131   --
6132   OPEN c_trxnmid(transaction_id_in,merchant_id_in,req_type_in,9);
6133   FETCH c_trxnmid INTO l_trxn_mid;
6134 
6135   IF (c_trxnmid%NOTFOUND) THEN
6136     CLOSE c_trxnmid;
6137   ELSE
6138     -- a transitional trxn (cut off in mid-process)
6139     -- exists ; update it instead of adding a new
6140     -- row
6141     CLOSE c_trxnmid;
6142 
6143     UPDATE iby_trxn_summaries_all
6144     SET ReqDate = NVL(time_in,reqdate),
6145         --Amount = amount_in,
6146         --CurrencyNameCode = currency_in,
6147         UpdateDate = NVL(time_in,updatedate),
6148         Status = status_in,
6149 	BEPCode = vendor_code_in,
6150         BEPMessage = vendor_message_in,
6151         Errorlocation = error_location_in,
6152         instrType = NVL(l_instrtype,instrType),
6153         instrsubtype = NVL(l_instrsubtype,instrsubtype),
6154         --org_id = org_id_in,
6155 	last_update_date = sysdate,
6156         last_updated_by = fnd_global.user_id,
6157 	last_update_login = fnd_global.login_id,
6158         object_version_number = object_version_number+1
6159     WHERE (trxnmid = l_trxn_mid);
6160 
6161     UPDATE iby_trxn_core
6162     SET AuthCode = authcode_in,
6163         ReferenceCode = referencecode_in,
6164         AVSCode = avscode_in,
6165         Acquirer = acquirer_in,
6166         Auxmsg = auxmsg_in,
6167 	TraceNumber = trace_number_in,
6168         InstrName = NVL(payment_name_in,instrname),
6169 	last_update_date = sysdate,
6170         last_updated_by = fnd_global.user_id,
6171         last_update_login = fnd_global.login_id,
6172         object_version_number = object_version_number+1
6173     WHERE (trxnmid = l_trxn_mid);
6174 
6175     COMMIT;
6176     RETURN;
6177   END IF;
6178 
6179    -- Check if row is already in table using unique
6180    -- key of order_id, merchant_id, vendor_id, transaction_type
6181    -- and status.  We dont want to update those
6182    -- rows which have non-zero status.	We would like to save
6183    -- them for history
6184 
6185   -- collate differnt trxn types as certain gateways may be returning
6186   -- codes different from the value stored in trnxtypeid
6187   --
6188   IF (trxn_type_in = 8 or trxn_type_in = 9) THEN
6189     num_rows := checkrows(order_id_in,merchant_id_in,vendor_id_in,status_in,8);
6190     num_rows := num_rows + checkrows(order_id_in,merchant_id_in,vendor_id_in,status_in,9);
6191   ELSIF (trxn_type_in = 5 or trxn_type_in = 10) THEN
6192     num_rows := checkrows(order_id_in,merchant_id_in,vendor_id_in,status_in,5);
6193     num_rows := num_rows + checkrows(order_id_in,merchant_id_in,vendor_id_in,status_in,10);
6194   ELSIF (trxn_type_in = 13 or trxn_type_in = 14) THEN
6195     num_rows := checkrows(order_id_in,merchant_id_in,vendor_id_in,status_in,13);
6196     num_rows := num_rows + checkrows(order_id_in,merchant_id_in,vendor_id_in,status_in,14);
6197   ELSIF (trxn_type_in = 17 or trxn_type_in = 18) THEN
6198     num_rows := checkrows(order_id_in,merchant_id_in,vendor_id_in,status_in,17);
6199     num_rows := num_rows + checkrows(order_id_in,merchant_id_in,vendor_id_in,status_in,18);
6200   ELSE
6201     num_rows := num_rows + checkrows(order_id_in,merchant_id_in,vendor_id_in,status_in,trxn_type_in);
6202   END IF;
6203 
6204   -- If no record found insert this row otherwise no need to update
6205   IF num_rows = 0
6206   THEN
6207 
6208       SELECT iby_trxnsumm_mid_s.NEXTVAL
6209 	INTO l_trxn_mid
6210 	FROM dual;
6211 
6212 	iby_accppmtmthd_pkg.getMPayeeId(merchant_id_in, l_mpayeeid);
6213 
6214 
6215 	-- try to get mtangibleid
6216 	select count(*) into l_cnt from iby_trxn_summaries_all
6217 	where tangibleid = order_id_in and
6218 	payeeid = merchant_id_in and
6219 	mtangibleid <> -1;
6220 
6221 	-- no -1:
6222 	-- see insert_batch_txn, we want to ignore trxns done directly
6223 	-- on BEP, w/o going through iPayment
6224 	-- and other unknown cases
6225 
6226 	if (l_cnt > 0) then
6227           OPEN c_order_info(order_id_in,merchant_id_in);
6228           FETCH c_order_info INTO l_mtangibleid, l_instrtype, l_instrsubtype,
6229 l_trxnref;
6230           CLOSE c_order_info;
6231 	else
6232 		-- I can not get mtangibleid from the iby_tangible table
6233 		-- because it is missing the payee info
6234 		l_mtangibleid := -1;
6235 	end if;
6236 
6237       INSERT INTO iby_trxn_summaries_all
6238 	(ECAppID, TrxnMID, TransactionID,TrxntypeID, ReqDate, ReqType,
6239 	 Amount,CurrencyNameCode, UpdateDate,Status,
6240 	 TangibleID,MPayeeID, PayeeID,BEPID, bepKey, MTangibleID,
6241 	 BEPCode,BEPMessage,Errorlocation, org_id,
6242 	 last_update_date,last_updated_by,creation_date,created_by,
6243 	 last_update_login,object_version_number,instrType,instrsubtype,trxnref,needsupdt)
6244       VALUES (ecappid_in, l_trxn_mid, transaction_id_in, trxn_type_in,
6245 		time_in, req_type_in,
6246 	      amount_in, currency_in, time_in, status_in,
6247 	      order_id_in, l_mpayeeid, merchant_id_in, vendor_id_in,
6248 		vendor_key_in, l_mtangibleid,
6249 	      vendor_code_in, vendor_message_in, error_location_in, org_id_in,
6250 		 sysdate,fnd_global.user_id,sysdate,fnd_global.user_id,
6251 		fnd_global.login_id,1,l_instrtype,l_instrsubtype,l_trxnref,'Y');
6252 
6253       INSERT INTO iby_trxn_core
6254 	(TrxnMID, AuthCode, ReferenceCode, AVSCode, Acquirer, Auxmsg,
6255 	TraceNumber, InstrName,
6256 	 last_update_date,last_updated_by,creation_date,created_by,last_update_login,
6257 
6258 	  object_version_number)
6259       VALUES (l_trxn_mid, authcode_in,referencecode_in,avscode_in, acquirer_in,
6260 auxmsg_in, trace_number_in, payment_name_in,
6261 
6262 	 sysdate,fnd_global.user_id,sysdate,fnd_global.user_id,fnd_global.login_id,1);
6263 
6264   END IF;
6265 
6266   COMMIT;
6267 
6268 
6269   END insert_query_txn;
6270 
6271 
6272   /* updates the statuses of trxns saved in a batch */
6273   PROCEDURE updateBatchedTrxns
6274 	(
6275 	payeeid_in	IN	iby_trxn_summaries_all.payeeid%TYPE,
6276 	bepid_in	IN	iby_trxn_summaries_all.bepid%TYPE,
6277 	bepkey_in	IN	iby_trxn_summaries_all.bepkey%TYPE,
6278 	oldstatus_in	IN	iby_trxn_summaries_all.status%TYPE,
6279 	newstatus_in	IN	iby_trxn_summaries_all.status%TYPE,
6280 	oldbatchid_in	IN	iby_trxn_summaries_all.batchid%TYPE,
6281 	newbatchid_in	IN      iby_trxn_summaries_all.batchid%TYPE
6282 	)
6283   IS
6284 	l_mbatchid	iby_trxn_summaries_all.mbatchid%TYPE;
6285   BEGIN
6286 
6287 	BEGIN
6288 	     getMBatchId(oldbatchid_in, payeeid_in, l_mbatchid);
6289 	--
6290 	-- catch exception in the case where the batch id has not been
6291 	-- stored yet in IBY_BATCHES_ALL ; this can happen when we
6292 	-- want to change the status of transitional trxns
6293 	--
6294 	EXCEPTION WHEN others THEN
6295 	     l_mbatchid := NULL;
6296 	END;
6297 
6298 	UPDATE iby_trxn_summaries_all
6299 	SET
6300 	  status = newstatus_in,
6301 	  batchid = newbatchid_in,
6302 	  mbatchid = l_mbatchid,
6303 	  last_update_date = sysdate,
6304           updatedate = sysdate,
6305           last_updated_by = fnd_global.user_id,
6306           object_version_number = object_version_number + 1
6307 	WHERE (bepid = bepid_in)
6308 	  AND (bepkey = bepkey_in)
6309 	  AND (payeeid = payeeid_in)
6310 	  AND (status = oldstatus_in)
6311           AND ((instrtype='CREDITCARD') OR (instrtype='PURCHASECARD') OR (instrtype IS NULL))
6312 	  AND ((batchid IS NULL AND oldbatchid_IN IS NULL) OR (batchid = oldbatchid_in));
6313 
6314 	COMMIT;
6315 
6316   END updateBatchedTrxns;
6317 
6318 
6319   /* Regular version of this method. */
6320   PROCEDURE updateBatchQueryTrxn
6321 	(
6322 	payeeid_in	IN	iby_trxn_summaries_all.payeeid%TYPE,
6323 	orderid_in	IN	iby_trxn_summaries_all.batchid%TYPE,
6324 	trxn_type_in	IN      iby_trxn_summaries_all.trxntypeid%TYPE,
6325 	batchid_in	IN	iby_trxn_summaries_all.batchid%TYPE,
6326 	status_in	IN	iby_trxn_summaries_all.status%TYPE,
6327 	bep_code_in     IN      iby_trxn_summaries_all.bepcode%TYPE,
6328 	bep_msg_in      IN      iby_trxn_summaries_all.bepmessage%TYPE,
6329 	error_loc_in    IN      iby_trxn_summaries_all.errorlocation%TYPE,
6330 	trxnid_out      OUT NOCOPY iby_trxn_summaries_all.transactionid%TYPE
6331 	)
6332   IS
6333   BEGIN
6334 
6335       UPDATE
6336 	iby_trxn_summaries_all
6337 
6338       SET
6339 	status=status_in,
6340 	--
6341 	-- only change these values if they have non-trivial values
6342 	--
6343 	bepcode=DECODE(NVL(bep_code_in,''), '',bepcode, bep_code_in),
6344 	bepmessage=DECODE(NVL(bep_msg_in,''), '',bepmessage, bep_msg_in),
6345 	errorlocation=DECODE(NVL(error_loc_in,''), '',errorlocation, error_loc_in),
6346 	last_update_date = sysdate,
6347 	last_updated_by = fnd_global.user_id,
6348 	object_version_number = object_version_number + 1
6349 
6350       WHERE
6351 
6352         --
6353         -- Where clause modified to support
6354         -- returns (transaction type 5):
6355         -- Returns(5) and credits(11) are to be
6356         -- treated as equivalents because in the
6357         -- processor model we send return transactions
6358         -- as credits. When we query for the status of
6359         -- such a credit, we must remember to update the
6360         -- status of the original return.
6361         --
6362 
6363 	(payeeid = payeeid_in) AND
6364 	(tangibleid = orderid_in) AND
6365 	(trxntypeid IN (trxn_type_in, 5)) AND
6366 	(batchid = batchid_in);
6367 
6368       IF (SQL%NOTFOUND) THEN
6369 	trxnid_out := -1;
6370       ELSE
6371         trxnid_out := getTID(payeeid_in, orderid_in);
6372       END IF;
6373 
6374       COMMIT;
6375 
6376   END updateBatchQueryTrxn;
6377 
6378 
6379   /* auth version of the method. */
6380   PROCEDURE updateBatchQueryTrxn
6381 	(
6382 	payeeid_in	IN	iby_trxn_summaries_all.payeeid%TYPE,
6383 	orderid_in	IN	iby_trxn_summaries_all.batchid%TYPE,
6384 	trxn_type_in	IN      iby_trxn_summaries_all.trxntypeid%TYPE,
6385 	batchid_in	IN	iby_trxn_summaries_all.batchid%TYPE,
6386 	status_in	IN	iby_trxn_summaries_all.status%TYPE,
6387 	bep_code_in     IN      iby_trxn_summaries_all.bepcode%TYPE,
6388 	bep_msg_in      IN      iby_trxn_summaries_all.bepmessage%TYPE,
6389 	error_loc_in    IN      iby_trxn_summaries_all.errorlocation%TYPE,
6390 	authcode_in     IN      iby_trxn_core.authcode%TYPE,
6391 	avscode_in      IN      iby_trxn_core.avscode%TYPE,
6392 	cvv2result_in   IN      iby_trxn_core.cvv2result%TYPE,
6393 	trxnid_out      OUT NOCOPY iby_trxn_summaries_all.transactionid%TYPE
6394 	)
6395   IS
6396 	l_trxnmid	iby_trxn_summaries_all.trxnmid%TYPE;
6397   BEGIN
6398 
6399      updateBatchQueryTrxn(payeeid_in,orderid_in,trxn_type_in,batchid_in,status_in,bep_code_in,bep_msg_in,error_loc_in,trxnid_out);
6400 
6401      SELECT
6402        trxnmid
6403      INTO
6404        l_trxnmid
6405      FROM
6406        iby_trxn_summaries_all
6407      WHERE
6408 
6409         --
6410         -- Where clause modified to support
6411         -- returns (transaction type 5):
6412         -- Returns(5) and credits(11) are to be
6413         -- treated as equivalents because in the
6414         -- processor model we send return transactions
6415         -- as credits. When we query for the status of
6416         -- such a credit, we must remember to update the
6417         -- status of the original return.
6418         --
6419 
6420        (transactionid = trxnid_out) AND
6421        (payeeid = payeeid_in) AND
6422        (trxntypeid IN (trxn_type_in, 5));
6423 
6424      IF (SQL%NOTFOUND) THEN
6425        RETURN;
6426      END IF;
6427 
6428      UPDATE
6429        iby_trxn_core
6430      SET
6431        authcode=authcode_in,
6432        cvv2result=cvv2result_in,
6433        avscode=avscode_in
6434      WHERE
6435        (trxnmid=l_trxnmid);
6436 
6437      COMMIT;
6438 
6439   END updateBatchQueryTrxn;
6440 
6441   PROCEDURE Update_Batch
6442   (
6443    ecapp_id_in          IN      iby_batches_all.ecappid%TYPE,
6444    payeeid_in	        IN      iby_trxn_summaries_all.payeeid%TYPE,
6445    batchid_in           IN      iby_trxn_summaries_all.batchid%TYPE,
6446    batch_status_in      IN      iby_batches_all.batchstatus%TYPE,
6447    batch_total_in       IN      iby_batches_all.batchtotal%TYPE,
6448    sale_amount_in       IN      iby_batches_all.batchsales%TYPE,
6449    credit_amount_in     IN      iby_batches_all.batchcredit%TYPE,
6450    bep_code_in          IN      iby_batches_all.bepcode%TYPE,
6451    bep_message_in       IN      iby_batches_all.bepmessage%TYPE,
6452    error_location_in    IN      iby_batches_all.errorlocation%TYPE,
6453    ack_type_in          IN      VARCHAR2,
6454    trxn_orderid_in	IN	JTF_VARCHAR2_TABLE_100,
6455    trxn_reqtype_in      IN      JTF_VARCHAR2_TABLE_100,
6456    trxn_status_in	IN	JTF_VARCHAR2_TABLE_100,
6457    trxn_bep_code_in     IN      JTF_VARCHAR2_TABLE_100,
6458    trxn_bep_msg_in      IN      JTF_VARCHAR2_TABLE_100,
6459    trxn_error_loc_in    IN      JTF_VARCHAR2_TABLE_100,
6460    trxn_authcode_in     IN      JTF_VARCHAR2_TABLE_100,
6461    trxn_avscode_in      IN      JTF_VARCHAR2_TABLE_100,
6462    trxn_cvv2result_in   IN      JTF_VARCHAR2_TABLE_100,
6463    trxn_tracenumber     IN      JTF_VARCHAR2_TABLE_100
6464   )
6465   IS
6466     l_tmid     iby_trxn_summaries_all.trxnmid%TYPE;
6467     l_tid      iby_trxn_summaries_all.transactionid%TYPE;
6468     l_needsupdt iby_trxn_summaries_all.needsupdt%TYPE;
6469     l_count    NUMBER := 0;
6470     l_module VARCHAR2(100) := G_DEBUG_MODULE || '.Update_Batch';
6471 
6472     CURSOR c_tmid
6473            (ci_payeeid iby_trxn_summaries_all.payeeid%TYPE,
6474             ci_orderid iby_trxn_summaries_all.tangibleid%TYPE,
6475             ci_reqtype iby_trxn_summaries_all.reqtype%TYPE,
6476             ci_mbatchid iby_trxn_summaries_all.mbatchid%TYPE
6477             )
6478     IS
6479       SELECT trxnmid, transactionid,needsupdt
6480       FROM iby_trxn_summaries_all
6481       WHERE (payeeid = ci_payeeid)
6482         AND (tangibleid = ci_orderid)
6483         -- ack cannot distinguish between credits and returns
6484         AND (DECODE(reqtype, 'ORAPMTRETURN','ORAPMTCREDIT', reqtype) =
6485            ci_reqtype)
6486         AND (status = iby_transactioncc_pkg.C_STATUS_BATCH_PENDING)
6487         AND (mbatchid = ci_mbatchid);
6488 
6489       -- [lmallick] - bug# 9414266
6490    -- gets the trxnmid of the capture trxn associated with the auth
6491    -- that includes the tracenumber.  The tracenumber is assigned only
6492    -- to the auth not capture trxns
6493 
6494    -- Modified the curser to strengthen the filter criteria by
6495    -- including 'mbatchid'. FDC doesn't accept tracenumbers of more
6496    -- than 6 digits in the IBY.Q (and above) versions. We need to reset
6497    -- the tracenumber field if it has reached a length of 7. This will
6498    -- cause duplicates. Including mbatchid in the filter will eliminate
6499    -- such possibilities to a great extent. (Maybe, in future,we can
6500    -- include orderid and/or authcode. But, currently these are passed
6501    -- as null. Fixes on those attributes may help us in making the flow
6502    -- even more robust.)
6503    -- Bug# 12385267
6504    -- Inluded trxn type for RETURN and CREDIT
6505    CURSOR c_tracenumber
6506           (ci_tracenumber iby_trxn_core.tracenumber%TYPE,
6507 	   ci_mbatchid iby_trxn_summaries_all.mbatchid%TYPE
6508 	  ) IS
6509     SELECT ibs.trxnmid, ibs.transactionid, ibs.needsupdt
6510       FROM iby_trxn_summaries_all ibs,
6511            iby_trxn_summaries_all orig_trxn,
6512            iby_trxn_core   ibc
6513      WHERE ibs.transactionid = orig_trxn.transactionid
6514        AND ibs.trxntypeid IN(8, 5, 11)
6515        AND orig_trxn.trxnmid=ibc.trxnmid
6516        AND ibc.tracenumber=ci_tracenumber
6517        AND ibs.mbatchid=ci_mbatchid
6518        AND ibs.status = iby_transactioncc_pkg.C_STATUS_BATCH_PENDING;
6519 
6520   BEGIN
6521 
6522     IF (c_tmid%ISOPEN) THEN CLOSE c_tmid; END IF;
6523     IF (c_tracenumber%ISOPEN) THEN CLOSE c_tracenumber; END IF;
6524     IF ( G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
6525 	    print_debuginfo(l_module,'batch_total_in:'|| batch_total_in);
6526 	    print_debuginfo(l_module,'sale_amount_in:'|| sale_amount_in);
6527 	    print_debuginfo(l_module,'credit_amount_in:'|| credit_amount_in);
6528 	    print_debuginfo(l_module,'bep_code_in:'|| bep_code_in);
6529 	    print_debuginfo(l_module,'bep_message_in:'|| bep_message_in);
6530     END IF;
6531 
6532     UPDATE iby_batches_all
6533     SET batchstatus = batch_status_in,
6534       batchtotal = batch_total_in,
6535       batchsales = sale_amount_in,
6536       batchcredit = credit_amount_in,
6537       bepcode = bep_code_in,
6538       bepmessage = bep_message_in,
6539       errorlocation = error_location_in,
6540       last_update_date = sysdate,
6541       last_updated_by = fnd_global.user_id,
6542       object_version_number = object_version_number + 1
6543     WHERE (payeeid = payeeid_in)
6544       AND (mbatchid = batchid_in);
6545 
6546     -- trxn status data probably not known
6547     -- immediately after batch close
6548     --
6549     IF ( G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
6550 	print_debuginfo(l_module,'trxn_status_in.count: '|| trxn_status_in.count);
6551     END IF;
6552 
6553     IF (trxn_status_in.count<>0) THEN
6554 
6555 
6556     FOR i IN trxn_status_in.FIRST .. trxn_status_in.LAST LOOP
6557 	IF ( G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
6558 	    print_debuginfo(l_module,'tracenumber= '||trxn_tracenumber(i));
6559     END IF;
6560     IF(NVL(trxn_tracenumber(i), 0)<>0)  THEN
6561 
6562 
6563    OPEN c_tracenumber(trxn_tracenumber(i), batchid_in);
6564    FETCH  c_tracenumber into l_tmid, l_tid, l_needsupdt;
6565 
6566    ELSE
6567      IF ( G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
6568 	      print_debuginfo(l_module,'tracenumber is 0 ');
6569       END IF;
6570 
6571       OPEN c_tmid(payeeid_in,trxn_orderid_in(i),trxn_reqtype_in(i),batchid_in);
6572       FETCH c_tmid INTO l_tmid, l_tid, l_needsupdt;
6573 
6574   END IF;
6575      IF ( G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
6576 	      print_debuginfo(l_module,'l_tmid= '||l_tmid||', l_tid = '||l_tid);
6577       END IF;
6578 
6579       --trxnid_out.extend(1);
6580       l_count := l_count +1;
6581 
6582       IF ( (trxn_status_in(i) <> 0) AND (l_needsupdt = 'N')) THEN
6583           l_needsupdt := 'Y';
6584       END IF;
6585 
6586       IF (l_tmid IS NOT NULL) THEN
6587 	      IF ( G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
6588 		print_debuginfo(l_module,'l_tmid is not null. Updating iby_trxn tables.');
6589 	      END IF;
6590         UPDATE iby_trxn_summaries_all
6591         SET status = TO_NUMBER(trxn_status_in(i)),
6592           bepcode = trxn_bep_code_in(i),
6593           bepmessage = trxn_bep_msg_in(i),
6594           errorlocation = TO_NUMBER(trxn_error_loc_in(i)),
6595           last_update_date = sysdate,
6596           last_updated_by = fnd_global.user_id,
6597           object_version_number = object_version_number + 1,
6598 	  needsupdt = l_needsupdt
6599         WHERE (trxnmid = l_tmid);
6600 
6601         UPDATE iby_trxn_core
6602         SET authcode = trxn_authcode_in(i),
6603           avscode = trxn_avscode_in(i),
6604           cvv2result = trxn_cvv2result_in(i),
6605           last_update_date = sysdate,
6606           last_updated_by = fnd_global.user_id,
6607           object_version_number = object_version_number + 1
6608         WHERE (trxnmid = l_tmid);
6609 
6610         --trxnid_out(i) := l_tid;
6611       ELSE
6612 
6613         --trxnid_out(i) := -1;
6614         null;
6615       END IF;
6616 
6617     IF (c_tmid%ISOPEN) THEN
6618       CLOSE c_tmid;
6619     END IF;
6620 
6621     IF (c_tracenumber%ISOPEN) THEN
6622       CLOSE c_tracenumber;
6623     END IF;
6624 
6625 
6626     END LOOP;
6627     ELSE
6628 
6629     -- for some acknowledgements missing transactions are
6630     -- implicitly assumed to have succeeded or failed
6631     --
6632     IF ( G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
6633 	    print_debuginfo(l_module,'ack_type is: '||ack_type_in);
6634     END IF;
6635     IF ((ack_type_in = 'P') OR (ack_type_in = 'N')) THEN
6636       IF ( G_LEVEL_STATEMENT >= G_CURRENT_RUNTIME_LEVEL) THEN
6637 	     print_debuginfo(l_module,'Updating transaction status:');
6638       END IF;
6639       UPDATE iby_trxn_summaries_all
6640       SET
6641           status = DECODE(ack_type_in,
6642                           'P',C_STATUS_BEP_FAIL,
6643                           'N',C_STATUS_SUCCESS,
6644                           C_STATUS_OPEN_BATCHED),
6645           last_update_date = sysdate,
6646           last_updated_by = fnd_global.user_id,
6647           object_version_number = object_version_number + 1
6648       WHERE (payeeid = payeeid_in)
6649         AND (mbatchid = batchid_in)
6650         AND (status = iby_transactioncc_pkg.C_STATUS_BATCH_PENDING);
6651     END IF;
6652     END IF;
6653 
6654     COMMIT;
6655     print_debuginfo(l_module,'Exit');
6656   END Update_Batch;
6657 
6658 
6659 /*
6660 ** Procedure: getMBatchId
6661 ** Purpose: retrieve mBatchid from iby_Batch table based on Batchid
6662 */
6663 
6664 
6665 Procedure getMBatchId(i_Batchid in iby_Batches_all.Batchid%type,
6666 			i_Payeeid in iby_Batches_all.Payeeid%type,
6667 			o_mBatchid out nocopy iby_Batches_all.mBatchid%type)
6668 is
6669   cursor  c_get_mBatchid(ci_Batchid iby_Batches_All.Batchid%type,
6670 			ci_PayeeId iby_batches_all.PayeeID%type)
6671   is
6672     SELECT mBatchid from iby_Batches_All
6673     WHERE Batchid = ci_Batchid
6674 	AND PayeeID = ci_PayeeID;
6675 BEGIN
6676 
6677   IF (c_get_mbatchid%isopen) THEN
6678 	close c_get_mBatchid;
6679   END IF;
6680 
6681   open c_get_mBatchid(i_Batchid, i_payeeid);
6682 
6683   fetch c_get_mBatchid into o_mBatchid;
6684     if ( c_get_mBatchid%notfound ) then
6685        	raise_application_error(-20000, 'IBY_20211#', FALSE);
6686 	--raise_application_error(-20211, 'Batchid not found', FALSE);
6687     end if;
6688 
6689   close c_get_mBatchid;
6690 END;
6691 
6692 
6693 /*
6694 	for QueryTrxn where there will be no orgid inserted
6695 	try to see if there is already some valid org id stored,
6696 	if so, use the non-null one first
6697 */
6698 Function getOrgId(i_tid in iby_trxn_summaries_all.transactionid%type)
6699 return number
6700 IS
6701    l_org_id NUMBER := NULL;
6702    l_count NUMBER;
6703 
6704    cursor c_getNonNullOrgId(ci_tid
6705 			iby_trxn_summaries_all.transactionid%type)
6706 
6707    is
6708 	SELECT DISTINCT org_id
6709 	FROM iby_trxn_summaries_all
6710 	WHERE transactionid = i_tid
6711 	AND status <> -99 AND status <> 14  -- ignore cancelled trxns
6712 	AND org_id IS NOT NULL;
6713 
6714 BEGIN
6715 
6716 	IF (c_getNonNullOrgId%isopen) THEN
6717 		close c_getNonNullOrgId;
6718 	END IF;
6719 
6720 	open c_getNonNullOrgId(i_tid);
6721 	Fetch c_getNonNullOrgId INTO l_org_id;
6722 	-- if not found, l_org_id will remain null
6723 	close c_getNonNullOrgId;
6724 
6725 	return l_org_id;
6726 END;
6727 
6728 
6729 /*    Count number of previous PENDING transactions, ignoring the
6730 	cancelled ones
6731 */
6732 
6733 Function getNumPendingTrxns(i_payeeid in iby_payee.payeeid%type,
6734 			i_tangibleid in iby_tangible.tangibleid%type,
6735 			i_reqtype in iby_trxn_summaries_all.reqtype%type)
6736 return number
6737 
6738 IS
6739 
6740 l_num_trxns number;
6741 
6742 BEGIN
6743 
6744      SELECT count(*)
6745        INTO l_num_trxns
6746        FROM iby_trxn_summaries_all
6747       WHERE TangibleID = i_tangibleid
6748 	AND UPPER(ReqType) = UPPER(i_reqtype)
6749 	AND PayeeID = i_payeeid
6750 	AND (status IN (11,9));
6751 
6752     IF (l_num_trxns > 1) THEN
6753       -- should never run into this block
6754        	raise_application_error(-20000, 'IBY_20422#', FALSE);
6755     END IF;
6756 
6757    return l_num_trxns;
6758 END;
6759 
6760 
6761 /* get TID based on orderid */
6762 Function getTID(i_payeeid in iby_payee.payeeid%type,
6763 		i_tangibleid in iby_tangible.tangibleid%type)
6764 return number
6765 
6766 IS
6767 
6768 l_tid number;
6769 cursor c_tid(ci_payeeid in iby_payee.payeeid%type,
6770 		ci_tangibleid in iby_tangible.tangibleid%type)
6771   is
6772 	SELECT distinct transactionid
6773 	FROM iby_trxn_summaries_all
6774 	WHERE tangibleid = ci_tangibleid
6775 	AND payeeid = ci_payeeid;
6776 
6777 BEGIN
6778 	if (c_tid%isopen) then
6779 	   close c_tid;
6780 	end if;
6781 
6782 	open c_tid(i_payeeid, i_tangibleid);
6783 	fetch c_tid into l_tid;
6784 	if (c_tid%notfound) then
6785 	  SELECT iby_trxnsumm_trxnid_s.NEXTVAL
6786 	  INTO l_tid
6787 	  FROM dual;
6788 	end if;
6789 
6790 	close c_tid;
6791 
6792 	return l_tid;
6793 
6794 END getTID;
6795 
6796 
6797 /* get TID based on orderid, payeeid (if unique) */
6798 Function getTIDUniqueCheck(i_payeeid in iby_payee.payeeid%type,
6799 		i_tangibleid in iby_tangible.tangibleid%type)
6800 return number
6801 
6802 IS
6803 
6804 l_tid number;
6805 cursor c_tid(ci_payeeid in iby_payee.payeeid%type,
6806 		ci_tangibleid in iby_tangible.tangibleid%type)
6807   is
6808 	SELECT distinct transactionid
6809 	FROM iby_trxn_summaries_all
6810 	WHERE tangibleid = ci_tangibleid
6811 	AND payeeid = ci_payeeid;
6812 
6813 BEGIN
6814 	if (c_tid%isopen) then
6815 	   close c_tid;
6816 	end if;
6817 
6818 	open c_tid(i_payeeid, i_tangibleid);
6819 	fetch c_tid into l_tid;
6820 
6821         -- If no exception was thrown it means
6822         -- that we found a record in the cursor
6823         -- that matches the given criteria (which
6824         -- further means that there already exists
6825         -- a transaction id for this (orderid, payeeid)
6826         -- combination). So return -1 to indicate that
6827         -- this transaction is non-unique.
6828         l_tid := -1;
6829 
6830 	if (c_tid%notfound) then
6831 	  SELECT iby_trxnsumm_trxnid_s.NEXTVAL
6832 	  INTO l_tid
6833 	  FROM dual;
6834 	end if;
6835 
6836 	close c_tid;
6837 
6838 	return l_tid;
6839 
6840 END getTIDUniqueCheck;
6841 
6842   FUNCTION unencrypt_instr_num
6843   (p_instrnum    IN iby_trxn_summaries_all.instrnumber%TYPE,
6844    p_payee_key   IN iby_security_pkg.des3_key_type,
6845    p_payee_subkey_cipher IN iby_payee_subkeys.subkey_cipher_text%TYPE,
6846    p_sys_key     IN RAW,
6847    p_sys_subkey_cipher IN iby_sys_security_subkeys.subkey_cipher_text%TYPE,
6848    p_segment_id  IN iby_security_segments.sec_segment_id%TYPE,
6849    p_segment_cipher IN iby_security_segments.segment_cipher_text%TYPE,
6850    p_card_prefix IN iby_cc_issuer_ranges.card_number_prefix%TYPE,
6851    p_card_len    IN iby_cc_issuer_ranges.card_number_length%TYPE,
6852    p_digit_check IN iby_creditcard_issuers_b.digit_check_flag%TYPE
6853   )
6854   RETURN iby_trxn_summaries_all.instrnumber%TYPE
6855   IS
6856   BEGIN
6857     RETURN IBY_SECURITY_PKG.unencrypt_instr_num
6858       (p_instrnum,
6859        p_payee_key,
6860        p_payee_subkey_cipher,
6861        p_sys_key,
6862        p_sys_subkey_cipher,
6863        p_segment_id,
6864        p_segment_cipher,
6865        p_card_prefix,
6866        p_card_len,
6867        p_digit_check);
6868   END unencrypt_instr_num;
6869 
6870   PROCEDURE unencrypt_instr_num
6871   (trxnmid_in    IN iby_trxn_summaries_all.trxnmid%TYPE,
6872    master_key_in IN iby_security_pkg.DES3_KEY_TYPE,
6873    instr_num_out OUT NOCOPY iby_trxn_summaries_all.instrnumber%TYPE
6874   )
6875   IS
6876   BEGIN
6877     IBY_SECURITY_PKG.unencrypt_instr_num
6878       (trxnmid_in,
6879        master_key_in,
6880        instr_num_out);
6881   END unencrypt_instr_num;
6882 
6883 
6884   FUNCTION unencrypt_instr_num
6885 	(
6886 	trxnmid_in	IN	iby_trxn_summaries_all.trxnmid%TYPE,
6887         master_key_in   IN      iby_security_pkg.DES3_KEY_TYPE
6888 	)
6889   RETURN iby_trxn_summaries_all.instrnumber%TYPE
6890   IS
6891 	l_instrnum iby_trxn_summaries_all.instrnumber%TYPE;
6892   BEGIN
6893 	unencrypt_instr_num(trxnmid_in,master_key_in,l_instrnum);
6894 	RETURN l_instrnum;
6895   END unencrypt_instr_num;
6896 
6897   FUNCTION unencrypt_instr_num_ui_wrp
6898 	(
6899 	trxnmid_in	IN	iby_trxn_summaries_all.trxnmid%TYPE,
6900         master_key_in   IN      iby_security_pkg.DES3_KEY_TYPE
6901 	)
6902   RETURN iby_trxn_summaries_all.instrnumber%TYPE
6903   IS
6904 	l_instrnum iby_trxn_summaries_all.instrnumber%TYPE;
6905   BEGIN
6906 	l_instrnum := unencrypt_instr_num(trxnmid_in,master_key_in);
6907 	RETURN l_instrnum;
6908 
6909   EXCEPTION
6910     WHEN OTHERS THEN
6911       return null;
6912 
6913   END unencrypt_instr_num_ui_wrp;
6914 
6915   PROCEDURE Encrypt_CC_Data
6916   (p_sys_key IN IBY_SECURITY_PKG.DES3_KEY_TYPE, x_err_code OUT NOCOPY VARCHAR2)
6917   IS
6918     -- types
6919     TYPE  Num15Tab IS TABLE OF NUMBER(15) INDEX BY BINARY_INTEGER;
6920     TYPE  Char60Tab IS TABLE OF VARCHAR2(60) INDEX BY BINARY_INTEGER;
6921 
6922     -- bulk tables
6923     l_trxnmid_tbl     Num15Tab;
6924     l_maskedcc_tbl    Char60Tab;
6925     l_issuer_tbl      Char60Tab;
6926     l_cchash_tbl      Char60Tab;
6927     l_rangeid_tbl     Num15Tab;
6928     l_instrlen_tbl    Num15Tab;
6929     l_segmentid_tbl   Num15Tab;
6930 
6931     l_index           NUMBER;
6932 
6933     -- variables for CHNAME and EXPDATE encryption
6934     l_chname_sec_segment_id iby_security_segments.sec_segment_id%TYPE;
6935     l_expdate_sec_segment_id iby_security_segments.sec_segment_id%TYPE;
6936     l_masked_chname     VARCHAR2(100) := NULL;
6937     l_encrypted         VARCHAR2(1) := 'N';
6938 
6939     CURSOR c_tx_ccnumber
6940     IS
6941       SELECT /*+ rowid(tx) */
6942         tx.trxnmid,
6943         iby_utility_pvt.decode64(instrnumber) ccnum,
6944         tx.instrtype
6945       FROM iby_trxn_summaries_all tx
6946       WHERE
6947         (NOT instrnumber IS NULL)
6948         AND (DECODE(instrtype, 'PINLESSDEBITCARD','CREDITCARD',
6949                                'PURCHASECARD','CREDITCARD',
6950         -- instrument type will be NULL for credit card credit trxns
6951                                NULL,DECODE(reqtype,
6952                                            'ORAPMTCREDIT','CREDITCARD',
6953                                            NULL),
6954                                instrtype) = 'CREDITCARD')
6955         AND (instrnum_sec_segment_id IS NULL);
6956 
6957 
6958    -- The below cursor will fetch all un-encrypted rows from
6959    -- IBY_TRXN_CORE table. Though we could probably have merged this
6960    -- cursor with the earlier one, we maintain a separate one since
6961    -- there could be records in this table that are un-encrypted but the
6962    -- corresponding records in iby_trxn_summaries_all are encrypted.
6963    CURSOR c_trxn_core
6964     IS
6965       SELECT
6966         tx.trxnmid tmid,
6967         core.instr_expirydate expdate,
6968         core.instr_owner_name chname
6969       FROM iby_trxn_summaries_all tx,
6970            iby_trxn_core core
6971       WHERE
6972          (DECODE(tx.instrtype, 'PINLESSDEBITCARD','CREDITCARD',
6973                                'PURCHASECARD','CREDITCARD',
6974         -- instrument type will be NULL for credit card credit trxns
6975                                NULL,DECODE(tx.reqtype,
6976                                            'ORAPMTCREDIT','CREDITCARD',
6977                                            NULL),
6978                                tx.instrtype) = 'CREDITCARD')
6979     	AND tx.trxnmid = core.trxnmid
6980 	AND NVL(core.encrypted, 'N') = 'N';
6981 
6982      l_dbg_mod VARCHAR2(100) := 'IBY_TRANSACTIONCC_PKG' || '.Encrypt_CC_Data';
6983   BEGIN
6984 
6985     IF (iby_creditcard_pkg.Get_CC_Encrypt_Mode() =
6986         iby_security_pkg.G_ENCRYPT_MODE_NONE)
6987     THEN
6988       RETURN;
6989     END IF;
6990     iby_security_pkg.validate_sys_key(p_sys_key,x_err_code);
6991     IF (NOT x_err_code IS NULL) THEN
6992       RETURN;
6993     END IF;
6994 
6995     l_index := 1;
6996 
6997     FOR txn_rec IN c_tx_ccnumber LOOP
6998       -- bug# 9532549
6999       -- Invoke the encryption API only if the card# is numeric, or else
7000       -- the API might thow an exception resulting in abrupt termination
7001       -- of the program.
7002       IF('Y' = IBY_UTILITY_PVT.isNumeric(txn_rec.ccnum)) THEN
7003         IBY_TRANSACTIONCC_PKG.prepare_instr_data
7004         (FND_API.G_FALSE,
7005          p_sys_key,
7006          txn_rec.ccnum,
7007          txn_rec.instrtype,
7008          l_maskedcc_tbl(l_index),
7009          l_issuer_tbl(l_index),
7010          l_cchash_tbl(l_index),
7011          l_rangeid_tbl(l_index),
7012          l_instrlen_tbl(l_index),
7013          l_segmentid_tbl(l_index)
7014         );
7015         l_trxnmid_tbl(l_index) := txn_rec.trxnmid;
7016 
7017         IF (l_index=1000) THEN
7018           FORALL i IN l_trxnmid_tbl.first..l_trxnmid_tbl.last
7019            UPDATE iby_trxn_summaries_all
7020             SET
7021               instrnumber = l_maskedcc_tbl(i),
7022               instrnum_hash = l_cchash_tbl(i),
7023               cc_issuer_range_id = l_rangeid_tbl(i),
7024               instrnum_length = l_instrlen_tbl(i),
7025               instrnum_sec_segment_id = l_segmentid_tbl(i)
7026             WHERE trxnmid=l_trxnmid_tbl(i);
7027 
7028           COMMIT;
7029 
7030           l_index := 1;
7031           l_maskedcc_tbl.delete;
7032           l_issuer_tbl.delete;
7033           l_cchash_tbl.delete;
7034           l_rangeid_tbl.delete;
7035           l_instrlen_tbl.delete;
7036           l_segmentid_tbl.delete;
7037           l_trxnmid_tbl.delete;
7038         ELSE
7039           l_index := l_index + 1;
7040         END IF;
7041       ELSE
7042         iby_debug_pub.add('Could not encrypt the transaction ' ||   txn_rec.trxnmid,IBY_DEBUG_PUB.G_LEVEL_INFO,l_dbg_mod);
7043       END IF;
7044     END LOOP;
7045 
7046     IF (l_trxnmid_tbl.COUNT>0) THEN
7047       FORALL i IN l_trxnmid_tbl.first..l_trxnmid_tbl.last
7048         UPDATE iby_trxn_summaries_all
7049         SET
7050            instrnumber = l_maskedcc_tbl(i),
7051            instrnum_hash = l_cchash_tbl(i),
7052            cc_issuer_range_id = l_rangeid_tbl(i),
7053            instrnum_length = l_instrlen_tbl(i),
7054            instrnum_sec_segment_id = l_segmentid_tbl(i)
7055          WHERE trxnmid=l_trxnmid_tbl(i);
7056 
7057        COMMIT;
7058     END IF;
7059 
7060   -- Loop thru the iby_trxn_core table only if the other card attributes
7061   -- present here need to be secured
7062 
7063   --IF( IBY_CREDITCARD_PKG.Other_CC_Attribs_Encrypted = 'Y') THEN
7064      FOR core_rec IN c_trxn_core LOOP
7065         l_chname_sec_segment_id :=
7066                  IBY_SECURITY_PKG.encrypt_field_vals(core_rec.chname,
7067 		                                     p_sys_key,
7068 						     null,
7069 						     'N'
7070 						     );
7071         l_expdate_sec_segment_id :=
7072                  IBY_SECURITY_PKG.encrypt_date_field(core_rec.expdate,
7073 		                                     p_sys_key,
7074 						     null,
7075 						     'N'
7076 						     );
7077         l_masked_chname :=
7078                 IBY_SECURITY_PKG.Mask_Data(core_rec.chname,
7079 		                           IBY_SECURITY_PKG.G_MASK_ALL,
7080 				           0,
7081 					   'X'
7082 					   );
7083         l_encrypted := 'Y';
7084 
7085         UPDATE iby_trxn_core SET
7086         encrypted = 'Y',
7087         instr_owner_name = l_masked_chname,
7088         chname_sec_segment_id = l_chname_sec_segment_id,
7089         instr_expirydate = NULL,
7090         expiry_sec_segment_id = l_expdate_sec_segment_id,
7091         object_version_number = object_version_number + 1,
7092         last_update_date = sysdate,
7093         last_updated_by = fnd_global.user_id,
7094         last_update_login = fnd_global.login_id
7095         WHERE (trxnmid = core_rec.tmid);
7096 
7097      END LOOP;
7098   --END IF;
7099 
7100   COMMIT;
7101 
7102   END Encrypt_CC_Data;
7103 
7104   PROCEDURE Decrypt_CC_Data
7105   (p_sys_key IN IBY_SECURITY_PKG.DES3_KEY_TYPE, x_err_code OUT NOCOPY VARCHAR2)
7106   IS
7107     -- types
7108     TYPE  Num15Tab IS TABLE OF NUMBER(15) INDEX BY BINARY_INTEGER;
7109     TYPE  Char60Tab IS TABLE OF VARCHAR2(60) INDEX BY BINARY_INTEGER;
7110 
7111     -- bulk tables
7112     l_trxnmid_tbl     Num15Tab;
7113     l_instrnum_tbl    Char60Tab;
7114     l_segmentid_tbl   Num15Tab;
7115 
7116     l_index           NUMBER;
7117 
7118     -- variabled for CHNAME and EXPDATE decryption
7119     l_chname            VARCHAR2(80);
7120     l_str_exp_date      VARCHAR2(20);
7121     l_exp_date          DATE;
7122 
7123     CURSOR c_tx_ccnumber(ci_sys_key IN IBY_SECURITY_PKG.DES3_KEY_TYPE)
7124     IS
7125       SELECT /*+ rowid(tx) */
7126         tx.trxnmid,
7127         iby_transactioncc_pkg.unencrypt_instr_num
7128         (tx.instrnumber, NULL, NULL, ci_sys_key,
7129          k.subkey_cipher_text, tx.instrnum_sec_segment_id,
7130          seg.segment_cipher_text, r.card_number_prefix,
7131          NVL(r.card_number_length,tx.instrnum_length),
7132          i.digit_check_flag) ccnum,
7133          instrnum_sec_segment_id
7134       FROM iby_trxn_summaries_all tx,
7135         iby_security_segments seg, iby_sys_security_subkeys k,
7136         iby_cc_issuer_ranges r, iby_creditcard_issuers_b i
7137       WHERE
7138 /*
7139         (NOT instrnumber IS NULL)
7140         AND (DECODE(instrtype, 'PINLESSDEBITCARD','CREDITCARD',
7141                                'PURCHASECARD','CREDITCARD',
7142         -- instrument type will be NULL for credit card credit trxns
7143                                NULL,DECODE(reqtype,
7144                                            'ORAPMTCREDIT','CREDITCARD',
7145                                            NULL),
7146                                instrtype) = 'CREDITCARD')
7147 */
7148         (NOT instrnum_sec_segment_id IS NULL)
7149         AND (tx.instrnum_sec_segment_id = seg.sec_segment_id(+))
7150         AND (seg.sec_subkey_id = k.sec_subkey_id(+))
7151         AND (tx.cc_issuer_range_id = r.cc_issuer_range_id(+))
7152         AND (tx.instrsubtype = i.card_issuer_code(+));
7153 
7154     CURSOR c_trxn_core
7155     IS
7156       SELECT
7157         trxnmid,
7158 	instr_expirydate,
7159         expiry_sec_segment_id,
7160 	instr_owner_name,
7161         chname_sec_segment_id
7162       FROM iby_trxn_core
7163       WHERE NVL(encrypted, 'N') = 'Y';
7164 
7165   BEGIN
7166     IF (iby_creditcard_pkg.Get_CC_Encrypt_Mode() =
7167         iby_security_pkg.G_ENCRYPT_MODE_NONE)
7168     THEN
7169       RETURN;
7170     END IF;
7171     iby_security_pkg.validate_sys_key(p_sys_key,x_err_code);
7172     IF (NOT x_err_code IS NULL) THEN
7173       RETURN;
7174     END IF;
7175 
7176     l_index := 1;
7177 
7178     FOR txn_rec IN c_tx_ccnumber(p_sys_key) LOOP
7179 
7180       l_trxnmid_tbl(l_index) := txn_rec.trxnmid;
7181       l_instrnum_tbl(l_index) := iby_utility_pvt.encode64(txn_rec.ccnum);
7182       l_segmentid_tbl(l_index) := txn_rec.instrnum_sec_segment_id;
7183 
7184       IF (l_index=1000) THEN
7185         FORALL i IN l_trxnmid_tbl.first..l_trxnmid_tbl.last
7186           UPDATE iby_trxn_summaries_all
7187           SET
7188             instrnumber = l_instrnum_tbl(i),
7189             instrnum_sec_segment_id = NULL
7190           WHERE trxnmid=l_trxnmid_tbl(i);
7191 
7192         FORALL i IN l_segmentid_tbl.first..l_segmentid_tbl.last
7193           DELETE iby_security_segments
7194           WHERE sec_segment_id = l_segmentid_tbl(i);
7195 
7196         COMMIT;
7197 
7198         l_index := 1;
7199         l_segmentid_tbl.delete;
7200         l_instrnum_tbl.delete;
7201         l_trxnmid_tbl.delete;
7202       ELSE
7203         l_index := l_index + 1;
7204       END IF;
7205     END LOOP;
7206 
7207     IF (l_trxnmid_tbl.COUNT>0) THEN
7208       FORALL i IN l_trxnmid_tbl.first..l_trxnmid_tbl.last
7209       UPDATE iby_trxn_summaries_all
7210          SET
7211            instrnumber = l_instrnum_tbl(i),
7212            instrnum_sec_segment_id = NULL
7213          WHERE trxnmid=l_trxnmid_tbl(i);
7214 
7215       FORALL i IN l_segmentid_tbl.first..l_segmentid_tbl.last
7216         DELETE iby_security_segments
7217         WHERE sec_segment_id = l_segmentid_tbl(i);
7218 
7219       COMMIT;
7220     END IF;
7221 
7222     --IF( IBY_CREDITCARD_PKG.Other_CC_Attribs_Encrypted = 'Y') THEN
7223        FOR core_rec IN c_trxn_core LOOP
7224          IF (core_rec.expiry_sec_segment_id IS NOT NULL) THEN
7225            l_exp_date := IBY_SECURITY_PKG.decrypt_date_field
7226 	                            (core_rec.expiry_sec_segment_id,
7227 				     p_sys_key
7228 				     );
7229 
7230          ELSE
7231            -- The exp date wasn't encrypted
7232            l_exp_date := core_rec.instr_expirydate;
7233          END IF;
7234 
7235          IF(core_rec.chname_sec_segment_id IS NOT NULL) THEN
7236            l_chname := IBY_SECURITY_PKG.decrypt_field_vals
7237 	                            (core_rec.chname_sec_segment_id,
7238 				     p_sys_key
7239 				     );
7240          ELSE
7241            -- CHNAME wasn't encrypted
7242            l_chname := core_rec.instr_owner_name;
7243          END IF;
7244 
7245         UPDATE iby_trxn_core SET
7246         encrypted = 'N',
7247         instr_owner_name = l_chname,
7248         chname_sec_segment_id = NULL,
7249         instr_expirydate = l_exp_date,
7250         expiry_sec_segment_id = NULL,
7251         object_version_number = object_version_number + 1,
7252         last_update_date = sysdate,
7253         last_updated_by = fnd_global.user_id,
7254         last_update_login = fnd_global.login_id
7255         WHERE (trxnmid = core_rec.trxnmid);
7256 
7257      END LOOP;
7258   --END IF;
7259 
7260   COMMIT;
7261 
7262   END Decrypt_CC_Data;
7263 
7264   PROCEDURE check_batch_size
7265         (
7266 	ecappid_in      IN      iby_trxn_summaries_all.ecappid%TYPE,
7267 	payeeid_in      IN      iby_trxn_summaries_all.payeeid%TYPE,
7268 	bepid_in        IN      iby_trxn_summaries_all.bepid%TYPE,
7269 	bepkey_in       IN      iby_trxn_summaries_all.bepkey%TYPE,
7270         orgid_in        IN      iby_batches_all.org_id%TYPE,
7271         seckey_present_in IN    VARCHAR2,
7272         trxncount_out   OUT NOCOPY NUMBER,
7273         batchid_out     OUT NOCOPY iby_batches_all.batchid%TYPE
7274         )
7275   IS
7276 
7277         l_max_batch_size iby_bepinfo.max_batch_size%TYPE;
7278         l_mbatch_id iby_batches_all.mbatchid%TYPE;
7279 
7280         CURSOR c_trxn_count
7281             (
7282             ci_ecappid iby_trxn_summaries_all.ecappid%TYPE,
7283             ci_payeeid iby_trxn_summaries_all.payeeid%TYPE,
7284             ci_bepid   iby_trxn_summaries_all.bepid%TYPE,
7285             ci_bepkey  iby_trxn_summaries_all.bepkey%TYPE
7286             ) IS
7287           SELECT count(transactionid)
7288           FROM iby_trxn_summaries_all
7289           WHERE (ci_bepid=bepid)
7290             AND (ci_payeeid=payeeid)
7291             AND (ci_bepkey=bepkey)
7292             --
7293             -- can have multiple trxns from a
7294             -- different ecapp's for a single payee account;
7295             -- don't bother until ecapp scoping is seriously
7296             -- supported by IBY
7297             --
7298             --AND (ci_ecappid=ecappid)
7299             AND (status=iby_transactioncc_pkg.C_STATUS_OPEN_BATCHED)
7300             AND (batchid IS NULL)
7301             AND (instrtype IN (iby_creditcard_pkg.C_INSTRTYPE_CCARD,
7302                            iby_creditcard_pkg.C_INSTRTYPE_PCARD)
7303                OR instrtype IS NULL);
7304 
7305         CURSOR c_max_bsize(ci_bepid iby_trxn_summaries_all.bepid%TYPE) IS
7306           SELECT NVL(max_batch_size,-1)
7307           FROM iby_bepinfo
7308           WHERE (ci_bepid=bepid);
7309 
7310   BEGIN
7311         IF (c_trxn_count%ISOPEN) THEN
7312           CLOSE c_trxn_count;
7313         END IF;
7314         IF (c_max_bsize%ISOPEN) THEN
7315           CLOSE c_max_bsize;
7316         END IF;
7317 
7318         OPEN c_max_bsize(bepid_in);
7319         FETCH c_max_bsize INTO l_max_batch_size;
7320 
7321         --
7322         -- nothing found; bep id must be bad
7323         --
7324         IF (c_max_bsize%NOTFOUND) THEN
7325            CLOSE c_max_bsize;
7326            raise_application_error(-20000, 'IBY_40201', FALSE);
7327         END IF;
7328 
7329         CLOSE c_max_bsize;
7330 
7331         OPEN c_trxn_count(ecappid_in,payeeid_in,bepid_in,bepkey_in);
7332         FETCH c_trxn_count INTO trxncount_out;
7333 
7334         IF (c_trxn_count%NOTFOUND) THEN
7335           trxncount_out := 0;
7336         END IF;
7337 
7338         CLOSE c_trxn_count;
7339 
7340         IF (l_max_batch_size>0) THEN
7341           IF (l_max_batch_size<=trxncount_out) THEN
7342             --
7343             -- lock required to ensure only 1 batch close occurs after
7344             -- the maximum size is surpassed among all competing concurrent
7345             -- threads; lock both tables (even though iby_batches_all
7346             -- is sufficient) so as to ensure no deadlock can happen
7347             -- later
7348             --
7349             --LOCK TABLE iby_batches_all, iby_trxn_summaries_all
7350               --IN EXCLUSIVE MODE;
7351 
7352             -- check batch size once more to ensure another thread has
7353             -- not closed it between the last check and possession of
7354             -- the table lock; necessary to prevent tiny batches of size
7355             -- 0, 1, etc. from being created
7356             --
7357             OPEN c_trxn_count(ecappid_in,payeeid_in,bepid_in,bepkey_in);
7358             FETCH c_trxn_count INTO trxncount_out;
7359 
7360             IF (c_trxn_count%NOTFOUND) THEN
7361               trxncount_out := 0;
7362             END IF;
7363 
7364             IF (l_max_batch_size>trxncount_out) THEN
7365               -- relinquish table locks
7366               ROLLBACK;
7367               RETURN;
7368             END IF;
7369 
7370             SELECT to_char(IBY_BATCHID_S.nextval)
7371             INTO batchid_out
7372             FROM dual;
7373             --
7374             -- define the batch; note that this method
7375             -- commits data, so no need for a commit
7376             -- statement to follow
7377             --
7378             iby_transactioncc_pkg.insert_batch_status
7379             (
7380             batchid_out,
7381             payeeid_in,
7382             bepid_in,
7383             bepkey_in,
7384             iby_creditcard_pkg.C_INSTRTYPE_CCARD,
7385             iby_transactioncc_pkg.C_STATUS_COMMUNICATION_ERROR,
7386             SYSDATE,
7387             '',
7388             '',
7389             trxncount_out,
7390             iby_transactioncc_pkg.C_STATUS_COMMUNICATION_ERROR,
7391             0,
7392             0,
7393             0,
7394             '',
7395             '',
7396             '',
7397             '',
7398             '',
7399             '',
7400             orgid_in,
7401             'ORAPMTCLOSEBATCH',
7402             seckey_present_in,
7403             l_mbatch_id
7404             );
7405 
7406           END IF;
7407         END IF;
7408 
7409         COMMIT;
7410 
7411   EXCEPTION
7412     --
7413     -- make sure to release the table lock
7414     --
7415     WHEN OTHERS THEN
7416       ROLLBACK;
7417       raise_application_error(SQLCODE, SQLERRM, FALSE);
7418   END check_batch_size;
7419 
7420 /*--------------------------------------------------------------------
7421  | NAME:
7422  |   Update_Payer_Notif_Batch
7423  |
7424  | PURPOSE:
7425  |     This procedure updates the payer_notification_required flag for
7426  |     all the transactions in a batch.
7427  |
7428  | PARAMETERS:
7429  |     IN
7430  |      p_debug_text - The debug message to be printed
7431  |
7432  |     OUT
7433  |
7434  |
7435  | RETURNS:
7436  |
7437  | NOTES:
7438  |
7439  *---------------------------------------------------------------------*/
7440  PROCEDURE Update_Payer_Notif_Batch(
7441      mbatchid_in  IN iby_batches_all.mbatchid%TYPE
7442  ) IS
7443 
7444     l_process_profile   iby_batches_all.process_profile_code%TYPE;
7445     l_payer_notif_flag  VARCHAR2(1);
7446     l_instrument_type   iby_batches_all.instrument_type%TYPE;
7447 
7448 
7449   CURSOR c_payer_notif_cc (c_user_profile iby_fndcpt_user_cc_pf_b.user_cc_profile_code%TYPE) IS
7450   SELECT DECODE(payer_notification_format, null, 'N', 'Y')
7451     FROM iby_fndcpt_user_cc_pf_b up, iby_fndcpt_sys_cc_pf_b sp
7452    WHERE up.sys_cc_profile_code = sp.sys_cc_profile_code
7453      AND up.user_cc_profile_code = c_user_profile;
7454 
7455   CURSOR c_payer_notif_dc (c_user_profile iby_fndcpt_user_dc_pf_b.user_dc_profile_code%TYPE) IS
7456   SELECT DECODE(payer_notification_format, null, 'N', 'Y')
7457     FROM iby_fndcpt_user_dc_pf_b up, iby_fndcpt_sys_dc_pf_b sp,
7458          iby_batches_all b
7459    WHERE up.sys_dc_profile_code = sp.sys_dc_profile_code
7460      AND up.user_dc_profile_code =c_user_profile;
7461 
7462   CURSOR c_payer_notif_eft (c_user_profile iby_fndcpt_user_eft_pf_b.user_eft_profile_code%TYPE) IS
7463   SELECT DECODE(payer_notification_format, null, 'N', 'Y')
7464     FROM iby_fndcpt_user_eft_pf_b up, iby_fndcpt_sys_eft_pf_b sp,
7465          iby_batches_all b
7466    WHERE up.sys_eft_profile_code = sp.sys_eft_profile_code
7467      AND up.user_eft_profile_code = c_user_profile;
7468 
7469   CURSOR c_instr_type(i_mbatchid iby_batches_all.mbatchid%TYPE) IS
7470   SELECT instrument_type, process_profile_code
7471     FROM iby_batches_all
7472    WHERE mbatchid = i_mbatchid;
7473 
7474  BEGIN
7475 
7476     IF (c_instr_type%ISOPEN) THEN CLOSE c_instr_type; END IF;
7477     IF (c_payer_notif_cc%ISOPEN) THEN CLOSE c_payer_notif_cc; END IF;
7478     IF (c_payer_notif_dc%ISOPEN) THEN CLOSE c_payer_notif_dc; END IF;
7479     IF (c_payer_notif_eft%ISOPEN) THEN CLOSE c_payer_notif_eft; END IF;
7480 
7481     OPEN c_instr_type(mbatchid_in);
7482     FETCH c_instr_type INTO l_instrument_type, l_process_profile;
7483     CLOSE c_instr_type;
7484 
7485     -- get the payer_notification depending on the instrument_type
7486     -- from the different FCPP
7487     IF l_instrument_type = 'DEBITCARD' THEN
7488       OPEN c_payer_notif_dc(l_process_profile);
7489       FETCH c_payer_notif_dc INTO l_payer_notif_flag;
7490       CLOSE c_payer_notif_dc;
7491 
7492     ELSIF l_instrument_type = 'BANKACCOUNT' THEN
7493       OPEN c_payer_notif_eft(l_process_profile);
7494       FETCH c_payer_notif_eft INTO l_payer_notif_flag;
7495       CLOSE c_payer_notif_eft;
7496 
7497     ELSE
7498       OPEN c_payer_notif_cc(l_process_profile);
7499       FETCH c_payer_notif_cc INTO l_payer_notif_flag;
7500       CLOSE c_payer_notif_cc;
7501 
7502     END IF;
7503 
7504     -- set the payer_notification_required flag to yes
7505     -- if the payer_notification_format is defined for the FCPP
7506     -- at batch and trxn level and if the batch is successfull.
7507     -- Only for settlement trxn
7508     UPDATE iby_batches_all
7509     SET
7510       last_update_date = sysdate,
7511       last_updated_by = fnd_global.user_id,
7512       object_version_number = object_version_number + 1,
7513       payer_notification_required = l_payer_notif_flag
7514     WHERE (mbatchid = mbatchid_in);
7515 
7516     -- the update will update only settlement trxn.
7517     -- authcapture, capture and markcapture
7518     UPDATE iby_trxn_summaries_all
7519        SET payer_notification_required = l_payer_notif_flag,
7520            last_update_date=sysdate,
7521            last_updated_by = fnd_global.user_id,
7522            object_version_number = object_version_number + 1
7523      WHERE mbatchid = mbatchid_in
7524        AND TrxntypeID IN (3,8,9,100);
7525 
7526  END Update_Payer_Notif_Batch;
7527 
7528  /*--------------------------------------------------------------------
7529  | NAME:
7530  |
7531  | PURPOSE:
7532  |     This procedure is used to free up the memory used by
7533  |     global memory structure
7534  |
7535  | PARAMETERS:
7536  |
7537  |     NONE
7538  |
7539  | RETURNS:
7540  |
7541  | NOTES:
7542  |
7543  *---------------------------------------------------------------------*/
7544  PROCEDURE delete_trxnTable IS
7545  l_module_name     CONSTANT VARCHAR2(200) := G_PKG_NAME ||
7546                                        '.delete_trxnTable';
7547  BEGIN
7548 
7549  print_debuginfo(l_module_name, 'ENTER');
7550  trxnTab.transactionid.delete;
7551  trxnTab.mbatchid.delete;
7552  trxnTab.batchid.delete;
7553  print_debuginfo(l_module_name, 'EXIT');
7554  END;
7555 
7556 END iby_transactioncc_pkg;