Subversion Repositories SmartDukaan

Rev

Rev 9878 | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
1678 rajveer 1
package in.shop2020.util;
2
 
5113 amit.gupta 3
import in.shop2020.logistics.DeliveryType;
4
import in.shop2020.logistics.LogisticsInfo;
5
import in.shop2020.logistics.LogisticsService;
4188 varun.gupt 6
import in.shop2020.metamodel.core.Entity;
4802 amit.gupta 7
import in.shop2020.metamodel.definitions.Catalog;
6025 amit.gupta 8
import in.shop2020.metamodel.definitions.Category;
4802 amit.gupta 9
import in.shop2020.metamodel.definitions.DefinitionsContainer;
4188 varun.gupt 10
import in.shop2020.metamodel.util.CreationUtils;
5945 mandeep.dh 11
import in.shop2020.model.v1.catalog.CatalogService.Client;
1678 rajveer 12
import in.shop2020.model.v1.catalog.Item;
4188 varun.gupt 13
import in.shop2020.model.v1.catalog.status;
14
import in.shop2020.model.v1.user.ItemCouponDiscount;
15
import in.shop2020.thrift.clients.CatalogClient;
5113 amit.gupta 16
import in.shop2020.thrift.clients.LogisticsClient;
4188 varun.gupt 17
import in.shop2020.thrift.clients.PromotionClient;
8143 amit.gupta 18
import in.shop2020.utils.GmailUtils;
4188 varun.gupt 19
 
2130 rajveer 20
import java.io.File;
5612 amit.gupta 21
import java.io.FileInputStream;
7837 amit.gupta 22
import java.io.FileNotFoundException;
23
import java.io.FileReader;
5612 amit.gupta 24
import java.io.IOException;
7837 amit.gupta 25
import java.io.Reader;
5612 amit.gupta 26
import java.nio.MappedByteBuffer;
27
import java.nio.channels.FileChannel;
28
import java.nio.charset.Charset;
1678 rajveer 29
import java.util.ArrayList;
5612 amit.gupta 30
import java.util.Arrays;
8143 amit.gupta 31
import java.util.Calendar;
4143 varun.gupt 32
import java.util.HashMap;
1678 rajveer 33
import java.util.List;
34
import java.util.Map;
35
 
8143 amit.gupta 36
import javax.mail.MessagingException;
7506 amit.gupta 37
import javax.xml.transform.Result;
38
import javax.xml.transform.Source;
39
import javax.xml.transform.Transformer;
40
import javax.xml.transform.TransformerConfigurationException;
41
import javax.xml.transform.TransformerException;
42
import javax.xml.transform.TransformerFactory;
43
import javax.xml.transform.dom.DOMSource;
44
import javax.xml.transform.stream.StreamResult;
45
 
4202 varun.gupt 46
import org.apache.commons.lang.StringEscapeUtils;
1678 rajveer 47
import org.apache.commons.lang.StringUtils;
7506 amit.gupta 48
import org.apache.commons.logging.Log;
49
import org.apache.commons.logging.LogFactory;
50
import org.apache.xerces.parsers.DOMParser;
4143 varun.gupt 51
import org.json.JSONObject;
7506 amit.gupta 52
import org.w3c.dom.Document;
53
import org.w3c.dom.Node;
54
import org.w3c.dom.NodeList;
1678 rajveer 55
 
7837 amit.gupta 56
import com.google.gson.Gson;
57
import com.google.gson.reflect.TypeToken;
58
 
1678 rajveer 59
/**
60
 * Command line utility to generate xml file for partners
61
 * 
62
 * @author rajveer
63
 *
64
 */
