Subversion Repositories SmartDukaan

Rev

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