Subversion Repositories SmartDukaan

Rev

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

Rev Author Line No. Line
3364 chandransh 1
package in.shop2020.support.controllers;
2
 
5945 mandeep.dh 3
import in.shop2020.logistics.DeliveryType;
4
import in.shop2020.logistics.LogisticsService.Client;
5
import in.shop2020.logistics.LogisticsServiceException;
6
import in.shop2020.model.v1.catalog.CatalogServiceException;
7
import in.shop2020.model.v1.catalog.Item;
8
import in.shop2020.model.v1.catalog.status;
9
import in.shop2020.model.v1.inventory.InventoryServiceException;
10
import in.shop2020.model.v1.inventory.ItemInventory;
11
import in.shop2020.support.utils.FileUtils;
12
import in.shop2020.support.utils.ReportsUtils;
13
import in.shop2020.thrift.clients.CatalogClient;
14
import in.shop2020.thrift.clients.InventoryClient;
15
import in.shop2020.thrift.clients.LogisticsClient;
16
import in.shop2020.utils.CategoryManager;
17
 
3364 chandransh 18
import java.io.ByteArrayOutputStream;
19
import java.io.File;
20
import java.io.FileNotFoundException;
21
import java.io.FileOutputStream;
22
import java.io.IOException;
23
import java.util.ArrayList;
24
import java.util.Calendar;
25
import java.util.GregorianCalendar;
4878 rajveer 26
import java.util.HashMap;
27
import java.util.LinkedHashMap;
3364 chandransh 28
import java.util.List;
29
import java.util.Map;
30
 
31
import javax.servlet.ServletContext;
32
import javax.servlet.ServletOutputStream;
33
import javax.servlet.http.HttpServletRequest;
34
import javax.servlet.http.HttpServletResponse;
35
import javax.servlet.http.HttpSession;
36
 
37
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
4913 rajveer 38
import org.apache.poi.ss.usermodel.Cell;
3364 chandransh 39
import org.apache.poi.ss.usermodel.Row;
40
import org.apache.poi.ss.usermodel.Sheet;
41
import org.apache.poi.ss.usermodel.Workbook;
42
import org.apache.struts2.convention.annotation.InterceptorRef;
43
import org.apache.struts2.convention.annotation.InterceptorRefs;
3936 chandransh 44
import org.apache.struts2.convention.annotation.Result;
45
import org.apache.struts2.convention.annotation.Results;
3364 chandransh 46
import org.apache.struts2.interceptor.ServletRequestAware;
47
import org.apache.struts2.interceptor.ServletResponseAware;
48
import org.apache.struts2.util.ServletContextAware;
49
import org.apache.thrift.TException;
50
import org.apache.thrift.transport.TTransportException;
51
import org.slf4j.Logger;
52
import org.slf4j.LoggerFactory;
53
 
54
 
