Subversion Repositories SmartDukaan

Rev

Rev 4802 | Rev 5229 | 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;
8
import in.shop2020.metamodel.definitions.DefinitionsContainer;
4188 varun.gupt 9
import in.shop2020.metamodel.util.CreationUtils;
1678 rajveer 10
import in.shop2020.model.v1.catalog.Item;
4188 varun.gupt 11
import in.shop2020.model.v1.catalog.status;
12
import in.shop2020.model.v1.user.ItemCouponDiscount;
13
import in.shop2020.thrift.clients.CatalogClient;
5113 amit.gupta 14
import in.shop2020.thrift.clients.LogisticsClient;
4188 varun.gupt 15
import in.shop2020.thrift.clients.PromotionClient;
16
 
2130 rajveer 17
import java.io.File;
1678 rajveer 18
import java.util.ArrayList;
4188 varun.gupt 19
import java.util.Date;
4143 varun.gupt 20
import java.util.HashMap;
1678 rajveer 21
import java.util.List;
22
import java.util.Map;
23
 
4202 varun.gupt 24
import org.apache.commons.lang.StringEscapeUtils;
1678 rajveer 25
import org.apache.commons.lang.StringUtils;
4143 varun.gupt 26
import org.json.JSONObject;
1678 rajveer 27
 
28
 
29
/**
30
 * Command line utility to generate xml file for partners
31
 * 
32
 * @author rajveer
33
 *
34
 */
