svn commit: r923223 [1/3] - in /ofbiz/trunk/specialpurpose: ebay/webapp/ebay/find/ ebay/widget/ ebaystore/config/ ebaystore/entitydef/ ebaystore/servicedef/ ebaystore/src/org/ofbiz/ebaystore/ ebaystore/webapp/ebaystore/WEB-INF/ ebaystore/webapp/ebaysto...

Previous Topic Next Topic
 
classic Classic list List threaded Threaded
1 message Options
Reply | Threaded
Open this post in threaded view
|

svn commit: r923223 [1/3] - in /ofbiz/trunk/specialpurpose: ebay/webapp/ebay/find/ ebay/widget/ ebaystore/config/ ebaystore/entitydef/ ebaystore/servicedef/ ebaystore/src/org/ofbiz/ebaystore/ ebaystore/webapp/ebaystore/WEB-INF/ ebaystore/webapp/ebaysto...

hansbak-2
Author: hansbak
Date: Mon Mar 15 13:44:53 2010
New Revision: 923223

URL: http://svn.apache.org/viewvc?rev=923223&view=rev
Log:
ebaystore update:
- add button to save listing xml data  when export to ebay and we will use this xml data for function auto relist (For function relist we will patch again next week becuase It not finnish yet now.)
- changed shipping options to selectbox
- item themes and descriptions in create listing screen
- add button to verify listing before export.

Added:
    ofbiz/trunk/specialpurpose/ebaystore/src/org/ofbiz/ebaystore/EbayStoreCategoryFacade.java
    ofbiz/trunk/specialpurpose/ebaystore/src/org/ofbiz/ebaystore/EbayStoreSiteFacade.java
    ofbiz/trunk/specialpurpose/ebaystore/webapp/ebaystore/WEB-INF/actions/store/PrepareProductListing.groovy
    ofbiz/trunk/specialpurpose/ebaystore/webapp/ebaystore/store/returnPolicy.ftl
Modified:
    ofbiz/trunk/specialpurpose/ebay/webapp/ebay/find/EbayKeywordSearch.ftl
    ofbiz/trunk/specialpurpose/ebay/webapp/ebay/find/ebayExportLink.ftl
    ofbiz/trunk/specialpurpose/ebay/widget/EbayScreens.xml
    ofbiz/trunk/specialpurpose/ebaystore/config/EbayStoreUiLabels.xml
    ofbiz/trunk/specialpurpose/ebaystore/entitydef/entitymodel.xml
    ofbiz/trunk/specialpurpose/ebaystore/servicedef/services.xml
    ofbiz/trunk/specialpurpose/ebaystore/src/org/ofbiz/ebaystore/EbayEvents.java
    ofbiz/trunk/specialpurpose/ebaystore/src/org/ofbiz/ebaystore/EbayStoreHelper.java
    ofbiz/trunk/specialpurpose/ebaystore/src/org/ofbiz/ebaystore/EbayStoreOptions.java
    ofbiz/trunk/specialpurpose/ebaystore/webapp/ebaystore/WEB-INF/controller.xml
    ofbiz/trunk/specialpurpose/ebaystore/webapp/ebaystore/store/productsearchExport.ftl
    ofbiz/trunk/specialpurpose/ebaystore/widget/EbayStoreScreens.xml

Modified: ofbiz/trunk/specialpurpose/ebay/webapp/ebay/find/EbayKeywordSearch.ftl
URL: http://svn.apache.org/viewvc/ofbiz/trunk/specialpurpose/ebay/webapp/ebay/find/EbayKeywordSearch.ftl?rev=923223&r1=923222&r2=923223&view=diff
==============================================================================
--- ofbiz/trunk/specialpurpose/ebay/webapp/ebay/find/EbayKeywordSearch.ftl (original)
+++ ofbiz/trunk/specialpurpose/ebay/webapp/ebay/find/EbayKeywordSearch.ftl Mon Mar 15 13:44:53 2010
@@ -77,6 +77,7 @@ under the License.
       <form method="post" name="products">
         <fieldset>
           <input type="hidden" name="productStoreId" value="${parameters.productStoreId?if_exists}" />
+          <input type="hidden" name="SEARCH_CATEGORY_ID" value="${(requestParameters.SEARCH_CATEGORY_ID)?if_exists}" />
           <table class="basic-table border-top border-bottom">
             <#assign listIndex = lowIndex />
             <#assign altRow = false />

Modified: ofbiz/trunk/specialpurpose/ebay/webapp/ebay/find/ebayExportLink.ftl
URL: http://svn.apache.org/viewvc/ofbiz/trunk/specialpurpose/ebay/webapp/ebay/find/ebayExportLink.ftl?rev=923223&r1=923222&r2=923223&view=diff
==============================================================================
--- ofbiz/trunk/specialpurpose/ebay/webapp/ebay/find/ebayExportLink.ftl (original)
+++ ofbiz/trunk/specialpurpose/ebay/webapp/ebay/find/ebayExportLink.ftl Mon Mar 15 13:44:53 2010
@@ -19,7 +19,11 @@ under the License.
 
 <script language="JavaScript" type="text/javascript">
     function exportToEbay() {
-        document.products.action="<@ofbizUrl>ProductsExportToEbay</@ofbizUrl>";
+        <#if toEbayStore?exists>
+            document.products.action="<@ofbizUrl>prepareProductListing</@ofbizUrl>";
+        <#else>
+            document.products.action="<@ofbizUrl>ProductsExportToEbay</@ofbizUrl>";
+        </#if>
         document.products.submit();
     }
 </script>

Modified: ofbiz/trunk/specialpurpose/ebay/widget/EbayScreens.xml
URL: http://svn.apache.org/viewvc/ofbiz/trunk/specialpurpose/ebay/widget/EbayScreens.xml?rev=923223&r1=923222&r2=923223&view=diff
==============================================================================
--- ofbiz/trunk/specialpurpose/ebay/widget/EbayScreens.xml (original)
+++ ofbiz/trunk/specialpurpose/ebay/widget/EbayScreens.xml Mon Mar 15 13:44:53 2010
@@ -234,6 +234,7 @@ under the License.
                 <entity-one entity-name="EbayConfig" value-field="ebayConfig"/>
                 <set field="tabButtonItem" value="${groovy:ebayConfig == null?'newEbayConfig' : 'editEbayConfig'}"/>
                 <set field="xmlGatewayUri" value="${groovy:ebayConfig == null?'' : org.ofbiz.base.util.StringUtil.wrapString(ebayConfig.xmlGatewayUri)}"/>
+                <set field="apiServerUrl" value="${groovy:ebayConfig == null?'' : org.ofbiz.base.util.StringUtil.wrapString(ebayConfig.apiServerUrl)}"/>
                 <set field="token" value="${groovy:ebayConfig == null?'' : org.ofbiz.base.util.StringUtil.wrapString(ebayConfig.token)}"/>
                 <set field="customXml" value="${groovy:ebayConfig == null?'' : org.ofbiz.base.util.StringUtil.wrapString(ebayConfig.customXml)}"/>
                 <!--set field="webSiteId" value="${groovy:ebayConfig == null?parameters.webSiteId : ebayConfig.webSiteId}"/-->

Modified: ofbiz/trunk/specialpurpose/ebaystore/config/EbayStoreUiLabels.xml
URL: http://svn.apache.org/viewvc/ofbiz/trunk/specialpurpose/ebaystore/config/EbayStoreUiLabels.xml?rev=923223&r1=923222&r2=923223&view=diff
==============================================================================
--- ofbiz/trunk/specialpurpose/ebaystore/config/EbayStoreUiLabels.xml (original)
+++ ofbiz/trunk/specialpurpose/ebaystore/config/EbayStoreUiLabels.xml Mon Mar 15 13:44:53 2010
@@ -190,6 +190,9 @@
         <value xml:lang="en">Buy It Now price</value>
         <value xml:lang="th">ราคาสุทธิ</value>
     </property>
+    <property key="FormFieldTitle_webSiteUrl">
+        <value xml:lang="en">Website Url</value>
+    </property>
     <property key="eBayOnlineAuction">
         <value xml:lang="en">Online Auction</value>
     </property>
@@ -275,7 +278,19 @@
     <property key="EbayAutoSendItemDispatchEmail">
         <value xml:lang="en">Automatic send item dispatched notification email</value>
     </property>
-        <property key="EbayUnsold">
+    <property key="EbayContinueListing">
+        <value xml:lang="en">Countinue</value>
+    </property>
+    <property key="EbayChangeCategory">
+        <value xml:lang="en">Change</value>
+    </property>
+    <property key="EbayStoreCategory">
+        <value xml:lang="en">eBay Store Category</value>
+    </property>
+    <property key="EbaySet">
+        <value xml:lang="en">Set</value>
+    </property>
+    <property key="EbayUnsold">
         <value xml:lang="en">unsold</value>
     </property>
     <property key="EbayActive">

Modified: ofbiz/trunk/specialpurpose/ebaystore/entitydef/entitymodel.xml
URL: http://svn.apache.org/viewvc/ofbiz/trunk/specialpurpose/ebaystore/entitydef/entitymodel.xml?rev=923223&r1=923222&r2=923223&view=diff
==============================================================================
--- ofbiz/trunk/specialpurpose/ebaystore/entitydef/entitymodel.xml (original)
+++ ofbiz/trunk/specialpurpose/ebaystore/entitydef/entitymodel.xml Mon Mar 15 13:44:53 2010
@@ -78,4 +78,38 @@ under the License.
             <key-map field-name="autoPrefJobId" rel-field-name="jobId"/>
         </relation>
     </entity>
