KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > ofbiz > accounting > thirdparty > valuelink > ValueLinkServices


1 /*
2  * $Id: ValueLinkServices.java 6148 2005-11-20 17:50:38Z jaz $
3  *
4  * Copyright (c) 2003 The Open For Business Project - www.ofbiz.org
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a
7  * copy of this software and associated documentation files (the "Software"),
8  * to deal in the Software without restriction, including without limitation
9  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
10  * and/or sell copies of the Software, and to permit persons to whom the
11  * Software is furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included
14  * in all copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
17  * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
19  * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
20  * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT
21  * OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR
22  * THE USE OR OTHER DEALINGS IN THE SOFTWARE.
23  *
24  */

25 package org.ofbiz.accounting.thirdparty.valuelink;
26
27 import java.util.HashMap JavaDoc;
28 import java.util.Iterator JavaDoc;
29 import java.util.List JavaDoc;
30 import java.util.Locale JavaDoc;
31 import java.util.Map JavaDoc;
32 import java.util.Properties JavaDoc;
33 import javax.transaction.xa.XAException JavaDoc;
34
35 import org.ofbiz.base.util.Debug;
36 import org.ofbiz.base.util.HttpClientException;
37 import org.ofbiz.base.util.StringUtil;
38 import org.ofbiz.base.util.UtilDateTime;
39 import org.ofbiz.base.util.UtilMisc;
40 import org.ofbiz.base.util.UtilProperties;
41 import org.ofbiz.base.util.UtilValidate;
42 import org.ofbiz.base.util.collections.ResourceBundleMapWrapper;
43 import org.ofbiz.entity.GenericDelegator;
44 import org.ofbiz.entity.GenericEntityException;
45 import org.ofbiz.entity.GenericValue;
46 import org.ofbiz.entity.util.EntityUtil;
47 import org.ofbiz.order.order.OrderReadHelper;
48 import org.ofbiz.product.store.ProductStoreWorker;
49 import org.ofbiz.service.DispatchContext;
50 import org.ofbiz.service.GenericServiceException;
51 import org.ofbiz.service.LocalDispatcher;
52 import org.ofbiz.service.ModelService;
53 import org.ofbiz.service.ServiceUtil;
54 import org.ofbiz.service.ServiceXaWrapper;
55
56 /**
57  * ValueLinkServices - Integration with ValueLink Gift Cards
58  *
59  * @author <a HREF="mailto:jaz@ofbiz.org">Andy Zeneski</a>
60  * @version $Rev: 6148 $
61  * @since 3.0
62  */