65
public class ProductListGenerator {
7506 amit.gupta 66
 
67
	private static Log log = LogFactory.getLog(ContentGenerationUtility.class);
1678 rajveer 68
 
69
	private String[] xmlIndentation = {"", "    ", "        ", "            ","                "};
5612 amit.gupta 70
	private Client cc = null;
6602 amit.gupta 71
	List <Long> inStockCatalogItemIds = new ArrayList<Long>();
72
 
2367 rajveer 73
	public Map<Long, List<Item>> entityIdItemMap;
5113 amit.gupta 74
	private static final String DEFAULT_PINCODE = "110001";
4802 amit.gupta 75
	DefinitionsContainer defContainer = Catalog.getInstance().getDefinitionsContainer();
6025 amit.gupta 76
	private List<Long> validParentCategories = Arrays.asList((long)Utils.LAPTOPS_CATEGORY, (long)Utils.CAMERAS_CATEGORY, (long)Utils.MOBILE_PHONES_CATAGORY, (long)Utils.TABLETS_CATEGORY);
7629 amit.gupta 77
	/*private List<Long> voucherEntities = new ArrayList<Long>();*/
1678 rajveer 78
 
2367 rajveer 79
	public ProductListGenerator(Map<Long, List<Item>> entityIdItemMap) throws Exception {
80
		this.entityIdItemMap = entityIdItemMap;
1678 rajveer 81
	}
82
 
7629 amit.gupta 83
	public ProductListGenerator(List<Item> items) throws Exception {
84
		populateEntityIdItemMap(items);
85
	}
1678 rajveer 86
 
7629 amit.gupta 87
 
1678 rajveer 88
	/**
2367 rajveer 89
	 * Get the url of the entity
1678 rajveer 90
	 * @param expEntity
91
	 * @return url
92
	 */
2367 rajveer 93
	private String getProductURL(long entityId, Item item){
4802 amit.gupta 94
		//long rootCategoryId = catm.getCategory(item.getCategory()).getParent_category_id();
95
		in.shop2020.metamodel.definitions.Category parentCategory = defContainer.getCategory(item.getCategory()).getParentCategory();
96
 
97
		String url = "http://www.saholic.com/" + parentCategory.getLabel().toLowerCase().replace(' ', '-') + "/";
2367 rajveer 98
		String productUrl = ((item.getBrand() != null) ? item.getBrand().trim() + " " : "").toLowerCase().replace(' ', '-')
99
        + "-" + ((item.getModelName() != null) ? item.getModelName().trim() + " " : "").toLowerCase().replace(' ', '-') 
100
	    + "-" + (( item.getModelNumber() != null ) ? item.getModelNumber().trim() + " ": "" ).toLowerCase().replace(' ', '-')
101
        + "-" + entityId;
1678 rajveer 102
		productUrl = productUrl.replaceAll("/", "-");
103
		url = url + productUrl;
2367 rajveer 104
		url = url.replaceAll("-+", "-");
1678 rajveer 105
		return url;
106
	}
6040 amit.gupta 107
 
108
 
109
	/**
110
	 * Get the url of the entity
111
	 * @param expEntity
112
	 * @return url
113
	 */
114
	private String getProductURL(long entityId, Item item, int affiliateId){
115
		//long rootCategoryId = catm.getCategory(item.getCategory()).getParent_category_id();
116
		in.shop2020.metamodel.definitions.Category parentCategory = defContainer.getCategory(item.getCategory()).getParentCategory();
117
 
118
		String url = "http://www.saholic.com/" + parentCategory.getLabel().toLowerCase().replace(' ', '-') + "/";
119
		String productUrl = ((item.getBrand() != null) ? item.getBrand().trim() + " " : "").toLowerCase().replace(' ', '-')
120
		+ "-" + ((item.getModelName() != null) ? item.getModelName().trim() + " " : "").toLowerCase().replace(' ', '-') 
121
		+ "-" + (( item.getModelNumber() != null ) ? item.getModelNumber().trim() + " ": "" ).toLowerCase().replace(' ', '-')
122
		+ "-" + entityId;
123
		productUrl = productUrl.replaceAll("/", "-");
124
		url = url + productUrl;
125
		url = url.replaceAll("-+", "-");
126
		return url + "?afid=" + affiliateId;
127
	}
1678 rajveer 128
 
2367 rajveer 129
 
130
 
1678 rajveer 131
	/**
3964 rajveer 132
	 * Get the minimum mrp of the items
133
	 * @param items
134
	 * @return
135
	 */
136
	private double getMinMRP(List<Item> items){
137
        double minPrice = Double.MAX_VALUE;
138
        for(Item item: items){
139
            if(minPrice > item.getMrp()){
140
                minPrice =  item.getMrp();
141
            }
142
        }
143
        return minPrice;
144
    }
145
 
6602 amit.gupta 146
	public List<Long> getInStockCatalogItemIds() {
147
		return inStockCatalogItemIds;
148
	}
3964 rajveer 149
 
6602 amit.gupta 150
 
151
 
3964 rajveer 152
 
153
	/**
2367 rajveer 154
	 * Get the minimum price of the items
155
	 * @param items
156
	 * @return
157
	 */
158
	private double getMinPrice(List<Item> items){
159
        double minPrice = Double.MAX_VALUE;
160
        for(Item item: items){
161
            if(minPrice > item.getSellingPrice()){
162
                minPrice = item.getSellingPrice();
163
            }
164
        }
165
        return minPrice;
166
    }
167
 
168
	/**
169
	 * Check whether product is mobile or not
170
	 * @param item
171
	 * @return
172
	 */
173
	private boolean isMobile(Item item){
4802 amit.gupta 174
		in.shop2020.metamodel.definitions.Category parentCategory = defContainer.getCategory(item.getCategory()).getParentCategory();
175
		return parentCategory.getID() == Utils.MOBILE_PHONES_CATAGORY;
2367 rajveer 176
	}
177
 
178
	/**
5229 varun.gupt 179
	 * Checks whether a product is tablet or not
180
	 */
181
	private boolean isTablet(Item item) {
182
		in.shop2020.metamodel.definitions.Category parentCategory = defContainer.getCategory(item.getCategory()).getParentCategory();
183
		return parentCategory.getID() == Utils.TABLETS_CATEGORY;
184
	}
5935 amit.gupta 185
 
186
	/**
187
	 * Checks whether a product is camera or not
188
	 */
189
	private boolean isCamera(Item item) {
190
		in.shop2020.metamodel.definitions.Category parentCategory = defContainer.getCategory(item.getCategory()).getParentCategory();
191
		return parentCategory.getID() == Utils.CAMERAS_CATEGORY;
192
	}
5229 varun.gupt 193
 
194
	/**
4143 varun.gupt 195
	 * Checks whether a product is laptop or not
196
	 */
197
	private boolean isLaptop(Item item) {
4802 amit.gupta 198
		in.shop2020.metamodel.definitions.Category parentCategory = defContainer.getCategory(item.getCategory()).getParentCategory();
199
		return parentCategory.getID() == Utils.LAPTOPS_CATEGORY;
4143 varun.gupt 200
	}
201
 
202
	/**
5355 varun.gupt 203
	 * Checks whether a product is accessory or not
204
	 */
205
	private boolean isAccessory(Item item)	{
206
		in.shop2020.metamodel.definitions.Category parentCategory = defContainer.getCategory(item.getCategory()).getParentCategory();
207
		return parentCategory.getID() == Utils.MOBILE_ACCESSORIES_CATEGORY || parentCategory.getID() == Utils.LAPTOP_ACCESSORIES_CATEGORY;
208
	}
209
 
210
	/**
2367 rajveer 211
	 * 
212
	 * @param item
213
	 * @return
214
	 */
215
	private String getProductTitle(Item item){
2542 rajveer 216
		String title = ((item.getBrand() != null) ? item.getBrand().trim() + " " : "")
217
		+ ((item.getModelName() != null) ? item.getModelName().trim() + " " : "")
218
		+ (( item.getModelNumber() != null ) ? item.getModelNumber().trim() : "" );
2561 rajveer 219
		title = title.replaceAll("  ", " ");
2367 rajveer 220
		return title;
221
	}
222
 
223
	/**
1678 rajveer 224
	 * get xml feed for partner sites
225
	 * @param irDataXMLSnippets
226
	 * @throws Exception
227
	 */
2367 rajveer 228
	private void getProductsXML(ArrayList<String> irDataXMLSnippets) throws Exception{
5113 amit.gupta 229
		LogisticsService.Client prod_client = null;
5350 varun.gupt 230
		Map<Long, ItemCouponDiscount> couponsAndDiscounts = new HashMap<Long, ItemCouponDiscount>();
231
 
5113 amit.gupta 232
		try {
5350 varun.gupt 233
 
234
			List<Long> itemIds = new ArrayList<Long>();
235
 
236
			for(Long entityId: entityIdItemMap.keySet()){
237
 
238
				List<Item> items = entityIdItemMap.get(entityId);
239
				Item firstItem = items.get(0);
240
 
6720 amit.gupta 241
				if(!firstItem.getItemStatus().equals(status.COMING_SOON) && isMobile(firstItem) || isLaptop(firstItem)) {
5350 varun.gupt 242
					itemIds.add(firstItem.getId());
243
				}
244
			}
245
 
246
			PromotionClient promotionClient = new PromotionClient();
247
			in.shop2020.model.v1.user.PromotionService.Client promotionServiceClient = promotionClient.getClient();
248
 
249
			List<ItemCouponDiscount> itemsCouponsAndDiscounts = promotionServiceClient.getItemDiscountMap(itemIds);
250
 
251
			for (ItemCouponDiscount itemCouponDiscount: itemsCouponsAndDiscounts) {
252
				couponsAndDiscounts.put(itemCouponDiscount.getItemId(), itemCouponDiscount);
253
			}
6625 amit.gupta 254
 
255
			LogisticsClient logistics_prod = new LogisticsClient("logistics_service_prod_server_host","logistics_service_prod_server_port");
256
			prod_client = logistics_prod.getClient();
5350 varun.gupt 257
 
5113 amit.gupta 258
		} catch (Exception e) {
259
			prod_client = null;
5350 varun.gupt 260
			Utils.info("Logistics estimations can't be fetched as Logistics Service is inaccessible" + e);
5113 amit.gupta 261
		}
5350 varun.gupt 262
 
2367 rajveer 263
		for(Long entityId: entityIdItemMap.keySet()){
264
			List<Item> items = entityIdItemMap.get(entityId);
265
			Item firstItem = items.get(0);
5229 varun.gupt 266
 
6720 amit.gupta 267
			if((firstItem.getItemStatus().equals(status.COMING_SOON) && !firstItem.isShowSellingPrice()) || !isMobile(firstItem) && !isTablet(firstItem))	{
1678 rajveer 268
				continue;
269
			}
270
 
271
			irDataXMLSnippets.add(this.xmlIndentation[1] + "<products>");	
272
 
2367 rajveer 273
			irDataXMLSnippets.add(this.xmlIndentation[2] + "<ProductSKU>" + entityId + "</ProductSKU>");
1678 rajveer 274
 
2367 rajveer 275
			String title = getProductTitle(firstItem);
1678 rajveer 276
			irDataXMLSnippets.add(this.xmlIndentation[2] + "<ProductName>" + title + "</ProductName>");
277
 
2367 rajveer 278
			String url = getProductURL(entityId, firstItem);
3929 mandeep.dh 279
 
280
			String imageUrl = "http://static" + ((entityId+1)%3) + ".saholic.com" + File.separator + "images" + File.separator +
281
			                  "website" + File.separator + entityId + File.separator + "icon.jpg";
282
 
1678 rajveer 283
			irDataXMLSnippets.add(this.xmlIndentation[2] + "<ProductURL>" + url + "</ProductURL>");
6602 amit.gupta 284
			irDataXMLSnippets.add(this.xmlIndentation[2] + "<Availability>" + (inStockCatalogItemIds.contains(entityId) ? "Y" : "N") + "</Availability>");
5350 varun.gupt 285
			double minPrice = getMinPrice(items);
1678 rajveer 286
 
5350 varun.gupt 287
			if(couponsAndDiscounts.containsKey(firstItem.getId()))	{
288
 
289
				int discountedPrice = (int)(minPrice - couponsAndDiscounts.get(firstItem.getId()).getDiscount());
290
				irDataXMLSnippets.add(this.xmlIndentation[2] + "<ProductPrice>" + discountedPrice + "</ProductPrice>");
291
 
292
			} else	{
293
				irDataXMLSnippets.add(this.xmlIndentation[2] + "<ProductPrice>" + minPrice + "</ProductPrice>");
294
			}
295
 
7034 amit.gupta 296
			if (StringUtils.isNotEmpty(firstItem.getBestDealText())) {
7110 amit.gupta 297
				irDataXMLSnippets.add(this.xmlIndentation[2] + "<DealText>" + StringEscapeUtils.escapeXml(firstItem.getBestDealText()) + "</DealText>");
7034 amit.gupta 298
			}
299
 
3964 rajveer 300
			irDataXMLSnippets.add(this.xmlIndentation[2] + "<ProductMRP>" + getMinMRP(items) + "</ProductMRP>");
301
 
5113 amit.gupta 302
			LogisticsInfo logisticsInfo = null;
9878 amit.gupta 303
			if(prod_client != null){
5113 amit.gupta 304
				try {
305
					Long itemId = prod_client.getEntityLogisticsEstimation(
306
							entityId, DEFAULT_PINCODE, DeliveryType.PREPAID)
9847 amit.gupta 307
							.get(0).getItemId();
5113 amit.gupta 308
					logisticsInfo = prod_client.getLogisticsEstimation(itemId,
309
							DEFAULT_PINCODE, DeliveryType.PREPAID);
310
					irDataXMLSnippets.add(this.xmlIndentation[2] + "<ProductDeliveryEstimate>" + logisticsInfo.getDeliveryTime() + "</ProductDeliveryEstimate>");
311
				} catch (Exception e1) {
312
					Utils.info("Unable to get Estimation for Entity: " + entityId + "\n" + e1);
313
				}
9878 amit.gupta 314
			}
2130 rajveer 315
			irDataXMLSnippets.add(this.xmlIndentation[2] + "<ProductImageURL>" + imageUrl + "</ProductImageURL>");
316
 
1678 rajveer 317
			irDataXMLSnippets.add(this.xmlIndentation[1] + "</products>");		
318
		}
319
	}
320
 
321
	/**
322
	 * Generate the xml list of all the active phones and store in a file
323
	 * @throws Exception
324
	 */
2227 rajveer 325
	public void generateProductsListXML() throws Exception {
1678 rajveer 326
		ArrayList<String> productXMLSnippets = new ArrayList<String>();
327
		productXMLSnippets.add("<saholic.com>");
328
 
329
		getProductsXML(productXMLSnippets);
330
 
331
		productXMLSnippets.add("</saholic.com>");
332
 
333
		String productDataXML = StringUtils.join(productXMLSnippets, "\n");
334
 
335
		Utils.info(productDataXML);
336
 
337
		// Write it to file
2130 rajveer 338
		String productXMLFilename = Utils.EXPORT_PARTNERS_CONTENT_PATH + "saholicmobilephones.xml";
1678 rajveer 339
		DBUtils.store(productDataXML, productXMLFilename);
340
	}
2227 rajveer 341
 
5355 varun.gupt 342
	/**
343
	 * Generate the xml list of all the active accessories and store in a file
344
	 * @throws Exception
345
	 */
346
	public void generateAccessoriesXML() throws Exception	{
347
		LogisticsService.Client prod_client = null;
348
 
349
		try	{
350
			LogisticsClient logistics_prod = new LogisticsClient("logistics_service_prod_server_host","logistics_service_prod_server_port");
351
			prod_client = logistics_prod.getClient();
352
 
353
		} catch (Exception e) {
354
			prod_client = null;
355
			Utils.info("Logistics estimations can't be fetched as Logistics Service is inaccessible" + e);
356
		}
357
		List<String> accessoriesXMLSnippets = new ArrayList<String>();
358
 
359
		accessoriesXMLSnippets.add("<saholic.com>");
360
 
361
		for(Long entityId: entityIdItemMap.keySet())	{
362
 
363
			List<Item> items = entityIdItemMap.get(entityId);
364
			Item firstItem = items.get(0);
365
 
366
			if(! isAccessory(firstItem))	{
367
				continue;
368
			}
369
			String title = getProductTitle(firstItem);
370
			String url = getProductURL(entityId, firstItem);
371
			String imageUrl = "http://static" + ((entityId+1)%3) + ".saholic.com" + File.separator + "images" + File.separator +
372
            "website" + File.separator + entityId + File.separator + "icon.jpg";
373
 
374
			accessoriesXMLSnippets.add(this.xmlIndentation[1] + "<products>");	
375
			accessoriesXMLSnippets.add(this.xmlIndentation[2] + "<ProductSKU>" + entityId + "</ProductSKU>");
5362 varun.gupt 376
			accessoriesXMLSnippets.add(this.xmlIndentation[2] + "<ProductName>" + StringEscapeUtils.escapeXml(title) + "</ProductName>");
5363 varun.gupt 377
			accessoriesXMLSnippets.add(this.xmlIndentation[2] + "<ProductURL>" + StringEscapeUtils.escapeXml(url) + "</ProductURL>");
5355 varun.gupt 378
			accessoriesXMLSnippets.add(this.xmlIndentation[2] + "<ProductPrice>" + getMinPrice(items) + "</ProductPrice>");
379
			accessoriesXMLSnippets.add(this.xmlIndentation[2] + "<ProductMRP>" + getMinMRP(items) + "</ProductMRP>");
380
 
381
			LogisticsInfo logisticsInfo = null;
9878 amit.gupta 382
			if(prod_client != null){
5355 varun.gupt 383
				try {
9847 amit.gupta 384
					Long itemId = prod_client.getEntityLogisticsEstimation(entityId, DEFAULT_PINCODE, DeliveryType.PREPAID).get(0).getItemId();
5355 varun.gupt 385
					logisticsInfo = prod_client.getLogisticsEstimation(itemId, DEFAULT_PINCODE, DeliveryType.PREPAID);
386
					accessoriesXMLSnippets.add(this.xmlIndentation[2] + "<ProductDeliveryEstimate>" + logisticsInfo.getDeliveryTime() + "</ProductDeliveryEstimate>");
387
				} catch (Exception e1) {
388
					Utils.info("Unable to get Estimation for Entity: " + entityId + "\n" + e1);
389
				}
9878 amit.gupta 390
			}
5355 varun.gupt 391
			accessoriesXMLSnippets.add(this.xmlIndentation[2] + "<ProductImageURL>" + imageUrl + "</ProductImageURL>");
392
			accessoriesXMLSnippets.add(this.xmlIndentation[1] + "</products>");		
393
		}
394
 
395
		accessoriesXMLSnippets.add("</saholic.com>");
2227 rajveer 396
 
5355 varun.gupt 397
		String accessoriesXML = StringUtils.join(accessoriesXMLSnippets, "\n");
398
 
399
		Utils.info(accessoriesXML);
400
 
401
		// Write it to file
402
		String accessoriesXMLFilename = Utils.EXPORT_PARTNERS_CONTENT_PATH + "saholicaccessories.xml";
403
		DBUtils.store(accessoriesXML, accessoriesXMLFilename);
404
	}
2227 rajveer 405
 
5935 amit.gupta 406
 
407
 
2227 rajveer 408
	/**
5935 amit.gupta 409
	 * Generate the xml list of all the active cameras and store in a file
410
	 * @throws Exception
411
	 */
412
	public void generateCamerasXML() throws Exception	{
413
		LogisticsService.Client prod_client = null;
414
 
415
		try	{
416
			LogisticsClient logistics_prod = new LogisticsClient("logistics_service_prod_server_host","logistics_service_prod_server_port");
417
			prod_client = logistics_prod.getClient();
418
 
419
		} catch (Exception e) {
420
			prod_client = null;
421
			Utils.info("Logistics estimations can't be fetched as Logistics Service is inaccessible" + e);
422
		}
423
		List<String> camerasXMLSnippets = new ArrayList<String>();
424
 
425
		camerasXMLSnippets.add("<saholic.com>");
426
 
427
		for(Long entityId: entityIdItemMap.keySet())	{
428
 
429
			List<Item> items = entityIdItemMap.get(entityId);
430
			Item firstItem = items.get(0);
431
 
432
			if(! isCamera(firstItem))	{
433
				continue;
434
			}
435
			String title = getProductTitle(firstItem);
436
			String url = getProductURL(entityId, firstItem);
437
			String imageUrl = "http://static" + ((entityId+1)%3) + ".saholic.com" + File.separator + "images" + File.separator +
438
			"website" + File.separator + entityId + File.separator + "icon.jpg";
439
 
440
			camerasXMLSnippets.add(this.xmlIndentation[1] + "<products>");	
441
			camerasXMLSnippets.add(this.xmlIndentation[2] + "<ProductSKU>" + entityId + "</ProductSKU>");
442
			camerasXMLSnippets.add(this.xmlIndentation[2] + "<ProductName>" + StringEscapeUtils.escapeXml(title) + "</ProductName>");
443
			camerasXMLSnippets.add(this.xmlIndentation[2] + "<ProductURL>" + StringEscapeUtils.escapeXml(url) + "</ProductURL>");
444
			camerasXMLSnippets.add(this.xmlIndentation[2] + "<ProductPrice>" + getMinPrice(items) + "</ProductPrice>");
445
			camerasXMLSnippets.add(this.xmlIndentation[2] + "<ProductMRP>" + getMinMRP(items) + "</ProductMRP>");
6602 amit.gupta 446
			camerasXMLSnippets.add(this.xmlIndentation[2] + "<Availability>" + (inStockCatalogItemIds.contains(entityId) ? "Y" : "N") + "</Availability>");
5935 amit.gupta 447
 
9878 amit.gupta 448
			LogisticsInfo logisticsInfo = null;
5935 amit.gupta 449
			if(prod_client != null){
450
				try {
9847 amit.gupta 451
					Long itemId = prod_client.getEntityLogisticsEstimation(entityId, DEFAULT_PINCODE, DeliveryType.PREPAID).get(0).getItemId();
5935 amit.gupta 452
					logisticsInfo = prod_client.getLogisticsEstimation(itemId, DEFAULT_PINCODE, DeliveryType.PREPAID);
453
					camerasXMLSnippets.add(this.xmlIndentation[2] + "<ProductDeliveryEstimate>" + logisticsInfo.getDeliveryTime() + "</ProductDeliveryEstimate>");
454
				} catch (Exception e1) {
455
					Utils.info("Unable to get Estimation for Entity: " + entityId + "\n" + e1);
456
				}
9878 amit.gupta 457
			}
5935 amit.gupta 458
			camerasXMLSnippets.add(this.xmlIndentation[2] + "<ProductImageURL>" + imageUrl + "</ProductImageURL>");
459
			camerasXMLSnippets.add(this.xmlIndentation[1] + "</products>");		
460
		}
461
 
462
		camerasXMLSnippets.add("</saholic.com>");
463
 
464
		String camerasXML = StringUtils.join(camerasXMLSnippets, "\n");
465
 
466
		Utils.info(camerasXML);
467
 
468
		// Write it to file
469
		String accessoriesXMLFilename = Utils.EXPORT_PARTNERS_CONTENT_PATH + "saholiccameras.xml";
470
		DBUtils.store(camerasXML, accessoriesXMLFilename);
471
	}
472
 
473
	/**
2227 rajveer 474
	 * get xml feed for partner sites
475
	 * @param irDataXMLSnippets
476
	 * @throws Exception
477
	 */
478
	private void getProductsJavascript(StringBuffer sb) throws Exception{
4143 varun.gupt 479
 
5347 amit.gupta 480
		Map<String, Map<String, Long>> products = new HashMap<String, Map<String,Long>>();
2367 rajveer 481
 
5347 amit.gupta 482
		for(Map.Entry<Long, List<Item>> entry : entityIdItemMap.entrySet())	{
483
			Item item = entry.getValue().get(0);
5930 amit.gupta 484
			in.shop2020.metamodel.definitions.Category category = defContainer.getCategory(item.getCategory());
485
			in.shop2020.metamodel.definitions.Category parentCategory = category.getParentCategory();
486
			String categoryLabel = category.getLabel();
5347 amit.gupta 487
			if(parentCategory.isComparable()){
5930 amit.gupta 488
				categoryLabel = parentCategory.getLabel();
2227 rajveer 489
			}
5930 amit.gupta 490
			if(!products.containsKey(categoryLabel)){
491
				Map<String, Long> catMap = new HashMap<String, Long>();
492
				products.put(categoryLabel, catMap);
493
			}
494
			products.get(categoryLabel).put(getProductTitle(item), entry.getKey());
2227 rajveer 495
		}
4143 varun.gupt 496
		sb.append(new JSONObject(products));
2227 rajveer 497
	}
498
 
499
 
500
	/**
501
	 * Generate the javascript list of all the active phones and store in a file
502
	 * @throws Exception
503
	 */
504
	public void generateProductListJavascript() throws Exception {
505
		StringBuffer productsJavascript = new StringBuffer();
506
 
4143 varun.gupt 507
		productsJavascript.append("var productIdNames=");
2227 rajveer 508
 
509
		getProductsJavascript(productsJavascript);
510
 
4143 varun.gupt 511
		productsJavascript.append(";");
2227 rajveer 512
 
513
		// Write it to file
514
		String productXMLFilename = Utils.EXPORT_JAVASCRIPT_CONTENT_PATH + "saholicmobilephones.js";
515
		DBUtils.store(productsJavascript.toString(), productXMLFilename);
516
	}
4188 varun.gupt 517
 
518
    private void populateEntityIdItemMap(List<Item> items){
7630 amit.gupta 519
    	entityIdItemMap = new HashMap<Long, List<Item>>(); 
4188 varun.gupt 520
        for(Item item: items){
521
            //TODO Can be removed as we are checking in calling function
7629 amit.gupta 522
            if(!(item.getItemStatus()==status.ACTIVE || item.getItemStatus() == status.PAUSED)){
4188 varun.gupt 523
                continue;
524
            }
7629 amit.gupta 525
            if( item.getSellingPrice() == 0){
4188 varun.gupt 526
                continue;
527
            }
528
            List<Item> itemList = entityIdItemMap.get(item.getCatalogItemId());
529
            if(itemList == null){
530
                itemList = new ArrayList<Item>();
531
            }
532
            itemList.add(item);
533
            entityIdItemMap.put(item.getCatalogItemId(), itemList);
534
        }
535
    }
5229 varun.gupt 536
 
537
    /**
538
     * Generate XML feed for mobile site
539
     * @throws Exception
540
     */
541
    public void generateXMLFeedForMobileSite() throws Exception	{
542
    	List<String> productXMLSnippets = new ArrayList<String>();
543
		productXMLSnippets.add("<Products>");
544
		List<Long> itemIds = new ArrayList<Long>();
545
 
546
		for(Long entityId: entityIdItemMap.keySet()){
547
			List<Item> items = entityIdItemMap.get(entityId);
548
			Item firstItem = items.get(0);
549
			Utils.info("first Item: " + firstItem);
550
 
551
			if(isMobile(firstItem) || isLaptop(firstItem)) {
552
				itemIds.add(firstItem.getId());
553
			}
554
		}
4188 varun.gupt 555
 
5229 varun.gupt 556
		List<String> descriptions = new ArrayList<String>();
557
		descriptions.add("8MP camera, Super AMOLED Plus display, Android Gingerbread");
558
		descriptions.add("Android OS v2.2 Froyo, 800MHz processor, 3.5\" capacitive display");
559
		descriptions.add("Dual-SIM, Wi-Fi, Bluetooth, Social networking &amp; IM");
560
		descriptions.add("Android Gingerbread, Facebook button, 5MP camera");
561
		descriptions.add("Android Gingerbread, 1GHz processor, 3.7\" Gorilla Glass display");
562
		descriptions.add("2GB RAM, 500GB HDD, Intel Core 2 Duo T6570 processor, DOS");
563
		descriptions.add("4GB RAM, 500GB HDD, Intel Core i5 2410M processor, Windows 7 Basic");
564
		descriptions.add("3.2\" touchscreen, 2MP camera, IM &amp; social networking");
565
 
566
		for(Long entityId: entityIdItemMap.keySet()) {
567
			List<Item> items = entityIdItemMap.get(entityId);
568
			Item firstItem = items.get(0);
569
 
570
			if(!isMobile(firstItem) && !isLaptop(firstItem)){
571
				continue;
572
			}
4188 varun.gupt 573
 
5229 varun.gupt 574
			String url = getProductURL(entityId, firstItem);
575
			String imageUrl = "http://www.saholic.com/images/website" + File.separator + entityId + File.separator + "thumbnail.jpg";
576
			String description = descriptions.get((int) (8 * Math.random()));
577
			double minPrice = getMinPrice(items);
578
 
579
			String productType = "";
580
 
8749 amit.gupta 581
			if (firstItem.getCategory() == 10006)	{
5229 varun.gupt 582
				productType = "Mobile Phone";
583
 
584
			} else if (firstItem.getCategory() == 10010)	{
585
				productType = "Tablet";
586
 
587
			} else if (firstItem.getCategory() == 10050)	{
588
				productType = "Laptop";
589
			}
590
 
591
			productXMLSnippets.add(this.xmlIndentation[1] + "<Product>");	
592
 
593
			productXMLSnippets.add(this.xmlIndentation[2] + "<ID>" + entityId + "</ID>");
594
			productXMLSnippets.add(this.xmlIndentation[2] + "<Type>" + productType + "</Type>");
595
			productXMLSnippets.add(this.xmlIndentation[2] + "<Brand>" + firstItem.getBrand() + "</Brand>");
596
			productXMLSnippets.add(this.xmlIndentation[2] + "<ModelName>" + firstItem.getModelName() + "</ModelName>");
597
			productXMLSnippets.add(this.xmlIndentation[2] + "<ModelNumber>" + firstItem.getModelNumber() + "</ModelNumber>");
598
			productXMLSnippets.add(this.xmlIndentation[2] + "<URL>" + url + "</URL>");
599
			productXMLSnippets.add(this.xmlIndentation[2] + "<ImageURL>" + imageUrl + "</ImageURL>");
600
			productXMLSnippets.add(this.xmlIndentation[2] + "<ShortDesc>" + description + "</ShortDesc>");
601
			productXMLSnippets.add(this.xmlIndentation[2] + "<MRP>" + firstItem.getMrp() + "</MRP>");
602
			productXMLSnippets.add(this.xmlIndentation[2] + "<SellingPrice>" + (int)minPrice  + "</SellingPrice>");
603
 
604
			productXMLSnippets.add(this.xmlIndentation[1] + "</Product>");
605
		}
606
 
607
		productXMLSnippets.add("</Products>");
608
 
609
		String productDataXML = StringUtils.join(productXMLSnippets, "\n");
610
 
611
		Utils.info(productDataXML);
612
 
613
		// Write it to file
614
		String productXMLFilename = Utils.EXPORT_PARTNERS_CONTENT_PATH + "msitedata.xml";
615
		DBUtils.store(productDataXML, productXMLFilename);
616
    }
617
 
4188 varun.gupt 618
	/**
619
	 * Generate the xml list of all the active phones and store in a file
620
	 * @throws Exception
621
	 */
622
	public void generateProductXMLForDisplayAds() throws Exception {
4384 varun.gupt 623
		Utils.info("Generating Product XML for display ads");
4188 varun.gupt 624
		List<String> productXMLSnippets = new ArrayList<String>();
625
		productXMLSnippets.add("<saholic.com>");
626
		List<Long> itemIds = new ArrayList<Long>();
4384 varun.gupt 627
 
628
		Utils.info("Entity Ids: " + entityIdItemMap.keySet());
4188 varun.gupt 629
 
630
		for(Long entityId: entityIdItemMap.keySet()){
631
			List<Item> items = entityIdItemMap.get(entityId);
632
			Item firstItem = items.get(0);
4384 varun.gupt 633
			Utils.info("first Item: " + firstItem);
634
 
4383 varun.gupt 635
			if(isMobile(firstItem) || isLaptop(firstItem)) {
4188 varun.gupt 636
				itemIds.add(firstItem.getId());
637
			}
638
		}
639
 
640
		PromotionClient promotionClient = new PromotionClient();
641
		in.shop2020.model.v1.user.PromotionService.Client promotionServiceClient = promotionClient.getClient();
642
 
643
		List<ItemCouponDiscount> itemsCouponsAndDiscounts = promotionServiceClient.getItemDiscountMap(itemIds);
644
 
645
		Map<Long, ItemCouponDiscount> couponsAndDiscounts = new HashMap<Long, ItemCouponDiscount>();
646
 
647
		for (ItemCouponDiscount itemCouponDiscount: itemsCouponsAndDiscounts) {
648
			couponsAndDiscounts.put(itemCouponDiscount.getItemId(), itemCouponDiscount);
649
		}
4384 varun.gupt 650
		Utils.info("Entity IDs: " + entityIdItemMap.keySet());
4188 varun.gupt 651
 
652
		for(Long entityId: entityIdItemMap.keySet()) {
653
			List<Item> items = entityIdItemMap.get(entityId);
654
			Item firstItem = items.get(0);
4384 varun.gupt 655
 
656
			Utils.info("First Item: " + firstItem);
657
 
4382 varun.gupt 658
			if(!isMobile(firstItem) && !isLaptop(firstItem)){
4188 varun.gupt 659
				continue;
660
			}
661
 
662
			productXMLSnippets.add(this.xmlIndentation[1] + "<products>");	
663
 
664
			productXMLSnippets.add(this.xmlIndentation[2] + "<ProductSKU>" + entityId + "</ProductSKU>");
665
 
666
			String title = getProductTitle(firstItem);
667
			productXMLSnippets.add(this.xmlIndentation[2] + "<ProductName>" + title + "</ProductName>");
668
 
669
			String url = getProductURL(entityId, firstItem);
670
 
671
			String imageUrl = "http://static" + ((entityId+1)%3) + ".saholic.com" + File.separator + "images" + File.separator + entityId + File.separator + "icon.jpg";    
672
 
673
			productXMLSnippets.add(this.xmlIndentation[2] + "<ProductURL>" + url + "</ProductURL>");
674
 
675
			productXMLSnippets.add(this.xmlIndentation[2] + "<ProductImageURL>" + imageUrl + "</ProductImageURL>");
676
 
677
			productXMLSnippets.add(this.xmlIndentation[2] + "<ProductMRP>" + firstItem.getMrp() + "</ProductMRP>");
678
 
679
			double minPrice = getMinPrice(items);
680
			productXMLSnippets.add(this.xmlIndentation[2] + "<ProductSellingPrice>" + (int)minPrice  + "</ProductSellingPrice>");
6602 amit.gupta 681
			productXMLSnippets.add(this.xmlIndentation[2] + "<Availability>" + (inStockCatalogItemIds.contains(entityId) ? "Y" : "N") + "</Availability>");
4188 varun.gupt 682
			productXMLSnippets.add(this.xmlIndentation[2] + "<ProductDiscount>" + (int)((firstItem.getMrp()-minPrice)/firstItem.getMrp()*100) + "</ProductDiscount>");
683
 
684
			long itemId = firstItem.getId();
685
 
686
			if(couponsAndDiscounts.containsKey(itemId))	{
687
 
688
				ItemCouponDiscount itemCouponDiscount = couponsAndDiscounts.get(itemId);
689
 
690
				productXMLSnippets.add(this.xmlIndentation[2] + "<ProductCoupons>");
691
				productXMLSnippets.add(this.xmlIndentation[3] + "<Coupon>");
692
				productXMLSnippets.add(this.xmlIndentation[4] + "<CouponCode>" + itemCouponDiscount.getCouponCode() + "</CouponCode>");
693
				productXMLSnippets.add(this.xmlIndentation[4] + "<PriceAfterCoupon>" + (int)(minPrice - itemCouponDiscount.getDiscount()) + "</PriceAfterCoupon>");
694
				productXMLSnippets.add(this.xmlIndentation[3] + "</Coupon>");
695
				productXMLSnippets.add(this.xmlIndentation[2] + "</ProductCoupons>");
696
 
697
			} else	{
698
				productXMLSnippets.add(this.xmlIndentation[2] + "<ProductCoupons />");
699
			}
700
 
701
			String description = "";
702
			Entity entity = CreationUtils.getEntity(entityId);
703
			if(entity!=null){
704
				if(entity.getSlide(130001) !=null){
4202 varun.gupt 705
					description = StringEscapeUtils.escapeXml(entity.getSlide(130001).getFreeformContent().getFreeformText());
4188 varun.gupt 706
				}
707
			}
708
 
709
			productXMLSnippets.add(this.xmlIndentation[2] + "<ProductDescription>" + description + "</ProductDescription>");
710
 
711
			productXMLSnippets.add(this.xmlIndentation[1] + "</products>");	
712
		}
713
 
714
		productXMLSnippets.add("</saholic.com>");
715
 
716
		String productDataXML = StringUtils.join(productXMLSnippets, "\n");
717
 
718
		Utils.info(productDataXML);
719
 
720
		// Write it to file
721
		String productXMLFilename = Utils.EXPORT_PARTNERS_CONTENT_PATH + "advertismentapi.xml";
722
		DBUtils.store(productDataXML, productXMLFilename);
723
	}
5229 varun.gupt 724
 
8143 amit.gupta 725
	public static void main(String[] args) {
726
			try {
7506 amit.gupta 727
			CatalogClient cl = new CatalogClient();
728
			in.shop2020.model.v1.catalog.CatalogService.Client client = cl.getClient();
7629 amit.gupta 729
			List<Item> items = client.getAllItemsByStatus(status.ACTIVE);
730
			items.addAll(client.getAllItemsByStatus(status.PAUSED));
731
			ProductListGenerator generator = new ProductListGenerator(items);
7506 amit.gupta 732
 
733
        	log.info("Before thinkdigit feed.");
734
        	generator.generateThinkDigitFeed();
5229 varun.gupt 735
 
7506 amit.gupta 736
 
737
    		log.info("Before product list xml.");
738
        	generator.generateProductsListXML();
739
 
740
        	log.info("Before product accessories xml.");
741
        	generator.generateAccessoriesXML();
742
 
743
        	log.info("Before product camera xml.");
744
        	generator.generateCamerasXML();
745
 
746
        	log.info("Before product display ads.");
8143 amit.gupta 747
			} catch (Exception ex){
748
				String logfile = "/tmp/content-from-cms.log";
749
				 GmailUtils gm = new GmailUtils();
12973 amit.gupta 750
			        String[] sendTo = { "anikendra.das@shop2020.in", "amit.gupta@shop2020.in" };
8143 amit.gupta 751
 
752
			        try {
753
			            gm.sendSSLMessage(sendTo, "Partners feed generation failed", ""
754
			                    + Calendar.getInstance().getTime().toString(),
755
			                    "build@shop2020.in", "cafe@nes", logfile);
756
			        } catch (MessagingException e) {
757
			            log.error("Could not send status mail", e);
758
			        }
759
			}
7506 amit.gupta 760
    		//generator.generateProductXMLForDisplayAds();
5229 varun.gupt 761
	}
5612 amit.gupta 762
 
763
    private String readFile(String path) throws IOException {
764
		FileInputStream stream = new FileInputStream(new File(path));
765
		try {
766
			FileChannel fc = stream.getChannel();
767
			MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size()-1);
768
			/* Instead of using default, pass in a decoder. */
769
			return Charset.defaultCharset().decode(bb).toString();
770
		}
771
		finally {
772
			stream.close();
773
		}
774
	}
