Subversion Repositories SmartDukaan

Rev

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