+    <entity entity-name="EbayProductListing" package-name="org.ofbiz.ebay.store"
+        title="eBay Product Listing">
+        <field name="productListingId" type="id-ne"/>
+        <field name="itemId" type="id-long"/>
+        <field name="productStoreId" type="id-ne"/>
+        <field name="productId" type="id-ne"/>
+        <field name="userLoginId" type="id-long"/>
+        <field name="statusId" type="id-ne"/>
+        <field name="listingXml" type="very-long"/>
+        <field name="startDateTime" type="date-time"/>
+        <field name="endDateTime" type="date-time"/>
+        <field name="autoRelisting" type="indicator"/>
+        <prim-key field="productListingId"/>
+        <relation type="one" fk-name="EBAY_PRODUCT" rel-entity-name="Product">
+            <key-map field-name="productId"/>
+        </relation>
+        <relation type="one" fk-name="EBAY_STORE" rel-entity-name="ProductStore">
+            <key-map field-name="productStoreId"/>
+        </relation>
+        <relation type="one" fk-name="EBAY_STATUS" rel-entity-name="StatusItem">
+            <key-map field-name="statusId"/>
+        </relation>
+    </entity>
+    <entity entity-name="EbayProductListingAttribute" package-name="org.ofbiz.ebay.store"
+        title="eBay Product Listing">
+        <field name="productListingId" type="id-ne"/>
+        <field name="attrName" type="id-long-ne"/>
+        <field name="attrValue" type="value"/>
+        <prim-key field="productListingId"/>
+        <prim-key field="attrName"/>
+        <relation type="one" fk-name="EBAY_PROD_ATTR" rel-entity-name="EbayProductListing">
+            <key-map field-name="productListingId"/>
+        </relation>
+    </entity>
 </entitymodel>
\ No newline at end of file

Modified: ofbiz/trunk/specialpurpose/ebaystore/servicedef/services.xml
URL: http://svn.apache.org/viewvc/ofbiz/trunk/specialpurpose/ebaystore/servicedef/services.xml?rev=923223&r1=923222&r2=923223&view=diff
==============================================================================
--- ofbiz/trunk/specialpurpose/ebaystore/servicedef/services.xml (original)
+++ ofbiz/trunk/specialpurpose/ebaystore/servicedef/services.xml Mon Mar 15 13:44:53 2010
@@ -378,12 +378,40 @@ under the License.
         <attribute name="jobId" mode="IN" type="String" optional="false"/>
         <attribute name="productStoreId" mode="IN" type="String" optional="false"/>
     </service>
+    <service name="getEbayStoreCategories" engine="java" transaction-timeout="3600"
+        location="org.ofbiz.ebaystore.EbayStore" invoke="getEbayStoreCategories" auth="true">
+        <description>Get Ebay Store Category</description>
+        <attribute name="productStoreId" type="String" mode="IN" optional="false"></attribute>
+        <attribute name="ebayStoreCategoryId" type="String" mode="IN" optional="true"></attribute>
+        <attribute name="storeCategories" type="List" mode="OUT" optional="false"></attribute>
+    </service>
     <service name="autoBlockItemsOutOfStock" engine="java" transaction-timeout="7200"
         location="org.ofbiz.ebaystore.EbayStoreAutoPreferences" invoke="autoBlockItemsOutOfStock" auth="false">
         <description>Automatic service to send item dispatched notification email when user mark sold listing as dispatched</description>
         <attribute name="jobId" mode="IN" type="String" optional="false"/>
         <attribute name="productStoreId" mode="IN" type="String" optional="false"/>
     </service>
+    <service name="exportProductEachItem" engine="java" transaction-timeout="7200"
+        location="org.ofbiz.ebaystore.EbayStoreHelper" invoke="exportProductEachItem" auth="false">
+        <description>Export Product Each Item</description>
+        <attribute name="itemObject" mode="IN" type="Object" optional="false"/>
+    </service>
+    <service name="createEbayProductListing" engine="entity-auto" default-entity-name="EbayProductListing" invoke="create" auth="true">
+        <auto-attributes include="pk" mode="INOUT" optional="true"/>
+        <auto-attributes include="nonpk" mode="IN" optional="true"/>
+        <attribute name="autoRelisting" mode="IN" type="String" optional="false" default-value="N"/>
+        <attribute name="listingXml" mode="IN" type="String" optional="true" allow-html="any"/>
+    </service>
+    <service name="updateEbayProductListing" engine="entity-auto" default-entity-name="EbayProductListing" invoke="update" auth="true" >
+        <attribute name="productListingId" mode="IN" type="String" optional="false"/>
+        <auto-attributes include="nonpk" mode="IN" optional="true" />
+        <attribute name="listingXml" mode="IN" type="String" optional="true" allow-html="any"/>
+    </service>
+    <service name="setEbayProductListingAttribute" engine="java" transaction-timeout="3600"
+        location="org.ofbiz.ebaystore.EbayStoreHelper" invoke="setEbayProductListingAttribute" auth="true">
+        <attribute name="productListingId" mode="IN" type="String" optional="false"/>
+        <attribute name="attributeMapList" mode="IN" type="java.util.HashMap" optional="false"/>
+    </service>
     <service name="getMyeBaySelling" engine="java" transaction-timeout="3600"
         location="org.ofbiz.ebaystore.EbayStore" invoke="getMyeBaySelling" auth="true">
         <attribute name="productStoreId" mode="IN" type="String" optional="false"/>

Modified: ofbiz/trunk/specialpurpose/ebaystore/src/org/ofbiz/ebaystore/EbayEvents.java
URL: http://svn.apache.org/viewvc/ofbiz/trunk/specialpurpose/ebaystore/src/org/ofbiz/ebaystore/EbayEvents.java?rev=923223&r1=923222&r2=923223&view=diff
==============================================================================
--- ofbiz/trunk/specialpurpose/ebaystore/src/org/ofbiz/ebaystore/EbayEvents.java (original)
+++ ofbiz/trunk/specialpurpose/ebaystore/src/org/ofbiz/ebaystore/EbayEvents.java Mon Mar 15 13:44:53 2010
@@ -18,24 +18,72 @@
  */
 package org.ofbiz.ebaystore;
 
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Locale;
 import java.util.Map;
+import java.util.HashMap;
 
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 import javax.servlet.http.HttpSession;
 
+import javolution.util.FastList;
 import javolution.util.FastMap;
 import org.ofbiz.base.util.Debug;
 import org.ofbiz.base.util.UtilHttp;
+import org.ofbiz.base.util.UtilMisc;
+import org.ofbiz.base.util.UtilValidate;
+import org.ofbiz.entity.util.EntityUtil;
+import org.ofbiz.entity.Delegator;
+import org.ofbiz.entity.GenericEntityException;
 import org.ofbiz.entity.GenericValue;
 import org.ofbiz.service.GenericServiceException;
 import org.ofbiz.service.LocalDispatcher;