6025 amit.gupta 775
    /**
776
     * Feed generated for thinkdigit that only contains the live items
777
     * feed should have s
778
     */
779
    public void generateThinkDigitFeed() throws Exception{
780
 
7837 amit.gupta 781
    	List<Long> riskyPausedItems = this.getRiskyPausedItems();
6025 amit.gupta 782
    	List<String> productXMLSnippets = new ArrayList<String>();
783
    	productXMLSnippets.add("<root>");
784
    	String thinkDigitFeedFileName = Utils.EXPORT_PARTNERS_CONTENT_PATH + "all-categories.xml";
6624 rajveer 785
    	for (Long entityId : entityIdItemMap.keySet()){
786
    		List<Item> items = entityIdItemMap.get(entityId);
7373 amit.gupta 787
    		long cate = items.get(0).getCategory();
7374 amit.gupta 788
 
789
    		Utils.info(items.get(0).getId() + ","  + String.valueOf(cate));
7373 amit.gupta 790
    		Category category = Catalog.getInstance().getDefinitionsContainer().getCategory(cate);
791
    		Category parentCategory = category.getParentCategory(); 
7837 amit.gupta 792
            for(Item item: items){
793
            	if(item.getItemStatus().equals(status.ACTIVE)) {
794
            		if(!(item.isRisky() && riskyPausedItems.contains(item.getId()) )){
795
            			inStockCatalogItemIds.add(entityId);
796
            			if(validParentCategories.contains(parentCategory.getID())) { 
797
            				productXMLSnippets.add(this.xmlIndentation[1] + "<products>");
798
            				productXMLSnippets.add(this.xmlIndentation[2] + "<id>" + item.getCatalogItemId() + "</id>");
799
            				productXMLSnippets.add(this.xmlIndentation[2] + "<product>" + getProductTitle(item) + "</product>");
800
            				productXMLSnippets.add(this.xmlIndentation[2] + "<Product_URL>" + getProductURL(item.getCatalogItemId(), item, 59) + "</Product_URL>");
801
            				productXMLSnippets.add(this.xmlIndentation[2] + "<Product_Price>" + (int)item.getSellingPrice() + "</Product_Price>");
802
            				productXMLSnippets.add(this.xmlIndentation[2] + "<Merchant_Name>" + "saholic.com" + "</Merchant_Name>");
803
            				productXMLSnippets.add(this.xmlIndentation[2] + "<Category_Name>" + parentCategory.getLabel() + "</Category_Name>");
804
            				productXMLSnippets.add(this.xmlIndentation[1] + "</products>");
805
            			}
806
            			break;
807
            		}
808
            	}
809
            }
6025 amit.gupta 810
    	}
811
    	productXMLSnippets.add("</root>");
812
    	String productDataXML = StringUtils.join(productXMLSnippets, "\n");
813
    	DBUtils.store(productDataXML, thinkDigitFeedFileName);
814
 
815
    }
