Subversion Repositories SmartDukaan

Rev

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

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