-import org.ofbiz.webapp.taglib.ServiceTag;
+import org.ofbiz.service.ServiceUtil;
+
+import com.ebay.sdk.ApiContext;
+import com.ebay.sdk.ApiException;
+import com.ebay.sdk.SdkException;
+import com.ebay.sdk.call.AddItemCall;
+import com.ebay.sdk.call.VerifyAddItemCall;
+import org.apache.axis.types.URI;
+import com.ebay.soap.eBLBaseComponents.AmountType;
+import com.ebay.soap.eBLBaseComponents.BuyerPaymentMethodCodeType;
+import com.ebay.soap.eBLBaseComponents.CategoryType;
+import com.ebay.soap.eBLBaseComponents.CountryCodeType;
+import com.ebay.soap.eBLBaseComponents.CurrencyCodeType;
+import com.ebay.soap.eBLBaseComponents.ItemSpecificsEnabledCodeType;
+import com.ebay.soap.eBLBaseComponents.ItemType;
+import com.ebay.soap.eBLBaseComponents.ListingTypeCodeType;
+import com.ebay.soap.eBLBaseComponents.PictureDetailsType;
+import com.ebay.soap.eBLBaseComponents.ReturnPolicyType;
+import com.ebay.soap.eBLBaseComponents.ShippingServiceDetailsType;
+import com.ebay.soap.eBLBaseComponents.ShippingTypeCodeType;
+import com.ebay.soap.eBLBaseComponents.SiteCodeType;
+import com.ebay.soap.eBLBaseComponents.VATDetailsType;
+import com.ebay.soap.eBLBaseComponents.WarningLevelCodeType;
+import com.ebay.soap.eBLBaseComponents.ListingDesignerType;
+import com.ebay.soap.eBLBaseComponents.ShippingDetailsType;
+import com.ebay.soap.eBLBaseComponents.ShippingServiceOptionsType;
+import com.ebay.soap.eBLBaseComponents.VerifyAddItemRequestType;
+import com.ebay.soap.eBLBaseComponents.VerifyAddItemResponseType;
+import com.ebay.soap.eBLBaseComponents.FeesType;
+import com.ebay.soap.eBLBaseComponents.FeeType;
+import com.ebay.soap.eBLBaseComponents.InsuranceDetailsType;
+import com.ebay.soap.eBLBaseComponents.SalesTaxType;
+import com.ebay.soap.eBLBaseComponents.AddItemRequestType;
+import com.ebay.soap.eBLBaseComponents.AddItemResponseType;
 
 public class EbayEvents {
 
-    public static final String module = ServiceTag.class.getName();
+    private static final int SHIPPING_SERVICE_ID_LIMIT = 50000;
+    public static final String module = EbayEvents.class.getName();
 
+    @SuppressWarnings("unchecked")
     public static String sendLeaveFeedback(HttpServletRequest request, HttpServletResponse response) {
         HttpSession session = request.getSession(true);
         LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
@@ -84,4 +132,774 @@ public class EbayEvents {
         }
         return "success";
     }
+    /* event to add products to prepare create & export listing */
+    @SuppressWarnings("unchecked")
+    public static String addProductListing(HttpServletRequest request, HttpServletResponse response) {
+        Delegator delegator = (Delegator) request.getAttribute("delegator");
+        Map<String,Object> requestParams = UtilHttp.getParameterMap(request);
+        Locale locale = UtilHttp.getLocale(request);
+
+        if (UtilValidate.isEmpty(requestParams.get("productStoreId"))) {
+            request.setAttribute("_ERROR_MESSAGE_","Required productStoreId and selected products.");
+            return "error";
+        }
+        List<String> productIds = (List<String>) requestParams.get("productIds");
+        if (UtilValidate.isNotEmpty(requestParams.get("productIds"))) {
+            productIds = (List<String>) requestParams.get("productIds");
+        } else if (UtilValidate.isNotEmpty(requestParams.get("selectResult"))) {
+            try {
+                productIds = (List<String>) requestParams.get("selectResult");
+            } catch (ClassCastException e) {
+                if (UtilValidate.isEmpty(productIds)) productIds = FastList.newInstance();
+                productIds.add((String) requestParams.get("selectResult"));
+            }
+        } else {
+            request.setAttribute("_ERROR_MESSAGE_","Required productStoreId and selected products.");
+            return "error";
+        }
+        String productStoreId = (String) requestParams.get("productStoreId");
+
+        ApiContext apiContext = EbayStoreHelper.getApiContext(productStoreId, locale, delegator);
+        //String webSiteUrl = (String) requestParams.get("webSiteUrl");
+        String webSiteUrl = "http://demo.ofbiz.org";
+        Map<String,Object> addItemObject = getAddItemListingObject(request, apiContext);
+        List<Map<String,Object>> itemObjs = null;
+        if (UtilValidate.isNotEmpty(addItemObject.get("itemListings"))) {
+            itemObjs = (List<Map<String,Object>>) addItemObject.get("itemListings");
+        } else {
+            itemObjs = FastList.newInstance();
+        }
+
+        if (UtilValidate.isNotEmpty(productIds)) {
+            try {
+                // check  add new product obj ? to export
+                for (String productId : productIds) {
+                    for (Map<String,Object> itObj : itemObjs) {
+                        if (UtilValidate.isNotEmpty(itObj.get(productId.concat("_Obj")))) {
+                            productIds.remove(productId);
+                        }
+                    }
+                }
+                Debug.log("run in with productIds "+productIds);
+                for (String productId : productIds) {
+                    AddItemCall addItemCall = new AddItemCall(apiContext);
+                    ItemType item = new ItemType();
+                    GenericValue product = delegator.findByPrimaryKey("Product", UtilMisc.toMap("productId", productId));
+                    item.setTitle(product.getString("internalName"));
+                    item.setCurrency(CurrencyCodeType.USD);
+                    String productDescription = "";
+                    String description = product.getString("description");
+                    String longDescription = product.getString("longDescription");
+                    if (UtilValidate.isNotEmpty(description)) {
+                        productDescription = description;
+                    } else if (UtilValidate.isNotEmpty(longDescription)) {
+                        productDescription = longDescription;
+                    } else if (UtilValidate.isNotEmpty(product.getString("productName"))) {
+                        productDescription = product.getString("productName");
+                    }
+                    item.setDescription(productDescription);
+                    item.setSKU(product.getString("productId"));
+                    item.setApplicationData(product.getString("productId"));
+                    item.setCountry(CountryCodeType.US);
+                    item.setQuantity(new Integer(1));
+                    String smallImage = product.getString("smallImageUrl");
+                    String mediumImage = product.getString("mediumImageUrl");
+                    String largeImage = product.getString("largeImageUrl");
+                    String ebayImage = null;
+                    if (UtilValidate.isNotEmpty(largeImage)) {
+                        ebayImage = largeImage;
+                    } else if (UtilValidate.isNotEmpty(mediumImage)) {
+                        ebayImage = mediumImage;
+                    } else if (UtilValidate.isNotEmpty(smallImage)) {
+                        ebayImage = smallImage;
+                    }
+                    if (UtilValidate.isNotEmpty(ebayImage)) {
+                        PictureDetailsType pic = new PictureDetailsType();
+                        String pictureUrl = webSiteUrl + ebayImage;
+                        String[] picURL = new String[1];
+                        picURL[0] = pictureUrl;
+                        //String[] picURL = {webSiteUrl + ebayImage};
+                        //pic.setPictureURL(picURL);
+                        pic.setPictureURL(picURL);
+                        item.setPictureDetails(pic);
+                    }
+                    item.setCategoryMappingAllowed(true);
+                    item.setSite(apiContext.getSite());
+                    addItemCall.setSite(apiContext.getSite());
+                    addItemCall.setItem(item);
+                    addItemCall.setWarningLevel(WarningLevelCodeType.HIGH);
+
+                    Map<String,Object> itemListing = null;
+                    for (Map<String,Object> itemObj : itemObjs) {
+                        if (UtilValidate.isNotEmpty(itemObj.get(productId.concat("_Obj")))) {
+                            itemListing = (Map<String,Object> )itemObj.get(productId.concat("_Obj"));
+                            itemListing.put("addItemCall", addItemCall);
+                            itemListing.put("productId", productId);
+                            break;
+                        }
+                    }
+                    if (UtilValidate.isEmpty(itemListing)) {
+                        itemListing = FastMap.newInstance();
+                        itemListing.put("addItemCall", addItemCall);
+                        itemListing.put("productId", productId);
+                        itemObjs.add(itemListing);
+                    }
+                }
+                addItemObject.put("itemListing", itemObjs);
+            } catch (Exception e) {
+                Debug.logError(e.getMessage(), module);
+                return "error";
+            }
+        }
+        return "success";
+    }
+
+    public static String prepareEbaySiteFacadeObject(HttpServletRequest request, HttpServletResponse response) {
+        HttpSession session = request.getSession(true);
+        if (request.getParameter("productStoreId") == null) {
+            return "error";
+        }
+        ApiContext apiContext = getApiContext(request);
+        try {
+            if (UtilValidate.isNotEmpty(apiContext)) {
+                String siteCode = apiContext.getSite().name();
+                if (UtilValidate.isNotEmpty(session.getAttribute("itemListings_".concat(siteCode)))) {
+                    request.setAttribute("productStoreId", request.getParameter("productStoreId"));
+                    return "prepare";
+                }
+                getSiteFacade(apiContext,request);
+            } else {
+                request.setAttribute("_ERROR_MESSAGE_","No apiContext for this account or this site please register on ebay or check you user account.");
+                return "error";
+            }
+        } catch (ApiException e) {
+            request.setAttribute("_ERROR_MESSAGE_","ApiException ".concat(e.getMessage()));
+            return "error";
+        } catch (SdkException e) {
+            request.setAttribute("_ERROR_MESSAGE_","SdkException ".concat(e.getMessage()));
+            return "error";
+        } catch (Exception e) {
+            request.setAttribute("_ERROR_MESSAGE_","Exception ".concat(e.getMessage()));
+            return "error";
+        }
+        return "success";
+    }
+
+    public static EbayStoreSiteFacade getSiteFacade(ApiContext apiContext, HttpServletRequest request) throws ApiException, SdkException, Exception{
+        String siteFacadeName = null;
+        EbayStoreSiteFacade siteFacade = null;
+
+        if (request.getParameter("productStoreId") == null) {
+            Debug.logError("Required productStoreId for get ebay information.", module);
+            return siteFacade;
+        }
+
+        HttpSession session = request.getSession(true);
+        if (UtilValidate.isNotEmpty(apiContext)) {
+            siteFacadeName = "siteFacade".concat("_".concat(apiContext.getSite().name()));
+        }
+
+        if (UtilValidate.isEmpty(session.getAttribute(siteFacadeName))) {
+            session.setAttribute(siteFacadeName,new EbayStoreSiteFacade(apiContext));
+            if (UtilValidate.isNotEmpty(session.getAttribute(siteFacadeName))) {
+                siteFacade = (EbayStoreSiteFacade)session.getAttribute(siteFacadeName);
+            }
+        } else {
+            siteFacade = (EbayStoreSiteFacade)session.getAttribute(siteFacadeName);
+        }
+        Debug.logInfo("loaded session for ebay site Facade is ".concat(siteFacadeName).concat(session.getAttribute(siteFacadeName).toString()),module);
+        return siteFacade;
+    }
+
+    public static ApiContext getApiContext(HttpServletRequest request) {
+        Locale locale = UtilHttp.getLocale(request);
+        Delegator delegator = (Delegator) request.getAttribute("delegator");
+
+        if (request.getParameter("productStoreId") == null && request.getAttribute("productStoreId") == null) {
+            Debug.logError("Required productStoreId for get ebay API config data.", module);
+            return null;
+        }
+        ApiContext apiContext = EbayStoreHelper.getApiContext((String)request.getParameter("productStoreId") != null ? request.getParameter("productStoreId"):(String)request.getAttribute("productStoreId"), locale, delegator);
+        return apiContext;
+    }
+
+    public static String clearProductListing(HttpServletRequest request, HttpServletResponse response) {
+        removeItemListingObject(request, getApiContext(request));
+        return "success";
+    }
+
+    public static void removeItemListingObject(HttpServletRequest request, ApiContext apiContext) {
+        HttpSession session = request.getSession(true);
+        String siteCode = apiContext.getSite().name();
+        Map<String,Object> addItemObject = (Map<String,Object>) session.getAttribute("itemListings_".concat(siteCode));
+        if (UtilValidate.isNotEmpty(addItemObject)) {
+            session.removeAttribute("itemListings_".concat(siteCode));
+        }
+    }
+
+    @SuppressWarnings("unchecked")
+    public static Map<String,Object> getAddItemListingObject(HttpServletRequest request, ApiContext apiContext) {
+        String siteCode = apiContext.getSite().name();
+        Map<String,Object> addItemObject = (Map<String,Object>) request.getAttribute("itemListings_".concat(siteCode));
+        HttpSession session = request.getSession(true);
+        if (addItemObject == null) {
+            addItemObject = (Map<String,Object>) session.getAttribute("itemListings_".concat(siteCode));
+        } else {
+            session.setAttribute("itemListings_".concat(siteCode), addItemObject);
+        }
+        if (addItemObject == null) {
+            addItemObject = FastMap.newInstance();
+            session.setAttribute("itemListings_".concat(siteCode), addItemObject);
+        }
+        return addItemObject;
+    }
+
+    // make ebay category list
+    @SuppressWarnings("unchecked")
+    public static List<CategoryType> getChildCategories(HttpServletRequest request) throws ApiException, SdkException, Exception{
+        List<CategoryType> categories = FastList.newInstance();
+        EbayStoreSiteFacade sf = null;
+        String categoryId = null;
+
+        if (request.getParameter("productStoreId") == null && request.getAttribute("productStoreId") == null) {
+            Debug.logError("Required productStoreId for get ebay LeafCategories.", module);
+            return categories;
+        }
+        if (request.getParameter("categoryId") != null || request.getAttribute("categoryId") != null) {
+            categoryId = (String) request.getParameter("categoryId") != null ? request.getParameter("categoryId") : (String) request.getAttribute("categoryId");
+            Debug.logInfo("Load child categories from session following site id and categoryId is ".concat(categoryId), module);
+        } else {
+            Debug.logWarning("No categoryId to get child categories.", module);
+        }
+
+        ApiContext apiContext = getApiContext(request);
+        sf = getSiteFacade(apiContext,request);
+        if (UtilValidate.isNotEmpty(sf)) {
+            Map<SiteCodeType, List<CategoryType>> csCateMaps = sf.getSiteCategoriesCSMap();
+            List<CategoryType> csCateList = csCateMaps.get(apiContext.getSite());
+            if (UtilValidate.isNotEmpty(csCateList)) {
+                if (UtilValidate.isNotEmpty(categoryId)) {
+                    // find child of selected ebay categories
+                    for (CategoryType csCate : csCateList) {
+                        String[] categoryParentIds = csCate.getCategoryParentID();
+                        for (String categoryParentId : categoryParentIds) {
+                            if (categoryId.equals(categoryParentId)) {
+                                categories.add(csCate);
+                            }
+                        }
+                    }
+                } else {
+                    // find first level of ebay categories
+                    for (CategoryType csCate : csCateList) {
+                        String[] categoryParentIds = csCate.getCategoryParentID();
+                        for (String categoryParentId : categoryParentIds) {
+                            if (csCate.getCategoryID().equals(categoryParentId)) {
+                                categories.add(csCate);
+                            }
+                        }
+                    }
+                }
+                //sort the cats list
+                Collections.sort(categories, new Comparator() {
+                    public int compare(Object a, Object b) {
+                        CategoryType cat1 = (CategoryType)a;
+                        CategoryType cat2 = (CategoryType)b;
+                        int catId1 = Integer.parseInt(cat1.getCategoryID());
+                        int catId2 = Integer.parseInt(cat2.getCategoryID());
+                        return catId1 - catId2;
+                    }
+                });
+            }
+        }
+        return categories;
+    }
+
+    public static CategoryType getCsCategoriesMapped(HttpServletRequest request) throws ApiException, SdkException, Exception{
+        EbayStoreSiteFacade sf = null;
+        String categoryId = null;
+        CategoryType cate = null;
+
+        if (request.getParameter("productStoreId") == null && request.getAttribute("productStoreId") == null) {
+            Debug.logError("Required productStoreId for get ebay LeafCategories.", module);
+            return null;
+        }
+        if (request.getParameter("categoryId") != null || request.getAttribute("categoryId") != null) {
+            categoryId = (String)request.getParameter("categoryId") != null ? request.getParameter("categoryId") : (String)request.getAttribute("categoryId");
+            Debug.logInfo("Load child categories from session following site id and categoryId is ".concat(categoryId), module);
+        } else {
+            Debug.logWarning("No categoryId to get child categories.", module);
+            return null;
+        }
+
+        ApiContext apiContext = getApiContext(request);
+        sf = getSiteFacade(apiContext,request);
+        if (UtilValidate.isNotEmpty(sf)) {
+            Map<SiteCodeType, List<CategoryType>> csCateMaps = sf.getSiteCategoriesCSMap();
+            List<CategoryType> csCateList = csCateMaps.get(apiContext.getSite());
+            if (UtilValidate.isNotEmpty(csCateList)) {
+                if (UtilValidate.isNotEmpty(categoryId)) {
+                    // find child of selected ebay categories
+                    for (CategoryType csCate : csCateList) {
+                        if (csCate.getCategoryID().equals(categoryId)) {
+                            cate = csCate;
+                            break;
+                        }
+                    }
+                }
+            }
+        }
+        return cate;
+    }
+
+    public static String setSelectedEbayCategory(HttpServletRequest request, HttpServletResponse response) {
+        Map<String,Object> requestParams = UtilHttp.getParameterMap(request);
+        Delegator delegator = (Delegator) request.getAttribute("delegator");
+        if (UtilValidate.isEmpty(requestParams.get("productStoreId"))) {
+            request.setAttribute("_ERROR_MESSAGE_","Required productStoreId.");
+            return "error";
+        }
+        if (UtilValidate.isEmpty(requestParams.get("isProductId"))) {
+            request.setAttribute("_ERROR_MESSAGE_","Required can not find form Id.");
+            return "error";
+        }
+        String isProductId = (String) requestParams.get("isProductId");
+        if (UtilValidate.isEmpty(requestParams.get("productId")) || UtilValidate.isEmpty(requestParams.get("ebayCategory"))) {
+            request.setAttribute("_ERROR_MESSAGE_","No ebay category or productId selected with form id ".concat(isProductId));
+            return "error";
+        }
+        String categoryId = (String)requestParams.get("ebayCategory");
+        if (categoryId.contains("false")) {
+            request.setAttribute("_ERROR_MESSAGE_","Please select ebay category with low level of categories.");
+            return "error";
+        } else {
+            if (categoryId.contains("true")) categoryId = categoryId.substring(0,categoryId.indexOf(":"));
+        }
+        String productId = (String) requestParams.get("isProductId");
+        EbayStoreCategoryFacade cf = null;
+        EbayStoreSiteFacade sf = null;
+        // find is exiting product and set category into item in additem call
+        try {
+            if (UtilValidate.isNotEmpty(delegator.findByPrimaryKey("Product", UtilMisc.toMap("productId", productId)))) {
+                ApiContext apiContext = getApiContext(request);
+                Map<String,Object> addItemObject = getAddItemListingObject(request, apiContext);
+                List<Map<String,Object>> addItemlist = (List<Map<String,Object>>) addItemObject.get("itemListing");
+
+                if (UtilValidate.isNotEmpty(addItemlist)) {
+                    for (Map<String,Object> addItemCall : addItemlist) {
+                        AddItemCall itemCall = (AddItemCall) addItemCall.get("addItemCall");
+                        ItemType item = itemCall.getItem();
+                        if (productId.equals(item.getSKU())) {
+                            request.setAttribute("categoryId", categoryId);
+                            CategoryType csCate = getCsCategoriesMapped(request);
+                            if (UtilValidate.isNotEmpty(csCate)) {
+                                Debug.logInfo("Set selected ebay category ".concat(csCate.getCategoryID().toString().concat(csCate.getCategoryName()).concat(String.valueOf((csCate.isLeafCategory())))), module);
+                                item.setPrimaryCategory(csCate);
+                                // get category feature and attributes
+                                sf = getSiteFacade(apiContext, request);
+                                String refName = "itemCateFacade_".concat(csCate.getCategoryID());
+                                if (UtilValidate.isEmpty(addItemObject.get(refName))) {
+                                    cf = new EbayStoreCategoryFacade(csCate.getCategoryID(), apiContext, sf.getAttrMaster(), sf);
+                                    addItemObject.put(refName, cf);
+                                }
+                                request.setAttribute("_EVENT_MESSAGE_","Set selected ebay category ".concat(csCate.getCategoryID().toString()).concat(" with product ".concat(productId).concat(" successed.")));
+                            } else {
+                                Debug.logWarning(categoryId.concat(" This category is not leaf category or ?"), module);
+                            }
+                            break;
+                        }
+                    }
+                }
+            }
+        } catch (GenericEntityException e) {
+            Debug.logError(e.getMessage(), module);
+        } catch (ApiException e) {
+            Debug.logError(e.getMessage(), module);
+        } catch (SdkException e) {
+            Debug.logError(e.getMessage(), module);
+        } catch (Exception e) {
+            Debug.logError(e.getMessage(), module);
+        }
+        request.setAttribute("productStoreId", requestParams.get("productStoreId"));
+        request.setAttribute("isProductId", productId);
+        request.removeAttribute("categoryId");
+        return "success";
+    }
+
+    /* for shipping service detail filter */
+    private static boolean isFlat(ShippingTypeCodeType[] st) {
+        for (int i = 0; i < st.length; i++) {
+            if (st[i].compareTo(ShippingTypeCodeType.FLAT) == 0) {
+                return true;
+            }
+        }
+        return false;
+    }
+
+    public static ShippingServiceDetailsType[] filterShippingService(ShippingServiceDetailsType[] array) {
+        ArrayList<ShippingServiceDetailsType> list = new ArrayList<ShippingServiceDetailsType>();
+        for (int i = 0; i < array.length; i++) {
+            if (isFlat(array[i].getServiceType()) && array[i].getShippingServiceID() < SHIPPING_SERVICE_ID_LIMIT) {
+                list.add(array[i]);
+            }
+        }
+        return list.toArray(new ShippingServiceDetailsType[0]);
+    }
+
+    public static String updateProductExportDetail(HttpServletRequest request, HttpServletResponse response) {
+        Delegator delegator = (Delegator) request.getAttribute("delegator");
+        HttpSession session = request.getSession(true);
+        LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
+        Map<String,Object> requestParams = UtilHttp.getParameterMap(request);
+        Locale locale = UtilHttp.getLocale(request);
+        GenericValue userLogin = (GenericValue) session.getAttribute("userLogin");
+        HashMap attributeMapList = new HashMap();
+        String id = "";
+        if (UtilValidate.isNotEmpty(requestParams.get("listype"))) {
+            if ("auction".equals(requestParams.get("listype"))) {
+                id = "_1";
+            } else {
+                id = "_2";
+            }
+        }
+        String startPrice = "";
+        if (UtilValidate.isNotEmpty(requestParams.get("startPrice".concat(id)))) {
+            startPrice = (String) requestParams.get("startPrice".concat(id));
+        }
+        String buyItNowPrice = "";
+        if (UtilValidate.isNotEmpty(requestParams.get("buyItNowPrice".concat(id)))) {
+            buyItNowPrice = (String) requestParams.get("buyItNowPrice".concat(id));
+        }
+        String productId = null;
+        if (UtilValidate.isNotEmpty(requestParams.get("productId"))) {
+            productId = requestParams.get("productId").toString();
+        }
+
+        String itemPkCateId = (String) requestParams.get("primaryCateId");
+        String shippingService = (String) requestParams.get("ShippingService");
+        String productStoreId = (String) requestParams.get("productStoreId");
+
+        try {
+            ApiContext apiContext = EbayStoreHelper.getApiContext(productStoreId, locale, delegator);
+            Map<String,Object> addItemObject = getAddItemListingObject(request, apiContext);
+            List<Map<String,Object>> listAddItem = null;
+            if (UtilValidate.isNotEmpty(addItemObject.get("itemListing"))) {
+                listAddItem = (List<Map<String,Object>>) addItemObject.get("itemListing");
+            } else {
+                listAddItem = FastList.newInstance();
+            }
+
+            for (Map<String,Object> itemObj : listAddItem) {
+                AddItemCall addItemCall = (AddItemCall) itemObj.get("addItemCall");
+                ItemType item = addItemCall.getItem();
+                String SKU = item.getSKU();
+                if (UtilValidate.isNotEmpty(productId)) {
+                    if (productId.equals(SKU)) {
+
+                        attributeMapList.put("Title", item.getTitle());
+                        attributeMapList.put("SKU", SKU);
+                        attributeMapList.put("Currency", item.getCurrency().value());
+                        attributeMapList.put("Description", item.getDescription());
+                        attributeMapList.put("ApplicationData", item.getApplicationData());
+                        attributeMapList.put("Country", item.getCountry().value());
+                        attributeMapList.put("PictureURL", item.getPictureDetails().getPictureURL(0));
+                        attributeMapList.put("Site", item.getSite().value());
+                        attributeMapList.put("UseTaxTable", "false");
+                        attributeMapList.put("BestOfferEnabled", "true");
+                        attributeMapList.put("AutoPayEnabled", "true");
+                        attributeMapList.put("CategoryID", item.getPrimaryCategory().getCategoryID());
+                        attributeMapList.put("CategoryLevel", item.getPrimaryCategory().getCategoryLevel());
+                        attributeMapList.put("CategoryName", item.getPrimaryCategory().getCategoryName());
+                        attributeMapList.put("CategoryParentID", item.getPrimaryCategory().getCategoryParentID(0).toString());
+                        attributeMapList.put("LeafCategory", "true");
+                        attributeMapList.put("LSD", "true");
+
+                        item.setUseTaxTable(false);
+                        item.setDispatchTimeMax(3);
+                        ReturnPolicyType policy = new ReturnPolicyType();
+                        policy.setReturnsAcceptedOption("ReturnsNotAccepted");
+                        item.setReturnPolicy(policy);
+                        attributeMapList.put("ReturnsAcceptedOption", "ReturnsNotAccepted");
+
+                        String currencyId = "";
+                        if (UtilValidate.isNotEmpty(requestParams.get("currencyId".concat(id)))) {
+                            currencyId = (String) requestParams.get("currencyId".concat(id));
+                        }
+                        if (UtilValidate.isNotEmpty(requestParams.get("enabledTheme")) && "Y".equals(requestParams.get("enabledTheme"))) {
+                            ListingDesignerType designer = new ListingDesignerType();
+                            String layoutId = (String) requestParams.get("themeGroup");
+                            String themeIdImage = (String) requestParams.get("theme");
+                            String themeId = themeIdImage.substring(0, themeIdImage.indexOf(":"));
+                            designer.setLayoutID(Integer.parseInt(layoutId));
+                            designer.setThemeID(Integer.parseInt(themeId));
+                            item.setListingDesigner(designer);
+                            attributeMapList.put("LayoutID", item.getListingDesigner().getLayoutID());
+                            attributeMapList.put("ThemeID", item.getListingDesigner().getThemeID());
+                        }
+                        if ("_1".equals(id)) {
+                            item.setListingType(ListingTypeCodeType.CHINESE);
+                            AmountType amtStart = new AmountType();
+                            amtStart.setCurrencyID(CurrencyCodeType.valueOf(currencyId));
+                            amtStart.setValue(Double.parseDouble(startPrice));
+                            item.setStartPrice(amtStart);
+
+                            AmountType amtBIN = new AmountType();
+                            amtBIN.setCurrencyID(CurrencyCodeType.valueOf(currencyId));
+                            amtBIN.setValue(Double.parseDouble(buyItNowPrice));
+                            item.setBuyItNowPrice(amtBIN);
+                            attributeMapList.put("BuyItNowPrice", item.getBuyItNowPrice().getValue());
+
+                            if (UtilValidate.isNotEmpty(requestParams.get("reservePrice".concat(id)))) {
+                                AmountType amtResv = new AmountType();
+                                amtResv.setCurrencyID(CurrencyCodeType.valueOf(currencyId));
+                                amtResv.setValue(Double.parseDouble(requestParams.get("reservePrice".concat(id)).toString()));
+                                item.setReservePrice(amtResv);
+                                attributeMapList.put("ReservePrice", item.getReservePrice().getValue());
+                            }
+                        } else if ("_2".equals(id)) {
+                            item.setListingType(ListingTypeCodeType.FIXED_PRICE_ITEM);
+                            AmountType amtBIN = new AmountType();
+                            amtBIN.setCurrencyID(CurrencyCodeType.valueOf(currencyId));
+                            amtBIN.setValue(Double.parseDouble(startPrice));
+                            item.setStartPrice(amtBIN);
+                            if (UtilValidate.isNotEmpty(requestParams.get("enableBestOffer".concat(id)))) {
+                                item.setBestOfferEnabled(new Boolean(requestParams.get("enableBestOffer".concat(id)).toString()));
+                            }
+                        }
+                        attributeMapList.put("ListingType", item.getListingType().value());
+                        attributeMapList.put("StartPrice", item.getStartPrice().getValue());
+
+                        EbayStoreHelper.mappedPaymentMethods(requestParams, itemPkCateId, addItemObject, item, attributeMapList);
+
+                        ShippingDetailsType shippingDetail = new ShippingDetailsType();
+                        ShippingServiceOptionsType[] shippingOptions = new ShippingServiceOptionsType[1];
+                        ShippingServiceOptionsType shippingOption = new ShippingServiceOptionsType();
+                        shippingOption.setShippingServicePriority(1);
+                        shippingOption.setShippingService(shippingService);
+                        AmountType amtServiceCost = new AmountType();
+                        amtServiceCost.setValue(5.0);
+                        amtServiceCost.setCurrencyID(CurrencyCodeType.USD);
+                        shippingOption.setShippingServiceCost(amtServiceCost);
+                        shippingOptions[0] = shippingOption;
+                        shippingDetail.setShippingType(ShippingTypeCodeType.FLAT);
+                        shippingDetail.setShippingServiceOptions(shippingOptions);
+                        item.setShippingDetails(shippingDetail);
+                        attributeMapList.put("ShippingService", shippingService);
+                        attributeMapList.put("ShippingServiceCost", ""+5.0);
+                        attributeMapList.put("ShippingServiceCostCurrency", "USD");
+                        attributeMapList.put("ShippingServicePriority", "1");
+                        attributeMapList.put("ShippingType", "Flat");
+                        
+
+                        EbayStoreHelper.mappedShippingLocations(requestParams, item, apiContext, request, attributeMapList);
+
+                        if (UtilValidate.isNotEmpty(requestParams.get("vatPercent".concat(id)))) {
+                            VATDetailsType vat = new VATDetailsType();
+                            vat.setVATPercent(new Float(requestParams.get("vatPercent".concat(id)).toString()));
+                            item.setVATDetails(vat);
+                            attributeMapList.put("VATPercent", vat);
+                        }
+                        if (UtilValidate.isNotEmpty(requestParams.get("location"))) {
+                            item.setLocation(requestParams.get("location").toString());
+                            attributeMapList.put("Location", requestParams.get("location").toString());
+                        }
+                        if (UtilValidate.isNotEmpty(requestParams.get("quantity".concat(id)))) {
+                            item.setQuantity(Integer.parseInt(requestParams.get("quantity".concat(id)).toString()));
+                            attributeMapList.put("Quantity", requestParams.get("quantity".concat(id)).toString());
+                        }
+                        if (UtilValidate.isNotEmpty(requestParams.get("duration".concat(id)))) {
+                             item.setListingDuration(requestParams.get("duration".concat(id)).toString());
+                             attributeMapList.put("ListingDuration", requestParams.get("duration".concat(id)).toString());
+                        }
+                        if (UtilValidate.isNotEmpty(requestParams.get("lotsize".concat(id)))) {
+                            item.setLotSize(Integer.parseInt(requestParams.get("lotsize".concat(id)).toString()));
+                            attributeMapList.put("LotSize", requestParams.get("lotsize".concat(id)).toString());
+                        }
+                        if (UtilValidate.isNotEmpty(requestParams.get("postalCode".concat(id)))) {
+                            item.setPostalCode(requestParams.get("postalCode".concat(id)).toString());
+                            attributeMapList.put("PostalCode", requestParams.get("postalCode".concat(id)).toString());
+                        }
+                        addItemCall.setItem(item);
+                        
+                        // create/update EbayProductListing entity
+                        Map<String, Object> prodMap = FastMap.newInstance();
+                        prodMap.put("productStoreId", productStoreId);
+                        prodMap.put("productId", productId);
+                        prodMap.put("userLogin", userLogin);
+                        if (UtilValidate.isNotEmpty(requestParams.get("isAutoRelist"))) {
+                            prodMap.put("autoRelisting", "Y");
+                            itemObj.put("isAutoRelist", "Y");
+                        }
+                        try {
+                            GenericValue storeRole = EntityUtil.getFirst(delegator.findByAnd("ProductStoreRole", UtilMisc.toMap("productStoreId", productStoreId, "roleTypeId", "EBAY_ACCOUNT")));
+                            if (UtilValidate.isNotEmpty(storeRole)) {
+                                List<GenericValue> ebayUserLoginList = delegator.findByAnd("UserLogin", UtilMisc.toMap("partyId", storeRole.get("partyId")));
+                                if (ebayUserLoginList.size() > 0) {
+                                    GenericValue eBayUserLogin = EntityUtil.getFirst(ebayUserLoginList);
+                                    if (UtilValidate.isNotEmpty(eBayUserLogin)) {
+                                        prodMap.put("userLoginId", eBayUserLogin.get("userLoginId").toString());
+                                    }
+                                }
+                            }
+                        } catch (GenericEntityException ex) {
+                            Debug.logError(ex.getMessage(), module);
+                            return "error";
+                        }
+                        String productListingId = null;
+                        if (UtilValidate.isEmpty(itemObj.get("productListingId"))) {
+                            try {
+                                prodMap.put("statusId", "ITEM_CREATED");
+                                Map<String, Object> result = dispatcher.runSync("createEbayProductListing", prodMap);
+                                productListingId = result.get("productListingId").toString();
+                                itemObj.put("productListingId", productListingId);
+                                itemObj.put("isSaved", "Y");
+                            } catch (GenericServiceException ex) {
+                                Debug.logError(ex.getMessage(), module);
+                                return "error";
+                            }
+                        } else {
+                            productListingId = itemObj.get("productListingId").toString();
+                            prodMap.put("productListingId", productListingId);
+                            try {
+                                dispatcher.runSync("updateEbayProductListing", prodMap);
+                            } catch (GenericServiceException ex) {
+                                Debug.logError(ex.getMessage(), module);
+                                return "error";
+                            }
+                        }
+
+                        // create/update EbayProductListingAttribute
+                        if (UtilValidate.isNotEmpty(productListingId)) {
+                            attributeMapList.put("productListingId", productListingId);
+                            Map<String, Object> ebayProdAttrMap = FastMap.newInstance();
+                            ebayProdAttrMap.put("productListingId", productListingId);
+                            ebayProdAttrMap.put("userLogin", userLogin);
+                            ebayProdAttrMap.put("attributeMapList", attributeMapList);
+                            try {
+                                dispatcher.runSync("setEbayProductListingAttribute", ebayProdAttrMap);
+                            } catch (GenericServiceException ex) {
+                                Debug.logError(ex.getMessage(), module);
+                                return "error";
+                            }
+                        }
+                    }
+                }
+            }
+            request.setAttribute("productStoreId", requestParams.get("productStoreId"));
+        } catch(Exception e) {
+            Debug.logError(e.getMessage(), module);
+            return "error";
+        }
+        return "success";
+    }
+
+    public static String verifyItemBeforeAdd(HttpServletRequest request, HttpServletResponse response) {
+        Delegator delegator = (Delegator) request.getAttribute("delegator");
+        Map<String,Object> requestParams = UtilHttp.getParameterMap(request);
+        Locale locale = UtilHttp.getLocale(request);
+        String productStoreId = (String) requestParams.get("productStoreId");
+
+        try {
+            ApiContext apiContext = EbayStoreHelper.getApiContext(productStoreId, locale, delegator);
+            VerifyAddItemRequestType req = new VerifyAddItemRequestType();
+            VerifyAddItemResponseType resp = null;
+
+            VerifyAddItemCall verifyCall = new VerifyAddItemCall(apiContext);
+            Map<String,Object> addItemObject = getAddItemListingObject(request, apiContext);
+            List<Map<String,Object>> listAddItem = null;
+            if (UtilValidate.isNotEmpty(addItemObject.get("itemListing"))) {
+                listAddItem = (List<Map<String,Object>>) addItemObject.get("itemListing");
+            } else {
+                listAddItem = FastList.newInstance();
+            }
+            double feesummary = 0.0;
+            for (Map<String,Object> itemObj : listAddItem) {
+                AddItemCall addItemCall = (AddItemCall) itemObj.get("addItemCall");
+                ItemType item = addItemCall.getItem();
+                String SKU = item.getSKU();
+                if (UtilValidate.isNotEmpty(requestParams.get("productId"))) {
+                    String productId = requestParams.get("productId").toString();
+                    if (productId.equals(SKU)) {
+                        req.setItem(item);
+                        resp = (VerifyAddItemResponseType) verifyCall.execute(req);
+                        if (resp != null && "SUCCESS".equals(resp.getAck().toString())) {
+                            itemObj.put("isVerify", "Y");
+                            FeesType feest = (FeesType) resp.getFees();
+                            FeeType[] fees = feest.getFee();
+                            for (FeeType fee : fees) {
+                                double dfee = fee.getFee().getValue();
+                                feesummary = feesummary + dfee;
+                            }
+                        }
+                    }
+                }
+            }
+            request.setAttribute("itemFee", feesummary);
+            request.setAttribute("productStoreId", requestParams.get("productStoreId"));
+            
+        } catch (Exception e) {
+            Debug.logError(e.getMessage(), module);
+            return "error";
+        }
+        return "success";
+    }
+
+    public static String removeProductFromListing(HttpServletRequest request, HttpServletResponse response) {
+        Delegator delegator = (Delegator) request.getAttribute("delegator");
+        Map<String,Object> requestParams = UtilHttp.getParameterMap(request);
+        Locale locale = UtilHttp.getLocale(request);
+        String productStoreId = (String) requestParams.get("productStoreId");
+        try {
+            ApiContext apiContext = EbayStoreHelper.getApiContext(productStoreId, locale, delegator);
+            Map<String,Object> addItemObject = getAddItemListingObject(request, apiContext);
+            List<Map<String,Object>> listAddItem = null;
+            if (UtilValidate.isNotEmpty(addItemObject.get("itemListing"))) {
+                listAddItem = (List<Map<String,Object>>) addItemObject.get("itemListing");
+            } else {
+                listAddItem = FastList.newInstance();
+            }
+            int i = 0;
+            for (Map<String,Object> itemObj : listAddItem) {
+                AddItemCall addItemCall = (AddItemCall) itemObj.get("addItemCall");
+                ItemType item = addItemCall.getItem();
+                String SKU = item.getSKU();
+                if (UtilValidate.isNotEmpty(requestParams.get("productId"))) {
+                    String productId = requestParams.get("productId").toString();
+                    if (productId.equals(SKU)) {
+                        listAddItem.remove(i);
+                    }
+                }
+                i++;
+            }
+            request.setAttribute("productStoreId", requestParams.get("productStoreId"));
+        } catch (Exception e) {
+            Debug.logError(e.getMessage(), module);
+            return "error";
+        }
+        return "success";
+    }
+
+    public static String exportListingToEbay(HttpServletRequest request, HttpServletResponse response) {
+        LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
+        Delegator delegator = (Delegator) request.getAttribute("delegator");
+        Map<String,Object> requestParams = UtilHttp.getParameterMap(request);
+        Locale locale = UtilHttp.getLocale(request);
+        String productStoreId = (String) requestParams.get("productStoreId");
+        try {
+            ApiContext apiContext = EbayStoreHelper.getApiContext(productStoreId, locale, delegator);
+            Map<String,Object> addItemObject = getAddItemListingObject(request, apiContext);
+            List<Map<String,Object>> listAddItem = null;
+            if (UtilValidate.isNotEmpty(addItemObject.get("itemListing"))) {
+                listAddItem = (List<Map<String,Object>>) addItemObject.get("itemListing");
+            } else {
+                listAddItem = FastList.newInstance();
+            }
+            for (Map<String,Object> itemObj : listAddItem) {
+                dispatcher.runSync("exportProductEachItem", UtilMisc.toMap("itemObject", itemObj));
+            }
+        } catch (Exception e) {
+            Debug.logError(e.getMessage(), module);
+            return "error";
+        }
+        return "success";
+    }
 }