6257 rajveer 816
 
817
    public static void updatePriceForEntity(long catalogItemId, double sp, double mrp){
818
    	try{
819
    		String filename = Utils.EXPORT_PARTNERS_CONTENT_PATH + "saholicmobilephones.xml";
820
    		File file = new File(filename);
821
    		if (file.exists()){
822
    			DOMParser parser = new DOMParser();
823
    			parser.parse(filename);
824
    			Document doc = parser.getDocument();
825
    			NodeList list = doc.getElementsByTagName("ProductSKU");
826
    			for(int i=0; i<list.getLength(); i++){
827
    				if(list.item(i).getTextContent().equals(catalogItemId+"")){
828
    					Node spNode = doc.getElementsByTagName("ProductPrice").item(i);
829
    					spNode.setTextContent(sp+"");
830
    					Node mrpNode = doc.getElementsByTagName("ProductMRP").item(i);
831
    					mrpNode.setTextContent(mrp+"");
832
    				}
833
    			}
834
    			writeXmlFile(doc, filename);
835
    		}
836
    		else{
837
    			System.out.println("File not found!");
838
    		}
839
    	}
840
    	catch (Exception e){
841
    		e.getMessage();
842
    	}
843
    }
844
 
845
    // This method writes a DOM document to a file
846
    public static void writeXmlFile(Document doc, String filename) {
847
    	try {
848
    		// Prepare the DOM document for writing
849
    		Source source = new DOMSource(doc);
850
 
851
    		// Prepare the output file
852
    		File file = new File(filename);
853
    		Result result = new StreamResult(file);
854
 
855
    		// Write the DOM document to the file
856
    		Transformer xformer = TransformerFactory.newInstance().newTransformer();
857
    		xformer.transform(source, result);
858
    	} catch (TransformerConfigurationException e) {
859
    	} catch (TransformerException e) {
860
    	}
861
    }
7837 amit.gupta 862
 
863
    private List<Long> getRiskyPausedItems() {
864
		try {
865
			Reader reader = new FileReader(Utils.EXPORT_PATH + Utils.RISKY_PAUSED_JSON);
866
			return new Gson().fromJson(reader, new TypeToken<List<Long>>() {}.getType());
867
		} catch (FileNotFoundException e) {
868
			log.error("Could not read paused file");
869
			e.printStackTrace();
870
			return new ArrayList<Long>();
871
		}
872
	}
4143 varun.gupt 873
}