diff --git a/googlebase/config/GoogleBaseUiLabels.xml b/googlebase/config/GoogleBaseUiLabels.xml index 031a30811..75abf53c0 100644 --- a/googlebase/config/GoogleBaseUiLabels.xml +++ b/googlebase/config/GoogleBaseUiLabels.xml @@ -72,6 +72,10 @@ ฐานข้อมูลสาธารณะทั้งหมด Google Base集成 + + Auto Update Options + อัพเดทแบบอัตโนมัติ + Ofbiz Ofbiz @@ -176,6 +180,10 @@ คุณไม่มีการอนุญาตให้แสดงหน้านี้. ("GOOGLEBASE_VIEW" ต้องการ) 你没有浏览这个页面的权限(需要GOOGLEBASE_VIEW)。 + + Allow Google Base Recommended + อนุญาติให้เพิ่มฟิลด์ที่แนะนำ + Export Products to Google Base Exporter les articles vers Google Base diff --git a/googlebase/config/autoUpdateToGoogleBase.properties b/googlebase/config/autoUpdateToGoogleBase.properties new file mode 100644 index 000000000..1c7fefe88 --- /dev/null +++ b/googlebase/config/autoUpdateToGoogleBase.properties @@ -0,0 +1,63 @@ +############################################################################### +# 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. +############################################################################### +#### +# OFBiz Auto Update To Google Base Setting +#### +# Google Base Configuration + +# separate each value by comma(',') with no space and setting of each productStore are ordered from left to right. +# for example: +# autoUpdateGoogleBase.productStoreId=9000,9001 +# autoUpdateGoogleBase.productStore.option.outOfStock=Y,N +# autoUpdateGoogleBase.productStore.option.backInStock=N,Y +# it means productStoreId:9000 has outOfStock option:Y and backInStock option:N +# and productStoreId:9001 has outOfStock option:N and backInStock option:Y +autoUpdateGoogleBase.productStoreId=9000 + +# productStore.option.outOfStock +# default value: "Y" +autoUpdateGoogleBase.productStore.option.outOfStock=Y +# productStore.option.backIntoStock +# default value: "Y" +autoUpdateGoogleBase.productStore.option.backInStock=Y + +# productStore.webSiteUrl of productStore; if null, it will get from standardContentPrefix field of WebSite entity +# default value: http://demo.ofbiz.org +autoUpdateGoogleBase.productStore.webSiteUrl=http://demo.ofbiz.org +# productStore.actionType including: "insert", "update", "delete" +# default value: "insert" +autoUpdateGoogleBase.productStore.actionType=insert +# productStore.statusId including "draft", "publish" +# default value: "draft" +autoUpdateGoogleBase.productStore.statusId=draft +# productStore.testMode including "Y", "N" +# default value: "N" +autoUpdateGoogleBase.productStore.testMode=N +# productStore.webSiteMountPoint +# default value: ecommerce +autoUpdateGoogleBase.productStore.webSiteMountPoint=ecommerce +# productStore.countryCode including "US", "GB", "DE" +# default value: "US" +autoUpdateGoogleBase.productStore.countryCode=US +# productStore.trackingCodeId +# default value: _NA_ +autoUpdateGoogleBase.productStore.trackingCodeId=_NA_ +# productStore.autoUpdateGoogleBase +# default value: "N" +autoUpdateGoogleBase.productStore.allowRecommended=N diff --git a/googlebase/data/GoogleBaseHelpData.xml b/googlebase/data/GoogleBaseHelpData.xml new file mode 100644 index 000000000..86dcb16c9 --- /dev/null +++ b/googlebase/data/GoogleBaseHelpData.xml @@ -0,0 +1,25 @@ + + + + + + + + diff --git a/googlebase/data/GoogleBaseTypeData.xml b/googlebase/data/GoogleBaseTypeData.xml index 333379de9..fe8320da1 100644 --- a/googlebase/data/GoogleBaseTypeData.xml +++ b/googlebase/data/GoogleBaseTypeData.xml @@ -22,4 +22,8 @@ under the License. + + + + diff --git a/googlebase/data/helpdata/HELP_GOOGLEBASE.xml b/googlebase/data/helpdata/HELP_GOOGLEBASE.xml new file mode 100644 index 000000000..9ea095a5c --- /dev/null +++ b/googlebase/data/helpdata/HELP_GOOGLEBASE.xml @@ -0,0 +1,89 @@ + + + + Google Base Help + The google base component provide to export products feed up to google base. + + + + Go to Google Base Component. + There are 3 main menus including Google Base Configurations, Export to Google Base and Auto Update Options. + + + + + How to add the Google Base Configurations? + First of all, you must add the google base configuration to each product store. + + + + At 'Add Google Base Configuration' screen. + Appropriately insert all field of the google base configuration. + Select the Product Store Id. + The Authentication Url is "https://www.google.com/accounts/ClientLogin". + The Post Items Url is "http://www.google.com/base/feeds/items/batch". + The Web Site Id is "GOOGLEBASE" (default). + Lastly, click 'Add'. + + + + Notice: The Developer Key is got from google base according to your google's account. + + + How to export product feed to google base? + You can export the selected products up to google base, this function generates the feed for google base. + Addition: Filter Product Status Description. + + + "Active Product" is the product which is active in OFBiz, not in Google Base. There use "thruDate" field to check what is active or not. + "Product not currently synced with Google Base" is the product which hasn't exported to Google Base yet. + + + Addition: Discontinued Description. + If you check "Exclude sending discontinued product and stock is zero" box, the search result will only has the product which is not discontinued and is available in stock. + + + + At 'Export To Google Base' screen. + Choose the product store, you can fill in any search option. + Click 'Find'. + Select any products, then click 'Export to Google Base'. + Fill in the configurations including "Country Code", "Web Site Url". For example; Country Code = "US", Web Site Url = "http://ofbizdemo2.antwebsystems.com", Web Site Mount Point = "ecommerce", Action Type = "insert", Status ID = "Publish Draft", Test Mode = "No". + You can select 'GoogleBaseRecommended' for add more detail of google base feed elements. + Click 'Export to Google Base', the system will exports product feed to Google Base. + + + + + + How to use the auto update to google base? + The auto update function repeats to export feed according to the frequency of scheduled job. So don't forget to add the scheduled job to run "autoUpdateToGoogleBase" service. + + + + Set the Auto Update to Google Base at "autoUpdateToGoogleBase.properties". + You can see that config at Google Base Auto Update Config section. + Add the scheduled job to run "autoUpdateToGoogleBase" service. + + + + Notice: After you once created the scheduled job of "autoUpdateToGoogleBase" service, you can start/stop scheduled at 'Start/Stop Auto Update to Google Base Scheduled' section. + + diff --git a/googlebase/script/org/ofbiz/googlebase/GooglebaseEvents.xml b/googlebase/script/org/ofbiz/googlebase/GooglebaseEvents.xml new file mode 100644 index 000000000..65f9cdaea --- /dev/null +++ b/googlebase/script/org/ofbiz/googlebase/GooglebaseEvents.xml @@ -0,0 +1,56 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/googlebase/script/org/ofbiz/googlebase/GooglebaseServices.xml b/googlebase/script/org/ofbiz/googlebase/GooglebaseServices.xml new file mode 100644 index 000000000..176402298 --- /dev/null +++ b/googlebase/script/org/ofbiz/googlebase/GooglebaseServices.xml @@ -0,0 +1,175 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/googlebase/servicedef/services.xml b/googlebase/servicedef/services.xml index 0dee1f252..397b3e43d 100644 --- a/googlebase/servicedef/services.xml +++ b/googlebase/servicedef/services.xml @@ -37,6 +37,7 @@ under the License. + @@ -63,4 +64,10 @@ under the License. + + + Auto update to google base + + diff --git a/googlebase/src/org/ofbiz/googlebase/GoogleBaseSearchEvents.java b/googlebase/src/org/ofbiz/googlebase/GoogleBaseSearchEvents.java index 509d0178d..a2177eccb 100644 --- a/googlebase/src/org/ofbiz/googlebase/GoogleBaseSearchEvents.java +++ b/googlebase/src/org/ofbiz/googlebase/GoogleBaseSearchEvents.java @@ -81,7 +81,17 @@ public class GoogleBaseSearchEvents { if (selectResult.startsWith("[")) { productExportList = StringUtil.toList(selectResult); } else { - productExportList.add(selectResult); + if(!selectResult.startsWith("{")){ + productExportList.add(selectResult); + }else { + List listTemp = FastList.newInstance(); + String temp = selectResult.substring(1, selectResult.length()-1); + String arrayTemp[] = temp.split(","); + for(int i=0; i exportResult = dispatcher.runSync("exportToGoogle", inMap); if (ServiceUtil.isError(exportResult)) { List errorMessages = UtilGenerics.checkList(exportResult.get(ModelService.ERROR_MESSAGE_LIST), String.class); @@ -119,12 +131,13 @@ public class GoogleBaseSearchEvents { } else if (ServiceUtil.isFailure(exportResult)) { List eventMessages = UtilGenerics.checkList(exportResult.get(ModelService.ERROR_MESSAGE_LIST), String.class); if (UtilValidate.isNotEmpty(eventMessages)) { - request.setAttribute("_EVENT_MESSAGE_LIST_", eventMessages); + request.setAttribute("_ERROR_MESSAGE_LIST_", eventMessages); } else { - request.setAttribute("_EVENT_MESSAGE_", ServiceUtil.getErrorMessage(exportResult)); + request.setAttribute("_ERROR_MESSAGE_", ServiceUtil.getErrorMessage(exportResult)); } + return "error"; } else { - request.setAttribute("_EVENT_MESSAGE_", exportResult.get("successMessage")); + request.setAttribute("_EVENT_MESSAGE_", exportResult.get("responseMessage")); } } catch (GenericServiceException e) { errMsg = UtilProperties.getMessage(resource, "googlebasesearchevents.exceptionCallingExportToGoogle", locale); diff --git a/googlebase/src/org/ofbiz/googlebase/ProductsExportToGoogle.java b/googlebase/src/org/ofbiz/googlebase/ProductsExportToGoogle.java index 976029865..7fb44cc3c 100644 --- a/googlebase/src/org/ofbiz/googlebase/ProductsExportToGoogle.java +++ b/googlebase/src/org/ofbiz/googlebase/ProductsExportToGoogle.java @@ -19,10 +19,17 @@ package org.ofbiz.googlebase; import java.io.BufferedReader; +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; +import java.io.OutputStreamWriter; +import java.io.UnsupportedEncodingException; +import java.math.BigDecimal; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; @@ -48,6 +55,7 @@ import org.ofbiz.entity.GenericEntityException; import org.ofbiz.entity.GenericValue; import org.ofbiz.entity.condition.EntityCondition; import org.ofbiz.entity.condition.EntityOperator; +import org.ofbiz.entity.util.EntityUtil; import org.ofbiz.service.DispatchContext; import org.ofbiz.service.GenericServiceException; import org.ofbiz.service.LocalDispatcher; @@ -56,6 +64,7 @@ import org.ofbiz.service.ServiceUtil; import org.ofbiz.base.util.StringUtil; import org.w3c.dom.Document; import org.w3c.dom.Element; +import org.w3c.dom.Node; public class ProductsExportToGoogle { @@ -83,8 +92,9 @@ public class ProductsExportToGoogle { if (token != null) { List newProductsInGoogle = UtilGenerics.checkList(result.get("newProductsInGoogle"), String.class); List productsRemovedFromGoogle = UtilGenerics.checkList(result.get("productsRemovedFromGoogle"), String.class); + String localeString = result.get("localeString").toString(); result = postItem(token, googleBaseConfigResult.get("postItemsUrl").toString(), googleBaseConfigResult.get("developerKey").toString(), dataItemsXml, - locale, (String)context.get("testMode"), newProductsInGoogle, productsRemovedFromGoogle, dispatcher, delegator); + locale, (String)context.get("testMode"), newProductsInGoogle, productsRemovedFromGoogle, dispatcher, delegator, localeString); } else { Debug.logError("Error during authentication to Google Account", module); return ServiceUtil.returnFailure(UtilProperties.getMessage(resource, "productsExportToGoogle.errorDuringAuthenticationToGoogle", locale)); @@ -246,7 +256,7 @@ public class ProductsExportToGoogle { private static Map postItem(String token, String postItemsUrl, String developerKey, StringBuffer dataItems, Locale locale, String testMode, List newProductsInGoogle, List productsRemovedFromGoogle, - LocalDispatcher dispatcher, Delegator delegator) throws IOException { + LocalDispatcher dispatcher, Delegator delegator, String localeString) throws IOException { if (Debug.verboseOn()) { Debug.logVerbose("Request To Google Base :\n" + dataItems.toString(), module); } @@ -277,7 +287,7 @@ public class ProductsExportToGoogle { inputStream = connection.getInputStream(); response = toString(inputStream); if (UtilValidate.isNotEmpty(response)) { - result = readResponseFromGoogle(response, newProductsInGoogle, productsRemovedFromGoogle, dispatcher, delegator, locale); + result = readResponseFromGoogle(response, newProductsInGoogle, productsRemovedFromGoogle, dispatcher, delegator, locale, localeString); //String msg = ServiceUtil.getErrorMessage(result); if (ServiceUtil.isError(result)) { result = ServiceUtil.returnFailure(UtilGenerics.checkList(result.get(ModelService.ERROR_MESSAGE_LIST))); @@ -301,6 +311,7 @@ public class ProductsExportToGoogle { Locale locale = (Locale)context.get("locale"); List newProductsInGoogle = FastList.newInstance(); List productsRemovedFromGoogle = FastList.newInstance(); + String localeString = null; try { Delegator delegator = dctx.getDelegator(); LocalDispatcher dispatcher = dctx.getDispatcher(); @@ -329,10 +340,13 @@ public class ProductsExportToGoogle { String productCurrency = null; if ("US".equals(countryCode)) { productCurrency = "USD"; + localeString = "en_US"; } else if ("GB".equals(countryCode)) { productCurrency = "GBP"; + localeString = "en_GB"; } else if ("DE".equals(countryCode)) { productCurrency = "EUR"; + localeString = "de"; } else { Debug.logError("Exception during building data items to Google, Country Code must be either US, UK or DE: "+countryCode, module); return ServiceUtil.returnFailure(UtilProperties.getMessage(resource, "productsExportToGoogle.invalidCountryCode", locale)); @@ -370,14 +384,39 @@ public class ProductsExportToGoogle { } // TODO: improve this (i.e. get the relative path from the properties file) String link = webSiteUrl + "/" + webSiteMountPoint + "/control/product/~product_id=" + prod.getString("productId") + trackingCodeId; - String title = UtilFormatOut.encodeXmlValue(prod.getString("productName")); - if (UtilValidate.isEmpty(title)) { + String productName = null; + String productDescription = null; + String productURL = null; + List productAndInfos = delegator.findByAnd("ProductContentAndInfo", UtilMisc.toMap("productId", prod.getString("productId"), "localeString", localeString, "thruDate", null)); + if (productAndInfos.size() > 0) { + for (GenericValue productContentAndInfo : productAndInfos ) { + String dataReSourceId = productContentAndInfo.getString("dataResourceId"); + GenericValue electronicText = delegator.findByPrimaryKey("ElectronicText", UtilMisc.toMap("dataResourceId", dataReSourceId)); + if ("PRODUCT_NAME".equals(productContentAndInfo.getString("productContentTypeId"))) + productName = electronicText.getString("textData"); + if ("LONG_DESCRIPTION".equals(productContentAndInfo.getString("productContentTypeId"))) + productDescription = electronicText.getString("textData"); + if ("PRODUCT_URL".equals(productContentAndInfo.getString("productContentTypeId"))) + productURL = electronicText.getString("textData"); + } + } else { + productName = prod.getString("internalName"); + productDescription = prod.getString("longDescription"); + if (UtilValidate.isEmpty(productDescription)) { + productDescription = prod.getString("description"); + } + } + String title = UtilFormatOut.encodeXmlValue(productName); + if (UtilValidate.isEmpty(title)) + title = UtilFormatOut.encodeXmlValue(prod.getString("productName")); + if (UtilValidate.isEmpty(title)) title = UtilFormatOut.encodeXmlValue(prod.getString("internalName")); - } - String description = UtilFormatOut.encodeXmlValue(prod.getString("description")); - if (UtilValidate.isEmpty(description)) { + String description = UtilFormatOut.encodeXmlValue(productDescription); + if (UtilValidate.isEmpty(description)) + description = UtilFormatOut.encodeXmlValue(prod.getString("description")); + if (UtilValidate.isEmpty(description)) description = UtilFormatOut.encodeXmlValue(prod.getString("internalName")); - } + String imageLink = ""; if (UtilValidate.isNotEmpty(prod.getString("largeImageUrl"))) { imageLink = webSiteUrl + prod.getString("largeImageUrl"); @@ -386,11 +425,32 @@ public class ProductsExportToGoogle { } else if (UtilValidate.isNotEmpty(prod.getString("smallImageUrl"))) { imageLink = webSiteUrl + prod.getString("smallImageUrl"); } - + + // should use image management script task. + /*try { + List productContentAndInfos = delegator.findByAnd("ProductContentAndInfo", + UtilMisc.toMap("productId", prod.getString("productId"), "productContentTypeId","DEFAULT_IMAGE")); + if (UtilValidate.isNotEmpty(productContentAndInfos)) { + imageLink = webSiteUrl + productContentAndInfos.get(0).getString("drObjectInfo"); + } else { + productContentAndInfos = delegator.findByAnd("ProductContentAndInfo", + UtilMisc.toMap("productId", prod.getString("productId"), + "productContentTypeId","IMAGE", + "statusId","IM_APPROVED", + "drIsPublic", "Y"), + UtilMisc.toList("contentId")); + if (UtilValidate.isNotEmpty(productContentAndInfos)) { + imageLink = webSiteUrl + productContentAndInfos.get(0).getString("drObjectInfo"); + } + } + } catch (Exception e) { + Debug.logError(e, module); + }*/ + String googleProductId = null; if (!"insert".equals(actionType)) { try { - googleProduct = delegator.findByPrimaryKey("GoodIdentification", UtilMisc.toMap("productId", prod.getString("productId"), "goodIdentificationTypeId", "GOOGLE_ID")); + googleProduct = delegator.findByPrimaryKey("GoodIdentification", UtilMisc.toMap("productId", prod.getString("productId"), "goodIdentificationTypeId", "GOOGLE_ID_" + localeString)); if (UtilValidate.isNotEmpty(googleProduct)) { googleProductId = googleProduct.getString("idValue"); } @@ -403,11 +463,16 @@ public class ProductsExportToGoogle { } Element entryElem = UtilXml.addChildElement(feedElem, "entry", feedDocument); Element batchElem = UtilXml.addChildElementNSElement(entryElem, "batch:operation", feedDocument, googleBaseBatchUrl); - Element batchOperationElem = UtilXml.firstChildElement(batchElem, "batch:operation"); + + Element batchOperationElem = (Element) batchElem.getFirstChild(); batchOperationElem.setAttribute("type", itemActionType); + + if("delete".equals(actionType) || "update".equals(actionType)){ + UtilXml.addChildElementNSValue(entryElem, "id", googleProductId, feedDocument, ""); + } Element appControlElem = UtilXml.addChildElementNSElement(entryElem, "app:control", feedDocument, googleBaseAppUrl); - Element appControlChildElem = UtilXml.firstChildElement(appControlElem, "app:control"); + Element appControlChildElem = (Element) appControlElem.getLastChild(); // Add the publishing priority for the product. By default it takes about 24 hours to publish your product if you submit data from Data Feed. By adding publishing priority your data // can be published in 15 - 30 minutes. UtilXml.addChildElementNSValue(appControlChildElem, "gm:publishing_priority", "high", feedDocument, googleBaseMetadataUrl); @@ -422,22 +487,18 @@ public class ProductsExportToGoogle { } } + //Add product title UtilXml.addChildElementValue(entryElem, "title", title, feedDocument); Element contentElem = UtilXml.addChildElementValue(entryElem, "content", description, feedDocument); contentElem.setAttribute("type", "xhtml"); - if (UtilValidate.isNotEmpty(googleProductId)) { - UtilXml.addChildElementNSValue(entryElem, "g:id", googleProductId, feedDocument, googleBaseNSUrl); - } else { - UtilXml.addChildElementNSValue(entryElem, "g:id", link, feedDocument, googleBaseNSUrl); - } - + UtilXml.addChildElementNSValue(entryElem, "g:id", prod.getString("productId"), feedDocument, googleBaseNSUrl); Element linkElem = UtilXml.addChildElement(entryElem, "link", feedDocument); - linkElem.setAttribute("rel", "alternate"); - linkElem.setAttribute("type", "text/html"); linkElem.setAttribute("href", link); - + linkElem.setAttribute("rel", "self"); + linkElem.setAttribute("type", "application/atom+xml"); + // item_type is the categories in which your product should belong. UtilXml.addChildElementNSValue(entryElem, "g:item_type", "products", feedDocument, googleBaseNSUrl); @@ -447,8 +508,14 @@ public class ProductsExportToGoogle { while (productCategoryMembersIter.hasNext()) { GenericValue productCategoryMember = productCategoryMembersIter.next(); GenericValue productCategory = productCategoryMember.getRelatedOne("ProductCategory"); - String productCategoryTypeId = productCategory.getString("productCategoryTypeId"); - if (UtilValidate.isNotEmpty(productCategoryTypeId) && "GOOGLE_BASE_CATEGORY".equals(productCategoryTypeId)) { + String productCategoryId = productCategory.getString("productCategoryId"); + String checkCategory = null; + if ("GB".equals(countryCode)) { + checkCategory = "UK"; + } else { + checkCategory = countryCode; + } + if (UtilValidate.isNotEmpty(productCategoryId) && (checkCategory.equals(productCategoryId.substring(0, 2)))) { String categoryDescription = ""; if (UtilValidate.isNotEmpty(productCategory.getString("categoryName"))) { categoryDescription = productCategory.getString("categoryName"); @@ -457,17 +524,14 @@ public class ProductsExportToGoogle { } else if (UtilValidate.isNotEmpty(productCategory.getString("longDescription"))) { categoryDescription = productCategory.getString("longDescription"); } - if (UtilValidate.isNotEmpty(productCategory)) { + if (UtilValidate.isNotEmpty(categoryDescription)) { UtilXml.addChildElementNSValue(entryElem, "g:product_type", StringUtil.wrapString(categoryDescription).toString() , feedDocument, googleBaseNSUrl); } } } - + //Add product price UtilXml.addChildElementNSValue(entryElem, "g:price", price, feedDocument, googleBaseNSUrl); - - // Might be nicer to load this from the product but for now we'll set it based on the country destination - UtilXml.addChildElementNSValue(entryElem, "g:currency", productCurrency, feedDocument, googleBaseNSUrl); - + // Ensure the load goes to the correct country location either US dollar, GB sterling or DE euro UtilXml.addChildElementNSValue(entryElem, "g:target_country", countryCode, feedDocument, googleBaseNSUrl); if (UtilValidate.isNotEmpty(prod.getString("brandName"))) { @@ -481,8 +545,14 @@ public class ProductsExportToGoogle { } catch (GenericEntityException gee) { Debug.logInfo("Unable to get the SKU for product [" + prod.getString("productId") + "]: " + gee.getMessage(), module); } - - UtilXml.addChildElementNSValue(entryElem, "g:condition", "new", feedDocument, googleBaseNSUrl); + + String condition = null; + if ("US".equals(countryCode) || "GB".equals(countryCode)) { + condition = "new"; + } else if ("DE".equals(countryCode)) { + condition = "new"; + } + UtilXml.addChildElementNSValue(entryElem, "g:condition", condition, feedDocument, googleBaseNSUrl); // This is a US specific requirement for product feeds // UtilXml.addChildElementValue(entryElem, "g:mpn", "", feedDocument); @@ -501,6 +571,10 @@ public class ProductsExportToGoogle { newProductsInGoogle.add(null); productsRemovedFromGoogle.add(null); } + //Add product condition + if ("Y".equals(context.get("allowRecommended"))) { + setRecommendedAttributes(prod, feedDocument, entryElem, delegator, countryCode, productCurrency); + } index++; } //Debug.logInfo("The value of generated String is ========\n" + UtilXml.writeXmlDocument(feedDocument), module); @@ -514,7 +588,8 @@ public class ProductsExportToGoogle { Map result = ServiceUtil.returnSuccess(); result.put("newProductsInGoogle", newProductsInGoogle); result.put("productsRemovedFromGoogle", productsRemovedFromGoogle); - Debug.log("======returning with result: " + result); + result.put("localeString", localeString); + //Debug.log("======returning with result: " + result); return result; } @@ -534,7 +609,7 @@ public class ProductsExportToGoogle { } private static Map readResponseFromGoogle(String msg, List newProductsInGoogle, List productsRemovedFromGoogle, - LocalDispatcher dispatcher, Delegator delegator, Locale locale) { + LocalDispatcher dispatcher, Delegator delegator, Locale locale, String localeString) { List message = FastList.newInstance(); // Debug.log("====get xml response from google: " + msg); try { @@ -544,13 +619,18 @@ public class ProductsExportToGoogle { Iterator extends Element> atomEntryElemIter = atomEntryList.iterator(); int index = 0; while (atomEntryElemIter.hasNext()) { + String id = null; Element atomEntryElement = atomEntryElemIter.next(); - String id = UtilXml.childElementValue(atomEntryElement, "atom:id", ""); + Node atomId = atomEntryElement.getElementsByTagName("atom:id").item(0); + if(UtilValidate.isNotEmpty(atomId)) { + id = atomId.getTextContent(); + } + String productId = ""; if (UtilValidate.isNotEmpty(id) && newProductsInGoogle.get(index) != null) { - String productId = newProductsInGoogle.get(index); + productId = newProductsInGoogle.get(index); try { GenericValue googleProductId = delegator.makeValue("GoodIdentification"); - googleProductId.set("goodIdentificationTypeId", "GOOGLE_ID"); + googleProductId.set("goodIdentificationTypeId", "GOOGLE_ID_" + localeString); googleProductId.set("productId", productId); googleProductId.set("idValue", id); delegator.createOrStore(googleProductId); @@ -559,20 +639,23 @@ public class ProductsExportToGoogle { } } if (UtilValidate.isNotEmpty(id) && productsRemovedFromGoogle.get(index) != null) { - String productId = productsRemovedFromGoogle.get(index); + productId = productsRemovedFromGoogle.get(index); try { - delegator.removeByAnd("GoodIdentification", UtilMisc.toMap("goodIdentificationTypeId", "GOOGLE_ID", "productId", productId)); + delegator.removeByAnd("GoodIdentification", UtilMisc.toMap("goodIdentificationTypeId", "GOOGLE_ID_" + localeString, "productId", productId)); } catch (GenericEntityException gee) { Debug.logError("Unable to remove Google id for product [" + productId + "]: " + gee.getMessage(), module); } } - String title = "Google response: " + UtilXml.childElementValue(atomEntryElement, "atom:title", ""); + if (UtilValidate.isEmpty(productId)){ + productId = atomEntryElement.getElementsByTagName("g:id").item(0).getTextContent(); + } + String title = "Google response:" + UtilXml.childElementValue(atomEntryElement, "atom:title", ""); List extends Element> batchStatusList = UtilXml.childElementList(atomEntryElement, "batch:status"); Iterator extends Element> batchStatusEntryElemIter = batchStatusList.iterator(); while (batchStatusEntryElemIter.hasNext()) { Element batchStatusEntryElement = batchStatusEntryElemIter.next(); if (UtilValidate.isNotEmpty(batchStatusEntryElement.getAttribute("reason"))) { - message.add(title + " " + batchStatusEntryElement.getAttribute("reason")); + message.add(title + " " + productId + ":" + batchStatusEntryElement.getAttribute("reason")); } } String errors = UtilXml.childElementValue(atomEntryElement, "batch:status", ""); @@ -585,10 +668,8 @@ public class ProductsExportToGoogle { Debug.logError("Exception reading response from Google: " + e.getMessage(), module); return ServiceUtil.returnError(UtilProperties.getMessage(resource, "productsExportToGoogle.exceptionReadingResponseFromGoogle", locale)); } - - if (message.size() > 0) { - return ServiceUtil.returnError(UtilProperties.getMessage(resource, "productsExportToGoogle.errorInTheResponseFromGoogle", locale), message); - } + //Debug.logInfo("===== batch:status - message: " + message, module); + //Debug.logInfo("===== Exports: " + message.size() + " products" , null); return ServiceUtil.returnSuccess(); } @@ -620,4 +701,70 @@ public class ProductsExportToGoogle { } return buildGoogleBaseConfigContext; } + private static void setRecommendedAttributes(GenericValue product, Document feedDocument, Element entryElem, Delegator delegator, String countryCode, String productCurrency) { + if (UtilValidate.isEmpty(product) && UtilValidate.isEmpty(feedDocument) && UtilValidate.isEmpty(countryCode) && UtilValidate.isNotEmpty(entryElem)) { + Debug.logError("Required parameters in setRecommended method", module); + } + try { + //Add brand name + if (UtilValidate.isNotEmpty(product.getString("brandName"))) { + UtilXml.addChildElementNSValue(entryElem, "g:brand", product.getString("brandName"), feedDocument, googleBaseNSUrl); + } + + //Add quantity item + List inventoryItems = delegator.findByAnd("InventoryItem", UtilMisc.toMap("productId", product.getString("productId"))); + if (UtilValidate.isNotEmpty(inventoryItems)) { + BigDecimal totalquantity = new BigDecimal(0); + for (GenericValue inventoryItem : inventoryItems) { + BigDecimal availableToPromiseTotal = new BigDecimal(inventoryItem.getString("availableToPromiseTotal")); + totalquantity = totalquantity.add(availableToPromiseTotal); + } + if ("DE".equals(countryCode)) { + UtilXml.addChildElementNSValue(entryElem, "g:menge", totalquantity.toString(), feedDocument, googleBaseNSUrl); + } else { + Integer intValue = totalquantity.intValue(); + UtilXml.addChildElementNSValue(entryElem, "g:quantity", intValue.toString(), feedDocument, googleBaseNSUrl); + } + } + //Add Online Only + UtilXml.addChildElementNSValue(entryElem, "g:online_only", "y", feedDocument, googleBaseNSUrl); + //Add shipping weight + if (UtilValidate.isNotEmpty(product.getString("weight")) && UtilValidate.isNotEmpty(product.getString("weightUomId"))) { + GenericValue uom = delegator.findByPrimaryKey("Uom", UtilMisc.toMap("uomId", product.getString("weightUomId"))); + String shippingWeight = product.getString("weight") + " " + uom.getString("description"); + UtilXml.addChildElementNSValue(entryElem, "g:shipping_weight", shippingWeight, feedDocument, googleBaseNSUrl); + } + List productFeatureAndAppls = delegator.findByAnd("ProductFeatureAndAppl", UtilMisc.toMap("productId", product.getString("productId"))); + if (productFeatureAndAppls.size() > 0) { + for (GenericValue productFeatureAndAppl : productFeatureAndAppls) { + //Add Genre + if ("GENRE".equals(productFeatureAndAppl.getString("productFeatureTypeId"))) { + UtilXml.addChildElementNSValue(entryElem, "g:genre", productFeatureAndAppl.getString("description"), feedDocument, googleBaseNSUrl); + } + //Add color + if ("COLOR".equals(productFeatureAndAppl.getString("productFeatureTypeId"))) { + UtilXml.addChildElementNSValue(entryElem, "g:color", productFeatureAndAppl.getString("description"), feedDocument, googleBaseNSUrl); + } + //Add size + if ("SIZE".equals(productFeatureAndAppl.getString("productFeatureTypeId"))) { + UtilXml.addChildElementNSValue(entryElem, "g:size", productFeatureAndAppl.getString("description"), feedDocument, googleBaseNSUrl); + } + //Add year + if ("YEAR_MADE".equals(productFeatureAndAppl.getString("productFeatureTypeId"))) { + UtilXml.addChildElementNSValue(entryElem, "g:year", productFeatureAndAppl.getString("description"), feedDocument, googleBaseNSUrl); + } + //Add author + if ("ARTIST".equals(productFeatureAndAppl.getString("productFeatureTypeId"))) { + UtilXml.addChildElementNSValue(entryElem, "g:author", productFeatureAndAppl.getString("description"), feedDocument, googleBaseNSUrl); + } + //Add edition + if ("EDITION".equals(productFeatureAndAppl.getString("productFeatureTypeId"))) { + UtilXml.addChildElementNSValue(entryElem, "g:edition", productFeatureAndAppl.getString("description"), feedDocument, googleBaseNSUrl); + } + } + } + } catch (Exception e) { + Debug.logError(e.toString(), module); + } + } } diff --git a/googlebase/webapp/googlebase/WEB-INF/actions/FilterProducts.groovy b/googlebase/webapp/googlebase/WEB-INF/actions/FilterProducts.groovy new file mode 100644 index 000000000..9574acf58 --- /dev/null +++ b/googlebase/webapp/googlebase/WEB-INF/actions/FilterProducts.groovy @@ -0,0 +1,91 @@ +/* + * 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. + */ +import javolution.util.FastList; +import org.ofbiz.base.util.UtilMisc; +import org.ofbiz.entity.util.EntityUtil; +import org.ofbiz.base.util.UtilValidate; +import org.ofbiz.base.util.UtilValidate; +import org.ofbiz.base.util.UtilDateTime; +import java.math.BigDecimal; +import javax.servlet.http.HttpSession; + +defaultLocaleString = ""; +if (parameters.productStoreId) { + productStore = delegator.findByAnd("ProductStore", ["productStoreId":parameters.productStoreId]); + defaultLocaleString = productStore[0].defaultLocaleString.toString() +} +active = parameters.ACTIVE_PRODUCT; +notSynced = parameters.GOOGLE_SYNCED; + +productList = FastList.newInstance(); +if (UtilValidate.isNotEmpty(productIds) && ("Y".equals(active) || "Y".equals(notSynced))) { + for (int i = 0; i < productIds.size(); i++) { + productId = productIds[i]; + productCategoryMembers = delegator.findByAnd("ProductCategoryMember", [productId : productId]); + productCategoryMember = EntityUtil.getFirst(productCategoryMembers); + if (UtilValidate.isNotEmpty(productCategoryMember)) { + if ("Y".equals(active) && "Y".equals(notSynced)) { + thruDate = productCategoryMember.get("thruDate"); + goodIdentification = delegator.findByPrimaryKey("GoodIdentification", [productId : productId, goodIdentificationTypeId : "GOOGLE_ID_" + defaultLocaleString]); + if (UtilValidate.isEmpty(thruDate) && UtilValidate.isEmpty(goodIdentification)) { + productList.add(productId); + } + } else if ("Y".equals(active)) { + thruDate = productCategoryMember.get("thruDate"); + if (UtilValidate.isEmpty(thruDate)) { + productList.add(productId); + } + parameters.GOOGLE_SYNCED = "N" + } else if ("Y".equals(notSynced)) { + goodIdentification = delegator.findByPrimaryKey("GoodIdentification", [productId : productId, goodIdentificationTypeId : "GOOGLE_ID_" + defaultLocaleString]); + if (UtilValidate.isEmpty(goodIdentification)) { + productList.add(productId); + } + parameters.ACTIVE_PRODUCT = "N" + } + } + } + productIds = productList; +} else { + parameters.ACTIVE_PRODUCT = "N" + parameters.GOOGLE_SYNCED = "N" +} + +//stop sending discontinued product. +def notDiscontProdList = [] +if(parameters.DISCONTINUED_PRODUCT == 'Y'){ + productIds.each { value -> + def stockIsZero = dispatcher.runSync("isStoreInventoryAvailable", ["productId": value, "productStoreId": parameters.productStoreId, "quantity": BigDecimal.valueOf(1.00)]); + def thisProduct = delegator.findByPrimaryKey("Product", [productId : value]); + if (stockIsZero.get("available") == 'Y'){ + notDiscontProdList.add(value); + }else { + if (thisProduct.salesDiscontinuationDate == null || thisProduct.salesDiscontinuationDate > UtilDateTime.nowTimestamp()){ + notDiscontProdList.add(value); + } + } + } +} else { + parameters.DISCONTINUED_PRODUCT = 'N' +} +if (notDiscontProdList){ + context.productIds = notDiscontProdList; +} else { + context.productIds = productIds; +} diff --git a/googlebase/webapp/googlebase/WEB-INF/actions/GoogleBaseAdvancedSearch.groovy b/googlebase/webapp/googlebase/WEB-INF/actions/GoogleBaseAdvancedSearch.groovy index 2b0bdfdfc..5125715dc 100644 --- a/googlebase/webapp/googlebase/WEB-INF/actions/GoogleBaseAdvancedSearch.groovy +++ b/googlebase/webapp/googlebase/WEB-INF/actions/GoogleBaseAdvancedSearch.groovy @@ -32,6 +32,10 @@ if (parameters.productStoreId) { productStoreId = ProductStoreWorker.getProductStoreId(request); } googleBaseConfigList = delegator.findList("GoogleBaseConfig", null, null, null, null, false); +if (!productStoreId) { + googleBaseProductStore = EntityUtil.getFirst(googleBaseConfigList); + productStoreId = googleBaseProductStore.productStoreId; +} if (productStoreId) { productStoreCatalogs = CatalogWorker.getStoreCatalogs(delegator, productStoreId); if (productStoreCatalogs) { diff --git a/googlebase/webapp/googlebase/WEB-INF/actions/autoUpdateConfig.groovy b/googlebase/webapp/googlebase/WEB-INF/actions/autoUpdateConfig.groovy new file mode 100644 index 000000000..d161afc5b --- /dev/null +++ b/googlebase/webapp/googlebase/WEB-INF/actions/autoUpdateConfig.groovy @@ -0,0 +1,61 @@ +/* + * 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. + */ +import javolution.util.FastList +import org.ofbiz.base.util.UtilProperties + +configList = [] +str = UtilProperties.getPropertyValue("autoUpdateToGoogleBase.properties", "autoUpdateGoogleBase.productStoreId") +productStoreIds = str.split(",") +str = UtilProperties.getPropertyValue("autoUpdateToGoogleBase.properties", "autoUpdateGoogleBase.productStore.option.outOfStock") +outOfStock = str.split(",") +str = UtilProperties.getPropertyValue("autoUpdateToGoogleBase.properties", "autoUpdateGoogleBase.productStore.option.backInStock") +backInStock = str.split(",") +str = UtilProperties.getPropertyValue("autoUpdateToGoogleBase.properties", "autoUpdateGoogleBase.productStore.webSiteUrl") +webSiteUrl = str.split(",") +str = UtilProperties.getPropertyValue("autoUpdateToGoogleBase.properties", "autoUpdateGoogleBase.productStore.actionType") +actionType = str.split(",") +str = UtilProperties.getPropertyValue("autoUpdateToGoogleBase.properties", "autoUpdateGoogleBase.productStore.statusId") +statusId = str.split(",") +str = UtilProperties.getPropertyValue("autoUpdateToGoogleBase.properties", "autoUpdateGoogleBase.productStore.testMode") +testMode = str.split(",") +str = UtilProperties.getPropertyValue("autoUpdateToGoogleBase.properties", "autoUpdateGoogleBase.productStore.webSiteMountPoint") +webSiteMountPoint = str.split(",") +str = UtilProperties.getPropertyValue("autoUpdateToGoogleBase.properties", "autoUpdateGoogleBase.productStore.countryCode") +countryCode = str.split(",") +str = UtilProperties.getPropertyValue("autoUpdateToGoogleBase.properties", "autoUpdateGoogleBase.productStore.trackingCodeId") +trackingCodeId = str.split(",") +str = UtilProperties.getPropertyValue("autoUpdateToGoogleBase.properties", "autoUpdateGoogleBase.productStore.allowRecommended") +allowRecommended = str.split(",") + +productStoreIds.eachWithIndex{ productStoreId, i -> + configMap = [:] + configMap.productStoreId = productStoreId + configMap.outOfStock = outOfStock[i] + configMap.backInStock = backInStock[i] + configMap.webSiteUrl = webSiteUrl[i] + configMap.actionType = actionType[i] + configMap.statusId = statusId[i] + configMap.testMode = testMode[i] + configMap.webSiteMountPoint = webSiteMountPoint[i] + configMap.countryCode = countryCode[i] + configMap.trackingCodeId = trackingCodeId[i] + configMap.allowRecommended = allowRecommended[i] + configList.add(configMap) +} +context.configList = configList diff --git a/googlebase/webapp/googlebase/WEB-INF/actions/googlebaseDivideList.groovy b/googlebase/webapp/googlebase/WEB-INF/actions/googlebaseDivideList.groovy new file mode 100644 index 000000000..c9d863eef --- /dev/null +++ b/googlebase/webapp/googlebase/WEB-INF/actions/googlebaseDivideList.groovy @@ -0,0 +1,27 @@ +import java.util.List; +import javolution.util.FastList; + +//productList.unique() like distinct sql command, return string type. +def productUniqueStr = productList.unique(); +def productUniqueStrList = productUniqueStr.toList(); +def googleBaseList = delegator.findByAnd("GoodIdentification",["goodIdentificationTypeId":"GOOGLE_ID_" + productStore.defaultLocaleString]); +//find product is existed in google base. +def notNeededList = productUniqueStrList - googleBaseList.productId; +def resultList = productUniqueStrList - notNeededList; +def list = []; +def productExportList = []; +//if feed more than 1000 always found an IO error, so should divide to any sections. +def amountPerSection = 1000; +def section = (int)(resultList.size()/amountPerSection); +if(resultList.size() % amountPerSection != 0){ + section = section+1; +} + +for(int i=0; i + prodCatalog = delegator.findOne("ProdCatalog", [prodCatalogId : productStoreCatalog.prodCatalogId], true); + prodCatalogList.add(prodCatalog); + } + } +} +currentCatalogId = null; +prodCatalogList.each { prodCatalogList -> + currentCatalogId = prodCatalogList.prodCatalogId + prodCatalogCategoryList = delegator.findByAnd("ProdCatalogCategory",["prodCatalogId":currentCatalogId, "prodCatalogCategoryTypeId":"PCCT_BROWSE_ROOT"]); + topCategory = prodCatalogCategoryList.productCategoryId[0]; + if (topCategory){ + relatedCategories = dispatcher.runSync("getRelatedCategories", [parentProductCategoryId: topCategory, userLogin: userLogin]); + categoryList = relatedCategories.categories + } else { + categoryIdsTemp.clear() + } + if (categoryList) { + categoryIdsTemp = EntityUtil.getFieldListFromEntityList(categoryList, "productCategoryId", true); + } + categoryIds.add(categoryIdsTemp) +} + +context.googleBaseConfigList = googleBaseConfigList; +context.categoryIds = categoryIds; +context.productStoreId = productStoreId; diff --git a/googlebase/webapp/googlebase/WEB-INF/controller.xml b/googlebase/webapp/googlebase/WEB-INF/controller.xml index 1ca646fe2..964de724d 100644 --- a/googlebase/webapp/googlebase/WEB-INF/controller.xml +++ b/googlebase/webapp/googlebase/WEB-INF/controller.xml @@ -48,6 +48,17 @@ under the License. + + + + + + + + + + + @@ -81,5 +92,6 @@ under the License. + diff --git a/googlebase/webapp/googlebase/find/GoogleBaseAdvancedSearch.ftl b/googlebase/webapp/googlebase/find/GoogleBaseAdvancedSearch.ftl index 954cf6298..73a1e6e53 100644 --- a/googlebase/webapp/googlebase/find/GoogleBaseAdvancedSearch.ftl +++ b/googlebase/webapp/googlebase/find/GoogleBaseAdvancedSearch.ftl @@ -150,6 +150,28 @@ under the License. #if> + + Filter Product Status: + + + + Active Product + + Product not currently synced with Google Base + + + + + + Discontinued: + + + + Exclude sending discontinued product and stock is zero. + + + + ${uiLabelMap.ProductProductName}: diff --git a/googlebase/webapp/googlebase/find/googleExportLink.ftl b/googlebase/webapp/googlebase/find/googleExportLink.ftl index bc0e85eb7..b0bbe88db 100644 --- a/googlebase/webapp/googlebase/find/googleExportLink.ftl +++ b/googlebase/webapp/googlebase/find/googleExportLink.ftl @@ -19,8 +19,18 @@ under the License. diff --git a/googlebase/widget/GoogleBaseForms.xml b/googlebase/widget/GoogleBaseForms.xml index 5193ed576..3cd7722d5 100644 --- a/googlebase/widget/GoogleBaseForms.xml +++ b/googlebase/widget/GoogleBaseForms.xml @@ -22,16 +22,14 @@ under the License. xsi:noNamespaceSchemaLocation="http://ofbiz.apache.org/dtds/widget-form.xsd"> + + + - - - - - - - - + + + @@ -69,6 +67,7 @@ under the License. + @@ -104,4 +103,44 @@ under the License. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/googlebase/widget/GoogleBaseMenus.xml b/googlebase/widget/GoogleBaseMenus.xml index 8d06654e9..d5c0db123 100644 --- a/googlebase/widget/GoogleBaseMenus.xml +++ b/googlebase/widget/GoogleBaseMenus.xml @@ -21,5 +21,6 @@ under the License. + diff --git a/googlebase/widget/GoogleBaseScreens.xml b/googlebase/widget/GoogleBaseScreens.xml index 3e4c11b5a..388c3eb58 100644 --- a/googlebase/widget/GoogleBaseScreens.xml +++ b/googlebase/widget/GoogleBaseScreens.xml @@ -49,6 +49,7 @@ under the License. + @@ -128,4 +129,29 @@ under the License. + + + + + + + + + + + + + + + + + + + + + + + + +