\ No newline at end of file

Added: ofbiz/trunk/specialpurpose/ebaystore/src/org/ofbiz/ebaystore/EbayStoreCategoryFacade.java
URL: http://svn.apache.org/viewvc/ofbiz/trunk/specialpurpose/ebaystore/src/org/ofbiz/ebaystore/EbayStoreCategoryFacade.java?rev=923223&view=auto
==============================================================================
--- ofbiz/trunk/specialpurpose/ebaystore/src/org/ofbiz/ebaystore/EbayStoreCategoryFacade.java (added)
+++ ofbiz/trunk/specialpurpose/ebaystore/src/org/ofbiz/ebaystore/EbayStoreCategoryFacade.java Mon Mar 15 13:44:53 2010
@@ -0,0 +1,346 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.ofbiz.ebaystore;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+
+import org.ofbiz.base.util.Debug;
+import org.ofbiz.base.util.UtilValidate;
+
+import javolution.util.FastList;
+import javolution.util.FastMap;
+import com.ebay.sdk.ApiContext;
+import com.ebay.sdk.ApiException;
+import com.ebay.sdk.SdkException;
+import com.ebay.sdk.SdkSoapException;
+import com.ebay.sdk.attributes.model.AttributeSet;
+import com.ebay.sdk.attributes.model.IAttributesMaster;
+import com.ebay.sdk.call.GetCategorySpecificsCall;
+import com.ebay.sdk.call.GetDescriptionTemplatesCall;
+import com.ebay.soap.eBLBaseComponents.BestOfferEnabledDefinitionType;
+import com.ebay.soap.eBLBaseComponents.BuyerPaymentMethodCodeType;
+import com.ebay.soap.eBLBaseComponents.CategoryFeatureType;
+import com.ebay.soap.eBLBaseComponents.CategoryType;
+import com.ebay.soap.eBLBaseComponents.DescriptionTemplateType;
+import com.ebay.soap.eBLBaseComponents.DetailLevelCodeType;
+import com.ebay.soap.eBLBaseComponents.FeatureDefinitionsType;
+import com.ebay.soap.eBLBaseComponents.GetDescriptionTemplatesRequestType;
+import com.ebay.soap.eBLBaseComponents.GetDescriptionTemplatesResponseType;
+import com.ebay.soap.eBLBaseComponents.ItemSpecificsEnabledCodeType;
+import com.ebay.soap.eBLBaseComponents.ListingDurationDefinitionType;
+import com.ebay.soap.eBLBaseComponents.ListingDurationDefinitionsType;
+import com.ebay.soap.eBLBaseComponents.ListingDurationReferenceType;
+import com.ebay.soap.eBLBaseComponents.ListingTypeCodeType;
+import com.ebay.soap.eBLBaseComponents.NameRecommendationType;
+import com.ebay.soap.eBLBaseComponents.RecommendationsType;
+import com.ebay.soap.eBLBaseComponents.SiteDefaultsType;
+import com.ebay.soap.eBLBaseComponents.StoreOwnerExtendedListingDurationsType;
+import com.ebay.soap.eBLBaseComponents.ThemeGroupType;
+
+public class EbayStoreCategoryFacade {
+    public static final String module = EbayStoreCategoryFacade.class.getName();
+    private ApiContext apiContext = null;
+    private String catId = null;
+    private IAttributesMaster attrMaster = null;
+    private EbayStoreSiteFacade siteFacade = null;
+
+    private AttributeSet[] joinedAttrSets = null;
+    private ItemSpecificsEnabledCodeType itemSpecificEnabled = null;
+    private Boolean retPolicyEnabled = null;
+    private Map<Integer,String[]> listingDurationMap = null;
+    private Map<String,Integer> listingDurationReferenceMap = null;
+    private BuyerPaymentMethodCodeType[] paymentMethods = null;
+    private NameRecommendationType[] nameRecommendationTypes = null;
+    private StoreOwnerExtendedListingDurationsType storeOwnerExtendedListingDuration = null;
+    private BestOfferEnabledDefinitionType bestOfferEnabled = null;
+    private List<Map<String,Object>> adItemTemplates = null;
+
+    public EbayStoreCategoryFacade(String catId, ApiContext apiContext, IAttributesMaster attrMaster, EbayStoreSiteFacade siteFacade) throws SdkException, Exception {
+        this.catId = catId;
+        this.apiContext = apiContext;
+        this.attrMaster = attrMaster;
+        this.siteFacade = siteFacade;
+        this.syncCategoryMetaData();
+    }
+
+    private void syncCategoryMetaData() throws SdkException, Exception {
+        syncJoinedAttrSets();
+        syncCategoryFeatures();
+        syncNameRecommendationTypes();
+        syncAdItemTemplates();
+    }
+
+    private void syncJoinedAttrSets() throws SdkException, Exception {
+        int[] ids = new int[1];
+        ids[0] = Integer.parseInt(this.getCatId());
+        AttributeSet[] itemSpecAttrSets = attrMaster.getItemSpecificAttributeSetsForCategories(ids);
+        AttributeSet[] siteWideAttrSets = attrMaster.getSiteWideAttributeSetsForCategories(ids);
+        AttributeSet[] joinedAttrSets = attrMaster.joinItemSpecificAndSiteWideAttributeSets(itemSpecAttrSets, siteWideAttrSets);
+        this.joinedAttrSets = joinedAttrSets;
+    }
+
+    private void syncNameRecommendationTypes() throws ApiException, SdkException, Exception {
+        GetCategorySpecificsCall getCatSpe = new GetCategorySpecificsCall(apiContext);
+        getCatSpe.setCategoryID(new String[]{this.catId});
+        DetailLevelCodeType[] detailLevels = new DetailLevelCodeType[] {DetailLevelCodeType.RETURN_ALL};
+        getCatSpe.setDetailLevel(detailLevels);
+        RecommendationsType[] recommendationsArray = getCatSpe.getCategorySpecifics();
+        if (recommendationsArray == null || recommendationsArray.length == 0)
+            return;
+        RecommendationsType recommendations = recommendationsArray[0];
+        this.nameRecommendationTypes = recommendations.getNameRecommendation();
+    }
+
+    public void syncCategoryFeatures() throws Exception {
+        Map<String, CategoryType> categoriesCacheMap = this.siteFacade.getSiteCategoriesMap().get(apiContext.getSite());
+
+        Map<String, CategoryFeatureType> cfsMap = this.siteFacade.getSiteCategoriesFeaturesMap().get(apiContext.getSite());
+        SiteDefaultsType siteDefaults = this.siteFacade.getSiteFeatureDefaultMap().get(apiContext.getSite());
+        FeatureDefinitionsType featureDefinition = this.siteFacade.getSiteFeatureDefinitionsMap().get(apiContext.getSite());
+
+        //get itemSpecificsEnabled feature
+        itemSpecificEnabled = (ItemSpecificsEnabledCodeType)getInheritProperty(catId, "getItemSpecificsEnabled", categoriesCacheMap, cfsMap);
+        if (itemSpecificEnabled == null) {
+            itemSpecificEnabled = siteDefaults.getItemSpecificsEnabled();
+        }
+        //get returnPolicyEnabled feature
+        retPolicyEnabled = (Boolean)getInheritProperty(catId, "isReturnPolicyEnabled", categoriesCacheMap, cfsMap);
+        if (retPolicyEnabled == null) {
+            retPolicyEnabled = siteDefaults.isReturnPolicyEnabled();
+        }
+
+        //get listing durations
+        ListingDurationDefinitionsType listDuration = featureDefinition.getListingDurations();
+        ListingDurationDefinitionType[] durationArray = listDuration.getListingDuration();
+        listingDurationMap = FastMap.newInstance();
+        for (int i = 0; i < durationArray.length; i++) {
+            listingDurationMap.put(durationArray[i].getDurationSetID(), durationArray[i].getDuration());
+        }
+
+        //get listing types
+        ListingDurationReferenceType[] listingDuration = (ListingDurationReferenceType[])getInheritProperty(catId, "getListingDuration", categoriesCacheMap, cfsMap);
+        if (listingDuration == null || listingDuration.length == 0) {
+            listingDuration = siteDefaults.getListingDuration();
+        }
+        listingDurationReferenceMap = FastMap.newInstance();
+        for (int i = 0; i < listingDuration.length; i++) {
+            listingDurationReferenceMap.put(listingDuration[i].getType().value(),listingDuration[i].getValue());
+        }
+
+        //get payment methods
+        paymentMethods = (BuyerPaymentMethodCodeType[])getInheritProperty(catId, "getPaymentMethod", categoriesCacheMap, cfsMap);
+        if (paymentMethods == null || paymentMethods.length == 0) {
+            paymentMethods = siteDefaults.getPaymentMethod();
+        }
+
+        //fix 'invalid enum' issue
+        paymentMethods = fiterPaymentMethod(paymentMethods);
+
+        storeOwnerExtendedListingDuration = siteDefaults.getStoreOwnerExtendedListingDurations();
+
+        bestOfferEnabled = featureDefinition.getBestOfferEnabled();
+    }
+
+    //remove all 'null' code type
+    private static BuyerPaymentMethodCodeType[] fiterPaymentMethod(BuyerPaymentMethodCodeType[] paymentMethods) {
+        ArrayList<BuyerPaymentMethodCodeType> al = new ArrayList<BuyerPaymentMethodCodeType>();
+        for (BuyerPaymentMethodCodeType pm : paymentMethods) {
+            if (pm != null) {
+                al.add(pm);
+            }
+        }
+        return (BuyerPaymentMethodCodeType[])al.toArray(new BuyerPaymentMethodCodeType[0]);
+    }
+
+    /**
+     * recursively check the parent category to find out category feature
+     * @param catId categoryID to be retrieved
+     * @param methodName method name to be invoked
+     * @param categoriesCacheMap cache of all the categories
+     * @param cfsMap category features map
+     * @return generic Object
+     * @throws Exception
+     */
+    private Object getInheritProperty(String catId,String methodName,
+            Map<String, CategoryType> categoriesCacheMap, Map<String, CategoryFeatureType> cfsMap) throws Exception {
+        if (cfsMap.containsKey(catId)) {
+            CategoryFeatureType cf = cfsMap.get(catId);
+            // invoke the method indicated by methodName
+            Object returnValue = invokeMethodByName(cf, methodName);
+            if (returnValue != null) {
+                return returnValue;
+            }
+        }
+
+        CategoryType cat = categoriesCacheMap.get(catId);
+        //if we reach top level, return null
+        if (cat.getCategoryLevel() == 1) {
+            return null;
+        }
+
+        //check parent category
+        return getInheritProperty(cat.getCategoryParentID(0), methodName, categoriesCacheMap, cfsMap);
+    }
+
+    /**
+     * invoke the method specified by methodName and return the corresponding return value
+     * @param cf CategoryFeatureType
+     * @param methodName String
+     * @return generic object
+     */
+    private Object invokeMethodByName(CategoryFeatureType cf, String methodName) {
+        java.lang.reflect.Method m = null;
+        try {
+            m = cf.getClass().getMethod(methodName);
+            if (m != null) {
+                return m.invoke(cf);
+            }
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+        return null;
+    }
+
+    public List<Map<String,Object>> syncAdItemTemplates() throws ApiException, SdkSoapException, SdkException {
+        GetDescriptionTemplatesRequestType req = null;
+        GetDescriptionTemplatesResponseType resp = null;
+        List<Map<String,Object>> temGroupList = FastList.newInstance();
+
+        GetDescriptionTemplatesCall call = new GetDescriptionTemplatesCall(this.apiContext);
+        req = new GetDescriptionTemplatesRequestType();
+        req.setCategoryID(this.catId);
+        resp = (GetDescriptionTemplatesResponseType) call.execute(req);
+        if (resp != null && "SUCCESS".equals(resp.getAck().toString())) {
+            DescriptionTemplateType[] descriptionTemplateTypeList = resp.getDescriptionTemplate();
+            Debug.log("layout of category "+ this.catId +":"+ resp.getLayoutTotal());
+            for (DescriptionTemplateType descTemplateType : descriptionTemplateTypeList) {
+                List<Map<String,Object>> templateList = null;
+                Map<String,Object> templateGroup = null;
+                if ("THEME".equals(String.valueOf(descTemplateType.getType()))) {
+                    Map<String,Object> template = FastMap.newInstance();
+                    template.put("TemplateId", String.valueOf(descTemplateType.getID()));
+                    template.put("TemplateImageURL", descTemplateType.getImageURL());
+                    template.put("TemplateName", descTemplateType.getName());
+                    template.put("TemplateType", descTemplateType.getType());
+
+                    // check group template by groupId
+                    for (Map<String,Object> temGroup : temGroupList) {
+                        if (temGroup.get("TemplateGroupId").equals(descTemplateType.getGroupID().toString())) {
+                            templateGroup = temGroup;
+                            break;
+                        }
+                    }
+                    if (templateGroup == null) {
+                        templateGroup = FastMap.newInstance();
+                        templateList = FastList.newInstance();
+                        templateGroup.put("TemplateGroupId", descTemplateType.getGroupID().toString());
+                        templateList.add(template);
+                        templateGroup.put("Templates", templateList);
+                        temGroupList.add(templateGroup);
+                    } else {
+                        if (templateGroup.get("Templates") != null) {
+                            templateList = (List<Map<String,Object>>) templateGroup.get("Templates");
+                            templateList.add(template);
+                        }
+                    }
+                } else if ("Layout".equals(String.valueOf(descTemplateType.getType()))) {
+                }
+            }
+            ThemeGroupType[] themes = resp.getThemeGroup();
+            if (themes != null && temGroupList != null) {
+                for (Map<String,Object> temGroup : temGroupList) {
+                    for (ThemeGroupType theme : themes) {
+                        if (theme.getGroupID() == Integer.parseInt(temGroup.get("TemplateGroupId").toString())) {
+                            if (theme != null) temGroup.put("TemplateGroupName", theme.getGroupName());
+                            break;
+                        } else {
+                            if (theme != null) temGroup.put("TemplateGroupName", "_NA_");
+                        }
+                    }
+                }
+            }
+        }
+        return adItemTemplates = temGroupList;
+    }
+
+    public List<Map<String,Object>> getAdItemTemplates(String temGroupId) {
+        List<Map<String,Object>> themes = FastList.newInstance();
+        for (Map<String,Object> temp : this.adItemTemplates) {
+            if (temp.get("TemplateGroupId").equals(temGroupId)) {
+                themes = (List<Map<String,Object>>) temp.get("Templates");
+                break;
+            }
+        }
+        return themes;
+    }
+
+    public String getCatId() {
+        return catId;
+    }
+
+    public void setCatId(String catId) {
+        this.catId = catId;
+    }
+
+    public AttributeSet[] getJoinedAttrSets() {
+        return joinedAttrSets;
+    }
+
+    public ItemSpecificsEnabledCodeType getItemSpecificEnabled() {
+        return itemSpecificEnabled;
+    }
+
+    public Boolean getRetPolicyEnabled() {
+        return retPolicyEnabled;
+    }
+
+    public Map<Integer, String[]> getListingDurationMap() {
+        return listingDurationMap;
+    }
+
+    public Map<String, Integer> getListingDurationReferenceMap() {
+        return listingDurationReferenceMap;
+    }
+
+    public BuyerPaymentMethodCodeType[] getPaymentMethods() {
+        return paymentMethods;
+    }
+
+    public NameRecommendationType[] getNameRecommendationTypes() {
+        return nameRecommendationTypes;
+    }
+
+    public boolean AttributesEnabled() {
+        return this.joinedAttrSets != null && this.joinedAttrSets.length > 0;
+    }
+
+    public StoreOwnerExtendedListingDurationsType getStoreOwnerExtendedListingDuration() {
+        return this.storeOwnerExtendedListingDuration;
+    }
+
+    public BestOfferEnabledDefinitionType getbestOfferEnabled() {
+        return this.bestOfferEnabled;
+    }
+
+    public List<Map<String,Object>> getAdItemTemplates() {
+        return this.adItemTemplates;
+    }
+}
\ No newline at end of file

Modified: ofbiz/trunk/specialpurpose/ebaystore/src/org/ofbiz/ebaystore/EbayStoreHelper.java
URL: http://svn.apache.org/viewvc/ofbiz/trunk/specialpurpose/ebaystore/src/org/ofbiz/ebaystore/EbayStoreHelper.java?rev=923223&r1=923222&r2=923223&view=diff
==============================================================================
--- ofbiz/trunk/specialpurpose/ebaystore/src/org/ofbiz/ebaystore/EbayStoreHelper.java (original)
+++ ofbiz/trunk/specialpurpose/ebaystore/src/org/ofbiz/ebaystore/EbayStoreHelper.java Mon Mar 15 13:44:53 2010
@@ -24,6 +24,11 @@ import java.util.Date;
 import java.util.List;
 import java.util.Locale;
 import java.util.Map;
+import java.util.HashMap;
+import java.util.Set;
+import java.util.Iterator;
+
+import javax.servlet.http.HttpServletRequest;
 
 import javolution.util.FastMap;
 
@@ -49,7 +54,14 @@ import com.ebay.sdk.ApiAccount;
 import com.ebay.sdk.ApiContext;
 import com.ebay.sdk.ApiCredential;
 import com.ebay.sdk.ApiLogging;
+import com.ebay.sdk.call.AddItemCall;
+import com.ebay.soap.eBLBaseComponents.AddItemRequestType;
+import com.ebay.soap.eBLBaseComponents.AddItemResponseType;
+import com.ebay.soap.eBLBaseComponents.BuyerPaymentMethodCodeType;
+import com.ebay.soap.eBLBaseComponents.GeteBayDetailsResponseType;
+import com.ebay.soap.eBLBaseComponents.ItemType;
 import com.ebay.soap.eBLBaseComponents.SiteCodeType;
+import com.ebay.soap.eBLBaseComponents.ShippingLocationDetailsType;
 
 import org.ofbiz.ebay.EbayHelper;
 
@@ -333,4 +345,133 @@ public class EbayStoreHelper {
         }
         return result;
     }
