Subversion Repositories SmartDukaan

Rev

Rev 7972 | Rev 9842 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
5128 amit.gupta 1
package in.shop2020.catalog.util;
2
 
3
import in.shop2020.catalog.dashboard.shared.Item;
4
import in.shop2020.catalog.dashboard.shared.VendorPricings;
5
import in.shop2020.config.ConfigException;
5946 rajveer 6
import in.shop2020.model.v1.catalog.CatalogService;
5384 phani.kuma 7
import in.shop2020.model.v1.catalog.ItemType;
5128 amit.gupta 8
import in.shop2020.model.v1.catalog.status;
5946 rajveer 9
import in.shop2020.model.v1.inventory.InventoryService.Client;
6165 amar.kumar 10
import in.shop2020.model.v1.inventory.Vendor;
5128 amit.gupta 11
import in.shop2020.thrift.clients.CatalogClient;
5946 rajveer 12
import in.shop2020.thrift.clients.InventoryClient;
5128 amit.gupta 13
import in.shop2020.thrift.clients.config.ConfigClient;
14
import in.shop2020.utils.CategoryManager;
15
import in.shop2020.utils.ConfigClientKeys;
16
 
17
import java.io.ByteArrayOutputStream;
18
import java.io.IOException;
19
import java.text.DecimalFormat;
20
import java.util.ArrayList;
21
import java.util.HashMap;
6165 amar.kumar 22
import java.util.Hashtable;
5128 amit.gupta 23
import java.util.List;
24
import java.util.Map;
25
 
26
import org.apache.log4j.Logger;
27
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
28
import org.apache.poi.hssf.util.HSSFColor;
29
import org.apache.poi.ss.usermodel.CellStyle;
30
import org.apache.poi.ss.usermodel.Font;
31
import org.apache.poi.ss.usermodel.Row;
32
import org.apache.poi.ss.usermodel.Sheet;
33
import org.apache.poi.ss.usermodel.Workbook;
34
 