35
public class ProductListGenerator {
36
 
37
	private String[] xmlIndentation = {"", "    ", "        ", "            ","                "};
2367 rajveer 38
	public Map<Long, List<Item>> entityIdItemMap;
5113 amit.gupta 39
	private static final String DEFAULT_PINCODE = "110001";
4802 amit.gupta 40
	DefinitionsContainer defContainer = Catalog.getInstance().getDefinitionsContainer();
1678 rajveer 41
 
2367 rajveer 42
	public ProductListGenerator(Map<Long, List<Item>> entityIdItemMap) throws Exception {
43
		this.entityIdItemMap = entityIdItemMap;
1678 rajveer 44
	}
45
 
46
 
47
	/**
2367 rajveer 48
	 * Get the url of the entity
1678 rajveer 49
	 * @param expEntity
50
	 * @return url
51
	 */
2367 rajveer 52
	private String getProductURL(long entityId, Item item){
4802 amit.gupta 53
		//long rootCategoryId = catm.getCategory(item.getCategory()).getParent_category_id();
54
		in.shop2020.metamodel.definitions.Category parentCategory = defContainer.getCategory(item.getCategory()).getParentCategory();
55
 
56
		String url = "http://www.saholic.com/" + parentCategory.getLabel().toLowerCase().replace(' ', '-') + "/";
2367 rajveer 57
		String productUrl = ((item.getBrand() != null) ? item.getBrand().trim() + " " : "").toLowerCase().replace(' ', '-')
58
        + "-" + ((item.getModelName() != null) ? item.getModelName().trim() + " " : "").toLowerCase().replace(' ', '-') 
59
	    + "-" + (( item.getModelNumber() != null ) ? item.getModelNumber().trim() + " ": "" ).toLowerCase().replace(' ', '-')
60
        + "-" + entityId;
1678 rajveer 61
		productUrl = productUrl.replaceAll("/", "-");
62
		url = url + productUrl;
2367 rajveer 63
		url = url.replaceAll("-+", "-");
1678 rajveer 64
		return url;
65
	}
66
 
2367 rajveer 67
 
68
 
1678 rajveer 69
	/**
3964 rajveer 70
	 * Get the minimum mrp of the items
71
	 * @param items
72
	 * @return
73
	 */
74
	private double getMinMRP(List<Item> items){
75
        double minPrice = Double.MAX_VALUE;
76
        for(Item item: items){
77
            if(minPrice > item.getMrp()){
78
                minPrice =  item.getMrp();
79
            }
80
        }
81
        return minPrice;
82
    }
83
 
84
 
85
 
86
	/**
2367 rajveer 87
	 * Get the minimum price of the items
88
	 * @param items
89
	 * @return
90
	 */
91
	private double getMinPrice(List<Item> items){
92
        double minPrice = Double.MAX_VALUE;
93
        for(Item item: items){
94
            if(minPrice > item.getSellingPrice()){
95
                minPrice = item.getSellingPrice();
96
            }
97
        }
98
        return minPrice;
99
    }
100
 
101
	/**
102
	 * Check whether product is mobile or not
103
	 * @param item
104
	 * @return
105
	 */
106
	private boolean isMobile(Item item){
4802 amit.gupta 107
		in.shop2020.metamodel.definitions.Category parentCategory = defContainer.getCategory(item.getCategory()).getParentCategory();
108
		return parentCategory.getID() == Utils.MOBILE_PHONES_CATAGORY;
2367 rajveer 109
	}
110
 
111
	/**
4143 varun.gupt 112
	 * Checks whether a product is laptop or not
113
	 */
114
	private boolean isLaptop(Item item) {
4802 amit.gupta 115
		in.shop2020.metamodel.definitions.Category parentCategory = defContainer.getCategory(item.getCategory()).getParentCategory();
116
		return parentCategory.getID() == Utils.LAPTOPS_CATEGORY;
4143 varun.gupt 117
	}
118
 
119
	/**
2367 rajveer 120
	 * 
121
	 * @param item
122
	 * @return
123
	 */
124
	private String getProductTitle(Item item){
2542 rajveer 125
		String title = ((item.getBrand() != null) ? item.getBrand().trim() + " " : "")
126
		+ ((item.getModelName() != null) ? item.getModelName().trim() + " " : "")
127
		+ (( item.getModelNumber() != null ) ? item.getModelNumber().trim() : "" );
2561 rajveer 128
		title = title.replaceAll("  ", " ");
2367 rajveer 129
		return title;
130
	}
131
 
132
	/**
1678 rajveer 133
	 * get xml feed for partner sites
134
	 * @param irDataXMLSnippets
135
	 * @throws Exception
136
	 */
2367 rajveer 137
	private void getProductsXML(ArrayList<String> irDataXMLSnippets) throws Exception{
5113 amit.gupta 138
		LogisticsService.Client prod_client = null;
139
		try {
140
			LogisticsClient logistics_prod = new LogisticsClient("logistics_service_prod_server_host","logistics_service_prod_server_port");
141
			prod_client = logistics_prod.getClient();
142
		} catch (Exception e) {
143
			prod_client = null;
144
			Utils.info("Logistics estimations can't be fetched as Logistics Service is inaccessible"
145
					+ e);
146
		}
2367 rajveer 147
		for(Long entityId: entityIdItemMap.keySet()){
148
			List<Item> items = entityIdItemMap.get(entityId);
149
			Item firstItem = items.get(0);
150
			if(!isMobile(firstItem)){
1678 rajveer 151
				continue;
152
			}
153
 
154
			irDataXMLSnippets.add(this.xmlIndentation[1] + "<products>");	
155
 
2367 rajveer 156
			irDataXMLSnippets.add(this.xmlIndentation[2] + "<ProductSKU>" + entityId + "</ProductSKU>");
1678 rajveer 157
 
2367 rajveer 158
			String title = getProductTitle(firstItem);
1678 rajveer 159
			irDataXMLSnippets.add(this.xmlIndentation[2] + "<ProductName>" + title + "</ProductName>");
160
 
2367 rajveer 161
			String url = getProductURL(entityId, firstItem);
3929 mandeep.dh 162
 
163
			String imageUrl = "http://static" + ((entityId+1)%3) + ".saholic.com" + File.separator + "images" + File.separator +
164
			                  "website" + File.separator + entityId + File.separator + "icon.jpg";
165
 
1678 rajveer 166
			irDataXMLSnippets.add(this.xmlIndentation[2] + "<ProductURL>" + url + "</ProductURL>");
167
 
168
 
2367 rajveer 169
			irDataXMLSnippets.add(this.xmlIndentation[2] + "<ProductPrice>" + getMinPrice(items) + "</ProductPrice>");
1678 rajveer 170
 
3964 rajveer 171
			irDataXMLSnippets.add(this.xmlIndentation[2] + "<ProductMRP>" + getMinMRP(items) + "</ProductMRP>");
172
 
5113 amit.gupta 173
			LogisticsInfo logisticsInfo = null;
174
			if(prod_client != null){
175
				try {
176
					Long itemId = prod_client.getEntityLogisticsEstimation(
177
							entityId, DEFAULT_PINCODE, DeliveryType.PREPAID)
178
							.get(0);
179
					logisticsInfo = prod_client.getLogisticsEstimation(itemId,
180
							DEFAULT_PINCODE, DeliveryType.PREPAID);
181
					irDataXMLSnippets.add(this.xmlIndentation[2] + "<ProductDeliveryEstimate>" + logisticsInfo.getDeliveryTime() + "</ProductDeliveryEstimate>");
182
				} catch (Exception e1) {
183
					Utils.info("Unable to get Estimation for Entity: " + entityId + "\n" + e1);
184
				}
185
			}
2130 rajveer 186
			irDataXMLSnippets.add(this.xmlIndentation[2] + "<ProductImageURL>" + imageUrl + "</ProductImageURL>");
187
 
1678 rajveer 188
			irDataXMLSnippets.add(this.xmlIndentation[1] + "</products>");		
189
		}
190
	}
191
 
192
	/**
193
	 * Generate the xml list of all the active phones and store in a file
194
	 * @throws Exception
195
	 */
2227 rajveer 196
	public void generateProductsListXML() throws Exception {
1678 rajveer 197
		ArrayList<String> productXMLSnippets = new ArrayList<String>();
198
		productXMLSnippets.add("<saholic.com>");
199
 
200
		getProductsXML(productXMLSnippets);
201
 
202
		productXMLSnippets.add("</saholic.com>");
203
 
204
		String productDataXML = StringUtils.join(productXMLSnippets, "\n");
205
 
206
		Utils.info(productDataXML);
207
 
208
		// Write it to file
2130 rajveer 209
		String productXMLFilename = Utils.EXPORT_PARTNERS_CONTENT_PATH + "saholicmobilephones.xml";
1678 rajveer 210
		DBUtils.store(productDataXML, productXMLFilename);
211
	}
2227 rajveer 212
 
213
 
214
 
215
 
216
	/**
217
	 * get xml feed for partner sites
218
	 * @param irDataXMLSnippets
219
	 * @throws Exception
220
	 */
221
	private void getProductsJavascript(StringBuffer sb) throws Exception{
4143 varun.gupt 222
 
223
		Map<String, Long> mobilePhones = new HashMap<String, Long>();
224
		Map<String, Long> laptops = new HashMap<String, Long>();
2367 rajveer 225
 
4143 varun.gupt 226
		for(Long entityId: entityIdItemMap.keySet())	{
227
			Item item = entityIdItemMap.get(entityId).get(0);
228
 
229
			if (isMobile(item))	{
230
				mobilePhones.put(getProductTitle(item), entityId);
2227 rajveer 231
			}
4143 varun.gupt 232
			else if (isLaptop(item))	{
233
				laptops.put(getProductTitle(item), entityId);
2233 rajveer 234
			}
2227 rajveer 235
		}
4143 varun.gupt 236
		Map<String, Map<String, Long>> products = new HashMap<String, Map<String,Long>>();
237
		products.put("mobiles", mobilePhones);
238
		products.put("laptops", laptops);
239
		sb.append(new JSONObject(products));
2227 rajveer 240
	}
241
 
242
 
243
	/**
244
	 * Generate the javascript list of all the active phones and store in a file
245
	 * @throws Exception
246
	 */
247
	public void generateProductListJavascript() throws Exception {
248
		StringBuffer productsJavascript = new StringBuffer();
249
 
4143 varun.gupt 250
		productsJavascript.append("var productIdNames=");
2227 rajveer 251
 
252
		getProductsJavascript(productsJavascript);
253
 
4143 varun.gupt 254
		productsJavascript.append(";");
2227 rajveer 255
 
256
		// Write it to file
257
		String productXMLFilename = Utils.EXPORT_JAVASCRIPT_CONTENT_PATH + "saholicmobilephones.js";
258
		DBUtils.store(productsJavascript.toString(), productXMLFilename);
259
	}
4188 varun.gupt 260
 
261
	public static void main(String[] args) throws Exception {
262
		CatalogClient cl = new CatalogClient();
263
		in.shop2020.model.v1.catalog.InventoryService.Client client = cl.getClient();
264
 
265
		List<Item> items = cl.getClient().getAllItemsByStatus(status.ACTIVE);
266
		items.addAll(cl.getClient().getAllItemsByStatus(status.PAUSED));
267
		items.addAll(cl.getClient().getAllItemsByStatus(status.PAUSED_BY_RISK));
268
 
269
		Map<Long, List<Item>> entityIdItemMap1 = new HashMap<Long, List<Item>>();
270
		ProductListGenerator pl = new ProductListGenerator(entityIdItemMap1);
271
		pl.populateEntityIdItemMap(items);
5113 amit.gupta 272
		pl.generateProductsListXML();
273
		//pl.generateProductXMLForDisplayAds();
4188 varun.gupt 274
	}
275
 
276
    private void populateEntityIdItemMap(List<Item> items){
277
        Date toDate = new Date();
278
        for(Item item: items){
279
            //TODO Can be removed as we are checking in calling function
280
            if(!(item.getItemStatus()==status.ACTIVE || item.getItemStatus()==status.CONTENT_COMPLETE || item.getItemStatus() == status.PAUSED)){
281
                continue;
282
            }
283
            if(toDate.getTime() < item.getStartDate() ||  item.getSellingPrice() == 0){
284
                continue;
285
            }
286
            List<Item> itemList = entityIdItemMap.get(item.getCatalogItemId());
287
            if(itemList == null){
288
                itemList = new ArrayList<Item>();
289
            }
290
            itemList.add(item);
291
            entityIdItemMap.put(item.getCatalogItemId(), itemList);
292
        }
293
 
294
        //Remove all items which have not been updated since last content generation.
295
        List<Long> removeEntities = new ArrayList<Long>();
296
        for(Long entityId:entityIdItemMap.keySet()){
297
            boolean isValidEntity = false;
298
            //If any one of the items has been updated before current timestamp, than we generate content for whole entity
299
            for(Item item: entityIdItemMap.get(entityId)){
300
                if(item.getUpdatedOn() > 0){
301
                    isValidEntity = true;
302
                }
303
            }
304
            if(!isValidEntity){
305
                removeEntities.add(entityId);
306
            }
307
        }
308
        for(Long entityId: removeEntities){
309
            entityIdItemMap.remove(entityId);
310
        }
311
    }
312
 
313
 
314
	/**
315
	 * Generate the xml list of all the active phones and store in a file
316
	 * @throws Exception
317
	 */
318
	public void generateProductXMLForDisplayAds() throws Exception {
4384 varun.gupt 319
		Utils.info("Generating Product XML for display ads");
4188 varun.gupt 320
		List<String> productXMLSnippets = new ArrayList<String>();
321
		productXMLSnippets.add("<saholic.com>");
322
		List<Long> itemIds = new ArrayList<Long>();
4384 varun.gupt 323
 
324
		Utils.info("Entity Ids: " + entityIdItemMap.keySet());
4188 varun.gupt 325
 
326
		for(Long entityId: entityIdItemMap.keySet()){
327
			List<Item> items = entityIdItemMap.get(entityId);
328
			Item firstItem = items.get(0);
4384 varun.gupt 329
			Utils.info("first Item: " + firstItem);
330
 
4383 varun.gupt 331
			if(isMobile(firstItem) || isLaptop(firstItem)) {
4188 varun.gupt 332
				itemIds.add(firstItem.getId());
333
			}
334
		}
335
 
336
		PromotionClient promotionClient = new PromotionClient();
337
		in.shop2020.model.v1.user.PromotionService.Client promotionServiceClient = promotionClient.getClient();
338
 
339
		List<ItemCouponDiscount> itemsCouponsAndDiscounts = promotionServiceClient.getItemDiscountMap(itemIds);
340
 
341
		Map<Long, ItemCouponDiscount> couponsAndDiscounts = new HashMap<Long, ItemCouponDiscount>();
342
 
343
		for (ItemCouponDiscount itemCouponDiscount: itemsCouponsAndDiscounts) {
344
			couponsAndDiscounts.put(itemCouponDiscount.getItemId(), itemCouponDiscount);
345
		}
4384 varun.gupt 346
		Utils.info("Entity IDs: " + entityIdItemMap.keySet());
4188 varun.gupt 347
 
348
		for(Long entityId: entityIdItemMap.keySet()) {
349
			List<Item> items = entityIdItemMap.get(entityId);
350
			Item firstItem = items.get(0);
4384 varun.gupt 351
 
352
			Utils.info("First Item: " + firstItem);
353
 
4382 varun.gupt 354
			if(!isMobile(firstItem) && !isLaptop(firstItem)){
4188 varun.gupt 355
				continue;
356
			}
357
 
358
			productXMLSnippets.add(this.xmlIndentation[1] + "<products>");	
359
 
360
			productXMLSnippets.add(this.xmlIndentation[2] + "<ProductSKU>" + entityId + "</ProductSKU>");
361
 
362
			String title = getProductTitle(firstItem);
363
			productXMLSnippets.add(this.xmlIndentation[2] + "<ProductName>" + title + "</ProductName>");
364
 
365
			String url = getProductURL(entityId, firstItem);
366
 
367
			String imageUrl = "http://static" + ((entityId+1)%3) + ".saholic.com" + File.separator + "images" + File.separator + entityId + File.separator + "icon.jpg";    
368
 
369
			productXMLSnippets.add(this.xmlIndentation[2] + "<ProductURL>" + url + "</ProductURL>");
370
 
371
			productXMLSnippets.add(this.xmlIndentation[2] + "<ProductImageURL>" + imageUrl + "</ProductImageURL>");
372
 
373
			productXMLSnippets.add(this.xmlIndentation[2] + "<ProductMRP>" + firstItem.getMrp() + "</ProductMRP>");
374
 
375
			double minPrice = getMinPrice(items);
376
			productXMLSnippets.add(this.xmlIndentation[2] + "<ProductSellingPrice>" + (int)minPrice  + "</ProductSellingPrice>");
377
 
378
			productXMLSnippets.add(this.xmlIndentation[2] + "<ProductDiscount>" + (int)((firstItem.getMrp()-minPrice)/firstItem.getMrp()*100) + "</ProductDiscount>");
379
 
380
			long itemId = firstItem.getId();
381
 
382
			if(couponsAndDiscounts.containsKey(itemId))	{
383
 
384
				ItemCouponDiscount itemCouponDiscount = couponsAndDiscounts.get(itemId);
385
 
386
				productXMLSnippets.add(this.xmlIndentation[2] + "<ProductCoupons>");
387
				productXMLSnippets.add(this.xmlIndentation[3] + "<Coupon>");
388
				productXMLSnippets.add(this.xmlIndentation[4] + "<CouponCode>" + itemCouponDiscount.getCouponCode() + "</CouponCode>");
389
				productXMLSnippets.add(this.xmlIndentation[4] + "<PriceAfterCoupon>" + (int)(minPrice - itemCouponDiscount.getDiscount()) + "</PriceAfterCoupon>");
390
				productXMLSnippets.add(this.xmlIndentation[3] + "</Coupon>");
391
				productXMLSnippets.add(this.xmlIndentation[2] + "</ProductCoupons>");
392
 
393
			} else	{
394
				productXMLSnippets.add(this.xmlIndentation[2] + "<ProductCoupons />");
395
			}
396
 
397
			String description = "";
398
			Entity entity = CreationUtils.getEntity(entityId);
399
			if(entity!=null){
400
				if(entity.getSlide(130001) !=null){
4202 varun.gupt 401
					description = StringEscapeUtils.escapeXml(entity.getSlide(130001).getFreeformContent().getFreeformText());
4188 varun.gupt 402
				}
403
			}
404
 
405
			productXMLSnippets.add(this.xmlIndentation[2] + "<ProductDescription>" + description + "</ProductDescription>");
406
 
407
			productXMLSnippets.add(this.xmlIndentation[1] + "</products>");	
408
		}
409
 
410
		productXMLSnippets.add("</saholic.com>");
411
 
412
		String productDataXML = StringUtils.join(productXMLSnippets, "\n");
413
 
414
		Utils.info(productDataXML);
415
 
416
		// Write it to file
417
		String productXMLFilename = Utils.EXPORT_PARTNERS_CONTENT_PATH + "advertismentapi.xml";
418
		DBUtils.store(productDataXML, productXMLFilename);
419
	}
4143 varun.gupt 420
}