+
+    public static void mappedPaymentMethods(Map requestParams, String itemPkCateId, Map<String,Object> addItemObject, ItemType item, HashMap attributeMapList) {
+        String refName = "itemCateFacade_"+itemPkCateId;
+        if (UtilValidate.isNotEmpty(addItemObject) && UtilValidate.isNotEmpty(requestParams)) {
+            EbayStoreCategoryFacade cf = (EbayStoreCategoryFacade) addItemObject.get(refName);
+            BuyerPaymentMethodCodeType[] paymentMethods = cf.getPaymentMethods();
+            if (UtilValidate.isNotEmpty(paymentMethods)) {
+                BuyerPaymentMethodCodeType[] tempPayments = new BuyerPaymentMethodCodeType[paymentMethods.length];
+                int i = 0;
+                for (BuyerPaymentMethodCodeType paymentMethod : paymentMethods) {
+                    String pmName = paymentMethod.value();
+                    String payPara = (String) requestParams.get("Payments_".concat(pmName));
+                    if ("true".equals(payPara)) {
+                        tempPayments[i] = paymentMethod;
+                        attributeMapList.put(""+pmName, pmName);
+                        if ("PayPal".equals(pmName)) {
+                            if (UtilValidate.isNotEmpty(requestParams.get("paymentMethodPaypalEmail"))) {
+                                item.setPayPalEmailAddress(requestParams.get("paymentMethodPaypalEmail").toString());
+                                attributeMapList.put("PaypalEmail", requestParams.get("paymentMethodPaypalEmail").toString());
+                            }
+                        }
+                        i++;
+                    }
+                }
+                item.setPaymentMethods(tempPayments);
+            }
+        }
+    }
+
+    public static void mappedShippingLocations(Map requestParams, ItemType item, ApiContext apiContext, HttpServletRequest request, HashMap attributeMapList) {
+        try {
+            if (UtilValidate.isNotEmpty(requestParams)) {
+                EbayStoreSiteFacade sf = (EbayStoreSiteFacade) EbayEvents.getSiteFacade(apiContext, request);
+                Map<SiteCodeType, GeteBayDetailsResponseType> eBayDetailsMap = sf.getEBayDetailsMap();
+                GeteBayDetailsResponseType eBayDetails = eBayDetailsMap.get(apiContext.getSite());
+                ShippingLocationDetailsType[] shippingLocationDetails = eBayDetails.getShippingLocationDetails();
+                if (UtilValidate.isNotEmpty(shippingLocationDetails)) {
+                    int i = 0;
+                    String[] tempShipLocation = new String[shippingLocationDetails.length];
+                    for (ShippingLocationDetailsType shippingLocationDetail : shippingLocationDetails) {
+                        String shippingLocation = (String) shippingLocationDetail.getShippingLocation();
+                        String shipParam = (String)requestParams.get("Shipping_".concat(shippingLocation));
+                        if ("true".equals(shipParam)) {
+                            tempShipLocation[i] = shippingLocation;
+                            attributeMapList.put(""+shippingLocation, shippingLocation);
+                            i++;
+                        }
+                    }
+                    item.setShipToLocations(tempShipLocation);
+                }
+            }
+        } catch(Exception e) {
+            Debug.logError(e.getMessage(), module);
+        }
+    }
+
+    public static Map<String, Object> exportProductEachItem(DispatchContext dctx, Map<String, Object> context) {
+        Map<String,Object> result = FastMap.newInstance();
+        LocalDispatcher dispatcher = (LocalDispatcher) dctx.getDispatcher();
+        Delegator delegator = dctx.getDelegator();
+        Map<String, Object> itemObject = (Map<String, Object>) context.get("itemObject");
+        String productListingId = itemObject.get("productListingId").toString();
+        AddItemCall addItemCall = (AddItemCall) itemObject.get("addItemCall");
+        AddItemRequestType req = new AddItemRequestType();
+        AddItemResponseType resp = null;
+        try {
+            GenericValue userLogin = delegator.findByPrimaryKey("UserLogin", UtilMisc.toMap("userLoginId", "system"));
+            ItemType item = addItemCall.getItem();
+            req.setItem(item);
+            resp = (AddItemResponseType) addItemCall.execute(req);
+            if (resp != null && "SUCCESS".equals(resp.getAck().toString()) || "WARNING".equals(resp.getAck().toString())) {
+                String itemId = resp.getItemID();
+                String listingXml = addItemCall.getRequestXml().toString();
+                Map<String, Object> updateItemMap = FastMap.newInstance();
+                updateItemMap.put("productListingId", productListingId);
+                updateItemMap.put("itemId", itemId);
+                updateItemMap.put("listingXml", listingXml);
+                updateItemMap.put("statusId", "ITEM_APPROVED");
+                updateItemMap.put("userLogin", userLogin);
+                try {
+                    dispatcher.runSync("updateEbayProductListing", updateItemMap);
+                } catch (GenericServiceException ex) {
+                    Debug.logError(ex.getMessage(), module);
+                    return ServiceUtil.returnError(ex.getMessage());
+                }
+            }
+            result = ServiceUtil.returnSuccess();
+        } catch (Exception e) {
+            return ServiceUtil.returnError(e.getMessage());
+        }
+        return result;
+    }
+
+    public static Map<String, Object> setEbayProductListingAttribute(DispatchContext dctx, Map<String, Object> context) {
+        Map<String, Object>result = FastMap.newInstance();
+        LocalDispatcher dispatcher = dctx.getDispatcher();
+        GenericValue userLogin = (GenericValue) context.get("userLogin");
+        Delegator delegator = dctx.getDelegator();
+        Locale locale = (Locale) context.get("locale");
+        HashMap attributeMapList = (HashMap) context.get("attributeMapList");
+        String productListingId = (String) context.get("productListingId");
+        try {
+           List<GenericValue> attributeToClears = delegator.findByAnd("EbayProductListingAttribute", UtilMisc.toMap("productListingId", productListingId));
+           for (int clearCount = 0; clearCount < attributeToClears.size(); clearCount++) {
+              GenericValue valueToClear = attributeToClears.get(clearCount);
+              if (valueToClear != null) {
+                 valueToClear.remove();
+              }
+           }
+           Set attributeSet = attributeMapList.entrySet();
+           Iterator itr = attributeSet.iterator();
+           while (itr.hasNext()) {
+             Map.Entry attrMap = (Map.Entry) itr.next();
+
+             if (UtilValidate.isNotEmpty(attrMap.getKey())) {
+                 GenericValue ebayProductListingAttribute = delegator.makeValue("EbayProductListingAttribute");
+                  ebayProductListingAttribute.set("productListingId", productListingId);
+                  ebayProductListingAttribute.set("attrName", attrMap.getKey().toString());
+                  ebayProductListingAttribute.set("attrValue", attrMap.getValue().toString());
+                  ebayProductListingAttribute.create();
+              }
+           }
+        } catch (GenericEntityException e) {
+            return ServiceUtil.returnError(e.getMessage());
+        }
+        return ServiceUtil.returnSuccess();
+    }
+
+
 }