35
public class ReportGenerator {
36
 
37
	private static Logger logger = Logger.getLogger(ReportGenerator.class);
38
	public static int TYPE_INACTIVE = 0;
39
	public static int TYPE_BREAKEVEN = 1;
40
	public static int TYPE_BOTH = 2;
41
	Map<String, String> configMap = getConfigdataforPriceCompare();
42
 
43
	public ByteArrayOutputStream generateExcelStream(int type) {
44
		ByteArrayOutputStream baosXLS = new ByteArrayOutputStream();
45
 
46
		DecimalFormat numberFormat = new DecimalFormat("#.##");
47
 
48
		Workbook wb = new HSSFWorkbook();
49
 
50
		Font font = wb.createFont();
51
		font.setBoldweight(Font.BOLDWEIGHT_BOLD);
52
		CellStyle styleBold = wb.createCellStyle();
53
		styleBold.setFont(font);
54
 
55
		CellStyle styleRedBG = wb.createCellStyle();
56
		styleRedBG.setFont(font);
57
		styleRedBG.setFillBackgroundColor(HSSFColor.RED.index);
58
 
59
		CellStyle styleWT = wb.createCellStyle();
60
		styleWT.setWrapText(true);
61
		short rowNo = 0;
62
 
63
        List<in.shop2020.model.v1.catalog.Item> thriftItemList = new ArrayList<in.shop2020.model.v1.catalog.Item>();
64
        List<in.shop2020.model.v1.catalog.Item> thriftItemListInactive = new ArrayList<in.shop2020.model.v1.catalog.Item>();
65
        try {
66
            CatalogClient catalogServiceClient = new CatalogClient(ConfigClientKeys.catalog_service_server_host_prod.toString(),
67
                    ConfigClientKeys.catalog_service_server_port.toString());
5946 rajveer 68
            CatalogService.Client catalogClient = catalogServiceClient.getClient();
69
 
70
            InventoryClient inventoryServiceClient = new InventoryClient();
71
            Client inventoryClient = inventoryServiceClient.getClient();
6165 amar.kumar 72
            List<Vendor> vendors = inventoryClient.getAllVendors();
73
            Map<Long, String> vendorIdNameMap = new Hashtable<Long, String>();
74
            for(Vendor vendor : vendors){
75
            	vendorIdNameMap.put(vendor.getId(), vendor.getName());
76
            }
5128 amit.gupta 77
            thriftItemListInactive.addAll(catalogClient.getAllItemsByStatus(status.PAUSED));
78
            if(TYPE_INACTIVE != type){
5183 amit.gupta 79
            	catalogServiceClient = new CatalogClient(ConfigClientKeys.catalog_service_server_host_prod.toString(),
80
                        ConfigClientKeys.catalog_service_server_port.toString());
81
            	catalogClient = catalogServiceClient.getClient();
5128 amit.gupta 82
	            thriftItemList.addAll(catalogClient.getAllItemsByStatus(status.ACTIVE));
5183 amit.gupta 83
 
84
	            catalogServiceClient = new CatalogClient(ConfigClientKeys.catalog_service_server_host_prod.toString(),
85
                        ConfigClientKeys.catalog_service_server_port.toString());
86
            	catalogClient = catalogServiceClient.getClient();
5128 amit.gupta 87
	            thriftItemList.addAll(catalogClient.getAllItemsByStatus(status.PAUSED_BY_RISK));
88
	            thriftItemList.addAll(thriftItemListInactive);
89
	            Sheet ngpSheet = wb.createSheet("Negative Gross Profit");
90
	            rowNo = 0;
91
 
92
	            Row headerRow = ngpSheet.createRow(rowNo);
93
	            headerRow.createCell(0).setCellValue("Item Id");
94
	            headerRow.getCell(0).setCellStyle(styleBold);
95
	            headerRow.createCell(1).setCellValue("Brand");
96
	            headerRow.getCell(1).setCellStyle(styleBold);
97
	            headerRow.createCell(2).setCellValue("Model Name");
98
	            headerRow.getCell(2).setCellStyle(styleBold);
99
	            headerRow.createCell(3).setCellValue("Model Number");
100
	            headerRow.getCell(3).setCellStyle(styleBold);
101
	            headerRow.createCell(4).setCellValue("Color");
102
	            headerRow.getCell(4).setCellStyle(styleBold);
6165 amar.kumar 103
	            headerRow.createCell(5).setCellValue("Transfer Price");
5128 amit.gupta 104
	            headerRow.getCell(5).setCellStyle(styleBold);
6165 amar.kumar 105
	            headerRow.createCell(6).setCellValue("Vendor");
5128 amit.gupta 106
	            headerRow.getCell(6).setCellStyle(styleBold);
6165 amar.kumar 107
	            headerRow.createCell(7).setCellValue("Selling Price");
5128 amit.gupta 108
	            headerRow.getCell(7).setCellStyle(styleBold);
6165 amar.kumar 109
	            headerRow.createCell(8).setCellValue("Break Even Price");
5128 amit.gupta 110
	            headerRow.getCell(8).setCellStyle(styleBold);
6165 amar.kumar 111
	            headerRow.createCell(9).setCellValue("Current Status");
112
	            headerRow.getCell(9).setCellStyle(styleBold);
113
	            headerRow.createCell(10).setCellValue("Reason");
114
	            headerRow.getCell(10).setCellStyle(styleBold);
5128 amit.gupta 115
	            for(in.shop2020.model.v1.catalog.Item thriftItem : thriftItemList) {
5946 rajveer 116
	            	List<in.shop2020.model.v1.inventory.VendorItemPricing> vip = inventoryClient.getAllItemPricing(thriftItem.getId());
5128 amit.gupta 117
	            	Item item = getItemFromThriftItem(thriftItem, vip);
118
	            	List<Object> breakeven = isBreakeven(item);
119
	            	if(!(Boolean)breakeven.get(0)){
120
	            		try{
121
	            		Row itemRow = ngpSheet.createRow(++rowNo);
122
	            		itemRow.createCell(0).setCellValue(item.getId());
123
	            		itemRow.createCell(1).setCellValue(item.getBrand());
124
	            		itemRow.createCell(2).setCellValue(item.getModelName());
125
	            		itemRow.createCell(3).setCellValue(item.getModelNumber());
126
	            		itemRow.createCell(4).setCellValue(item.getColor());
127
 
6165 amar.kumar 128
	            		try{
129
	            			itemRow.createCell(5).setCellValue(numberFormat.format((Double)breakeven.get(2)));
130
	            		} catch (Exception e){
131
	            			itemRow.createCell(5).setCellValue("Empty");
132
	            		}
133
 
134
	            		try{
135
	            			itemRow.createCell(6).setCellValue(vendorIdNameMap.get(breakeven.get(3)));
136
	            		} catch (Exception e){
137
	            			itemRow.createCell(6).setCellValue("Empty");
138
	            		}
139
 
5128 amit.gupta 140
	            		Double sellingPrice = item.getSellingPrice();
141
	            		if(sellingPrice != null){
6165 amar.kumar 142
	            			itemRow.createCell(7).setCellValue(numberFormat.format(sellingPrice));
5128 amit.gupta 143
	            		} else {
6165 amar.kumar 144
	            			itemRow.createCell(7).setCellValue("NULL");
5128 amit.gupta 145
	            		}
146
 
147
	            		try{
6165 amar.kumar 148
	            			itemRow.createCell(8).setCellValue(numberFormat.format((Double)breakeven.get(1)));
5128 amit.gupta 149
	            		} catch (Exception e){
6165 amar.kumar 150
	            			itemRow.createCell(8).setCellValue("Empty");
5128 amit.gupta 151
	            		}
6165 amar.kumar 152
	            		itemRow.createCell(9).setCellValue(thriftItem.getItemStatus().toString());
5128 amit.gupta 153
	            		try { 
6165 amar.kumar 154
	            			itemRow.createCell(10).setCellValue((String)breakeven.get(1));
5128 amit.gupta 155
	            		}catch (Exception e) {
6165 amar.kumar 156
	            			itemRow.createCell(10).setCellValue("");							
5128 amit.gupta 157
						}
158
	            		}catch (Exception e) {
159
							logger.info("Error occurred for item : " + item.getId());
160
							System.out.println("Item id failed for breakeven report: " + item.getId());
161
						}
162
	            	}
163
	            }
164
            }
165
 
166
 
167
            if(TYPE_BREAKEVEN != type){
5183 amit.gupta 168
            	catalogServiceClient = new CatalogClient(ConfigClientKeys.catalog_service_server_host_prod.toString(),
169
                         ConfigClientKeys.catalog_service_server_port.toString());
170
             	catalogClient = catalogServiceClient.getClient();
171
 
5128 amit.gupta 172
            	thriftItemListInactive.addAll(catalogClient.getAllItemsByStatus(status.PHASED_OUT));
173
            	Sheet inactiveItemsSheet = wb.createSheet("Inactive Items with Positive Inventory");
174
	            rowNo = 0;
175
	            Row anotherHeaderRow = inactiveItemsSheet.createRow(0);
176
	            anotherHeaderRow.createCell(0).setCellValue("Item Id");
177
	            anotherHeaderRow.getCell(0).setCellStyle(styleBold);
178
	            anotherHeaderRow.createCell(1).setCellValue("Brand");
179
	            anotherHeaderRow.getCell(1).setCellStyle(styleBold);
180
	            anotherHeaderRow.createCell(2).setCellValue("Model Name");
181
	            anotherHeaderRow.getCell(2).setCellStyle(styleBold);
182
	            anotherHeaderRow.createCell(3).setCellValue("Model Number");
183
	            anotherHeaderRow.getCell(3).setCellStyle(styleBold);
184
	            anotherHeaderRow.createCell(4).setCellValue("Color");
185
	            anotherHeaderRow.getCell(4).setCellStyle(styleBold);
186
	            anotherHeaderRow.createCell(5).setCellValue("Status");
187
	            anotherHeaderRow.getCell(5).setCellStyle(styleBold);
188
	            anotherHeaderRow.createCell(6).setCellValue("Available Pieces");
189
	            anotherHeaderRow.getCell(6).setCellStyle(styleBold);
190
				for (in.shop2020.model.v1.catalog.Item thriftItem : thriftItemListInactive) {
191
					try {
5946 rajveer 192
						in.shop2020.model.v1.inventory.ItemInventory itemInventory = inventoryClient.getItemInventoryByItemId(thriftItem.getId());
5128 amit.gupta 193
						long available = 0;
194
						for(long count : itemInventory.getAvailability().values()){
195
							available += count;
196
						}
197
						for(long count : itemInventory.getReserved().values()){
198
							available -= count;
199
						}
200
						if(available > 0){
201
							Row itemRow = inactiveItemsSheet.createRow(++rowNo);
202
		                	itemRow.createCell(0).setCellValue(thriftItem.getId());
203
		                	itemRow.createCell(1).setCellValue(thriftItem.getBrand());
204
		                	itemRow.createCell(2).setCellValue(thriftItem.getModelName());
205
		                	itemRow.createCell(3).setCellValue(thriftItem.getModelNumber());
206
		                	itemRow.createCell(4).setCellValue(thriftItem.getColor());
207
		                	itemRow.createCell(5).setCellValue(thriftItem.getItemStatus().toString());
208
		                	itemRow.createCell(6).setCellValue(available);
209
						}
210
					} catch (Exception e) {
211
						logger.error("Error getting live inventory for item" + thriftItem.getId() + "\n"
212
								+ e);
213
					}
214
				}
215
            }
216
            try {
217
            	wb.write(baosXLS);
218
            	baosXLS.close();
219
            } catch (IOException e) {
220
            	e.printStackTrace();
221
            	throw e;
222
            }
223
 
224
        } catch (Exception e) {
225
        	e.printStackTrace();
226
        	baosXLS = null;
227
            logger.error("Error getting items from Catalog\n" + e);
228
        }
229
 
230
 
231
		return baosXLS;
232
	}
233
 
234
	private List<Object> isBreakeven(Item newItem) {
235
		List<Object> list = new ArrayList<Object>();
236
		boolean message = true;
6165 amar.kumar 237
		Long vendor = 0L;
5128 amit.gupta 238
 
239
		if (newItem.getSellingPrice() == null || newItem.getSellingPrice().compareTo(0d) <= 0) {
240
			message=false;
241
			list.add(message);
242
			list.add("Selling price is empty or 0");
243
			return list;
244
		}
245
 
246
		double transferPrice;
247
		if (newItem.getPreferredVendor() == null
248
				&& !newItem.getVendorPricesMap().isEmpty()) {
249
			transferPrice = -1;
250
			for (VendorPricings vendorDetail : newItem.getVendorPricesMap()
251
					.values()) {
252
				if (transferPrice > vendorDetail.getTransferPrice()
253
						|| transferPrice == -1) {
254
					transferPrice = vendorDetail.getTransferPrice();
6165 amar.kumar 255
					vendor = vendorDetail.getVendorId();
5128 amit.gupta 256
				}
257
			}
258
		} else if (!newItem.getVendorPricesMap().isEmpty()
259
				&& newItem.getVendorPricesMap().containsKey(
260
						newItem.getPreferredVendor())) {
261
			transferPrice = newItem.getVendorPricesMap()
262
					.get(newItem.getPreferredVendor()).getTransferPrice();
6165 amar.kumar 263
			vendor = newItem.getVendorPricesMap().get(newItem.getPreferredVendor()).getVendorId();
5128 amit.gupta 264
		} else {
265
			message = false;
266
			list.add(message);
267
			list.add("Preferred vendor is not in Vendor Item Mapping.");
268
			return list;
269
		}
270
 
271
		double breakeven;
272
 
273
		//if weight is not mention add courier cost as Rs. 60
274
		if (newItem.getWeight() == null) {
275
			breakeven = transferPrice + 60;
276
		} else {
277
 
278
			double weightfactor = Math.ceil((newItem.getWeight() * 1000)
279
					/ Double.parseDouble(configMap.get("courier_weight_factor")));
280
			double couriercost = Double.parseDouble(configMap
281
					.get("courier_cost_factor")) * weightfactor;
282
			double costfactor = (Double.parseDouble(configMap
283
					.get("transfer_price_percentage")) * transferPrice) / 100;
284
			if (costfactor < Double.parseDouble(configMap
285
					.get("transfer_price_factor"))) {
286
				breakeven = transferPrice
287
						+ couriercost
288
						+ Double.parseDouble(configMap
289
								.get("breakeven_additon_factor"));
290
			} else {
291
				breakeven = (transferPrice + couriercost)
292
						/ Double.parseDouble(configMap.get("breakeven_divisor"));
293
			}
294
		}
295
 
296
		if (Double.compare(breakeven, newItem.getSellingPrice())>=0) {
297
			message=false;
298
			list.add(message);
299
			list.add(breakeven);
6165 amar.kumar 300
			list.add(transferPrice);
301
			list.add(vendor);
5128 amit.gupta 302
			return list;
303
		}
304
		list.add(message);
305
		return list;
306
	}
307
 
308
	private Map<String, String> getConfigdataforPriceCompare() {
309
		Map<String, String> ConfigMap = new HashMap<String, String>();
310
		try {
311
			ConfigMap.put(
312
					"courier_cost_factor",
313
					ConfigClient.getClient().get(
314
							ConfigClientKeys.courier_cost_factor.toString()));
315
			ConfigMap.put("courier_weight_factor", ConfigClient.getClient()
316
					.get(ConfigClientKeys.courier_weight_factor.toString()));
317
			ConfigMap.put(
318
					"breakeven_divisor",
319
					ConfigClient.getClient().get(
320
							ConfigClientKeys.breakeven_divisor.toString()));
321
			ConfigMap.put("breakeven_additon_factor", ConfigClient.getClient()
322
					.get(ConfigClientKeys.breakeven_additon_factor.toString()));
323
			ConfigMap
324
					.put("transfer_price_percentage",
325
							ConfigClient.getClient().get(
326
									ConfigClientKeys.transfer_price_percentage
327
											.toString()));
328
			ConfigMap.put("transfer_price_factor", ConfigClient.getClient()
329
					.get(ConfigClientKeys.transfer_price_factor.toString()));
330
		} catch (ConfigException ce) {
331
			logger.error(
332
					"Unable to connect to the config server. Setting sensible defaults.",
333
					ce);
334
			ConfigMap.put("courier_cost_factor", "60");
335
			ConfigMap.put("courier_weight_factor", "500");
336
			ConfigMap.put("breakeven_divisor", "0.98");
337
			ConfigMap.put("breakeven_additon_factor", "50");
338
			ConfigMap.put("transfer_price_percentage", "2");
339
			ConfigMap.put("transfer_price_factor", "50");
340
		}
341
		return ConfigMap;
342
	}
343
 
344
	/**
345
	 * Creates a new Item object and populates its attributes from thrift item
346
	 * passed as parameter. Also creates a Map each for VendorItemPricing,
347
	 * VendorItemMapping, SourceItemPricing and SimilarItems and adds these maps
348
	 * to the new Item object.
349
	 * 
350
	 * @param thriftItem
351
	 * @param tVendorPricings
352
	 * @param tVendorMappings
353
	 * @param tSourceMappings
354
	 * @param tSimilarItems
355
	 * @return item object with attributes copied from thrift item object.
356
	 */
357
	private Item getItemFromThriftItem(
358
			in.shop2020.model.v1.catalog.Item thriftItem,
5946 rajveer 359
			List<in.shop2020.model.v1.inventory.VendorItemPricing> tVendorPricings) {
5128 amit.gupta 360
 
361
		Map<Long, VendorPricings> vendorPricingMap = new HashMap<Long, VendorPricings>();
362
		VendorPricings vPricings;
363
		if (tVendorPricings != null) {
5946 rajveer 364
			for (in.shop2020.model.v1.inventory.VendorItemPricing vip : tVendorPricings) {
5128 amit.gupta 365
				vPricings = new VendorPricings();
366
				vPricings.setVendorId(vip.getVendorId());
367
				vPricings.setMop(vip.getMop());
368
				vPricings.setDealerPrice(vip.getDealerPrice());
369
				vPricings.setTransferPrice(vip.getTransferPrice());
370
				vendorPricingMap.put(vPricings.getVendorId(), vPricings);
371
			}
372
		}
373
 
6824 amar.kumar 374
		in.shop2020.catalog.dashboard.shared.ItemStockPurchaseParams stockPurchaseParams = 
375
        	new in.shop2020.catalog.dashboard.shared.ItemStockPurchaseParams();
5128 amit.gupta 376
 
377
		Item item = new Item(thriftItem.getId(), thriftItem.getProductGroup(),
378
				thriftItem.getBrand(), thriftItem.getModelNumber(),
379
				thriftItem.getModelName(), thriftItem.getColor(),
380
				CategoryManager.getCategoryManager().getCategoryLabel(
381
						thriftItem.getCategory()), thriftItem.getCategory(),
382
				thriftItem.getComments(), thriftItem.getCatalogItemId(),
383
				thriftItem.getFeatureId(), thriftItem.getFeatureDescription(),
384
				thriftItem.isSetMrp() ? thriftItem.getMrp() : null,
385
				thriftItem.isSetSellingPrice() ? thriftItem.getSellingPrice()
386
						: null,
387
				thriftItem.isSetWeight() ? thriftItem.getWeight() : null,
388
				thriftItem.getAddedOn(), thriftItem.getStartDate(),
5219 amit.gupta 389
				thriftItem.getComingSoonStartDate(), thriftItem.getExpectedArrivalDate(),
5128 amit.gupta 390
				thriftItem.getRetireDate(), thriftItem.getUpdatedOn(),
391
				thriftItem.getItemStatus().name(), thriftItem.getItemStatus()
392
						.getValue(), thriftItem.getStatus_description(),
5309 rajveer 393
				thriftItem.getBestDealText(),
6777 vikram.rag 394
				thriftItem.getBestDealsDetailsText(),
395
				thriftItem.getBestDealsDetailsLink(),
5128 amit.gupta 396
				thriftItem.isSetBestDealValue() ? thriftItem.getBestDealValue()
397
						: null,
398
				thriftItem.isSetBestSellingRank() ? thriftItem
399
						.getBestSellingRank() : null,
400
				thriftItem.isDefaultForEntity(), thriftItem.isRisky(),
401
				thriftItem.isSetExpectedDelay() ? thriftItem.getExpectedDelay()
402
						: null,
403
				thriftItem.isIsWarehousePreferenceSticky(),
5384 phani.kuma 404
				thriftItem.isHasItemNo(),
405
                ItemType.SERIALIZED.equals(thriftItem.getType()),
6241 amit.gupta 406
                thriftItem.isSetShowSellingPrice() ? thriftItem.isShowSellingPrice() : false,
5128 amit.gupta 407
				thriftItem.isSetPreferredVendor() ? thriftItem
6838 vikram.rag 408
						.getPreferredVendor() : null,
409
				thriftItem.isSetPreferredInsurer() ? thriftItem.getPreferredInsurer() : null, null,
6824 amar.kumar 410
				vendorPricingMap, null, null, null, null, stockPurchaseParams.getNumOfDaysStock(), 
9838 rajveer 411
				stockPurchaseParams.getMinStockLevel(), null, null,thriftItem.getAsin());
5128 amit.gupta 412
		return item;
413
	}
414
 
415
}