55
@InterceptorRefs({
56
    @InterceptorRef("defaultStack"),
57
    @InterceptorRef("login")
58
})
3936 chandransh 59
@Results({
60
    @Result(name="authfail", type="redirectAction", params = {"actionName" , "reports"})
61
})
3364 chandransh 62
public class StockReportsController implements ServletRequestAware, ServletResponseAware, ServletContextAware{
63
 
64
    private static Logger logger = LoggerFactory.getLogger(StockReportsController.class);    
65
 
66
    private static final String REPORT_DIR = "/inventory-report";
67
 
4823 rajveer 68
    private static final String DEFAULT_PINCODE = "110001"; 
5387 rajveer 69
    private static final long REPORT_GENERATION_INTERVAL = 3;
4830 rajveer 70
    private static final long CUT_OFF_TIME = 15;
71
    private static long NEXT_DAY_DELAY = 1;
4823 rajveer 72
 
4830 rajveer 73
    private static final int ID = 0, BRAND = 1, MODEL_NUMBER = 2, MODEL_NAME = 3, COLOR = 4, DELIVERY_DAYS = 5, TOTAL_AVAILABILITY = 6, TOTAL_RESERVED = 7;
5931 rajveer 74
	private static final int WH1_AVAILABILITY = 8, WH1_RESERVED = 9, WH5_AVALABILITY = 10, WH5_RESERVED = 11, WH7_AVALABILITY = 12, WH7_RESERVED = 13, RISKY = 14, EXPECTED_DELAY = 15, STICKY = 16, SIMILAR_ITEMS = 17;
4823 rajveer 75
 
3364 chandransh 76
    private HttpSession session;
77
    private HttpServletRequest request;
78
    private HttpServletResponse response;
79
    private ServletContext context;
80
 
81
    private String errorMsg = "";
82
 
83
    public String index(){
84
        if(!ReportsUtils.canAccessReport((Long)session.getAttribute(ReportsUtils.ROLE), request.getServletPath())) {
3936 chandransh 85
            return "authfail";
3364 chandransh 86
        }
87
        return "index";
88
    }
89
 
4823 rajveer 90
    public String create() throws NumberFormatException, IOException{
3364 chandransh 91
 
92
        Calendar date = new GregorianCalendar();
93
        int year = date.get(Calendar.YEAR);
94
        int month = date.get(Calendar.MONTH) +1;
95
        int day = date.get(Calendar.DAY_OF_MONTH);
4830 rajveer 96
        int hour = date.get(Calendar.HOUR_OF_DAY);
4823 rajveer 97
        long currentTimestamp = date.getTimeInMillis();
4824 rajveer 98
        String lastTimestampString = org.apache.commons.io.FileUtils.readFileToString(new File(REPORT_DIR + File.separator + "last.timestamp"));
99
        lastTimestampString = lastTimestampString.replace("\"", "").replace("\n", "");
100
        long lastTimestamp = Long.parseLong(lastTimestampString);
3364 chandransh 101
 
4823 rajveer 102
        String filename = "inventory-report." + year + "-" + month + "-" + day + "-" + lastTimestamp + ".xls";
4830 rajveer 103
        if(hour >= CUT_OFF_TIME){
104
        	NEXT_DAY_DELAY = 2;
105
        }else{
106
        	NEXT_DAY_DELAY = 1;
107
        }
4825 rajveer 108
        if(currentTimestamp - lastTimestamp > REPORT_GENERATION_INTERVAL*60*60*1000){
4823 rajveer 109
        	filename = "inventory-report." + year + "-" + month + "-" + day + "-" + currentTimestamp + ".xls";
110
        	File inventoryReportFile = new File(REPORT_DIR + File.separator + filename);
3364 chandransh 111
            ByteArrayOutputStream baosXLS = generateInventoryStockReport();
112
            if (baosXLS == null) {
113
                errorMsg = "Could not get output";
114
                return "index";
115
            }
116
 
117
            try {
118
                FileOutputStream f = new FileOutputStream(inventoryReportFile);
119
                baosXLS.writeTo(f);
120
                f.close();
4823 rajveer 121
                org.apache.commons.io.FileUtils.writeStringToFile(new File(REPORT_DIR + File.separator + "last.timestamp"), currentTimestamp+"");
3364 chandransh 122
            } catch (FileNotFoundException e) {
123
                logger.error("Error while writing the inventory report", e);
124
                return "index";
125
            } catch (IOException e) {
126
                logger.error("Error while writing the inventory report", e);
127
                return "index";
128
            }
129
        }
130
 
131
        response.setContentType("application/vnd.ms-excel");
132
        response.setHeader("Content-disposition", "inline; filename=" + filename);
133
        try {
134
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
135
            baos.write(FileUtils.getBytesFromFile(new File(REPORT_DIR + File.separator + filename)));
136
            ServletOutputStream sos = response.getOutputStream();
137
            baos.writeTo(sos);
138
            sos.flush();
139
            errorMsg = "Report generated";
140
        } catch (IOException e) {
141
            logger.error("Unable to stream the inventory stock report", e);
142
            errorMsg = "Failed to write to response.";
143
        }
144
        return "index";
145
    }
146
 
147
    private ByteArrayOutputStream generateInventoryStockReport(){
4878 rajveer 148
    	Map<String, Map<String, List<RowItem>>> categoryWiseStock = new LinkedHashMap<String, Map<String, List<RowItem>>>();
149
    	String nextDay = "Deliverable on Next Day";
150
    	String notNextDay = "Not Deliverable on Next Day";
151
    	String notAvailable = "Out of Stock";
4823 rajveer 152
        LogisticsClient logisticsServiceClient;
3364 chandransh 153
        CatalogClient catalogClientService;
154
        try {
155
            catalogClientService = new CatalogClient();
5945 mandeep.dh 156
            InventoryClient inventoryClientService = new InventoryClient();
4823 rajveer 157
            logisticsServiceClient = new LogisticsClient();
5945 mandeep.dh 158
            in.shop2020.model.v1.catalog.CatalogService.Client client = catalogClientService.getClient();
159
            in.shop2020.model.v1.inventory.InventoryService.Client iclient = inventoryClientService.getClient();
3364 chandransh 160
            List<Item> items = client.getAllItems(false);
4823 rajveer 161
			Client logisticsClient = logisticsServiceClient.getClient();
3364 chandransh 162
 
4878 rajveer 163
			CategoryManager catm = CategoryManager.getCategoryManager();
4823 rajveer 164
			for(Item item : items){
4878 rajveer 165
				status state = item.getItemStatus();
3364 chandransh 166
                switch(state){
167
                case IN_PROCESS:
168
                case CONTENT_COMPLETE:
169
                case DELETED:
170
                case PHASED_OUT:
171
                    continue;
172
                case PAUSED:
173
                case PAUSED_BY_RISK:
174
                case ACTIVE:
4878 rajveer 175
                	if(item.getCategory() == -1 || item.getCategory() == 0){
176
                		continue;
177
                	}
178
                	String category = catm.getCategory(catm.getCategory(item.getCategory()).getParent_category_id()).getLabel();
179
 
180
                	Map<String, List<RowItem>> sheetsMap = categoryWiseStock.get(category);
181
                	if(sheetsMap ==  null){
182
                		sheetsMap = new HashMap<String, List<RowItem>>();
183
                		categoryWiseStock.put(category, sheetsMap);
184
                		sheetsMap.put(nextDay, new ArrayList<RowItem>());
185
                		sheetsMap.put(notNextDay, new ArrayList<RowItem>());
186
                		sheetsMap.put(notAvailable, new ArrayList<RowItem>());
187
                	}
188
 
189
 
190
                	long deliveryDays = 3;
4830 rajveer 191
                	try{
4878 rajveer 192
 
4830 rajveer 193
                		deliveryDays = logisticsClient.getLogisticsEstimation(item.getId(), DEFAULT_PINCODE, DeliveryType.PREPAID).getDeliveryTime();
194
                	}catch (LogisticsServiceException e) {
195
                		logger.error("Error while getting estimate of the inventory for item " + item.getId(), e);
196
                	}
5945 mandeep.dh 197
                	ItemInventory inventory = iclient.getItemInventoryByItemId(item.getId());
5306 rajveer 198
                	RowItem rowItem = new RowItem(item, deliveryDays, inventory);
4830 rajveer 199
                	if(state == status.ACTIVE){
200
                    	if(deliveryDays == NEXT_DAY_DELAY)
4878 rajveer 201
                    		sheetsMap.get(nextDay).add(rowItem);
3364 chandransh 202
                        else
4878 rajveer 203
                        	sheetsMap.get(notNextDay).add(rowItem);    
4913 rajveer 204
                    }else{
4878 rajveer 205
                    	sheetsMap.get(notAvailable).add(rowItem);
4913 rajveer 206
                    	List<Item> similaritems= client.getAllSimilarItems(item.getId());
207
                    	if(similaritems!=null){
208
                    		boolean isFirst = true;
209
                    		for(Item item1: similaritems){
4916 rajveer 210
                    			if(isFirst){
211
                    				isFirst = false;
212
                    			}else{
4914 rajveer 213
                    				rowItem.similarItems += "\n";
214
                    			}
4916 rajveer 215
                    			rowItem.similarItems += item1.getBrand() + " " + item1.getModelName() + " " + item1.getModelNumber() + " " + item1.getColor();
4913 rajveer 216
                    		}
217
                    	}
218
                    }
3364 chandransh 219
                }
220
            }
221
        } catch (TTransportException e) {
222
            logger.error("Unable to get the items from the inventory", e);
223
            return null;
5945 mandeep.dh 224
        } catch (CatalogServiceException e) {
3364 chandransh 225
            logger.error("Error while getting the items from the inventory", e);
226
            return null;
227
        } catch (TException e) {
228
            logger.error("Error while getting the items from the inventory", e);
229
            return null;
5945 mandeep.dh 230
		} catch (InventoryServiceException e) {
231
		    logger.error("Error while getting the items from the inventory", e);
232
            return null;
233
        }
3364 chandransh 234
 
235
        ByteArrayOutputStream baosXLS = new ByteArrayOutputStream();
236
 
237
        Workbook wb = new HSSFWorkbook();
238
 
4878 rajveer 239
//        for(String category: categoryWiseStock.keySet()){
240
//        	Map<String, List<RowItem>> value = categoryWiseStock.get(category);  
241
//        	createSheet(wb, category + " - " + nextDay, value.get(nextDay));
242
//        	createSheet(wb, category + " - " + notNextDay, value.get(notNextDay));
243
//        	createSheet(wb, category + " - " + notAvailable, value.get(notAvailable));
244
//        }
3364 chandransh 245
 
4878 rajveer 246
        //Hardcoding to maintain category
247
        List<String> categories = new ArrayList<String>();
248
        categories.add("Mobile Phones");
249
        categories.add("Tablets");
250
        categories.add("Mobile Accessories");
251
        categories.add("Laptops");
252
        categories.add("Laptop Accessories");
253
        for(String category: categories){
254
        	Map<String, List<RowItem>> value = categoryWiseStock.get(category);  
255
        	createSheet(wb, category + " - " + nextDay, value.get(nextDay));
256
        	createSheet(wb, category + " - " + notNextDay, value.get(notNextDay));
257
        	createSheet(wb, category + " - " + notAvailable, value.get(notAvailable));
258
        }
259
 
260
 
3364 chandransh 261
        try {
262
            wb.write(baosXLS);
263
            baosXLS.close();
264
        } catch (IOException e) {
265
            logger.error("Error while streaming inventory stock report", e);
266
            return null;
267
        }
268
        return baosXLS;
269
    }
270
 
271
    private void createSheet(Workbook wb, String name, List<RowItem> items){
272
        Sheet sheet = wb.createSheet(name);
273
        short serialNo = 0;
274
        Row headerRow = sheet.createRow(serialNo++);
275
        headerRow.createCell(ID).setCellValue("Item Id");
276
        headerRow.createCell(BRAND).setCellValue("Brand");
277
        headerRow.createCell(MODEL_NUMBER).setCellValue("Model Number");
278
        headerRow.createCell(MODEL_NAME).setCellValue("Model Name");
279
        headerRow.createCell(COLOR).setCellValue("Color");
4830 rajveer 280
        headerRow.createCell(DELIVERY_DAYS).setCellValue("Delivery Days");
4823 rajveer 281
        headerRow.createCell(TOTAL_AVAILABILITY).setCellValue("Total Availability");
282
        headerRow.createCell(TOTAL_RESERVED).setCellValue("Total Reserved");
4830 rajveer 283
        headerRow.createCell(WH1_AVAILABILITY).setCellValue("901 Availabality");
284
        headerRow.createCell(WH1_RESERVED).setCellValue("901 Reserved");
285
        headerRow.createCell(WH5_AVALABILITY).setCellValue("9D2 Availabality");
286
        headerRow.createCell(WH5_RESERVED).setCellValue("9D2 Reserved");
287
        headerRow.createCell(WH7_AVALABILITY).setCellValue("MP Availabality");
288
        headerRow.createCell(WH7_RESERVED).setCellValue("MP Reserved");
5931 rajveer 289
        headerRow.createCell(RISKY).setCellType(Cell.CELL_TYPE_STRING);
290
        headerRow.getCell(RISKY).setCellValue("Risky");
291
        headerRow.createCell(EXPECTED_DELAY).setCellValue("Expected Delay");
292
        headerRow.createCell(STICKY).setCellType(Cell.CELL_TYPE_STRING);
293
        headerRow.getCell(STICKY).setCellValue("Sticky");
4913 rajveer 294
        headerRow.createCell(SIMILAR_ITEMS).setCellType(Cell.CELL_TYPE_STRING);
295
        headerRow.getCell(SIMILAR_ITEMS).setCellValue("Similar Items");
296
 
4823 rajveer 297
        //        headerRow.createCell(WH2_A).setCellValue("WH2 Availabality");
298
        //        headerRow.createCell(WH3_A).setCellValue("WH3 Availabality");
299
        //        headerRow.createCell(WH4_A).setCellValue("WH4 Availabality");     
300
        //        headerRow.createCell(WH2_R).setCellValue("WH2 Reserved");
301
        //        headerRow.createCell(WH3_R).setCellValue("WH3 Reserved");
302
        //        headerRow.createCell(WH4_R).setCellValue("WH4 Reserved");
303
 
3364 chandransh 304
        for(RowItem item : items){
305
            Row contentRow = sheet.createRow(serialNo++);
306
            contentRow.createCell(ID).setCellValue(item.id);
307
            contentRow.createCell(BRAND).setCellValue(item.brand);
308
            contentRow.createCell(MODEL_NUMBER).setCellValue(item.modelNumber);
309
            contentRow.createCell(MODEL_NAME).setCellValue(item.modelName);
310
            contentRow.createCell(COLOR).setCellValue(item.color);
4830 rajveer 311
            contentRow.createCell(DELIVERY_DAYS).setCellValue(item.deliveryEstimate);
4823 rajveer 312
            contentRow.createCell(TOTAL_AVAILABILITY).setCellValue(item.totalAvailability);
313
            contentRow.createCell(TOTAL_RESERVED).setCellValue(item.totalReserved);
314
            contentRow.createCell(WH1_AVAILABILITY).setCellValue(item.wh1Availability);
315
            contentRow.createCell(WH1_RESERVED).setCellValue(item.wh1Reserved);
316
            contentRow.createCell(WH5_AVALABILITY).setCellValue(item.wh5Availability);
317
            contentRow.createCell(WH5_RESERVED).setCellValue(item.wh5Reserved);
318
            contentRow.createCell(WH7_AVALABILITY).setCellValue(item.wh7Availability);
319
            contentRow.createCell(WH7_RESERVED).setCellValue(item.wh7Reserved);
5931 rajveer 320
            contentRow.createCell(RISKY).setCellValue(item.risky);
321
            contentRow.createCell(EXPECTED_DELAY).setCellValue(item.expectedDelay);
322
            contentRow.createCell(STICKY).setCellValue(item.sticky);
4913 rajveer 323
            contentRow.createCell(SIMILAR_ITEMS).setCellValue(item.similarItems);
3364 chandransh 324
        }
4913 rajveer 325
        sheet.autoSizeColumn(SIMILAR_ITEMS);
326
 
3364 chandransh 327
    }
328
 
329
    public String getErrorMsg() {
330
        return errorMsg;
331
    }
332
 
333
    @Override
334
    public void setServletRequest(HttpServletRequest req) {
335
        this.request = req;
336
        this.session = req.getSession();
337
    }
338
 
339
    @Override
340
    public void setServletResponse(HttpServletResponse res) {
341
        this.response = res;
342
    }
343
 
344
    @Override
345
    public void setServletContext(ServletContext context) {
346
        this.context = context;
347
    }
348
 
349
    public String getServletContextPath() {
350
        return context.getContextPath();
351
    }
352
 
353
    public static void main(String[] args) {
354
        StockReportsController src = new StockReportsController();
355
        try {
356
            String userHome = System.getProperty("user.home");
357
            FileOutputStream f = new FileOutputStream(userHome + "/stock-report.xls");
358
            ByteArrayOutputStream baosXLS = src.generateInventoryStockReport();
359
            baosXLS.writeTo(f);
360
            f.close();
361
        } catch (FileNotFoundException e) {
362
            logger.error("Error creating inventory stock report", e);
363
        } catch (IOException e) {
364
            logger.error("IO error while creating inventory stock report", e);
365
        }
366
        System.out.println("Successfully generated the inventory stock report");
367
    }
368
 
369
    class RowItem {
370
        public long id;
371
        public String brand;
372
        public String modelNumber;
373
        public String modelName;
374
        public String color;
4830 rajveer 375
        public long deliveryEstimate = 0;
4823 rajveer 376
        public long totalAvailability = 0;
377
        public long totalReserved = 0;
378
        public long wh1Availability = 0;
379
        public long wh1Reserved = 0;
380
        public long wh5Availability = 0;
381
        public long wh5Reserved = 0;
382
        public long wh7Availability = 0;
383
        public long wh7Reserved = 0;
4913 rajveer 384
        public String similarItems = "";
5931 rajveer 385
        public String risky;
386
        public String sticky;
387
        public long expectedDelay = 0;
3364 chandransh 388
 
5306 rajveer 389
        public RowItem(Item item, long estimate, ItemInventory itemInventory){
3364 chandransh 390
           id = item.getId();
391
           brand = item.getBrand();
392
           modelNumber = item.getModelNumber();
393
           modelName = item.getModelName();
394
           color = item.getColor();
4830 rajveer 395
           deliveryEstimate = estimate;
5931 rajveer 396
           risky = item.isRisky() ? "True" : "False";
397
           sticky = item.isIsWarehousePreferenceSticky() ? "True" : "False";
398
           expectedDelay = item.getExpectedDelay();
4823 rajveer 399
           totalAvailability = 0;
400
           for(Map.Entry<Long, Long> entry : itemInventory.getAvailability().entrySet()){
401
        	   long value = entry.getValue();
402
        	   switch (entry.getKey().intValue()) {
403
        	   case 1:
404
        		   wh1Availability = value;
405
        		   break;
406
        	   case 5:
407
        		   wh5Availability = value;
408
        		   break;
409
        	   case 7:
410
        		   wh7Availability = value;
411
        		   break;
412
        	   default:
413
        		   break;
414
        	   }
415
        	   totalAvailability += value;
3364 chandransh 416
           }
4823 rajveer 417
           for(Map.Entry<Long, Long> entry : itemInventory.getReserved().entrySet()){
418
        	   long value = entry.getValue();
419
        	   switch (entry.getKey().intValue()) {
420
        	   case 1:
421
        		   wh1Reserved = value;
422
        		   break;
423
        	   case 5:
424
        		   wh5Reserved = value;
425
        		   break;
426
        	   case 7:
427
        		   wh7Reserved = value;
428
        		   break;
429
        	   default:
430
        		   break;
431
        	   }
432
        	   totalReserved += value;
433
           }
3364 chandransh 434
        }
435
    }
436
}