63 public class ValueLinkServices {
64
65     public static final String JavaDoc module = ValueLinkServices.class.getName();
66
67     // generate/display new public/private/kek keys
68
public static Map JavaDoc createKeys(DispatchContext dctx, Map JavaDoc context) {
69         GenericDelegator delegator = dctx.getDelegator();
70         Properties JavaDoc props = getProperties(context);
71         ValueLinkApi vl = ValueLinkApi.getInstance(delegator, props);
72         vl.reload();
73
74         Boolean JavaDoc kekOnly = context.get("kekOnly") != null ? (Boolean JavaDoc) context.get("kekOnly") : new Boolean JavaDoc(false);
75         String JavaDoc kekTest = (String JavaDoc) context.get("kekTest");
76         Debug.log("KEK Only : " + kekOnly.booleanValue(), module);
77
78         StringBuffer JavaDoc buf = vl.outputKeyCreation(kekOnly.booleanValue(), kekTest);
79         String JavaDoc output = buf.toString();
80         Debug.log(":: Key Generation Output ::\n\n" + output, module);
81
82         Map JavaDoc result = ServiceUtil.returnSuccess();
83         result.put("output", output);
84         return result;
85     }
86
87     // test the KEK encryption
88
public static Map JavaDoc testKekEncryption(DispatchContext dctx, Map JavaDoc context) {
89         GenericDelegator delegator = dctx.getDelegator();
90         //GenericValue userLogin = (GenericValue) context.get("userLogin");
91
Properties JavaDoc props = getProperties(context);
92
93         // get an api instance
94
ValueLinkApi vl = ValueLinkApi.getInstance(delegator, props);
95         vl.reload();
96
97         String JavaDoc testString = (String JavaDoc) context.get("kekTest");
98         Integer JavaDoc mode = (Integer JavaDoc) context.get("mode");
99         byte[] testBytes = StringUtil.fromHexString(testString);
100
101         // place holder
102
byte[] testEncryption = new byte[0];
103         String JavaDoc desc = "";
104
105         if (mode.intValue() == 1) {
106             // encrypt the test bytes
107
testEncryption = vl.encryptViaKek(testBytes);
108             desc = "Encrypted";
109         } else {
110             // decrypt the test bytes
111
testEncryption = vl.decryptViaKek(testBytes);
112             desc = "Decrypted";
113         }
114
115         // setup the output
116
StringBuffer JavaDoc buf = new StringBuffer JavaDoc();
117         buf.append("======== Begin Test String (" + testString.length() + ") ========\n");
118         buf.append(testString + "\n");
119         buf.append("======== End Test String ========\n\n");
120
121         buf.append("======== Begin Test Bytes (" + testBytes.length + ") ========\n");
122         buf.append(StringUtil.toHexString(testBytes) + "\n");
123         buf.append("======== End Test Bytes ========\n\n");
124
125         buf.append("======== Begin Test Bytes " + desc + " (" + testEncryption.length + ") ========\n");
126         buf.append(StringUtil.toHexString(testEncryption) + "\n");
127         buf.append("======== End Test Bytes " + desc + " ========\n\n");
128
129         String JavaDoc output = buf.toString();
130         Debug.log(":: KEK Test Output ::\n\n" + output, module);
131
132         Map JavaDoc result = ServiceUtil.returnSuccess();
133         result.put("output", output);
134         return result;
135     }
136
137     // change working key service
138
public static Map JavaDoc assignWorkingKey(DispatchContext dctx, Map JavaDoc context) {
139         GenericDelegator delegator = dctx.getDelegator();
140         GenericValue userLogin = (GenericValue) context.get("userLogin");
141         Properties JavaDoc props = getProperties(context);
142
143         // get an api instance
144
ValueLinkApi vl = ValueLinkApi.getInstance(delegator, props);
145         vl.reload();
146
147         // place holder
148
byte[] mwk = null;
149
150         // see if we passed in the DES hex string
151
String JavaDoc desHexString = (String JavaDoc) context.get("desHexString");
152         if (desHexString == null || desHexString.length() == 0) {
153             mwk = vl.generateMwk();
154         } else {
155             mwk = vl.generateMwk(StringUtil.fromHexString(desHexString));
156         }
157
158         // encrypt the mwk
159
String JavaDoc mwkHex = StringUtil.toHexString(vl.encryptViaKek(mwk));
160
161         // build the request
162
Map JavaDoc request = vl.getInitialRequestMap(context);
163         request.put("Interface", "Encrypt");
164         request.put("EncryptKey", mwkHex);
165         request.put("EncryptID", new Long JavaDoc(vl.getWorkingKeyIndex().longValue() + 1));
166
167         // send the request
168
Map JavaDoc response = null;
169         try {
170             response = vl.send(request);
171         } catch(HttpClientException e) {
172             Debug.logError(e, "Problem communicating with VL");
173             return ServiceUtil.returnError("Unable to update MWK");
174         }
175         Debug.log("Response : " + response, module);
176
177         // on success update the database / reload the cached api
178
if (response != null) {
179             String JavaDoc responseCode = (String JavaDoc) response.get("responsecode");
180             if (responseCode.equals("00")) {
181                 GenericValue vlKeys = GenericValue.create(vl.getGenericValue());
182                 vlKeys.set("lastWorkingKey", vlKeys.get("workingKey"));
183                 vlKeys.set("workingKey", StringUtil.toHexString(mwk));
184                 vlKeys.set("workingKeyIndex", request.get("EncryptID"));
185                 vlKeys.set("lastModifiedDate", UtilDateTime.nowTimestamp());
186                 vlKeys.set("lastModifiedByUserLogin", userLogin != null ? userLogin.get("userLoginId") : null);
187                 try {
188                     vlKeys.store();
189                 } catch (GenericEntityException e) {
190                     Debug.logError(e, "Unable to store updated keys; the keys were changed with ValueLink : " + vlKeys, module);
191                     return ServiceUtil.returnError("Unable to store updated keys");
192                 }
193                 vl.reload();
194                 return ServiceUtil.returnSuccess();
195             } else {
196                 return ServiceUtil.returnError("Transaction failed with response code : " + responseCode);
197             }
198         } else {
199             return ServiceUtil.returnError("Recevied back an empty response");
200         }
201     }
202
203     public static Map JavaDoc activate(DispatchContext dctx, Map JavaDoc context) {
204         GenericDelegator delegator = dctx.getDelegator();
205         Properties JavaDoc props = getProperties(context);
206         String JavaDoc vlPromoCode = (String JavaDoc) context.get("vlPromoCode");
207         String JavaDoc cardNumber = (String JavaDoc) context.get("cardNumber");
208         String JavaDoc pin = (String JavaDoc) context.get("pin");
209         String JavaDoc currency = (String JavaDoc) context.get("currency");
210         String JavaDoc orderId = (String JavaDoc) context.get("orderId");
211         String JavaDoc partyId = (String JavaDoc) context.get("partyId");
212         Double JavaDoc amount = (Double JavaDoc) context.get("amount");
213
214         // override interface for void/rollback
215
String JavaDoc iFace = (String JavaDoc) context.get("Interface");
216
217         // get an api instance
218
ValueLinkApi vl = ValueLinkApi.getInstance(delegator, props);
219         Map JavaDoc request = vl.getInitialRequestMap(context);
220         request.put("Interface", iFace != null ? iFace : "Activate");
221         if (vlPromoCode != null && vlPromoCode.length() > 0) {
222             request.put("PromoCode", vlPromoCode);
223         }
224         request.put("Amount", vl.getAmount(amount));
225         request.put("LocalCurr", vl.getCurrency(currency));
226
227         if (cardNumber != null && cardNumber.length() > 0) {
228             request.put("CardNo", cardNumber);
229         }
230         if (pin != null && pin.length() > 0) {
231             request.put("PIN", vl.encryptPin(pin));
232         }
233
234         // user defined field #1
235
if (orderId != null && orderId.length() > 0) {
236             request.put("User1", orderId);
237         }
238
239         // user defined field #2
240
if (partyId != null && partyId.length() > 0) {
241             request.put("User2", partyId);
242         }
243
244         // set the timeout reversal
245
setTimeoutReversal(dctx, context, request);
246
247         // send the request
248
Map JavaDoc response = null;
249         try {
250             response = vl.send(request);
251         } catch(HttpClientException e) {
252             Debug.logError(e, "Problem communicating with VL");
253             return ServiceUtil.returnError("Unable to activate gift card");
254         }
255
256         if (response != null) {
257             String JavaDoc responseCode = (String JavaDoc) response.get("responsecode");
258             Map JavaDoc result = ServiceUtil.returnSuccess();
259             if (responseCode.equals("00")) {
260                 result.put("processResult", new Boolean JavaDoc(true));
261                 result.put("pin", vl.decryptPin((String JavaDoc) response.get("pin")));
262             } else {
263                 result.put("processResult", new Boolean JavaDoc(false));
264                 result.put("pin", response.get("PIN"));
265             }
266             result.put("responseCode", responseCode);
267             result.put("authCode", response.get("authcode"));
268             result.put("cardNumber", response.get("cardno"));
269             result.put("amount", vl.getAmount((String JavaDoc) response.get("currbal")));
270             result.put("expireDate", response.get("expiredate"));
271             result.put("cardClass", response.get("cardclass"));
272             result.put("referenceNum", response.get("traceno"));
273             Debug.log("Activate Result : " + result, module);
274             return result;
275         } else {
276             return ServiceUtil.returnError("Empty response returned from ValueLink");
277         }
278     }
279
280     public static Map JavaDoc linkPhysicalCard(DispatchContext dctx, Map JavaDoc context) {
281         GenericDelegator delegator = dctx.getDelegator();
282         Properties JavaDoc props = getProperties(context);
283         String JavaDoc virtualCard = (String JavaDoc) context.get("virtualCard");
284         String JavaDoc virtualPin = (String JavaDoc) context.get("virtualPin");
285         String JavaDoc physicalCard = (String JavaDoc) context.get("physicalCard");
286         String JavaDoc physicalPin = (String JavaDoc) context.get("physicalPin");
287         String JavaDoc partyId = (String JavaDoc) context.get("partyId");
288
289         // get an api instance
290
ValueLinkApi vl = ValueLinkApi.getInstance(delegator, props);
291         Map JavaDoc request = vl.getInitialRequestMap(context);
292         request.put("Interface", "Link");
293         request.put("VCardNo", virtualCard);
294         request.put("VPIN", vl.encryptPin(virtualPin));
295         request.put("PCardNo", physicalCard);
296         request.put("PPIN", vl.encryptPin(physicalPin));
297
298         // user defined field #2
299
if (partyId != null && partyId.length() > 0) {
300             request.put("User2", partyId);
301         }
302
303         // send the request
304
Map JavaDoc response = null;
305         try {
306             response = vl.send(request);
307         } catch(HttpClientException e) {
308             Debug.logError(e, "Problem communicating with VL");
309             return ServiceUtil.returnError("Unable to link gift card(s)");
310         }
311
312         if (response != null) {
313             String JavaDoc responseCode = (String JavaDoc) response.get("responsecode");
314             Map JavaDoc result = ServiceUtil.returnSuccess("Activation of physical card complete.");
315             if (responseCode.equals("00")) {
316
317                 result.put("processResult", new Boolean JavaDoc(true));
318             } else {
319                 result.put("processResult", new Boolean JavaDoc(false));
320             }
321             result.put("responseCode", responseCode);
322             result.put("authCode", response.get("authcode"));
323             result.put("amount", vl.getAmount((String JavaDoc) response.get("newbal")));
324             result.put("expireDate", response.get("expiredate"));
325             result.put("cardClass", response.get("cardclass"));
326             result.put("referenceNum", response.get("traceno"));
327             Debug.log("Link Result : " + result, module);
328             return result;
329         } else {
330             return ServiceUtil.returnError("Empty response returned from ValueLink");
331         }
332     }
333
334     public static Map JavaDoc disablePin(DispatchContext dctx, Map JavaDoc context) {
335         GenericDelegator delegator = dctx.getDelegator();
336         Properties JavaDoc props = getProperties(context);
337         String JavaDoc cardNumber = (String JavaDoc) context.get("cardNumber");
338         String JavaDoc pin = (String JavaDoc) context.get("pin");
339         String JavaDoc orderId = (String JavaDoc) context.get("orderId");
340         String JavaDoc partyId = (String JavaDoc) context.get("partyId");
341         Double JavaDoc amount = (Double JavaDoc) context.get("amount");
342
343         // get an api instance
344
ValueLinkApi vl = ValueLinkApi.getInstance(delegator, props);
345         Map JavaDoc request = vl.getInitialRequestMap(context);
346         request.put("Interface", "Disable");
347         request.put("CardNo", cardNumber);
348         request.put("PIN", vl.encryptPin(pin));
349         request.put("Amount", vl.getAmount(amount));
350
351         // user defined field #1
352
if (orderId != null && orderId.length() > 0) {
353             request.put("User1", orderId);
354         }
355
356         // user defined field #2
357
if (partyId != null && partyId.length() > 0) {
358             request.put("User2", partyId);
359         }
360
361         // send the request
362
Map JavaDoc response = null;
363         try {
364             response = vl.send(request);
365         } catch(HttpClientException e) {
366             Debug.logError(e, "Problem communicating with VL");
367             return ServiceUtil.returnError("Unable to call disble pin");
368         }
369
370         if (response != null) {
371             String JavaDoc responseCode = (String JavaDoc) response.get("responsecode");
372             Map JavaDoc result = ServiceUtil.returnSuccess("PIN disabled.");
373             if (responseCode.equals("00")) {
374                 result.put("processResult", new Boolean JavaDoc(true));
375             } else {
376                 result.put("processResult", new Boolean JavaDoc(false));
377             }
378             result.put("responseCode", responseCode);
379             result.put("balance", vl.getAmount((String JavaDoc) response.get("currbal")));
380             result.put("expireDate", response.get("expiredate"));
381             result.put("cardClass", response.get("cardclass"));
382             result.put("referenceNum", response.get("traceno"));
383             Debug.log("Disable Result : " + result, module);
384             return result;
385         } else {
386             return ServiceUtil.returnError("Empty response returned from ValueLink");
387         }
388     }
389
390     public static Map JavaDoc redeem(DispatchContext dctx, Map JavaDoc context) {
391         GenericDelegator delegator = dctx.getDelegator();
392         Properties JavaDoc props = getProperties(context);
393         String JavaDoc cardNumber = (String JavaDoc) context.get("cardNumber");
394         String JavaDoc pin = (String JavaDoc) context.get("pin");
395         String JavaDoc currency = (String JavaDoc) context.get("currency");
396         String JavaDoc orderId = (String JavaDoc) context.get("orderId");
397         String JavaDoc partyId = (String JavaDoc) context.get("partyId");
398         Double JavaDoc amount = (Double JavaDoc) context.get("amount");
399
400         // override interface for void/rollback
401
String JavaDoc iFace = (String JavaDoc) context.get("Interface");
402
403         // get an api instance
404
ValueLinkApi vl = ValueLinkApi.getInstance(delegator, props);
405         Map JavaDoc request = vl.getInitialRequestMap(context);
406         request.put("Interface", iFace != null ? iFace : "Redeem");
407         request.put("CardNo", cardNumber);
408         request.put("PIN", vl.encryptPin(pin));
409         request.put("Amount", vl.getAmount(amount));
410         request.put("LocalCurr", vl.getCurrency(currency));
411
412         // user defined field #1
413
if (orderId != null && orderId.length() > 0) {
414             request.put("User1", orderId);
415         }
416
417         // user defined field #2
418
if (partyId != null && partyId.length() > 0) {
419             request.put("User2", partyId);
420         }
421
422         // set the timeout reversal
423
setTimeoutReversal(dctx, context, request);
424
425         // send the request
426
Map JavaDoc response = null;
427         try {
428             response = vl.send(request);
429         } catch(HttpClientException e) {
430             Debug.logError(e, "Problem communicating with VL");
431             return ServiceUtil.returnError("Unable to redeem gift card");
432         }
433
434         if (response != null) {
435             String JavaDoc responseCode = (String JavaDoc) response.get("responsecode");
436             Map JavaDoc result = ServiceUtil.returnSuccess();
437             if (responseCode.equals("00")) {
438                 result.put("processResult", new Boolean JavaDoc(true));
439             } else {
440                 result.put("processResult", new Boolean JavaDoc(false));
441             }
442             result.put("responseCode", responseCode);
443             result.put("authCode", response.get("authcode"));
444             result.put("previousAmount", vl.getAmount((String JavaDoc) response.get("prevbal")));
445             result.put("amount", vl.getAmount((String JavaDoc) response.get("newbal")));
446             result.put("expireDate", response.get("expiredate"));
447             result.put("cardClass", response.get("cardclass"));
448             result.put("cashBack", vl.getAmount((String JavaDoc) response.get("cashback")));
449             result.put("referenceNum", response.get("traceno"));
450             Debug.log("Redeem Result : " + result, module);
451             return result;
452         } else {
453             return ServiceUtil.returnError("Empty response returned from ValueLink");
454         }
455     }
456
457     public static Map JavaDoc reload(DispatchContext dctx, Map JavaDoc context) {
458         GenericDelegator delegator = dctx.getDelegator();
459         Properties JavaDoc props = getProperties(context);
460         String JavaDoc cardNumber = (String JavaDoc) context.get("cardNumber");
461         String JavaDoc pin = (String JavaDoc) context.get("pin");
462         String JavaDoc currency = (String JavaDoc) context.get("currency");
463         String JavaDoc orderId = (String JavaDoc) context.get("orderId");
464         String JavaDoc partyId = (String JavaDoc) context.get("partyId");
465         Double JavaDoc amount = (Double JavaDoc) context.get("amount");
466
467         // override interface for void/rollback
468
String JavaDoc iFace = (String JavaDoc) context.get("Interface");
469
470         // get an api instance
471
ValueLinkApi vl = ValueLinkApi.getInstance(delegator, props);
472         Map JavaDoc request = vl.getInitialRequestMap(context);
473         request.put("Interface", iFace != null ? iFace : "Reload");
474         request.put("CardNo", cardNumber);
475         request.put("PIN", vl.encryptPin(pin));
476         request.put("Amount", vl.getAmount(amount));
477         request.put("LocalCurr", vl.getCurrency(currency));
478
479         // user defined field #1
480
if (orderId != null && orderId.length() > 0) {
481             request.put("User1", orderId);
482         }
483
484         // user defined field #2
485
if (partyId != null && partyId.length() > 0) {
486             request.put("User2", partyId);
487         }
488
489         // set the timeout reversal
490
setTimeoutReversal(dctx, context, request);
491
492         // send the request
493
Map JavaDoc response = null;
494         try {
495             response = vl.send(request);
496         } catch(HttpClientException e) {
497             Debug.logError(e, "Problem communicating with VL");
498             return ServiceUtil.returnError("Unable to reload gift card");
499         }
500
501         if (response != null) {
502             String JavaDoc responseCode = (String JavaDoc) response.get("responsecode");
503             Map JavaDoc result = ServiceUtil.returnSuccess();
504             if (responseCode.equals("00")) {
505                 result.put("processResult", new Boolean JavaDoc(true));
506             } else {
507                 result.put("processResult", new Boolean JavaDoc(false));
508             }
509             result.put("responseCode", responseCode);
510             result.put("authCode", response.get("authcode"));
511             result.put("previousAmount", vl.getAmount((String JavaDoc) response.get("prevbal")));
512             result.put("amount", vl.getAmount((String JavaDoc) response.get("newbal")));
513             result.put("expireDate", response.get("expiredate"));
514             result.put("cardClass", response.get("cardclass"));
515             result.put("referenceNum", response.get("traceno"));
516             Debug.log("Reload Result : " + result, module);
517             return result;
518         } else {
519             return ServiceUtil.returnError("Empty response returned from ValueLink");
520         }
521     }
522
523     public static Map JavaDoc balanceInquire(DispatchContext dctx, Map JavaDoc context) {
524         GenericDelegator delegator = dctx.getDelegator();
525         Properties JavaDoc props = getProperties(context);
526         String JavaDoc cardNumber = (String JavaDoc) context.get("cardNumber");
527         String JavaDoc pin = (String JavaDoc) context.get("pin");
528         String JavaDoc currency = (String JavaDoc) context.get("currency");
529         String JavaDoc orderId = (String JavaDoc) context.get("orderId");
530         String JavaDoc partyId = (String JavaDoc) context.get("partyId");
531
532         // get an api instance
533
ValueLinkApi vl = ValueLinkApi.getInstance(delegator, props);
534         Map JavaDoc request = vl.getInitialRequestMap(context);
535         request.put("Interface", "Balance");
536         request.put("CardNo", cardNumber);
537         request.put("PIN", vl.encryptPin(pin));
538         request.put("LocalCurr", vl.getCurrency(currency));
539
540         // user defined field #1
541
if (orderId != null && orderId.length() > 0) {
542             request.put("User1", orderId);
543         }
544
545         // user defined field #2
546
if (partyId != null && partyId.length() > 0) {
547             request.put("User2", partyId);
548         }
549
550         // send the request
551
Map JavaDoc response = null;
552         try {
553             response = vl.send(request);
554         } catch(HttpClientException e) {
555             Debug.logError(e, "Problem communicating with VL");
556             return ServiceUtil.returnError("Unable to call balance inquire");
557         }
558
559         if (response != null) {
560             String JavaDoc responseCode = (String JavaDoc) response.get("responsecode");
561             Map JavaDoc result = ServiceUtil.returnSuccess();
562             if (responseCode.equals("00")) {
563                 result.put("processResult", new Boolean JavaDoc(true));
564             } else {
565                 result.put("processResult", new Boolean JavaDoc(false));
566             }
567             result.put("responseCode", responseCode);
568             result.put("balance", vl.getAmount((String JavaDoc) response.get("currbal")));
569             result.put("expireDate", response.get("expiredate"));
570             result.put("cardClass", response.get("cardclass"));
571             result.put("referenceNum", response.get("traceno"));
572             Debug.log("Balance Result : " + result, module);
573             return result;
574         } else {
575             return ServiceUtil.returnError("Empty response returned from ValueLink");
576         }
577     }
578
579     public static Map JavaDoc transactionHistory(DispatchContext dctx, Map JavaDoc context) {
580         GenericDelegator delegator = dctx.getDelegator();
581         Properties JavaDoc props = getProperties(context);
582         String JavaDoc cardNumber = (String JavaDoc) context.get("cardNumber");
583         String JavaDoc pin = (String JavaDoc) context.get("pin");
584         String JavaDoc orderId = (String JavaDoc) context.get("orderId");
585         String JavaDoc partyId = (String JavaDoc) context.get("partyId");
586
587         // get an api instance
588
ValueLinkApi vl = ValueLinkApi.getInstance(delegator, props);
589         Map JavaDoc request = vl.getInitialRequestMap(context);
590         request.put("Interface", "History");
591         request.put("CardNo", cardNumber);
592         request.put("PIN", vl.encryptPin(pin));
593
594         // user defined field #1
595
if (orderId != null && orderId.length() > 0) {
596             request.put("User1", orderId);
597         }
598
599         // user defined field #2
600
if (partyId != null && partyId.length() > 0) {
601             request.put("User2", partyId);
602         }
603
604         // send the request
605
Map JavaDoc response = null;
606         try {
607             response = vl.send(request);
608         } catch(HttpClientException e) {
609             Debug.logError(e, "Problem communicating with VL");
610             return ServiceUtil.returnError("Unable to call history inquire");
611         }
612
613         if (response != null) {
614             String JavaDoc responseCode = (String JavaDoc) response.get("responsecode");
615             Map JavaDoc result = ServiceUtil.returnSuccess();
616             if (responseCode.equals("00")) {
617                 result.put("processResult", new Boolean JavaDoc(true));
618             } else {
619                 result.put("processResult", new Boolean JavaDoc(false));
620             }
621             result.put("responseCode", responseCode);
622             result.put("balance", vl.getAmount((String JavaDoc) response.get("currbal")));
623             result.put("history", response.get("history"));
624             result.put("expireDate", response.get("expiredate"));
625             result.put("cardClass", response.get("cardclass"));
626             result.put("referenceNum", response.get("traceno"));
627             Debug.log("History Result : " + result, module);
628             return result;
629         } else {
630             return ServiceUtil.returnError("Empty response returned from ValueLink");
631         }
632     }
633
634     public static Map JavaDoc refund(DispatchContext dctx, Map JavaDoc context) {
635         GenericDelegator delegator = dctx.getDelegator();
636         Properties JavaDoc props = getProperties(context);
637         String JavaDoc cardNumber = (String JavaDoc) context.get("cardNumber");
638         String JavaDoc pin = (String JavaDoc) context.get("pin");
639         String JavaDoc currency = (String JavaDoc) context.get("currency");
640         String JavaDoc orderId = (String JavaDoc) context.get("orderId");
641         String JavaDoc partyId = (String JavaDoc) context.get("partyId");
642         Double JavaDoc amount = (Double JavaDoc) context.get("amount");
643
644         // override interface for void/rollback
645
String JavaDoc iFace = (String JavaDoc) context.get("Interface");
646
647         // get an api instance
648
ValueLinkApi vl = ValueLinkApi.getInstance(delegator, props);
649         Map JavaDoc request = vl.getInitialRequestMap(context);
650         request.put("Interface", iFace != null ? iFace : "Refund");
651         request.put("CardNo", cardNumber);
652         request.put("PIN", vl.encryptPin(pin));
653         request.put("Amount", vl.getAmount(amount));
654         request.put("LocalCurr", vl.getCurrency(currency));
655
656         // user defined field #1
657
if (orderId != null && orderId.length() > 0) {
658             request.put("User1", orderId);
659         }
660
661         // user defined field #2
662
if (partyId != null && partyId.length() > 0) {
663             request.put("User2", partyId);
664         }
665
666         // set the timeout reversal
667
setTimeoutReversal(dctx, context, request);
668
669         // send the request
670
Map JavaDoc response = null;
671         try {
672             response = vl.send(request);
673         } catch(HttpClientException e) {
674             Debug.logError(e, "Problem communicating with VL");
675             return ServiceUtil.returnError("Unable to refund gift card");
676         }
677
678         if (response != null) {
679             String JavaDoc responseCode = (String JavaDoc) response.get("responsecode");
680             Map JavaDoc result = ServiceUtil.returnSuccess();
681             if (responseCode.equals("00")) {
682                 result.put("processResult", new Boolean JavaDoc(true));
683             } else {
684                 result.put("processResult", new Boolean JavaDoc(false));
685             }
686             result.put("responseCode", responseCode);
687             result.put("authCode", response.get("authcode"));
688             result.put("previousAmount", vl.getAmount((String JavaDoc) response.get("prevbal")));
689             result.put("amount", vl.getAmount((String JavaDoc) response.get("newbal")));
690             result.put("expireDate", response.get("expiredate"));
691             result.put("cardClass", response.get("cardclass"));
692             result.put("referenceNum", response.get("traceno"));
693             Debug.log("Refund Result : " + result, module);
694             return result;
695         } else {
696             return ServiceUtil.returnError("Empty response returned from ValueLink");
697         }
698     }
699
700     public static Map JavaDoc voidRedeem(DispatchContext dctx, Map JavaDoc context) {
701         context.put("Interface", "Redeem/Void");
702         return redeem(dctx, context);
703     }
704
705     public static Map JavaDoc voidRefund(DispatchContext dctx, Map JavaDoc context) {
706         context.put("Interface", "Refund/Void");
707         return refund(dctx, context);
708     }
709
710     public static Map JavaDoc voidReload(DispatchContext dctx, Map JavaDoc context) {
711         context.put("Interface", "Reload/Void");
712         return reload(dctx, context);
713     }
714
715     public static Map JavaDoc voidActivate(DispatchContext dctx, Map JavaDoc context) {
716         context.put("Interface", "Activate/Void");
717         return activate(dctx, context);
718     }
719
720     public static Map JavaDoc timeOutReversal(DispatchContext dctx, Map JavaDoc context) {
721         String JavaDoc vlInterface = (String JavaDoc) context.get("Interface");
722         Debug.log("704 Interface : " + vlInterface, module);
723         if (vlInterface != null) {
724             if (vlInterface.startsWith("Activate")) {
725                 if (vlInterface.equals("Activate/Rollback")) {
726                     return ServiceUtil.returnError("This transaction is not supported by ValueLink");
727                 }
728                 return activate(dctx, context);
729             } else if (vlInterface.startsWith("Redeem")) {
730                 return redeem(dctx, context);
731             } else if (vlInterface.startsWith("Reload")) {
732                 return reload(dctx, context);
733             } else if (vlInterface.startsWith("Refund")) {
734                 return refund(dctx, context);
735             }
736         }
737
738         return ServiceUtil.returnError("Not a valid 0704 transaction");
739     }
740
741     // 0704 Timeout Reversal (Supports - Activate/Void, Redeem, Redeem/Void, Reload, Reload/Void, Refund, Refund/Void)
742
private static void setTimeoutReversal(DispatchContext dctx, Map JavaDoc ctx, Map JavaDoc request) {
743         String JavaDoc vlInterface = (String JavaDoc) request.get("Interface");
744         // clone the context
745
Map JavaDoc context = new HashMap JavaDoc(ctx);
746
747         // append the rollback interface
748
if (!vlInterface.endsWith("Rollback")) {
749             context.put("Interface", vlInterface + "/Rollback");
750         } else {
751             // no need to re-run ourself we are persisted
752
return;
753         }
754
755         // set the old tx time and number
756
context.put("MerchTime", request.get("MerchTime"));
757         context.put("TermTxnNo", request.get("TermTxnNo"));
758
759         // Activate/Rollback is not supported by valuelink
760
if (!vlInterface.equals("Activate")) {
761             // create the listener
762
ServiceXaWrapper xaw = new ServiceXaWrapper(dctx);
763             xaw.setRollbackService("vlTimeOutReversal", context);
764             //xaw.setCommitService("vlTimeOutReversal", context);
765
Debug.log("Set 704 context : " + context, module);
766             try {
767                 xaw.enlist();
768             } catch (XAException JavaDoc e) {
769                 Debug.logError(e, "Unable to setup 0704 Timeout Reversal", module);
770             }
771         }
772     }
773
774     private static Properties JavaDoc getProperties(Map JavaDoc context) {
775         String JavaDoc paymentProperties = (String JavaDoc) context.get("paymentConfig");
776         if (paymentProperties == null) {
777             paymentProperties = "payment.properties";
778         }
779         return UtilProperties.getProperties(paymentProperties);
780     }
781
782
783     // payment processing wrappers (process/release/refund)
784

785     public static Map JavaDoc giftCardProcessor(DispatchContext dctx, Map JavaDoc context) {
786         LocalDispatcher dispatcher = dctx.getDispatcher();
787         GenericValue userLogin = (GenericValue) context.get("userLogin");
788
789         GenericValue giftCard = (GenericValue) context.get("giftCard");
790         GenericValue party = (GenericValue) context.get("billToParty");
791         String JavaDoc paymentConfig = (String JavaDoc) context.get("paymentConfig");
792         String JavaDoc currency = (String JavaDoc) context.get("currency");
793         String JavaDoc orderId = (String JavaDoc) context.get("orderId");
794         Double JavaDoc amount = (Double JavaDoc) context.get("processAmount");
795
796         // make sure we have a currency
797
if (currency == null) {
798             currency = UtilProperties.getPropertyValue("general.properties", "currency.uom.id.default", "USD");
799         }
800
801         Map JavaDoc redeemCtx = new HashMap JavaDoc();
802         redeemCtx.put("userLogin", userLogin);
803         redeemCtx.put("paymentConfig", paymentConfig);
804         redeemCtx.put("cardNumber", giftCard.get("cardNumber"));
805         redeemCtx.put("pin", giftCard.get("pinNumber"));
806         redeemCtx.put("currency", currency);
807         redeemCtx.put("orderId", orderId);
808         redeemCtx.put("partyId", party.get("partyId"));
809         redeemCtx.put("amount", amount);
810
811         // invoke the redeem service
812
Map JavaDoc redeemResult = null;
813         try {
814             redeemResult = dispatcher.runSync("redeemGiftCard", redeemCtx);
815         } catch (GenericServiceException e) {
816             Debug.logError(e, "Problem calling the redeem service", module);
817             return ServiceUtil.returnError("Redeem service failed");
818         }
819
820         Map JavaDoc result = ServiceUtil.returnSuccess();
821         if (redeemResult != null) {
822             Boolean JavaDoc processResult = (Boolean JavaDoc) redeemResult.get("processResult");
823             // confirm the amount redeemed; since VL does not error in insufficient funds
824
if (processResult.booleanValue()) {
825                 Double JavaDoc previous = (Double JavaDoc) redeemResult.get("previousAmount");
826                 if (previous == null) previous = new Double JavaDoc(0);
827                 Double JavaDoc current = (Double JavaDoc) redeemResult.get("amount");
828                 if (current == null) current = new Double JavaDoc(0);
829                 double redeemed = (((double) Math.round((previous.doubleValue() - current.doubleValue()) * 100)) / 100);
830                 Debug.logInfo("Redeemed (" + amount + "): " + redeemed + " / " + previous + " : " + current, module);
831                 if (redeemed < amount.doubleValue()) {
832                     // we didn't redeem enough void the transaction and return false
833
Map JavaDoc voidResult = null;
834                     try {
835                         voidResult = dispatcher.runSync("voidRedeemGiftCard", redeemCtx);
836                     } catch (GenericServiceException e) {
837                         Debug.logError(e, module);
838                     }
839                     if (ServiceUtil.isError(voidResult)) {
840                         return voidResult;
841                     }
842                     processResult = new Boolean JavaDoc(false);
843                     amount = new Double JavaDoc(redeemed);
844                     result.put("authMessage", "Gift card did not contain enough funds");
845                 }
846             }
847             result.put("processAmount", amount);
848             result.put("authFlag", redeemResult.get("responseCode"));
849             result.put("authResult", processResult);
850             result.put("captureResult", processResult);
851             result.put("authCode", redeemResult.get("authCode"));
852             result.put("captureCode", redeemResult.get("authCode"));
853             result.put("authRefNum", redeemResult.get("referenceNum"));
854             result.put("captureRefNum", redeemResult.get("referenceNum"));
855         }
856
857         return result;
858     }
859
860     public static Map JavaDoc giftCardRelease(DispatchContext dctx, Map JavaDoc context) {
861         LocalDispatcher dispatcher = dctx.getDispatcher();
862         GenericValue userLogin = (GenericValue) context.get("userLogin");
863
864         GenericValue paymentPref = (GenericValue) context.get("orderPaymentPreference");
865         String JavaDoc paymentConfig = (String JavaDoc) context.get("paymentConfig");
866         String JavaDoc currency = (String JavaDoc) context.get("currency");
867         Double JavaDoc amount = (Double JavaDoc) context.get("releaseAmount");
868
869         // get the orderId for tracking
870
String JavaDoc orderId = paymentPref.getString("orderId");
871
872         // get the GiftCard VO
873
GenericValue giftCard = null;
874         try {
875             giftCard = paymentPref.getRelatedOne("GiftCard");
876         } catch (GenericEntityException e) {
877             Debug.logError("Unable to get GiftCard from OrderPaymentPreference", module);
878             return ServiceUtil.returnError("Unable to locate GiftCard Information");
879         }
880
881         if (giftCard == null) {
882             return ServiceUtil.returnError("Attempt to release GiftCard payment faild; not a valid GiftCard record");
883         }
884
885         // make sure we have a currency
886
if (currency == null) {
887             currency = UtilProperties.getPropertyValue("general.properties", "currency.uom.id.default", "USD");
888         }
889
890         Map JavaDoc redeemCtx = new HashMap JavaDoc();
891         redeemCtx.put("userLogin", userLogin);
892         redeemCtx.put("paymentConfig", paymentConfig);
893         redeemCtx.put("cardNumber", giftCard.get("cardNumber"));
894         redeemCtx.put("pin", giftCard.get("pinNumber"));
895         redeemCtx.put("currency", currency);
896         redeemCtx.put("orderId", orderId);
897         redeemCtx.put("amount", amount);
898
899         // invoke the void redeem service
900
Map JavaDoc redeemResult = null;
901         try {
902             redeemResult = dispatcher.runSync("voidRedeemGiftCard", redeemCtx);
903         } catch (GenericServiceException e) {
904             Debug.logError(e, "Problem calling the redeem service", module);
905             return ServiceUtil.returnError("Redeem service failed");
906         }
907
908         Map JavaDoc result = ServiceUtil.returnSuccess();
909         if (redeemResult != null) {
910             Boolean JavaDoc processResult = (Boolean JavaDoc) redeemResult.get("processResult");
911             result.put("releaseAmount", redeemResult.get("amount"));
912             result.put("releaseFlag", redeemResult.get("responseCode"));
913             result.put("releaseResult", processResult);
914             result.put("releaseCode", redeemResult.get("authCode"));
915             result.put("releaseRefNum", redeemResult.get("referenceNum"));
916         }
917
918         return result;
919     }
920
921     public static Map JavaDoc giftCardRefund(DispatchContext dctx, Map JavaDoc context) {
922         LocalDispatcher dispatcher = dctx.getDispatcher();
923         GenericValue userLogin = (GenericValue) context.get("userLogin");
924
925         GenericValue paymentPref = (GenericValue) context.get("orderPaymentPreference");
926         String JavaDoc paymentConfig = (String JavaDoc) context.get("paymentConfig");
927         String JavaDoc currency = (String JavaDoc) context.get("currency");
928         Double JavaDoc amount = (Double JavaDoc) context.get("refundAmount");
929
930         // get the orderId for tracking
931
String JavaDoc orderId = paymentPref.getString("orderId");
932
933         // get the GiftCard VO
934
GenericValue giftCard = null;
935         try {
936             giftCard = paymentPref.getRelatedOne("GiftCard");
937         } catch (GenericEntityException e) {
938             Debug.logError("Unable to get GiftCard from OrderPaymentPreference", module);
939             return ServiceUtil.returnError("Unable to locate GiftCard Information");
940         }
941
942         if (giftCard == null) {
943             return ServiceUtil.returnError("Attempt to release GiftCard payment faild; not a valid GiftCard record");
944         }
945
946         // make sure we have a currency
947
if (currency == null) {
948             currency = UtilProperties.getPropertyValue("general.properties", "currency.uom.id.default", "USD");
949         }
950
951         Map JavaDoc refundCtx = new HashMap JavaDoc();
952         refundCtx.put("userLogin", userLogin);
953         refundCtx.put("paymentConfig", paymentConfig);
954         refundCtx.put("cardNumber", giftCard.get("cardNumber"));
955         refundCtx.put("pin", giftCard.get("pinNumber"));
956         refundCtx.put("currency", currency);
957         refundCtx.put("orderId", orderId);
958         refundCtx.put("amount", amount);
959
960         // invoke the refund service
961
Map JavaDoc redeemResult = null;
962         try {
963             redeemResult = dispatcher.runSync("refundGiftCard", refundCtx);
964         } catch (GenericServiceException e) {
965             Debug.logError(e, "Problem calling the refund service", module);
966             return ServiceUtil.returnError("Refund service failed");
967         }
968
969         Map JavaDoc result = ServiceUtil.returnSuccess();
970         if (redeemResult != null) {
971             Boolean JavaDoc processResult = (Boolean JavaDoc) redeemResult.get("processResult");
972             result.put("refundAmount", redeemResult.get("amount"));
973             result.put("refundFlag", redeemResult.get("responseCode"));
974             result.put("refundResult", processResult);
975             result.put("refundCode", redeemResult.get("authCode"));
976             result.put("refundRefNum", redeemResult.get("referenceNum"));
977         }
978
979         return result;
980     }
981
982     // item fulfillment wrappers (purchase/reload)
983

984     public static Map JavaDoc giftCardPurchase(DispatchContext dctx, Map JavaDoc context) {
985         // this service should always be called via FULFILLMENT_EXTASYNC
986
LocalDispatcher dispatcher = dctx.getDispatcher();
987         GenericDelegator delegator = dctx.getDelegator();
988         GenericValue userLogin = (GenericValue) context.get("userLogin");
989         GenericValue orderItem = (GenericValue) context.get("orderItem");
990         Locale JavaDoc locale = (Locale JavaDoc) context.get("locale");
991
992         // order ID for tracking
993
String JavaDoc orderId = orderItem.getString("orderId");
994
995         // the order header for store info
996
GenericValue orderHeader = null;
997         try {
998             orderHeader = orderItem.getRelatedOne("OrderHeader");
999         } catch (GenericEntityException e) {
1000            Debug.logError(e, "Unable to get OrderHeader from OrderItem",module);
1001            return ServiceUtil.returnError("Unable to get OrderHeader from OrderItem");
1002        }
1003
1004        // get the order read helper
1005
OrderReadHelper orh = new OrderReadHelper(orderHeader);
1006
1007        // get the currency
1008
String JavaDoc currency = orh.getCurrency();
1009
1010        // make sure we have a currency
1011
if (currency == null) {
1012            currency = UtilProperties.getPropertyValue("general.properties", "currency.uom.id.default", "USD");
1013        }
1014
1015        // get the product store
1016
String JavaDoc productStoreId = null;
1017        if (orderHeader != null) {
1018            productStoreId = orh.getProductStoreId();
1019        }
1020        if (productStoreId == null) {
1021            return ServiceUtil.returnError("Unable to process gift card purchase; no productStoreId on OrderHeader : " + orderId);
1022        }
1023
1024        // payment config
1025
GenericValue paymentSetting = ProductStoreWorker.getProductStorePaymentSetting(delegator, productStoreId, "GIFT_CARD", null, true);
1026        String JavaDoc paymentConfig = null;
1027        if (paymentSetting != null) {
1028            paymentConfig = paymentSetting.getString("paymentPropertiesPath");
1029        }
1030        if (paymentConfig == null) {
1031            return ServiceUtil.returnError("Unable to get payment configuration file");
1032        }
1033
1034        // party ID for tracking
1035
GenericValue placingParty = orh.getPlacingParty();
1036        String JavaDoc partyId = null;
1037        if (placingParty != null) {
1038            partyId = placingParty.getString("partyId");
1039        }
1040
1041        // amount/quantity of the gift card(s)
1042
Double JavaDoc amount = orderItem.getDouble("unitPrice");
1043        Double JavaDoc quantity = orderItem.getDouble("quantity");
1044
1045        // the product entity needed for information
1046
GenericValue product = null;
1047        try {
1048            product = orderItem.getRelatedOne("Product");
1049        } catch (GenericEntityException e) {
1050            Debug.logError("Unable to get Product from OrderItem", module);
1051        }
1052        if (product == null) {
1053            return ServiceUtil.returnError("No product associated with OrderItem, cannot fulfill gift card");
1054        }
1055
1056        // get the productFeature type TYPE (VL promo code)
1057
GenericValue typeFeature = null;
1058        try {
1059            Map JavaDoc fields = UtilMisc.toMap("productId", product.get("productId"), "productFeatureTypeId", "TYPE");
1060            List JavaDoc order = UtilMisc.toList("-fromDate");
1061            List JavaDoc featureAppls = delegator.findByAndCache("ProductFeatureAndAppl", fields, order);
1062            featureAppls = EntityUtil.filterByDate(featureAppls);
1063            typeFeature = EntityUtil.getFirst(featureAppls);
1064        } catch (GenericEntityException e) {
1065            Debug.logError(e, module);
1066            return ServiceUtil.returnError("Unable to get the required feature type TYPE from Product");
1067        }
1068        if (typeFeature == null) {
1069            return ServiceUtil.returnError("Required feature type TYPE not found for product : " + product.get("productId"));
1070        }
1071
1072        // get the VL promo code
1073
String JavaDoc promoCode = typeFeature.getString("idCode");
1074        if (promoCode == null || promoCode.length() == 0) {
1075            return ServiceUtil.returnError("Invalid promo code set on idCode field of feature type TYPE");
1076        }
1077
1078        // survey information
1079
String JavaDoc surveyId = UtilProperties.getPropertyValue(paymentConfig, "payment.giftcert.purchase.surveyId");
1080
1081        // get the survey response
1082
GenericValue surveyResponse = null;
1083        try {
1084            Map JavaDoc fields = UtilMisc.toMap("orderId", orderId, "orderItemSeqId", orderItem.get("orderItemSeqId"), "surveyId", surveyId);
1085            List JavaDoc order = UtilMisc.toList("-responseDate");
1086            List JavaDoc responses = delegator.findByAnd("SurveyResponse", fields, order);
1087            // there should be only one
1088
surveyResponse = EntityUtil.getFirst(responses);
1089        } catch (GenericEntityException e) {
1090            Debug.logError(e, module);
1091            return ServiceUtil.returnError("Unable to get survey response information; cannot fulfill gift card");
1092        }
1093
1094        // get the response answers
1095
List JavaDoc responseAnswers = null;
1096        try {
1097            responseAnswers = surveyResponse.getRelated("SurveyResponseAnswer");
1098        } catch (GenericEntityException e) {
1099            Debug.logError(e, module);
1100            return ServiceUtil.returnError("Unable to get survey response answers from survey response; cannot fulfill gift card");
1101        }
1102
1103        // make a map of answer info
1104
Map JavaDoc answerMap = new HashMap JavaDoc();
1105        if (responseAnswers != null) {
1106            Iterator JavaDoc rai = responseAnswers.iterator();
1107            while (rai.hasNext()) {
1108                GenericValue answer = (GenericValue) rai.next();
1109                GenericValue question = null;
1110                try {
1111                    question = answer.getRelatedOne("SurveyQuestion");
1112                } catch (GenericEntityException e) {
1113                    Debug.logError(e, module);
1114                    return ServiceUtil.returnError("Unable to get survey question from answer");
1115                }
1116                if (question != null) {
1117                    String JavaDoc desc = question.getString("description");
1118                    String JavaDoc ans = answer.getString("textResponse"); // only support text response types for now
1119
answerMap.put(desc, ans);
1120                }
1121            }
1122        }
1123
1124        // get the send to email address - key defined in properties file
1125
String JavaDoc sendToKey = UtilProperties.getPropertyValue(paymentConfig, "payment.giftcert.purchase.survey.sendToEmail");
1126        String JavaDoc sendToEmail = (String JavaDoc) answerMap.get(sendToKey);
1127
1128        // get the copyMe flag and set the order email address
1129
String JavaDoc orderEmails = orh.getOrderEmailString();
1130        String JavaDoc copyMeField = UtilProperties.getPropertyValue(paymentConfig, "payment.giftcert.purchase.survey.copyMe");
1131        String JavaDoc copyMeResp = copyMeField != null ? (String JavaDoc) answerMap.get(copyMeField) : null;
1132        boolean copyMe = (UtilValidate.isNotEmpty(copyMeField)
1133                && UtilValidate.isNotEmpty(copyMeResp) && "true".equalsIgnoreCase(copyMeResp)) ? true : false;
1134
1135        int qtyLoop = quantity.intValue();
1136        for (int i = 0; i < qtyLoop; i++) {
1137            // activate a gift card
1138
Map JavaDoc activateCtx = new HashMap JavaDoc();
1139            activateCtx.put("paymentConfig", paymentConfig);
1140            activateCtx.put("vlPromoCode", promoCode);
1141            activateCtx.put("currency", currency);
1142            activateCtx.put("partyId", partyId);
1143            activateCtx.put("orderId", orderId);
1144            activateCtx.put("amount", amount);
1145            activateCtx.put("userLogin", userLogin);
1146
1147            boolean failure = false;
1148            Map JavaDoc activateResult = null;
1149            try {
1150                activateResult = dispatcher.runSync("activateGiftCard", activateCtx);
1151            } catch (GenericServiceException e) {
1152                Debug.logError(e, "Unable to activate gift card(s)", module);
1153                return ServiceUtil.returnError("Problem running activation service");
1154            }
1155
1156            Boolean JavaDoc processResult = (Boolean JavaDoc) activateResult.get("processResult");
1157            if (activateResult == null || activateResult.containsKey(ModelService.ERROR_MESSAGE) || !processResult.booleanValue()) {
1158                failure = true;
1159            }
1160
1161            if (!failure) {
1162                // set the void on rollback wrapper
1163
ServiceXaWrapper xaw = new ServiceXaWrapper(dctx);
1164                activateCtx.put("cardNumber", activateResult.get("cardNumber"));
1165                activateCtx.put("pin", activateResult.get("pin"));
1166                xaw.setRollbackService("voidActivateGiftCard", activateCtx);
1167                try {
1168                    xaw.enlist();
1169                } catch (XAException JavaDoc e) {
1170                    Debug.logError(e, "Unable to setup Activate/Void on error", module);
1171                }
1172            }
1173
1174            // create the fulfillment record
1175
Map JavaDoc vlFulFill = new HashMap JavaDoc();
1176            vlFulFill.put("typeEnumId", "GC_ACTIVATE");
1177            vlFulFill.put("merchantId", UtilProperties.getPropertyValue(paymentConfig, "payment.valuelink.merchantId"));
1178            vlFulFill.put("partyId", partyId);
1179            vlFulFill.put("orderId", orderId);
1180            vlFulFill.put("orderItemSeqId", orderItem.get("orderItemSeqId"));
1181            vlFulFill.put("surveyResponseId", surveyResponse.get("surveyResponseId"));
1182            vlFulFill.put("cardNumber", activateResult.get("cardNumber"));
1183            vlFulFill.put("pinNumber", activateResult.get("pin"));
1184            vlFulFill.put("amount", activateResult.get("amount"));
1185            vlFulFill.put("responseCode", activateResult.get("responseCode"));
1186            vlFulFill.put("referenceNum", activateResult.get("referenceNum"));
1187            vlFulFill.put("authCode", activateResult.get("authCode"));
1188            vlFulFill.put("userLogin", userLogin);
1189            try {
1190                dispatcher.runAsync("createGcFulFillmentRecord", vlFulFill, true);
1191            } catch (GenericServiceException e) {
1192                Debug.logError(e, module);
1193                return ServiceUtil.returnError("Unable to store fulfillment info");
1194            }
1195
1196            if (failure) {
1197                return ServiceUtil.returnError("Activate Failed");
1198            }
1199
1200            // add some information to the answerMap for the email
1201
answerMap.put("cardNumber", activateResult.get("cardNumber"));
1202            answerMap.put("pinNumber", activateResult.get("pin"));
1203            answerMap.put("amount", activateResult.get("amount"));
1204
1205            // get the email setting for this email type
1206
GenericValue productStoreEmail = null;
1207            String JavaDoc emailType = "PRDS_GC_PURCHASE";
1208            try {
1209                productStoreEmail = delegator.findByPrimaryKey("ProductStoreEmailSetting", UtilMisc.toMap("productStoreId", productStoreId, "emailType", emailType));
1210            } catch (GenericEntityException e) {
1211                Debug.logError(e, "Unable to get product store email setting for gift card purchase", module);
1212            }
1213            if (productStoreEmail == null) {
1214                Debug.logError("No gift card purchase email setting found for this store; cannot send gift card information", module);
1215            } else {
1216                ResourceBundleMapWrapper uiLabelMap = (ResourceBundleMapWrapper) UtilProperties.getResourceBundleMap("EcommerceUiLabels", locale);
1217                uiLabelMap.addBottomResourceBundle("OrderUiLabels");
1218                uiLabelMap.addBottomResourceBundle("CommonUiLabels");
1219                answerMap.put("uiLabelMap", uiLabelMap);
1220                answerMap.put("locale", locale);
1221
1222                // set the bcc address(s)
1223
String JavaDoc bcc = productStoreEmail.getString("bccAddress");
1224                if (copyMe) {
1225                    if (UtilValidate.isNotEmpty(bcc)) {
1226                        bcc = bcc + "," + orderEmails;
1227                    } else {
1228                        bcc = orderEmails;
1229                    }
1230                }
1231
1232                Map JavaDoc emailCtx = new HashMap JavaDoc();
1233                String JavaDoc bodyScreenLocation = productStoreEmail.getString("bodyScreenLocation");
1234                if (UtilValidate.isEmpty(bodyScreenLocation)) {
1235                    bodyScreenLocation = ProductStoreWorker.getDefaultProductStoreEmailScreenLocation(emailType);
1236                }
1237                emailCtx.put("bodyScreenUri", bodyScreenLocation);
1238                emailCtx.put("bodyParameters", answerMap);
1239                emailCtx.put("sendTo", sendToEmail);
1240                emailCtx.put("contentType", productStoreEmail.get("contentType"));
1241                emailCtx.put("sendFrom", productStoreEmail.get("fromAddress"));
1242                emailCtx.put("sendCc", productStoreEmail.get("ccAddress"));
1243                emailCtx.put("sendBcc", bcc);
1244                emailCtx.put("subject", productStoreEmail.getString("subject"));
1245                emailCtx.put("userLogin", userLogin);
1246
1247                // send off the email async so we will retry on failed attempts
1248
try {
1249                    dispatcher.runAsync("sendMailFromScreen", emailCtx);
1250                } catch (GenericServiceException e) {
1251                    Debug.logError(e, "Problem sending mail", module);
1252                    // this is fatal; we will rollback and try again later
1253
return ServiceUtil.returnError("Error sending Gift Card notice email: " + e.toString());
1254                }
1255            }
1256        }
1257
1258        return ServiceUtil.returnSuccess();
1259    }
1260
1261    public static Map JavaDoc giftCardReload(DispatchContext dctx, Map JavaDoc context) {
1262        // this service should always be called via FULFILLMENT_EXTSYNC
1263
LocalDispatcher dispatcher = dctx.getDispatcher();
1264        GenericDelegator delegator = dctx.getDelegator();
1265        GenericValue userLogin = (GenericValue) context.get("userLogin");
1266        GenericValue orderItem = (GenericValue) context.get("orderItem");
1267        Locale JavaDoc locale = (Locale JavaDoc) context.get("locale");
1268
1269        // order ID for tracking
1270
String JavaDoc orderId = orderItem.getString("orderId");
1271
1272        // the order header for store info
1273
GenericValue orderHeader = null;
1274        try {
1275            orderHeader = orderItem.getRelatedOne("OrderHeader");
1276        } catch (GenericEntityException e) {
1277            Debug.logError(e, "Unable to get OrderHeader from OrderItem",module);
1278            return ServiceUtil.returnError("Unable to get OrderHeader from OrderItem");
1279        }
1280
1281        // get the order read helper
1282
OrderReadHelper orh = new OrderReadHelper(orderHeader);
1283
1284        // get the currency
1285
String JavaDoc currency = orh.getCurrency();
1286
1287        // make sure we have a currency
1288
if (currency == null) {
1289            currency = UtilProperties.getPropertyValue("general.properties", "currency.uom.id.default", "USD");
1290        }
1291
1292        // get the product store
1293
String JavaDoc productStoreId = null;
1294        if (orderHeader != null) {
1295            productStoreId = orh.getProductStoreId();
1296        }
1297        if (productStoreId == null) {
1298            return ServiceUtil.returnError("Unable to process gift card reload; no productStoreId on OrderHeader : " + orderId);
1299        }
1300
1301        // payment config
1302
GenericValue paymentSetting = ProductStoreWorker.getProductStorePaymentSetting(delegator, productStoreId, "GIFT_CARD", null, true);
1303        String JavaDoc paymentConfig = null;
1304        if (paymentSetting != null) {
1305            paymentConfig = paymentSetting.getString("paymentPropertiesPath");
1306        }
1307        if (paymentConfig == null) {
1308            return ServiceUtil.returnError("Unable to get payment configuration file");
1309        }
1310
1311        // party ID for tracking
1312
GenericValue placingParty = orh.getPlacingParty();
1313        String JavaDoc partyId = null;
1314        if (placingParty != null) {
1315            partyId = placingParty.getString("partyId");
1316        }
1317
1318        // amount of the gift card reload
1319
Double JavaDoc amount = orderItem.getDouble("unitPrice");
1320
1321        // survey information
1322
String JavaDoc surveyId = UtilProperties.getPropertyValue(paymentConfig, "payment.giftcert.reload.surveyId");
1323
1324        // get the survey response
1325
GenericValue surveyResponse = null;
1326        try {
1327            Map JavaDoc fields = UtilMisc.toMap("orderId", orderId, "orderItemSeqId", orderItem.get("orderItemSeqId"), "surveyId", surveyId);
1328            List JavaDoc order = UtilMisc.toList("-responseDate");
1329            List JavaDoc responses = delegator.findByAnd("SurveyResponse", fields, order);
1330            // there should be only one
1331
surveyResponse = EntityUtil.getFirst(responses);
1332        } catch (GenericEntityException e) {
1333            Debug.logError(e, module);
1334            return ServiceUtil.returnError("Unable to get survey response information; cannot fulfill gift card reload");
1335        }
1336
1337        // get the response answers
1338
List JavaDoc responseAnswers = null;
1339        try {
1340            responseAnswers = surveyResponse.getRelated("SurveyResponseAnswer");
1341        } catch (GenericEntityException e) {
1342            Debug.logError(e, module);
1343            return ServiceUtil.returnError("Unable to get survey response answers from survey response; cannot fulfill gift card reload");
1344        }
1345
1346        // make a map of answer info
1347
Map JavaDoc answerMap = new HashMap JavaDoc();
1348        if (responseAnswers != null) {
1349            Iterator JavaDoc rai = responseAnswers.iterator();
1350            while (rai.hasNext()) {
1351                GenericValue answer = (GenericValue) rai.next();
1352                GenericValue question = null;
1353                try {
1354                    question = answer.getRelatedOne("SurveyQuestion");
1355                } catch (GenericEntityException e) {
1356                    Debug.logError(e, module);
1357                    return ServiceUtil.returnError("Unable to get survey question from answer");
1358                }
1359                if (question != null) {
1360                    String JavaDoc desc = question.getString("description");
1361                    String JavaDoc ans = answer.getString("textResponse"); // only support text response types for now
1362
answerMap.put(desc, ans);
1363                }
1364            }
1365        }
1366
1367        String JavaDoc cardNumberKey = UtilProperties.getPropertyValue(paymentConfig, "payment.giftcert.reload.survey.cardNumber");
1368        String JavaDoc pinNumberKey = UtilProperties.getPropertyValue(paymentConfig, "payment.giftcert.reload.survey.pinNumber");
1369        String JavaDoc cardNumber = (String JavaDoc) answerMap.get(cardNumberKey);
1370        String JavaDoc pinNumber = (String JavaDoc) answerMap.get(pinNumberKey);
1371
1372        // reload the gift card
1373
Map JavaDoc reloadCtx = new HashMap JavaDoc();
1374        reloadCtx.put("paymentConfig", paymentConfig);
1375        reloadCtx.put("currency", currency);
1376        reloadCtx.put("partyId", partyId);
1377        reloadCtx.put("orderId", orderId);
1378        reloadCtx.put("cardNumber", cardNumber);
1379        reloadCtx.put("pin", pinNumber);
1380        reloadCtx.put("amount", amount);
1381        reloadCtx.put("userLogin", userLogin);
1382
1383        Map JavaDoc reloadResult = null;
1384        try {
1385            reloadResult = dispatcher.runSync("reloadGiftCard", reloadCtx);
1386        } catch (GenericServiceException e) {
1387            Debug.logError(e, "Unable to reload gift card", module);
1388            return ServiceUtil.returnError("Problem running reload service");
1389        }
1390
1391        // create the fulfillment record
1392
Map JavaDoc vlFulFill = new HashMap JavaDoc();
1393        vlFulFill.put("typeEnumId", "GC_RELOAD");
1394        vlFulFill.put("merchantId", UtilProperties.getPropertyValue(paymentConfig, "payment.valuelink.merchantId"));
1395        vlFulFill.put("partyId", partyId);
1396        vlFulFill.put("orderId", orderId);
1397        vlFulFill.put("orderItemSeqId", orderItem.get("orderItemSeqId"));
1398        vlFulFill.put("surveyResponseId", surveyResponse.get("surveyResponseId"));
1399        vlFulFill.put("cardNumber", cardNumber);
1400        vlFulFill.put("pinNumber", pinNumber);
1401        vlFulFill.put("amount", amount);
1402        vlFulFill.put("responseCode", reloadResult.get("responseCode"));
1403        vlFulFill.put("referenceNum", reloadResult.get("referenceNum"));
1404        vlFulFill.put("authCode", reloadResult.get("authCode"));
1405        vlFulFill.put("userLogin", userLogin);
1406        try {
1407            dispatcher.runAsync("createGcFulFillmentRecord", vlFulFill, true);
1408        } catch (GenericServiceException e) {
1409            Debug.logError(e, module);
1410            return ServiceUtil.returnError("Unable to store fulfillment info");
1411        }
1412
1413        Boolean JavaDoc processResult = (Boolean JavaDoc) reloadResult.get("processResult");
1414        if (reloadResult == null || reloadResult.containsKey(ModelService.ERROR_MESSAGE) || !processResult.booleanValue()) {
1415            Debug.logError("Reload Failed Need to Refund : " + reloadResult, module);
1416
1417            // process the return
1418
try {
1419                Map JavaDoc refundCtx = UtilMisc.toMap("orderItem", orderItem, "partyId", partyId, "userLogin", userLogin);
1420                dispatcher.runAsync("refundGcPurchase", refundCtx, null, true, 300, true);
1421            } catch (GenericServiceException e) {
1422                Debug.logError(e, "ERROR! Unable to call create refund service; this failed reload will NOT be refunded", module);
1423            }
1424
1425            String JavaDoc responseCode = "-1";
1426            if (processResult != null) {
1427                responseCode = (String JavaDoc) reloadResult.get("responseCode");
1428            }
1429            if ("17".equals(responseCode)) {
1430                Debug.logError("Error code : " + responseCode + " : Max Balance Exceeded", module);
1431                return ServiceUtil.returnError("Gift Card Reload Failed : Max Balance Exceeded; charges will be refunded");
1432            } else {
1433                Debug.logError("Error code : " + responseCode + " : Processing Error", module);
1434                return ServiceUtil.returnError("Gift Card Reload Failed : Processing Error; charges will be refunded");
1435            }
1436        }
1437
1438        // add some information to the answerMap for the email
1439
answerMap.put("processResult", reloadResult.get("processResult"));
1440        answerMap.put("responseCode", reloadResult.get("responseCode"));
1441        answerMap.put("previousAmount", reloadResult.get("previousAmount"));
1442        answerMap.put("amount", reloadResult.get("amount"));
1443
1444        // get the email setting for this email type
1445
GenericValue productStoreEmail = null;
1446        String JavaDoc emailType = "PRDS_GC_RELOAD";
1447        try {
1448            productStoreEmail = delegator.findByPrimaryKey("ProductStoreEmailSetting", UtilMisc.toMap("productStoreId", productStoreId, "emailType", emailType));
1449        } catch (GenericEntityException e) {
1450            Debug.logError(e, "Unable to get product store email setting for gift card purchase", module);
1451        }
1452        if (productStoreEmail == null) {
1453            Debug.logError("No gift card purchase email setting found for this store; cannot send gift card information", module);
1454        } else {
1455            Map JavaDoc emailCtx = new HashMap JavaDoc();
1456            ResourceBundleMapWrapper uiLabelMap = (ResourceBundleMapWrapper) UtilProperties.getResourceBundleMap("EcommerceUiLabels", locale);
1457            uiLabelMap.addBottomResourceBundle("OrderUiLabels");
1458            uiLabelMap.addBottomResourceBundle("CommonUiLabels");
1459            answerMap.put("uiLabelMap", uiLabelMap);
1460            answerMap.put("locale", locale);
1461            
1462            String JavaDoc bodyScreenLocation = productStoreEmail.getString("bodyScreenLocation");
1463            if (UtilValidate.isEmpty(bodyScreenLocation)) {
1464                bodyScreenLocation = ProductStoreWorker.getDefaultProductStoreEmailScreenLocation(emailType);
1465            }
1466            emailCtx.put("bodyScreenUri", bodyScreenLocation);
1467            emailCtx.put("bodyParameters", answerMap);
1468            emailCtx.put("sendTo", orh.getOrderEmailString());
1469            emailCtx.put("contentType", productStoreEmail.get("contentType"));
1470            emailCtx.put("sendFrom", productStoreEmail.get("fromAddress"));
1471            emailCtx.put("sendCc", productStoreEmail.get("ccAddress"));
1472            emailCtx.put("sendBcc", productStoreEmail.get("bccAddress"));
1473            emailCtx.put("subject", productStoreEmail.getString("subject"));
1474            emailCtx.put("userLogin", userLogin);
1475
1476            // send off the email async so we will retry on failed attempts
1477
try {
1478                dispatcher.runAsync("sendMailFromScreen", emailCtx);
1479            } catch (GenericServiceException e) {
1480                Debug.logError(e, "Problem sending mail", module);
1481                // this is fatal; we will rollback and try again later
1482
return ServiceUtil.returnError("Error sending Gift Card notice email: " + e.toString());
1483            }
1484        }
1485
1486        return ServiceUtil.returnSuccess();
1487    }
1488}
1489
Popular Tags